agestra 4.10.3 → 4.10.4

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,53 +1,53 @@
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 LS=Object.create;var Oc=Object.defineProperty;var FS=Object.getOwnPropertyDescriptor;var ZS=Object.getOwnPropertyNames;var US=Object.getPrototypeOf,qS=Object.prototype.hasOwnProperty;var Er=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ve=(t,e)=>{for(var r in e)Oc(t,r,{get:e[r],enumerable:!0})},VS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ZS(e))!qS.call(t,o)&&o!==r&&Oc(t,o,{get:()=>e[o],enumerable:!(n=FS(e,o))||n.enumerable});return t};var uf=(t,e,r)=>(r=t!=null?LS(US(t)):{},VS(e||!t||!t.__esModule?Oc(r,"default",{value:t,enumerable:!0}):r,t));var lf,vo,df,pf,ff,mf,hf,_o,gf,Hs,yf,vf,_f,bf,wf,xf,Ks,Mc,Nc,Jj,Sf,gn,jc,Lc,$f,kf,Js,Rr,Fc,Pf,Tf,yn,qt=Er(()=>{"use strict";lf="4.10.3",vo="http://localhost:11434",df="llama3",pf=".agestra/.jobs",ff=".agestra/traces",mf=".agestra/worktrees",hf=".agestra/sessions",_o=".agestra/workspace",gf="individual",Hs="debates",yf="synthesis",vf="issue",_f=".agestra/workers",bf=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),wf=2,xf=6e4,Ks=20,Mc=5e4,Nc=10,Jj=Object.freeze([3,5,10]),Sf=Object.freeze(["agree","disagree","abstain","revise"]),gn="votes",jc=2,Lc=2,$f=1440*60*1e3,kf=3600*1e3,Js=Object.freeze(["ko","zh","ja","en"]),Rr="ko",Fc="en",Pf="[REDACTED]",Tf=["","--- REQUIRED RESPONSE FORMAT ---","Respond with JSON only, matching exactly this shape:",'{ "agrees": true | false, "feedback": "specific issues or why you agree", "suggestions": "concrete changes if you disagree (optional, may be omitted)" }',"No prose, markdown, or explanation outside the JSON object. The JSON must be the entire response or wrapped in a single ```json code fence.","-------------------------------"].join(`
4
- `),yn=Object.freeze({auto:Object.freeze({name:"auto",description:"Auto-detect build profile from project structure (package.json scripts, tsconfig, vitest config, etc.).",command:"npx",args:Object.freeze([])}),tsc:Object.freeze({name:"tsc",description:"TypeScript project-references build via `npx tsc -b --noEmit`.",command:"npx",args:Object.freeze(["tsc","-b","--noEmit"])}),vitest:Object.freeze({name:"vitest",description:"Run the Vitest unit-test suite in CI mode.",command:"npx",args:Object.freeze(["vitest","run","--reporter=dot"])}),"npm-build":Object.freeze({name:"npm-build",description:"Run the project's `npm run build` script.",command:"npm",args:Object.freeze(["run","build"])}),"npm-test":Object.freeze({name:"npm-test",description:"Run the project's `npm test` script.",command:"npm",args:Object.freeze(["test","--","--run"])})})});import{execFileSync as BS}from"child_process";function vn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return BS("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0}),{delivered:!0}}catch{try{return process.kill(t),{delivered:!0}}catch{return{delivered:!1}}}try{return process.kill(-t,"SIGTERM"),{delivered:!0}}catch{try{return process.kill(t,"SIGTERM"),{delivered:!0}}catch{return{delivered:!1}}}}function At(t,e=3e3){let r=t.pid;if(r)vn(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e).unref?.()}var bo=Er(()=>{"use strict"});import{execFileSync as WS,spawn as HS}from"child_process";import{existsSync as KS}from"fs";function GS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:JS.has(t.toLowerCase())}function YS(t){if(t.includes("\0"))throw new Error(`Windows shim arg contains null byte: ${JSON.stringify(t)}`);if(t.includes("%"))throw new Error(`Windows shim arg contains '%' which would trigger cmd.exe env expansion: ${JSON.stringify(t)}`);return/[\s"&^<>|()!]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function XS(t){let e=t.toLowerCase();if(_n.has(e))return _n.get(e)??null;try{let n=WS("where.exe",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:5e3}).split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(n.length===0)return _n.set(e,null),null;let o=n.find(a=>/\.(cmd|bat)$/i.test(a));if(o){let a={type:"cmd",path:o};return _n.set(e,a),a}let i=`${n[0]}.ps1`;if(KS(i)){let a={type:"powershell",path:i};return _n.set(e,a),a}}catch{}return _n.set(e,null),null}function Vt(t,e){if(!GS(t))return{command:t,args:e};let r=XS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>YS(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function Me(t){let{command:e,args:r,timeout:n=12e4,cwd:o,env:s,stdin:i,maxBuffer:a=10485760,onStderrChunk:c,signal:u}=t;return new Promise((l,d)=>{if(u?.aborted){d(new ct(u.reason));return}let p=Vt(e,r),f=HS(p.command,p.args,{cwd:o,env:s?{...process.env,...s}:void 0,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),m="",g="",v=0,_=0,S=!1,y=null,x=!1,$=null,M=()=>{$&&u&&u.removeEventListener("abort",$)},O=!1,Y=()=>{!O&&v+_>a&&(S=!0,O=!0,At(f))},Pe=()=>{x||(At(f),x=!0,M(),d(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`)))},K=setTimeout(Pe,n);u&&($=()=>{x||(x=!0,clearTimeout(K),At(f),M(),d(new ct(u.reason)))},u.addEventListener("abort",$));let ot=()=>{O||(clearTimeout(K),K=setTimeout(Pe,n))};if(f.stdout.on("data",Re=>{v+=Re.length,v<=a&&(m+=Re.toString()),Y(),ot()}),f.stderr.on("data",Re=>{_+=Re.length;let Pr=Re.toString();if(_<=a&&(g+=Pr),Y(),!O&&c){let Tr=c(Pr);Tr&&(y=Tr,O=!0,At(f))}ot()}),i&&f.stdin){f.stdin.on("error",()=>{});try{f.stdin.write(i),f.stdin.end()}catch{}}f.on("close",Re=>{if(clearTimeout(K),!x){if(y){x=!0,M(),d(y);return}x=!0,M(),l({stdout:m,stderr:g,exitCode:Re??1,truncated:S})}}),f.on("error",Re=>{clearTimeout(K),!x&&(x=!0,M(),d(new Error(`CLI spawn error: ${Re.message}`)))})})}var ct,JS,_n,bn=Er(()=>{"use strict";bo();ct=class extends Error{constructor(e){let r=e instanceof Error?`: ${e.message}`:typeof e=="string"&&e?`: ${e}`:"";super(`CLI aborted${r}`),this.name="CliAbortedError"}},JS=new Set(["codex","gemini","npm","npx"]),_n=new Map});import{writeFileSync as wk,mkdirSync as ko,openSync as Bc,writeSync as Wc,fsyncSync as Wf,closeSync as Hc,renameSync as xk,unlinkSync as Bf,appendFileSync as Sk,copyFileSync as $k}from"fs";import{dirname as Po,join as kk}from"path";import{randomUUID as Pk}from"crypto";function oe(t,e){let r=Po(t);ko(r,{recursive:!0});let n=kk(r,`.tmp-${Pk().slice(0,8)}`);try{wk(n,e,"utf-8");try{xk(n,t)}catch(o){if(o.code!=="EXDEV")throw o;$k(n,t),Bf(n)}}catch(o){try{Bf(n)}catch{}throw o}}function je(t,e){oe(t,JSON.stringify(e,null,2))}function ai(t,e){let r=Po(t);ko(r,{recursive:!0});let n=Bc(t,"a");try{Wc(n,e),Wf(n)}finally{Hc(n)}}var ii,ci=Er(()=>{"use strict";ii=class{buffer=new Map;flushTimer=null;flushIntervalMs;maxBufferSize;auditFsync;destroyed=!1;constructor(e){this.flushIntervalMs=e?.flushIntervalMs??2e3,this.maxBufferSize=e?.maxBufferSize??100,this.auditFsync=e?.auditFsync??!0,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer&&typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}append(e,r,n){if(this.destroyed)throw new Error("DurableAppendWriter has been destroyed");if(n==="audit"){if(this.auditFsync)ai(e,r);else{let s=Po(e);ko(s,{recursive:!0}),Sk(e,r)}return}let o=this.buffer.get(e);o||(o=[],this.buffer.set(e,o)),o.push(r),o.length>=this.maxBufferSize&&this.flushFile(e),this.flushIntervalMs===0&&this.flushFile(e)}flush(){for(let e of this.buffer.keys())this.flushFile(e)}panicFlush(){for(let[e,r]of this.buffer)if(r.length!==0)try{let n=Po(e);ko(n,{recursive:!0});let o=Bc(e,"a");try{Wc(o,r.join("")),Wf(o)}finally{Hc(o)}}catch{}this.buffer.clear()}destroy(){this.destroyed||(this.destroyed=!0,this.flushTimer!==null&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush())}flushFile(e){let r=this.buffer.get(e);if(!r||r.length===0)return;let n=Po(e);ko(n,{recursive:!0});let o=Bc(e,"a");try{Wc(o,r.join(""))}finally{Hc(o)}this.buffer.delete(e)}}});import{openSync as Tk,writeSync as Ek,closeSync as Rk,unlinkSync as Hf,statSync as Ik,mkdirSync as Ak}from"fs";import{dirname as Ck}from"path";function Mk(t){if(t<=0)return;let e=new SharedArrayBuffer(4),r=new Int32Array(e);Atomics.wait(r,0,0,t)}function Hr(t,e,r={}){let n=r.staleMs??Dk,o=r.acquireTimeoutMs??zk,s=r.pollMs??Ok;Ak(Ck(t),{recursive:!0});let i=Date.now(),a=null;for(;a===null;)try{a=Tk(t,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=!1;try{let p=Ik(t);l=Date.now()-p.mtimeMs>n}catch{continue}if(l){try{Hf(t)}catch{}continue}let d=Date.now()-i;if(d>=o)throw new Kc(t,d);Mk(s)}try{try{Ek(a,`${process.pid}@${Date.now()}
5
- `)}catch{}return e()}finally{try{Rk(a)}catch{}try{Hf(t)}catch{}}}var Dk,zk,Ok,Kc,Jc=Er(()=>{"use strict";Dk=3e4,zk=5e3,Ok=10,Kc=class extends Error{constructor(e,r){super(`withFileLock: timed out after ${r}ms waiting for ${e}`),this.name="FileLockTimeoutError"}}});import{existsSync as Kf,realpathSync as Nk}from"fs";import{basename as jk,dirname as Lk,isAbsolute as Yc,join as Fk,normalize as Gf,resolve as Xc,relative as Zk}from"path";function Uk(t){return t===""||!t.startsWith("..")&&!Yc(t)}function Gc(t){let e=[],r=Xc(t);for(;!Kf(r);){let o=Lk(r);if(o===r)break;e.unshift(jk(r)),r=o}let n=Kf(r)?Nk(r):r;return e.reduce((o,s)=>Fk(o,s),n)}function Yf(t,e){let r=Gc(e),n=Gc(t),o=Zk(r,n);return Uk(o)}function Qc(t,e){let r=Xc(e,t);return Yf(r,e)}function pt(t,e){let r=Xc(e,t);if(!Yf(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Le(t,e){if(t.length===0)throw new Error("Filename must not be empty");if(t.includes("\0"))throw new Error(`Filename contains null byte: ${JSON.stringify(t)}`);if(t.includes("/")||t.includes("\\"))throw new Error(`Filename must not contain path separators: ${JSON.stringify(t)}`);if(t.includes(".."))throw new Error(`Filename must not contain '..': ${JSON.stringify(t)}`);return pt(t,e)}function Gt(t,e){if(Yc(t)){let r=Gf(t);if(!Qc(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return pt(t,e)}function eu(t,e){return Yc(t)?Gc(Gf(t)):pt(t,e)}function dr(t){return qk.test(t)}function ui(t,e){if(!t||typeof t!="string")throw new st(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new st(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new st(t,"command must not contain path separators");if(!Jf.has(t))throw new st(t,`command is not in the allowlist (${[...Jf].join(", ")})`);for(let r of e){if(typeof r!="string")throw new st(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new st(t,`arg contains null byte: ${JSON.stringify(r)}`);if(Vk.has(r))throw new st(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var qk,Jf,Vk,st,To=Er(()=>{"use strict";qk=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Jf=new Set(["gemini","codex","npx","node","npm","tsc"]),Vk=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),st=class extends Error{command;reason;constructor(e,r){super(`CLI command rejected: ${e} \u2014 ${r}`),this.command=e,this.reason=r,this.name="CliCommandRejectedError"}}});var em={};Ve(em,{CLI_PROVIDERS:()=>Xf,resolveCliConfig:()=>Qf});import{readFileSync as tu}from"fs";import{join as it}from"path";import{spawn as Bk}from"child_process";function Qf(t){let e=Wk[t.provider]??t.provider;return Xf[e]??null}function Kr(t,e){let r=it(t,"status.json"),n=`${r}.lock`;Hr(n,()=>{let o=JSON.parse(tu(r,"utf-8"));je(r,{...o,...e})})}async function Hk(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(tu(it(t,"job.json"),"utf-8"))}catch{try{je(it(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),oe(it(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=Qf(e);r||(Kr(t,{state:"missing_cli",completedAt:new Date().toISOString()}),oe(it(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;Kr(t,{state:"running",startedAt:new Date().toISOString()});let s=tu(it(t,"prompt.txt"),"utf-8"),i=o(s);try{ui(n,i)}catch(c){let u=c instanceof st?c.message:`Argv rejected: ${c.message}`;Kr(t,{state:"error",completedAt:new Date().toISOString()}),oe(it(t,"error.txt"),u);return}let a;if(e.cwd)try{a=pt(e.cwd,process.cwd())}catch(c){Kr(t,{state:"error",completedAt:new Date().toISOString()}),oe(it(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}return new Promise(c=>{let u=Vt(n,i),l=Bk(u.command,u.args,{cwd:a,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",v=>{f+=v.length,f<=10485760&&(d+=v.toString())}),l.stderr.on("data",v=>{m+=v.length,m<=10485760&&(p+=v.toString())});let g=setTimeout(()=>{At(l),oe(it(t,"output.txt"),d),oe(it(t,"error.txt"),p),Kr(t,{state:"timed_out",completedAt:new Date().toISOString()}),c()},e.timeout);l.on("close",v=>{clearTimeout(g),oe(it(t,"output.txt"),d),oe(it(t,"error.txt"),p);let _=d.trim().length>0;Kr(t,{state:v===0||_?"completed":"error",exitCode:v??1,completedAt:new Date().toISOString()}),c()}),l.on("error",v=>{clearTimeout(g);let _=v.code==="ENOENT"?"missing_cli":"error";oe(it(t,"error.txt"),v.message),Kr(t,{state:_,completedAt:new Date().toISOString()}),c()})})}var Wk,Xf,Kk,tm=Er(()=>{"use strict";ci();Jc();bo();To();bn();Wk={"gemini-cli":"gemini","codex-cli":"codex"},Xf={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--skip-git-repo-check","--full-auto","--ephemeral",t]}};Kk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");Kk&&Hk().catch(()=>process.exit(1))});var ms=E(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var ps=class{};se._CodeOrName=ps;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var nn=class extends ps{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=nn;var gt=class extends ps{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof nn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};se._Code=gt;se.nil=new gt("");function t_(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ml(r,e[n]),r.push(t[++n]);return new gt(r)}se._=t_;var Ol=new gt("+");function r_(t,...e){let r=[fs(t[0])],n=0;for(;n<e.length;)r.push(Ol),Ml(r,e[n]),r.push(Ol,fs(t[++n]));return WR(r),new gt(r)}se.str=r_;function Ml(t,e){e instanceof gt?t.push(...e._items):e instanceof nn?t.push(e):t.push(JR(e))}se.addCodeArg=Ml;function WR(t){let e=1;for(;e<t.length-1;){if(t[e]===Ol){let r=HR(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function HR(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof nn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof nn))return`"${t}${e.slice(1)}`}function KR(t,e){return e.emptyStr()?t:t.emptyStr()?e:r_`${t}${e}`}se.strConcat=KR;function JR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:fs(Array.isArray(t)?t.join(","):t)}function GR(t){return new gt(fs(t))}se.stringify=GR;function fs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}se.safeStringify=fs;function YR(t){return typeof t=="string"&&se.IDENTIFIER.test(t)?new gt(`.${t}`):t_`[${t}]`}se.getProperty=YR;function XR(t){if(typeof t=="string"&&se.IDENTIFIER.test(t))return new gt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}se.getEsmExportName=XR;function QR(t){return new gt(t.toString())}se.regexpCode=QR});var Ll=E(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.ValueScope=tt.ValueScopeName=tt.Scope=tt.varKinds=tt.UsedValueState=void 0;var et=ms(),Nl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ha;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ha||(tt.UsedValueState=ha={}));tt.varKinds={const:new et.Name("const"),let:new et.Name("let"),var:new et.Name("var")};var ga=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof et.Name?e:this.name(e)}name(e){return new et.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};tt.Scope=ga;var ya=class extends et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,et._)`.${new et.Name(r)}[${n}]`}};tt.ValueScopeName=ya;var eI=(0,et._)`\n`,jl=class extends ga{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?eI:et.nil}}get(){return this._scope}name(e){return new ya(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,et._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=et.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ha.Started);let l=r(u);if(l){let d=this.opts.es5?tt.varKinds.var:tt.varKinds.const;s=(0,et._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,et._)`${s}${l}${this.opts._n}`;else throw new Nl(u);c.set(u,ha.Completed)})}return s}};tt.ValueScope=jl});var W=E(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.or=H.and=H.not=H.CodeGen=H.operators=H.varKinds=H.ValueScopeName=H.ValueScope=H.Scope=H.Name=H.regexpCode=H.stringify=H.getProperty=H.nil=H.strConcat=H.str=H._=void 0;var re=ms(),$t=Ll(),vr=ms();Object.defineProperty(H,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(H,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(H,"strConcat",{enumerable:!0,get:function(){return vr.strConcat}});Object.defineProperty(H,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(H,"getProperty",{enumerable:!0,get:function(){return vr.getProperty}});Object.defineProperty(H,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(H,"regexpCode",{enumerable:!0,get:function(){return vr.regexpCode}});Object.defineProperty(H,"Name",{enumerable:!0,get:function(){return vr.Name}});var wa=Ll();Object.defineProperty(H,"Scope",{enumerable:!0,get:function(){return wa.Scope}});Object.defineProperty(H,"ValueScope",{enumerable:!0,get:function(){return wa.ValueScope}});Object.defineProperty(H,"ValueScopeName",{enumerable:!0,get:function(){return wa.ValueScopeName}});Object.defineProperty(H,"varKinds",{enumerable:!0,get:function(){return wa.varKinds}});H.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var er=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Fl=class extends er{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Hn(this.rhs,e,r)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},va=class extends er{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Hn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return ba(e,this.rhs)}},Zl=class extends va{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ul=class extends er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ql=class extends er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Vl=class extends er{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Bl=class extends er{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Hn(this.code,e,r),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},hs=class extends er{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(tI(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>an(e,r.names),{})}},tr=class extends hs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Wl=class extends hs{},Wn=class extends tr{};Wn.kind="else";var on=class t extends tr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Wn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(n_(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Hn(this.condition,e,r),this}get names(){let e=super.names;return ba(e,this.condition),this.else&&an(e,this.else.names),e}};on.kind="if";var sn=class extends tr{};sn.kind="for";var Hl=class extends sn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Hn(this.iteration,e,r),this}get names(){return an(super.names,this.iteration.names)}},Kl=class extends sn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?$t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ba(super.names,this.from);return ba(e,this.to)}},_a=class extends sn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Hn(this.iterable,e,r),this}get names(){return an(super.names,this.iterable.names)}},gs=class extends tr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};gs.kind="func";var ys=class extends hs{render(e){return"return "+super.render(e)}};ys.kind="return";var Jl=class extends tr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&an(e,this.catch.names),this.finally&&an(e,this.finally.names),e}},vs=class extends tr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};vs.kind="catch";var _s=class extends tr{render(e){return"finally"+super.render(e)}};_s.kind="finally";var Gl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
6
- `:""},this._extScope=e,this._scope=new $t.Scope({parent:e}),this._nodes=[new Wl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Fl(e,s,n)),s}const(e,r,n){return this._def($t.varKinds.const,e,r,n)}let(e,r,n){return this._def($t.varKinds.let,e,r,n)}var(e,r,n){return this._def($t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new va(e,r,n))}add(e,r){return this._leafNode(new Zl(e,H.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Bl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,re.addCodeArg)(r,o));return r.push("}"),new re._Code(r)}if(e,r,n){if(this._blockNode(new on(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new on(e))}else(){return this._elseNode(new Wn)}endIf(){return this._endBlockNode(on,Wn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Hl(e),r)}forRange(e,r,n,o,s=this.opts.es5?$t.varKinds.var:$t.varKinds.let){let i=this._scope.toName(e);return this._for(new Kl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=$t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof re.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,re._)`${i}.length`,a=>{this.var(s,(0,re._)`${i}[${a}]`),n(s)})}return this._for(new _a("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?$t.varKinds.var:$t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new _a("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(sn)}label(e){return this._leafNode(new Ul(e))}break(e){return this._leafNode(new ql(e))}return(e){let r=new ys;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ys)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Jl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new vs(s),r(s)}return n&&(this._currNode=o.finally=new _s,this.code(n)),this._endBlockNode(vs,_s)}throw(e){return this._leafNode(new Vl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=re.nil,n,o){return this._blockNode(new gs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(gs)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof on))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};H.CodeGen=Gl;function an(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ba(t,e){return e instanceof re._CodeOrName?an(t,e.names):t}function Hn(t,e,r){if(t instanceof re.Name)return n(t);if(!o(t))return t;return new re._Code(t._items.reduce((s,i)=>(i instanceof re.Name&&(i=n(i)),i instanceof re._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof re._Code&&s._items.some(i=>i instanceof re.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function tI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function n_(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,re._)`!${Yl(t)}`}H.not=n_;var rI=o_(H.operators.AND);function nI(...t){return t.reduce(rI)}H.and=nI;var oI=o_(H.operators.OR);function sI(...t){return t.reduce(oI)}H.or=sI;function o_(t){return(e,r)=>e===re.nil?r:r===re.nil?e:(0,re._)`${Yl(e)} ${t} ${Yl(r)}`}function Yl(t){return t instanceof re.Name?t:(0,re._)`(${t})`}});var ie=E(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var le=W(),iI=ms();function aI(t){let e={};for(let r of t)e[r]=!0;return e}J.toHash=aI;function cI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(a_(t,e),!c_(e,t.self.RULES.all))}J.alwaysValidSchema=cI;function a_(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||d_(t,`unknown keyword: "${s}"`)}J.checkUnknownRules=a_;function c_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}J.schemaHasRules=c_;function uI(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}J.schemaHasRulesButRef=uI;function lI({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,le._)`${r}`}return(0,le._)`${t}${e}${(0,le.getProperty)(n)}`}J.schemaRefOrVal=lI;function dI(t){return u_(decodeURIComponent(t))}J.unescapeFragment=dI;function pI(t){return encodeURIComponent(Ql(t))}J.escapeFragment=pI;function Ql(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=Ql;function u_(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=u_;function fI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}J.eachItem=fI;function s_({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof le.Name?(s instanceof le.Name?t(o,s,i):e(o,s,i),i):s instanceof le.Name?(e(o,i,s),s):r(s,i);return a===le.Name&&!(c instanceof le.Name)?n(o,c):c}}J.mergeEvaluated={props:s_({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,le._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,le._)`${r} || {}`).code((0,le._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,le._)`${r} || {}`),ed(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:l_}),items:s_({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,le._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,le._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function l_(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&ed(t,r,e),r}J.evaluatedPropsToName=l_;function ed(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}J.setEvaluated=ed;var i_={};function mI(t,e){return t.scopeValue("func",{ref:e,code:i_[e.code]||(i_[e.code]=new iI._Code(e.code))})}J.useFunc=mI;var Xl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Xl||(J.Type=Xl={}));function hI(t,e,r){if(t instanceof le.Name){let n=e===Xl.Num;return r?n?(0,le._)`"[" + ${t} + "]"`:(0,le._)`"['" + ${t} + "']"`:n?(0,le._)`"/" + ${t}`:(0,le._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,le.getProperty)(t).toString():"/"+Ql(t)}J.getErrorPath=hI;function d_(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}J.checkStrictMode=d_});var rr=E(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var Ze=W(),gI={data:new Ze.Name("data"),valCxt:new Ze.Name("valCxt"),instancePath:new Ze.Name("instancePath"),parentData:new Ze.Name("parentData"),parentDataProperty:new Ze.Name("parentDataProperty"),rootData:new Ze.Name("rootData"),dynamicAnchors:new Ze.Name("dynamicAnchors"),vErrors:new Ze.Name("vErrors"),errors:new Ze.Name("errors"),this:new Ze.Name("this"),self:new Ze.Name("self"),scope:new Ze.Name("scope"),json:new Ze.Name("json"),jsonPos:new Ze.Name("jsonPos"),jsonLen:new Ze.Name("jsonLen"),jsonPart:new Ze.Name("jsonPart")};td.default=gI});var bs=E(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.extendErrors=Ue.resetErrorsCount=Ue.reportExtraError=Ue.reportError=Ue.keyword$DataError=Ue.keywordError=void 0;var ne=W(),xa=ie(),Je=rr();Ue.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function yI(t,e=Ue.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=m_(t,e,r);n??(i||a)?p_(s,c):f_(o,(0,ne._)`[${c}]`)}Ue.reportError=yI;function vI(t,e=Ue.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=m_(t,e,r);p_(o,a),s||i||f_(n,Je.default.vErrors)}Ue.reportExtraError=vI;function _I(t,e){t.assign(Je.default.errors,e),t.if((0,ne._)`${Je.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Je.default.vErrors}.length`,e),()=>t.assign(Je.default.vErrors,null)))}Ue.resetErrorsCount=_I;function bI({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Je.default.errors,a=>{t.const(i,(0,ne._)`${Je.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Je.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Ue.extendErrors=bI;function p_(t,e){let r=t.const("err",e);t.if((0,ne._)`${Je.default.vErrors} === null`,()=>t.assign(Je.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Je.default.vErrors}.push(${r})`),t.code((0,ne._)`${Je.default.errors}++`)}function f_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var cn={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function m_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:wI(t,e,r)}function wI(t,e,r={}){let{gen:n,it:o}=t,s=[xI(o,r),SI(t,r)];return $I(t,e,s),n.object(...s)}function xI({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,xa.getErrorPath)(e,xa.Type.Str)}`:t;return[Je.default.instancePath,(0,ne.strConcat)(Je.default.instancePath,r)]}function SI({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,xa.getErrorPath)(r,xa.Type.Str)}`),[cn.schemaPath,o]}function $I(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([cn.keyword,o],[cn.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([cn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([cn.schema,i],[cn.parentSchema,(0,ne._)`${l}${d}`],[Je.default.data,s]),u&&n.push([cn.propertyName,u])}});var g_=E(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.boolOrEmptySchema=Kn.topBoolOrEmptySchema=void 0;var kI=bs(),PI=W(),TI=rr(),EI={message:"boolean schema is false"};function RI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?h_(t,!1):typeof r=="object"&&r.$async===!0?e.return(TI.default.data):(e.assign((0,PI._)`${n}.errors`,null),e.return(!0))}Kn.topBoolOrEmptySchema=RI;function II(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),h_(t)):r.var(e,!0)}Kn.boolOrEmptySchema=II;function h_(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,kI.reportError)(o,EI,void 0,e)}});var rd=E(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.getRules=Jn.isJSONType=void 0;var AI=["string","number","integer","boolean","null","object","array"],CI=new Set(AI);function DI(t){return typeof t=="string"&&CI.has(t)}Jn.isJSONType=DI;function zI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Jn.getRules=zI});var nd=E(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.shouldUseRule=_r.shouldUseGroup=_r.schemaHasRulesForType=void 0;function OI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&y_(t,n)}_r.schemaHasRulesForType=OI;function y_(t,e){return e.rules.some(r=>v_(t,r))}_r.shouldUseGroup=y_;function v_(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}_r.shouldUseRule=v_});var ws=E(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.reportTypeError=qe.checkDataTypes=qe.checkDataType=qe.coerceAndCheckDataType=qe.getJSONTypes=qe.getSchemaTypes=qe.DataType=void 0;var MI=rd(),NI=nd(),jI=bs(),U=W(),__=ie(),Gn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gn||(qe.DataType=Gn={}));function LI(t){let e=b_(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}qe.getSchemaTypes=LI;function b_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(MI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}qe.getJSONTypes=b_;function FI(t,e){let{gen:r,data:n,opts:o}=t,s=ZI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,NI.schemaHasRulesForType)(t,e[0]));if(i){let a=sd(e,n,o.strictNumbers,Gn.Wrong);r.if(a,()=>{s.length?UI(t,e,s):id(t)})}return i}qe.coerceAndCheckDataType=FI;var w_=new Set(["string","number","integer","boolean","null"]);function ZI(t,e){return e?t.filter(r=>w_.has(r)||e==="array"&&r==="array"):[]}function UI(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,U._)`typeof ${o}`),a=n.let("coerced",(0,U._)`undefined`);s.coerceTypes==="array"&&n.if((0,U._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,U._)`${o}[0]`).assign(i,(0,U._)`typeof ${o}`).if(sd(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,U._)`${a} !== undefined`);for(let u of r)(w_.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),id(t),n.endIf(),n.if((0,U._)`${a} !== undefined`,()=>{n.assign(o,a),qI(t,a)});function c(u){switch(u){case"string":n.elseIf((0,U._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,U._)`"" + ${o}`).elseIf((0,U._)`${o} === null`).assign(a,(0,U._)`""`);return;case"number":n.elseIf((0,U._)`${i} == "boolean" || ${o} === null
7
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,U._)`+${o}`);return;case"integer":n.elseIf((0,U._)`${i} === "boolean" || ${o} === null
8
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,U._)`+${o}`);return;case"boolean":n.elseIf((0,U._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,U._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,U._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,U._)`${i} === "string" || ${i} === "number"
9
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,U._)`[${o}]`)}}}function qI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,U._)`${e} !== undefined`,()=>t.assign((0,U._)`${e}[${r}]`,n))}function od(t,e,r,n=Gn.Correct){let o=n===Gn.Correct?U.operators.EQ:U.operators.NEQ,s;switch(t){case"null":return(0,U._)`${e} ${o} null`;case"array":s=(0,U._)`Array.isArray(${e})`;break;case"object":s=(0,U._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,U._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,U._)`typeof ${e} ${o} ${t}`}return n===Gn.Correct?s:(0,U.not)(s);function i(a=U.nil){return(0,U.and)((0,U._)`typeof ${e} == "number"`,a,r?(0,U._)`isFinite(${e})`:U.nil)}}qe.checkDataType=od;function sd(t,e,r,n){if(t.length===1)return od(t[0],e,r,n);let o,s=(0,__.toHash)(t);if(s.array&&s.object){let i=(0,U._)`typeof ${e} != "object"`;o=s.null?i:(0,U._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=U.nil;s.number&&delete s.integer;for(let i in s)o=(0,U.and)(o,od(i,e,r,n));return o}qe.checkDataTypes=sd;var VI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,U._)`{type: ${t}}`:(0,U._)`{type: ${e}}`};function id(t){let e=BI(t);(0,jI.reportError)(e,VI)}qe.reportTypeError=id;function BI(t){let{gen:e,data:r,schema:n}=t,o=(0,__.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var S_=E(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.assignDefaults=void 0;var Yn=W(),WI=ie();function HI(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)x_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>x_(t,s,o.default))}Sa.assignDefaults=HI;function x_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Yn._)`${s}${(0,Yn.getProperty)(e)}`;if(o){(0,WI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Yn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Yn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Yn._)`${a} = ${(0,Yn.stringify)(r)}`)}});var yt=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=W(),ad=ie(),br=rr(),KI=ie();function JI(t,e){let{gen:r,data:n,it:o}=t;r.if(ud(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=JI;function GI({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(ud(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=GI;function YI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=YI;function $_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=$_;function cd(t,e,r){return(0,ge._)`${$_(t)}.call(${e}, ${r})`}ue.isOwnProperty=cd;function XI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${cd(t,e,r)}`:o}ue.propertyInData=XI;function ud(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(cd(t,e,r))):o}ue.noPropertyInData=ud;function k_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=k_;function QI(t,e){return k_(e).filter(r=>!(0,ad.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=QI;function eA({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[br.default.instancePath,(0,ge.strConcat)(br.default.instancePath,s)],[br.default.parentData,i.parentData],[br.default.parentDataProperty,i.parentDataProperty],[br.default.rootData,br.default.rootData]];i.opts.dynamicRef&&d.push([br.default.dynamicAnchors,br.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=eA;var tA=(0,ge._)`new RegExp`;function rA({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?tA:(0,KI.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=rA;function nA(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ad.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=nA;function oA(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,ad.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ue.validateUnion=oA});var E_=E(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.validateKeywordUsage=Nt.validSchemaType=Nt.funcKeywordCode=Nt.macroKeywordCode=void 0;var Ge=W(),un=rr(),sA=yt(),iA=bs();function aA(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=T_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ge.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Nt.macroKeywordCode=aA;function cA(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;lA(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=T_(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&P_(t),v(()=>t.error());else{let _=e.async?f():m();e.modifying&&P_(t),v(()=>uA(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,Ge._)`await `),S=>n.assign(d,!1).if((0,Ge._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,Ge._)`${S}.errors`),()=>n.throw(S))),_}function m(){let _=(0,Ge._)`${l}.errors`;return n.assign(_,null),g(Ge.nil),_}function g(_=e.async?(0,Ge._)`await `:Ge.nil){let S=c.opts.passContext?un.default.this:un.default.self,y=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ge._)`${_}${(0,sA.callValidateCode)(t,l,S,y)}`,e.modifying)}function v(_){var S;n.if((0,Ge.not)((S=e.valid)!==null&&S!==void 0?S:d),_)}}Nt.funcKeywordCode=cA;function P_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ge._)`${n.parentData}[${n.parentDataProperty}]`))}function uA(t,e){let{gen:r}=t;r.if((0,Ge._)`Array.isArray(${e})`,()=>{r.assign(un.default.vErrors,(0,Ge._)`${un.default.vErrors} === null ? ${e} : ${un.default.vErrors}.concat(${e})`).assign(un.default.errors,(0,Ge._)`${un.default.vErrors}.length`),(0,iA.extendErrors)(t)},()=>t.error())}function lA({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function T_(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ge.stringify)(r)})}function dA(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Nt.validSchemaType=dA;function pA({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Nt.validateKeywordUsage=pA});var I_=E(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;var jt=W(),R_=ie();function fA(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,jt._)`${t.schemaPath}${(0,jt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,jt._)`${t.schemaPath}${(0,jt.getProperty)(e)}${(0,jt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,R_.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}wr.getSubschema=fA;function mA(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,jt._)`${e.data}${(0,jt.getProperty)(r)}`,!0);c(p),t.errorPath=(0,jt.str)`${u}${(0,R_.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,jt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof jt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}wr.extendSubschemaData=mA;function hA(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}wr.extendSubschemaMode=hA});var ld=E((lB,A_)=>{"use strict";A_.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var D_=E((dB,C_)=>{"use strict";var xr=C_.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};$a(e,n,o,t,"",t)};xr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};xr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};xr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};xr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function $a(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in xr.arrayKeywords)for(var p=0;p<d.length;p++)$a(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in xr.propsKeywords){if(d&&typeof d=="object")for(var f in d)$a(t,e,r,d[f],o+"/"+l+"/"+gA(f),s,o,l,n,f)}else(l in xr.keywords||t.allKeys&&!(l in xr.skipKeywords))&&$a(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function gA(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var xs=E(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getSchemaRefs=rt.resolveUrl=rt.normalizeId=rt._getFullPath=rt.getFullPath=rt.inlineRef=void 0;var yA=ie(),vA=ld(),_A=D_(),bA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wA(t,e=!0){return typeof t=="boolean"?!0:e===!0?!dd(t):e?z_(t)<=e:!1}rt.inlineRef=wA;var xA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function dd(t){for(let e in t){if(xA.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(dd)||typeof r=="object"&&dd(r))return!0}return!1}function z_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!bA.has(r)&&(typeof t[r]=="object"&&(0,yA.eachItem)(t[r],n=>e+=z_(n)),e===1/0))return 1/0}return e}function O_(t,e="",r){r!==!1&&(e=Xn(e));let n=t.parse(e);return M_(t,n)}rt.getFullPath=O_;function M_(t,e){return t.serialize(e).split("#")[0]+"#"}rt._getFullPath=M_;var SA=/#\/?$/;function Xn(t){return t?t.replace(SA,""):""}rt.normalizeId=Xn;function $A(t,e,r){return r=Xn(r),t.resolve(e,r)}rt.resolveUrl=$A;var kA=/^[a-z_][-a-z0-9._]*$/i;function PA(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xn(t[r]||e),s={"":o},i=O_(n,o,!1),a={},c=new Set;return _A(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,v=s[m];typeof d[r]=="string"&&(v=_.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[p]=v;function _(y){let x=this.opts.uriResolver.resolve;if(y=Xn(v?x(v,y):y),c.has(y))throw l(y);c.add(y);let $=this.refs[y];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(d,$.schema,y):y!==Xn(g)&&(y[0]==="#"?(u(d,a[y],y),a[y]=d):this.refs[y]=g),y}function S(y){if(typeof y=="string"){if(!kA.test(y))throw new Error(`invalid anchor "${y}"`);_.call(this,`#${y}`)}}}),a;function u(d,p,f){if(p!==void 0&&!vA(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}rt.getSchemaRefs=PA});var ks=E(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.getData=Sr.KeywordCxt=Sr.validateFunctionCode=void 0;var Z_=g_(),N_=ws(),fd=nd(),ka=ws(),TA=S_(),$s=E_(),pd=I_(),D=W(),F=rr(),EA=xs(),nr=ie(),Ss=bs();function RA(t){if(V_(t)&&(B_(t),q_(t))){CA(t);return}U_(t,()=>(0,Z_.topBoolOrEmptySchema)(t))}Sr.validateFunctionCode=RA;function U_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,D._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,D._)`"use strict"; ${j_(r,o)}`),AA(t,o),t.code(s)}):t.func(e,(0,D._)`${F.default.data}, ${IA(o)}`,n.$async,()=>t.code(j_(r,o)).code(s))}function IA(t){return(0,D._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,D._)`, ${F.default.dynamicAnchors}={}`:D.nil}}={}`}function AA(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,D._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,D._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,D._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,D._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,D._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,D._)`""`),t.var(F.default.parentData,(0,D._)`undefined`),t.var(F.default.parentDataProperty,(0,D._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,D._)`{}`)})}function CA(t){let{schema:e,opts:r,gen:n}=t;U_(t,()=>{r.$comment&&e.$comment&&H_(t),NA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&DA(t),W_(t),FA(t)})}function DA(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,D._)`${r}.evaluated`),e.if((0,D._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,D._)`${t.evaluated}.props`,(0,D._)`undefined`)),e.if((0,D._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,D._)`${t.evaluated}.items`,(0,D._)`undefined`))}function j_(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function zA(t,e){if(V_(t)&&(B_(t),q_(t))){OA(t,e);return}(0,Z_.boolOrEmptySchema)(t,e)}function q_({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function V_(t){return typeof t.schema!="boolean"}function OA(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&H_(t),jA(t),LA(t);let s=n.const("_errs",F.default.errors);W_(t,s),n.var(e,(0,D._)`${s} === ${F.default.errors}`)}function B_(t){(0,nr.checkUnknownRules)(t),MA(t)}function W_(t,e){if(t.opts.jtd)return L_(t,[],!1,e);let r=(0,N_.getSchemaTypes)(t.schema),n=(0,N_.coerceAndCheckDataType)(t,r);L_(t,r,!n,e)}function MA(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,nr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function NA(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,nr.checkStrictMode)(t,"default is ignored in the schema root")}function jA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,EA.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function LA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function H_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,D._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,D.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,D._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function FA(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,D._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,D._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,D._)`${n}.errors`,F.default.vErrors),s.unevaluated&&ZA(t),e.return((0,D._)`${F.default.errors} === 0`))}function ZA({gen:t,evaluated:e,props:r,items:n}){r instanceof D.Name&&t.assign((0,D._)`${e}.props`,r),n instanceof D.Name&&t.assign((0,D._)`${e}.items`,n)}function L_(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,nr.schemaHasRulesButRef)(s,l))){o.block(()=>J_(t,"$ref",l.all.$ref.definition));return}c.jtd||UA(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,fd.shouldUseGroup)(s,p)&&(p.type?(o.if((0,ka.checkDataType)(p.type,i,c.strictNumbers)),F_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,ka.reportTypeError)(t)),o.endIf()):F_(t,p),a||o.if((0,D._)`${F.default.errors} === ${n||0}`))}}function F_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,TA.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,fd.shouldUseRule)(n,s)&&J_(t,s.keyword,s.definition,e.type)})}function UA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(qA(t,e),t.opts.allowUnionTypes||VA(t,e),BA(t,t.dataTypes))}function qA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{K_(t.dataTypes,r)||md(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),HA(t,e)}}function VA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&md(t,"use allowUnionTypes to allow union type keyword")}function BA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,fd.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>WA(e,i))&&md(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function WA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function K_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function HA(t,e){let r=[];for(let n of t.dataTypes)K_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function md(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,nr.checkStrictMode)(t,e,t.opts.strictTypes)}var Pa=class{constructor(e,r,n){if((0,$s.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,nr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",G_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,$s.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",F.default.errors))}result(e,r,n){this.failResult((0,D.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,D.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,D._)`${r} !== undefined && (${(0,D.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Ss.reportExtraError:Ss.reportError)(this,this.def.error,r)}$dataError(){(0,Ss.reportError)(this,this.def.$dataError||Ss.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ss.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=D.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,D.or)((0,D._)`${o} === undefined`,r)),e!==D.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==D.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,D.or)(i(),a());function i(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,ka.checkDataTypes)(c,r,s.opts.strictNumbers,ka.DataType.Wrong)}`}return D.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(e,r){let n=(0,pd.getSubschema)(this.it,e);(0,pd.extendSubschemaData)(n,this.it,e),(0,pd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return zA(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=nr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=nr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,D.Name)),!0}};Sr.KeywordCxt=Pa;function J_(t,e,r,n){let o=new Pa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,$s.funcKeywordCode)(o,r):"macro"in r?(0,$s.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,$s.funcKeywordCode)(o,r)}var KA=/^\/(?:[^~]|~0|~1)*$/,JA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function G_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!KA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=JA.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,D._)`${s}${(0,D.getProperty)((0,nr.unescapeJsonPointer)(u))}`,i=(0,D._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Sr.getData=G_});var Ta=E(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var hd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};gd.default=hd});var Ps=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var yd=xs(),vd=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,yd.resolveUrl)(e,r,n),this.missingSchema=(0,yd.normalizeId)((0,yd.getFullPath)(e,this.missingRef))}};_d.default=vd});var Ra=E(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.resolveSchema=vt.getCompilingSchema=vt.resolveRef=vt.compileSchema=vt.SchemaEnv=void 0;var kt=W(),GA=Ta(),ln=rr(),Pt=xs(),Y_=ie(),YA=ks(),Qn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Pt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};vt.SchemaEnv=Qn;function wd(t){let e=X_.call(this,t);if(e)return e;let r=(0,Pt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new kt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:GA.default,code:(0,kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ln.default.data,parentData:ln.default.parentData,parentDataProperty:ln.default.parentDataProperty,dataNames:[ln.default.data],dataPathArr:[kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,kt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:kt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,kt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,YA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(ln.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${ln.default.self}`,`${ln.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=u;f.evaluated={props:m instanceof kt.Name?void 0:m,items:g instanceof kt.Name?void 0:g,dynamicProps:m instanceof kt.Name,dynamicItems:g instanceof kt.Name},f.source&&(f.source.evaluated=(0,kt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}vt.compileSchema=wd;function XA(t,e,r){var n;r=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=tC.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Qn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=QA.call(this,s)}vt.resolveRef=XA;function QA(t){return(0,Pt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:wd.call(this,t)}function X_(t){for(let e of this._compilations)if(eC(e,t))return e}vt.getCompilingSchema=X_;function eC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function tC(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ea.call(this,t,e)}function Ea(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pt._getFullPath)(this.opts.uriResolver,r),o=(0,Pt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return bd.call(this,r,t);let s=(0,Pt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ea.call(this,t,i);return typeof a?.schema!="object"?void 0:bd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||wd.call(this,i),s===(0,Pt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pt.resolveUrl)(this.opts.uriResolver,o,u)),new Qn({schema:a,schemaId:c,root:t,baseId:o})}return bd.call(this,r,i)}}vt.resolveSchema=Ea;var rC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function bd(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Y_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!rC.has(a)&&u&&(e=(0,Pt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Y_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ea.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Qn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Q_=E((yB,nC)=>{nC.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Sd=E((vB,nb)=>{"use strict";var oC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),tb=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function xd(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var sC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function eb(t){return t.length=0,!0}function iC(t,e,r){if(t.length){let n=xd(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function aC(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=iC;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=eb}else{o.push(u);continue}}return o.length&&(a===eb?r.zone=o.join(""):i?n.push(o.join("")):n.push(xd(o))),r.address=n.join(""),r}function rb(t){if(cC(t,":")<2)return{host:t,isIPV6:!1};let e=aC(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function cC(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function uC(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function lC(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function dC(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!tb(r)){let n=rb(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}nb.exports={nonSimpleDomain:sC,recomposeAuthority:dC,normalizeComponentEncoding:lC,removeDotSegments:uC,isIPv4:tb,isUUID:oC,normalizeIPv6:rb,stringArrayToHexStripped:xd}});var cb=E((_B,ab)=>{"use strict";var{isUUID:pC}=Sd(),fC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,mC=["http","https","ws","wss","urn","urn:uuid"];function hC(t){return mC.indexOf(t)!==-1}function $d(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function ob(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function sb(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function gC(t){return t.secure=$d(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function yC(t){if((t.port===($d(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function vC(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(fC);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=kd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function _C(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=kd(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function bC(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!pC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function wC(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var ib={scheme:"http",domainHost:!0,parse:ob,serialize:sb},xC={scheme:"https",domainHost:ib.domainHost,parse:ob,serialize:sb},Ia={scheme:"ws",domainHost:!0,parse:gC,serialize:yC},SC={scheme:"wss",domainHost:Ia.domainHost,parse:Ia.parse,serialize:Ia.serialize},$C={scheme:"urn",parse:vC,serialize:_C,skipNormalize:!0},kC={scheme:"urn:uuid",parse:bC,serialize:wC,skipNormalize:!0},Aa={http:ib,https:xC,ws:Ia,wss:SC,urn:$C,"urn:uuid":kC};Object.setPrototypeOf(Aa,null);function kd(t){return t&&(Aa[t]||Aa[t.toLowerCase()])||void 0}ab.exports={wsIsSecure:$d,SCHEMES:Aa,isValidSchemeName:hC,getSchemeHandler:kd}});var db=E((bB,Da)=>{"use strict";var{normalizeIPv6:PC,removeDotSegments:Ts,recomposeAuthority:TC,normalizeComponentEncoding:Ca,isIPv4:EC,nonSimpleDomain:RC}=Sd(),{SCHEMES:IC,getSchemeHandler:ub}=cb();function AC(t,e){return typeof t=="string"?t=Lt(or(t,e),e):typeof t=="object"&&(t=or(Lt(t,e),e)),t}function CC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=lb(or(t,n),or(e,n),n,!0);return n.skipEscape=!0,Lt(o,n)}function lb(t,e,r,n){let o={};return n||(t=or(Lt(t,r),r),e=or(Lt(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ts(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ts(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ts(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Ts(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function DC(t,e,r){return typeof t=="string"?(t=unescape(t),t=Lt(Ca(or(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Lt(Ca(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Lt(Ca(or(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Lt(Ca(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Lt(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=ub(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=TC(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Ts(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var zC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function or(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(zC);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(EC(n.host)===!1){let c=PC(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=ub(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&RC(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Pd={SCHEMES:IC,normalize:AC,resolve:CC,resolveComponent:lb,equal:DC,serialize:Lt,parse:or};Da.exports=Pd;Da.exports.default=Pd;Da.exports.fastUri=Pd});var fb=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var pb=db();pb.code='require("ajv/dist/runtime/uri").default';Td.default=pb});var wb=E(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.CodeGen=ze.Name=ze.nil=ze.stringify=ze.str=ze._=ze.KeywordCxt=void 0;var OC=ks();Object.defineProperty(ze,"KeywordCxt",{enumerable:!0,get:function(){return OC.KeywordCxt}});var eo=W();Object.defineProperty(ze,"_",{enumerable:!0,get:function(){return eo._}});Object.defineProperty(ze,"str",{enumerable:!0,get:function(){return eo.str}});Object.defineProperty(ze,"stringify",{enumerable:!0,get:function(){return eo.stringify}});Object.defineProperty(ze,"nil",{enumerable:!0,get:function(){return eo.nil}});Object.defineProperty(ze,"Name",{enumerable:!0,get:function(){return eo.Name}});Object.defineProperty(ze,"CodeGen",{enumerable:!0,get:function(){return eo.CodeGen}});var MC=Ta(),vb=Ps(),NC=rd(),Es=Ra(),jC=W(),Rs=xs(),za=ws(),Rd=ie(),mb=Q_(),LC=fb(),_b=(t,e)=>new RegExp(t,e);_b.code="new RegExp";var FC=["removeAdditional","useDefaults","coerceTypes"],ZC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),UC={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},qC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},hb=200;function VC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,v,_,S,y,x,$,M,O,Y,Pe;let K=t.strict,ot=(e=t.code)===null||e===void 0?void 0:e.optimize,Re=ot===!0||ot===void 0?1:ot||0,Pr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:_b,Tr=(o=t.uriResolver)!==null&&o!==void 0?o:LC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:K)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:K)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:K)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:K)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:K)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Re,regExp:Pr}:{optimize:Re,regExp:Pr},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:hb,loopEnum:(v=t.loopEnum)!==null&&v!==void 0?v:hb,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(y=t.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(M=t.validateSchema)!==null&&M!==void 0?M:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(Y=t.unicodeRegExp)!==null&&Y!==void 0?Y:!0,int32range:(Pe=t.int32range)!==null&&Pe!==void 0?Pe:!0,uriResolver:Tr}}var Is=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...VC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new jC.ValueScope({scope:{},prefixes:ZC,es5:r,lines:n}),this.logger=GC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,NC.getRules)(),gb.call(this,UC,e,"NOT SUPPORTED"),gb.call(this,qC,e,"DEPRECATED","warn"),this._metaOpts=KC.call(this),e.formats&&WC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&HC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),BC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=mb;n==="id"&&(o={...mb},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof vb.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Rs.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=yb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Es.SchemaEnv({schema:{},schemaId:n});if(r=Es.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=yb.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Rs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(XC.call(this,n,r),!r)return(0,Rd.eachItem)(n,s=>Ed.call(this,s)),this;eD.call(this,r);let o={...r,type:(0,za.getJSONTypes)(r.type),schemaType:(0,za.getJSONTypes)(r.schemaType)};return(0,Rd.eachItem)(n,o.type.length===0?s=>Ed.call(this,s,o):s=>o.type.forEach(i=>Ed.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=bb(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Rs.normalizeId)(i||n);let u=Rs.getSchemaRefs.call(this,e,n);return c=new Es.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Es.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Es.compileSchema.call(this,e)}finally{this.opts=r}}};Is.ValidationError=MC.default;Is.MissingRefError=vb.default;ze.default=Is;function gb(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function yb(t){return t=(0,Rs.normalizeId)(t),this.schemas[t]||this.refs[t]}function BC(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function WC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function HC(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function KC(){let t={...this.opts};for(let e of FC)delete t[e];return t}var JC={log(){},warn(){},error(){}};function GC(t){if(t===!1)return JC;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var YC=/^[a-z_$][a-z0-9_$:-]*$/i;function XC(t,e){let{RULES:r}=this;if((0,Rd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!YC.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Ed(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,za.getJSONTypes)(e.type),schemaType:(0,za.getJSONTypes)(e.schemaType)}};e.before?QC.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function QC(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function eD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=bb(e)),t.validateSchema=this.compile(e,!0))}var tD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function bb(t){return{anyOf:[t,tD]}}});var xb=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var rD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Id.default=rD});var Pb=E(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.callRef=dn.getValidate=void 0;var nD=Ps(),Sb=yt(),nt=W(),to=rr(),$b=Ra(),Oa=ie(),oD={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=$b.resolveRef.call(c,u,o,r);if(l===void 0)throw new nD.default(n.opts.uriResolver,o,r);if(l instanceof $b.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Ma(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Ma(t,(0,nt._)`${m}.validate`,u,u.$async)}function p(m){let g=kb(t,m);Ma(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,nt.stringify)(m)}:{ref:m}),v=e.name("valid"),_=t.subschema({schema:m,dataTypes:[],schemaPath:nt.nil,topSchemaRef:g,errSchemaPath:r},v);t.mergeEvaluated(_),t.ok(v)}}};function kb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,nt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}dn.getValidate=kb;function Ma(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?to.default.this:nt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,nt._)`await ${(0,Sb.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,nt._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,Sb.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,nt._)`${m}.errors`;o.assign(to.default.vErrors,(0,nt._)`${to.default.vErrors} === null ? ${g} : ${to.default.vErrors}.concat(${g})`),o.assign(to.default.errors,(0,nt._)`${to.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let v=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(s.props=Oa.mergeEvaluated.props(o,v.props,s.props));else{let _=o.var("props",(0,nt._)`${m}.evaluated.props`);s.props=Oa.mergeEvaluated.props(o,_,s.props,nt.Name)}if(s.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(s.items=Oa.mergeEvaluated.items(o,v.items,s.items));else{let _=o.var("items",(0,nt._)`${m}.evaluated.items`);s.items=Oa.mergeEvaluated.items(o,_,s.items,nt.Name)}}}dn.callRef=Ma;dn.default=oD});var Tb=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var sD=xb(),iD=Pb(),aD=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",sD.default,iD.default];Ad.default=aD});var Eb=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Na=W(),$r=Na.operators,ja={maximum:{okStr:"<=",ok:$r.LTE,fail:$r.GT},minimum:{okStr:">=",ok:$r.GTE,fail:$r.LT},exclusiveMaximum:{okStr:"<",ok:$r.LT,fail:$r.GTE},exclusiveMinimum:{okStr:">",ok:$r.GT,fail:$r.LTE}},cD={message:({keyword:t,schemaCode:e})=>(0,Na.str)`must be ${ja[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Na._)`{comparison: ${ja[t].okStr}, limit: ${e}}`},uD={keyword:Object.keys(ja),type:"number",schemaType:"number",$data:!0,error:cD,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Na._)`${r} ${ja[e].fail} ${n} || isNaN(${r})`)}};Cd.default=uD});var Rb=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var As=W(),lD={message:({schemaCode:t})=>(0,As.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,As._)`{multipleOf: ${t}}`},dD={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:lD,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,As._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,As._)`${i} !== parseInt(${i})`;t.fail$data((0,As._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Dd.default=dD});var Ab=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});function Ib(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}zd.default=Ib;Ib.code='require("ajv/dist/runtime/ucs2length").default'});var Cb=E(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var pn=W(),pD=ie(),fD=Ab(),mD={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,pn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,pn._)`{limit: ${t}}`},hD={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:mD,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?pn.operators.GT:pn.operators.LT,i=o.opts.unicode===!1?(0,pn._)`${r}.length`:(0,pn._)`${(0,pD.useFunc)(t.gen,fD.default)}(${r})`;t.fail$data((0,pn._)`${i} ${s} ${n}`)}};Od.default=hD});var Db=E(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var gD=yt(),La=W(),yD={message:({schemaCode:t})=>(0,La.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,La._)`{pattern: ${t}}`},vD={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:yD,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,La._)`(new RegExp(${o}, ${i}))`:(0,gD.usePattern)(t,n);t.fail$data((0,La._)`!${a}.test(${e})`)}};Md.default=vD});var zb=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var Cs=W(),_D={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Cs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Cs._)`{limit: ${t}}`},bD={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_D,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Cs.operators.GT:Cs.operators.LT;t.fail$data((0,Cs._)`Object.keys(${r}).length ${o} ${n}`)}};Nd.default=bD});var Ob=E(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var Ds=yt(),zs=W(),wD=ie(),xD={message:({params:{missingProperty:t}})=>(0,zs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,zs._)`{missingProperty: ${t}}`},SD={keyword:"required",type:"object",schemaType:"array",$data:!0,error:xD,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let g of r)if(f?.[g]===void 0&&!m.has(g)){let v=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${v}" (strictRequired)`;(0,wD.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(zs.nil,d);else for(let f of r)(0,Ds.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Ds.checkMissingProp)(t,r,f)),(0,Ds.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ds.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ds.propertyInData)(e,o,f,a.ownProperties)),e.if((0,zs.not)(m),()=>{t.error(),e.break()})},zs.nil)}}};jd.default=SD});var Mb=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Os=W(),$D={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Os.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Os._)`{limit: ${t}}`},kD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:$D,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Os.operators.GT:Os.operators.LT;t.fail$data((0,Os._)`${r}.length ${o} ${n}`)}};Ld.default=kD});var Fa=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Nb=ld();Nb.code='require("ajv/dist/runtime/equal").default';Fd.default=Nb});var jb=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Zd=ws(),Oe=W(),PD=ie(),TD=Fa(),ED={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},RD={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ED,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Zd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Oe._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Oe._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,Oe._)`${m} > 1`,()=>(d()?p:f)(m,g))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,g){let v=e.name("item"),_=(0,Zd.checkDataTypes)(u,v,a.opts.strictNumbers,Zd.DataType.Wrong),S=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${m}--;`,()=>{e.let(v,(0,Oe._)`${r}[${m}]`),e.if(_,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${v} == "string"`,(0,Oe._)`${v} += "_"`),e.if((0,Oe._)`typeof ${S}[${v}] == "number"`,()=>{e.assign(g,(0,Oe._)`${S}[${v}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${S}[${v}] = ${m}`)})}function f(m,g){let v=(0,PD.useFunc)(e,TD.default),_=e.name("outer");e.label(_).for((0,Oe._)`;${m}--;`,()=>e.for((0,Oe._)`${g} = ${m}; ${g}--;`,()=>e.if((0,Oe._)`${v}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Ud.default=RD});var Lb=E(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var qd=W(),ID=ie(),AD=Fa(),CD={message:"must be equal to constant",params:({schemaCode:t})=>(0,qd._)`{allowedValue: ${t}}`},DD={keyword:"const",$data:!0,error:CD,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,qd._)`!${(0,ID.useFunc)(e,AD.default)}(${r}, ${o})`):t.fail((0,qd._)`${s} !== ${r}`)}};Vd.default=DD});var Fb=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var Ms=W(),zD=ie(),OD=Fa(),MD={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ms._)`{allowedValues: ${t}}`},ND={keyword:"enum",schemaType:"array",$data:!0,error:MD,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,zD.useFunc)(e,OD.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Ms.or)(...o.map((m,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Ms._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Ms._)`${u()}(${r}, ${f}[${m}])`:(0,Ms._)`${r} === ${g}`}}};Bd.default=ND});var Zb=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var jD=Eb(),LD=Rb(),FD=Cb(),ZD=Db(),UD=zb(),qD=Ob(),VD=Mb(),BD=jb(),WD=Lb(),HD=Fb(),KD=[jD.default,LD.default,FD.default,ZD.default,UD.default,qD.default,VD.default,BD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},WD.default,HD.default];Wd.default=KD});var Kd=E(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.validateAdditionalItems=void 0;var fn=W(),Hd=ie(),JD={message:({params:{len:t}})=>(0,fn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,fn._)`{limit: ${t}}`},GD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JD,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Hd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Ub(t,n)}};function Ub(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,fn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,fn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Hd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,fn._)`${a} <= ${e.length}`);r.if((0,fn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Hd.Type.Num},u),i.allErrors||r.if((0,fn.not)(u),()=>r.break())})}}Ns.validateAdditionalItems=Ub;Ns.default=GD});var Jd=E(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.validateTuple=void 0;var qb=W(),Za=ie(),YD=yt(),XD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Vb(t,"additionalItems",e);r.items=!0,!(0,Za.alwaysValidSchema)(r,e)&&t.ok((0,YD.validateArray)(t))}};function Vb(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Za.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,qb._)`${s}.length`);r.forEach((d,p)=>{(0,Za.alwaysValidSchema)(a,d)||(n.if((0,qb._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,g=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let v=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Za.checkStrictMode)(a,v,p.strictTuples)}}}js.validateTuple=Vb;js.default=XD});var Bb=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var QD=Jd(),ez={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,QD.validateTuple)(t,"items")};Gd.default=ez});var Hb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var Wb=W(),tz=ie(),rz=yt(),nz=Kd(),oz={message:({params:{len:t}})=>(0,Wb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Wb._)`{limit: ${t}}`},sz={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:oz,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,tz.alwaysValidSchema)(n,e)&&(o?(0,nz.validateAdditionalItems)(t,o):t.ok((0,rz.validateArray)(t)))}};Yd.default=sz});var Kb=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var _t=W(),Ua=ie(),iz={message:({params:{min:t,max:e}})=>e===void 0?(0,_t.str)`must contain at least ${t} valid item(s)`:(0,_t.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,_t._)`{minContains: ${t}}`:(0,_t._)`{minContains: ${t}, maxContains: ${e}}`},az={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iz,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,_t._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ua.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ua.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ua.alwaysValidSchema)(s,r)){let g=(0,_t._)`${l} >= ${i}`;a!==void 0&&(g=(0,_t._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,_t._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),v=e.let("count",0);f(g,()=>e.if(g,()=>m(v)))}function f(g,v){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:Ua.Type.Num,compositeRule:!0},g),v()})}function m(g){e.code((0,_t._)`${g}++`),a===void 0?e.if((0,_t._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,_t._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,_t._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Xd.default=az});var Yb=E(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.validateSchemaDeps=Ft.validatePropertyDeps=Ft.error=void 0;var Qd=W(),cz=ie(),Ls=yt();Ft.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Qd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Qd._)`{property: ${t},
3
+ var FS=Object.create;var Mc=Object.defineProperty;var ZS=Object.getOwnPropertyDescriptor;var US=Object.getOwnPropertyNames;var qS=Object.getPrototypeOf,VS=Object.prototype.hasOwnProperty;var Tr=(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)Mc(t,r,{get:e[r],enumerable:!0})},BS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of US(e))!VS.call(t,o)&&o!==r&&Mc(t,o,{get:()=>e[o],enumerable:!(n=ZS(e,o))||n.enumerable});return t};var df=(t,e,r)=>(r=t!=null?FS(qS(t)):{},BS(e||!t||!t.__esModule?Mc(r,"default",{value:t,enumerable:!0}):r,t));var pf,_o,ff,mf,hf,gf,yf,bo,vf,Hs,_f,bf,wf,xf,Sf,$f,Ks,Nc,jc,Qj,kf,gn,Lc,Fc,Pf,Tf,Gs,Er,Zc,Ef,Rf,yn,Vt=Tr(()=>{"use strict";pf="4.10.4",_o="http://localhost:11434",ff="llama3",mf=".agestra/.jobs",hf=".agestra/traces",gf=".agestra/worktrees",yf=".agestra/sessions",bo=".agestra/workspace",vf="individual",Hs="debates",_f="synthesis",bf="issue",wf=".agestra/workers",xf=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),Sf=2,$f=6e4,Ks=20,Nc=5e4,jc=10,Qj=Object.freeze([3,5,10]),kf=Object.freeze(["agree","disagree","abstain","revise"]),gn="votes",Lc=2,Fc=2,Pf=1440*60*1e3,Tf=3600*1e3,Gs=Object.freeze(["ko","zh","ja","en"]),Er="ko",Zc="en",Ef="[REDACTED]",Rf=["","--- REQUIRED RESPONSE FORMAT ---","Respond with JSON only, matching exactly this shape:",'{ "agrees": true | false, "feedback": "specific issues or why you agree", "suggestions": "concrete changes if you disagree (optional, may be omitted)" }',"No prose, markdown, or explanation outside the JSON object. The JSON must be the entire response or wrapped in a single ```json code fence.","-------------------------------"].join(`
4
+ `),yn=Object.freeze({auto:Object.freeze({name:"auto",description:"Auto-detect build profile from project structure (package.json scripts, tsconfig, vitest config, etc.).",command:"npx",args:Object.freeze([])}),tsc:Object.freeze({name:"tsc",description:"TypeScript project-references build via `npx tsc -b --noEmit`.",command:"npx",args:Object.freeze(["tsc","-b","--noEmit"])}),vitest:Object.freeze({name:"vitest",description:"Run the Vitest unit-test suite in CI mode.",command:"npx",args:Object.freeze(["vitest","run","--reporter=dot"])}),"npm-build":Object.freeze({name:"npm-build",description:"Run the project's `npm run build` script.",command:"npm",args:Object.freeze(["run","build"])}),"npm-test":Object.freeze({name:"npm-test",description:"Run the project's `npm test` script.",command:"npm",args:Object.freeze(["test","--","--run"])})})});import{execFileSync as WS}from"child_process";function vn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return WS("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0}),{delivered:!0}}catch{try{return process.kill(t),{delivered:!0}}catch{return{delivered:!1}}}try{return process.kill(-t,"SIGTERM"),{delivered:!0}}catch{try{return process.kill(t,"SIGTERM"),{delivered:!0}}catch{return{delivered:!1}}}}function At(t,e=3e3){let r=t.pid;if(r)vn(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e).unref?.()}var wo=Tr(()=>{"use strict"});import{execFileSync as HS,spawn as KS}from"child_process";import{existsSync as GS}from"fs";function YS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:JS.has(t.toLowerCase())}function XS(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 QS(t){let e=t.toLowerCase();if(_n.has(e))return _n.get(e)??null;try{let n=HS("where.exe",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:5e3}).split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(n.length===0)return _n.set(e,null),null;let o=n.find(a=>/\.(cmd|bat)$/i.test(a));if(o){let a={type:"cmd",path:o};return _n.set(e,a),a}let i=`${n[0]}.ps1`;if(GS(i)){let a={type:"powershell",path:i};return _n.set(e,a),a}}catch{}return _n.set(e,null),null}function Bt(t,e){if(!YS(t))return{command:t,args:e};let r=QS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>XS(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function Me(t){let{command:e,args:r,timeout:n=12e4,cwd:o,env:s,stdin:i,maxBuffer:a=10485760,onStderrChunk:c,signal:u}=t;return new Promise((l,d)=>{if(u?.aborted){d(new at(u.reason));return}let p=Bt(e,r),f=KS(p.command,p.args,{cwd:o,env:s?{...process.env,...s}:void 0,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),m="",g="",y=0,v=0,S=!1,w=null,_=!1,P=null,A=()=>{P&&u&&u.removeEventListener("abort",P)},D=!1,U=()=>{!D&&y+v>a&&(S=!0,D=!0,At(f))},$e=()=>{_||(At(f),_=!0,A(),d(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`)))},G=setTimeout($e,n);u&&(P=()=>{_||(_=!0,clearTimeout(G),At(f),A(),d(new at(u.reason)))},u.addEventListener("abort",P));let _t=()=>{D||(clearTimeout(G),G=setTimeout($e,n))};if(f.stdout.on("data",Te=>{y+=Te.length,y<=a&&(m+=Te.toString()),U(),_t()}),f.stderr.on("data",Te=>{v+=Te.length;let Pr=Te.toString();if(v<=a&&(g+=Pr),U(),!D&&c){let fn=c(Pr);fn&&(w=fn,D=!0,At(f))}_t()}),i&&f.stdin){f.stdin.on("error",()=>{});try{f.stdin.write(i),f.stdin.end()}catch{}}f.on("close",Te=>{if(clearTimeout(G),!_){if(w){_=!0,A(),d(w);return}_=!0,A(),l({stdout:m,stderr:g,exitCode:Te??1,truncated:S})}}),f.on("error",Te=>{clearTimeout(G),!_&&(_=!0,A(),d(new Error(`CLI spawn error: ${Te.message}`)))})})}var at,JS,_n,bn=Tr(()=>{"use strict";wo();at=class extends Error{constructor(e){let r=e instanceof Error?`: ${e.message}`:typeof e=="string"&&e?`: ${e}`:"";super(`CLI aborted${r}`),this.name="CliAbortedError"}},JS=new Set(["codex","gemini","npm","npx"]),_n=new Map});import{writeFileSync as xk,mkdirSync as Po,openSync as Wc,writeSync as Hc,fsyncSync as Kf,closeSync as Kc,renameSync as Sk,unlinkSync as Hf,appendFileSync as $k,copyFileSync as kk}from"fs";import{dirname as To,join as Pk}from"path";import{randomUUID as Tk}from"crypto";function oe(t,e){let r=To(t);Po(r,{recursive:!0});let n=Pk(r,`.tmp-${Tk().slice(0,8)}`);try{xk(n,e,"utf-8");try{Sk(n,t)}catch(o){if(o.code!=="EXDEV")throw o;kk(n,t),Hf(n)}}catch(o){try{Hf(n)}catch{}throw o}}function je(t,e){oe(t,JSON.stringify(e,null,2))}function ai(t,e){let r=To(t);Po(r,{recursive:!0});let n=Wc(t,"a");try{Hc(n,e),Kf(n)}finally{Kc(n)}}var ii,ci=Tr(()=>{"use strict";ii=class{buffer=new Map;flushTimer=null;flushIntervalMs;maxBufferSize;auditFsync;destroyed=!1;constructor(e){this.flushIntervalMs=e?.flushIntervalMs??2e3,this.maxBufferSize=e?.maxBufferSize??100,this.auditFsync=e?.auditFsync??!0,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer&&typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}append(e,r,n){if(this.destroyed)throw new Error("DurableAppendWriter has been destroyed");if(n==="audit"){if(this.auditFsync)ai(e,r);else{let s=To(e);Po(s,{recursive:!0}),$k(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=To(e);Po(n,{recursive:!0});let o=Wc(e,"a");try{Hc(o,r.join("")),Kf(o)}finally{Kc(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=To(e);Po(n,{recursive:!0});let o=Wc(e,"a");try{Hc(o,r.join(""))}finally{Kc(o)}this.buffer.delete(e)}}});import{openSync as Ek,writeSync as Rk,closeSync as Ik,unlinkSync as Gf,statSync as Ak,mkdirSync as Ck}from"fs";import{dirname as Dk}from"path";function Nk(t){if(t<=0)return;let e=new SharedArrayBuffer(4),r=new Int32Array(e);Atomics.wait(r,0,0,t)}function Wr(t,e,r={}){let n=r.staleMs??zk,o=r.acquireTimeoutMs??Ok,s=r.pollMs??Mk;Ck(Dk(t),{recursive:!0});let i=Date.now(),a=null;for(;a===null;)try{a=Ek(t,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=!1;try{let p=Ak(t);l=Date.now()-p.mtimeMs>n}catch{continue}if(l){try{Gf(t)}catch{}continue}let d=Date.now()-i;if(d>=o)throw new Gc(t,d);Nk(s)}try{try{Rk(a,`${process.pid}@${Date.now()}
5
+ `)}catch{}return e()}finally{try{Ik(a)}catch{}try{Gf(t)}catch{}}}var zk,Ok,Mk,Gc,Jc=Tr(()=>{"use strict";zk=3e4,Ok=5e3,Mk=10,Gc=class extends Error{constructor(e,r){super(`withFileLock: timed out after ${r}ms waiting for ${e}`),this.name="FileLockTimeoutError"}}});import{existsSync as Jf,realpathSync as jk}from"fs";import{basename as Lk,dirname as Fk,isAbsolute as Xc,join as Zk,normalize as Xf,resolve as Qc,relative as Uk}from"path";function qk(t){return t===""||!t.startsWith("..")&&!Xc(t)}function Yc(t){let e=[],r=Qc(t);for(;!Jf(r);){let o=Fk(r);if(o===r)break;e.unshift(Lk(r)),r=o}let n=Jf(r)?jk(r):r;return e.reduce((o,s)=>Zk(o,s),n)}function Qf(t,e){let r=Yc(e),n=Yc(t),o=Uk(r,n);return qk(o)}function eu(t,e){let r=Qc(e,t);return Qf(r,e)}function dt(t,e){let r=Qc(e,t);if(!Qf(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Le(t,e){if(t.length===0)throw new Error("Filename must not be empty");if(t.includes("\0"))throw new Error(`Filename contains null byte: ${JSON.stringify(t)}`);if(t.includes("/")||t.includes("\\"))throw new Error(`Filename must not contain path separators: ${JSON.stringify(t)}`);if(t.includes(".."))throw new Error(`Filename must not contain '..': ${JSON.stringify(t)}`);return dt(t,e)}function Yt(t,e){if(Xc(t)){let r=Xf(t);if(!eu(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return dt(t,e)}function tu(t,e){return Xc(t)?Yc(Xf(t)):dt(t,e)}function dr(t){return Vk.test(t)}function ui(t,e){if(!t||typeof t!="string")throw new ot(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new ot(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new ot(t,"command must not contain path separators");if(!Yf.has(t))throw new ot(t,`command is not in the allowlist (${[...Yf].join(", ")})`);for(let r of e){if(typeof r!="string")throw new ot(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new ot(t,`arg contains null byte: ${JSON.stringify(r)}`);if(Bk.has(r))throw new ot(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var Vk,Yf,Bk,ot,Eo=Tr(()=>{"use strict";Vk=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Yf=new Set(["gemini","codex","claude","npx","node","npm","tsc"]),Bk=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),ot=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 rm={};Be(rm,{CLI_PROVIDERS:()=>em,resolveCliConfig:()=>tm});import{readFileSync as ru}from"fs";import{join as st}from"path";import{spawn as Wk}from"child_process";function tm(t){let e=Hk[t.provider]??t.provider;return em[e]??null}function Hr(t,e){let r=st(t,"status.json"),n=`${r}.lock`;Wr(n,()=>{let o=JSON.parse(ru(r,"utf-8"));je(r,{...o,...e})})}async function Kk(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(ru(st(t,"job.json"),"utf-8"))}catch{try{je(st(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),oe(st(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=tm(e);r||(Hr(t,{state:"missing_cli",completedAt:new Date().toISOString()}),oe(st(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;Hr(t,{state:"running",startedAt:new Date().toISOString()});let s=ru(st(t,"prompt.txt"),"utf-8"),i=o(s);try{ui(n,i)}catch(c){let u=c instanceof ot?c.message:`Argv rejected: ${c.message}`;Hr(t,{state:"error",completedAt:new Date().toISOString()}),oe(st(t,"error.txt"),u);return}let a;if(e.cwd)try{a=dt(e.cwd,process.cwd())}catch(c){Hr(t,{state:"error",completedAt:new Date().toISOString()}),oe(st(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}return new Promise(c=>{let u=Bt(n,i),l=Wk(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(()=>{At(l),oe(st(t,"output.txt"),d),oe(st(t,"error.txt"),p),Hr(t,{state:"timed_out",completedAt:new Date().toISOString()}),c()},e.timeout);l.on("close",y=>{clearTimeout(g),oe(st(t,"output.txt"),d),oe(st(t,"error.txt"),p);let v=d.trim().length>0;Hr(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";oe(st(t,"error.txt"),y.message),Hr(t,{state:v,completedAt:new Date().toISOString()}),c()})})}var Hk,em,Gk,nm=Tr(()=>{"use strict";ci();Jc();wo();Eo();bn();Hk={"gemini-cli":"gemini","codex-cli":"codex","claude-cli":"claude"},em={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--skip-git-repo-check","--full-auto","--ephemeral",t]},claude:{command:"claude",buildArgs:t=>["-p",t]}};Gk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");Gk&&Kk().catch(()=>process.exit(1))});var hs=E(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var fs=class{};se._CodeOrName=fs;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var rn=class extends fs{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=rn;var ht=class extends fs{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 rn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};se._Code=ht;se.nil=new ht("");function n_(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Nl(r,e[n]),r.push(t[++n]);return new ht(r)}se._=n_;var Ml=new ht("+");function o_(t,...e){let r=[ms(t[0])],n=0;for(;n<e.length;)r.push(Ml),Nl(r,e[n]),r.push(Ml,ms(t[++n]));return HR(r),new ht(r)}se.str=o_;function Nl(t,e){e instanceof ht?t.push(...e._items):e instanceof rn?t.push(e):t.push(JR(e))}se.addCodeArg=Nl;function HR(t){let e=1;for(;e<t.length-1;){if(t[e]===Ml){let r=KR(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function KR(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof rn||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 rn))return`"${t}${e.slice(1)}`}function GR(t,e){return e.emptyStr()?t:t.emptyStr()?e:o_`${t}${e}`}se.strConcat=GR;function JR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ms(Array.isArray(t)?t.join(","):t)}function YR(t){return new ht(ms(t))}se.stringify=YR;function ms(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}se.safeStringify=ms;function XR(t){return typeof t=="string"&&se.IDENTIFIER.test(t)?new ht(`.${t}`):n_`[${t}]`}se.getProperty=XR;function QR(t){if(typeof t=="string"&&se.IDENTIFIER.test(t))return new ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}se.getEsmExportName=QR;function eI(t){return new ht(t.toString())}se.regexpCode=eI});var Fl=E(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.ValueScope=tt.ValueScopeName=tt.Scope=tt.varKinds=tt.UsedValueState=void 0;var et=hs(),jl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ha;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ha||(tt.UsedValueState=ha={}));tt.varKinds={const:new et.Name("const"),let:new et.Name("let"),var:new et.Name("var")};var ga=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof et.Name?e:this.name(e)}name(e){return new et.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};tt.Scope=ga;var ya=class extends et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,et._)`.${new et.Name(r)}[${n}]`}};tt.ValueScopeName=ya;var tI=(0,et._)`\n`,Ll=class extends ga{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?tI:et.nil}}get(){return this._scope}name(e){return new ya(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,et._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=et.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ha.Started);let l=r(u);if(l){let d=this.opts.es5?tt.varKinds.var:tt.varKinds.const;s=(0,et._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,et._)`${s}${l}${this.opts._n}`;else throw new jl(u);c.set(u,ha.Completed)})}return s}};tt.ValueScope=Ll});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 re=hs(),$t=Fl(),vr=hs();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return vr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return vr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return vr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return vr.Name}});var wa=Fl();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return wa.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return wa.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return wa.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return wa.varKinds}});K.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var er=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Zl=class extends er{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Hn(this.rhs,e,r)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},va=class extends er{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Hn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return ba(e,this.rhs)}},Ul=class extends va{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ql=class extends er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Vl=class extends er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Bl=class extends er{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Wl=class extends er{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Hn(this.code,e,r),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},gs=class extends er{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(rI(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>sn(e,r.names),{})}},tr=class extends gs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Hl=class extends gs{},Wn=class extends tr{};Wn.kind="else";var nn=class t extends tr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Wn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(s_(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Hn(this.condition,e,r),this}get names(){let e=super.names;return ba(e,this.condition),this.else&&sn(e,this.else.names),e}};nn.kind="if";var on=class extends tr{};on.kind="for";var Kl=class extends on{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Hn(this.iteration,e,r),this}get names(){return sn(super.names,this.iteration.names)}},Gl=class extends on{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?$t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ba(super.names,this.from);return ba(e,this.to)}},_a=class extends on{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Hn(this.iterable,e,r),this}get names(){return sn(super.names,this.iterable.names)}},ys=class extends tr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ys.kind="func";var vs=class extends gs{render(e){return"return "+super.render(e)}};vs.kind="return";var Jl=class extends tr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&sn(e,this.catch.names),this.finally&&sn(e,this.finally.names),e}},_s=class extends tr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};_s.kind="catch";var bs=class extends tr{render(e){return"finally"+super.render(e)}};bs.kind="finally";var Yl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
6
+ `:""},this._extScope=e,this._scope=new $t.Scope({parent:e}),this._nodes=[new Hl]}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 Zl(e,s,n)),s}const(e,r,n){return this._def($t.varKinds.const,e,r,n)}let(e,r,n){return this._def($t.varKinds.let,e,r,n)}var(e,r,n){return this._def($t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new va(e,r,n))}add(e,r){return this._leafNode(new Ul(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Wl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,re.addCodeArg)(r,o));return r.push("}"),new re._Code(r)}if(e,r,n){if(this._blockNode(new nn(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 nn(e))}else(){return this._elseNode(new Wn)}endIf(){return this._endBlockNode(nn,Wn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Kl(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 Gl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=$t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof re.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,re._)`${i}.length`,a=>{this.var(s,(0,re._)`${i}[${a}]`),n(s)})}return this._for(new _a("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?$t.varKinds.var:$t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new _a("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(on)}label(e){return this._leafNode(new ql(e))}break(e){return this._leafNode(new Vl(e))}return(e){let r=new vs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(vs)}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 _s(s),r(s)}return n&&(this._currNode=o.finally=new bs,this.code(n)),this._endBlockNode(_s,bs)}throw(e){return this._leafNode(new Bl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=re.nil,n,o){return this._blockNode(new ys(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ys)}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 nn))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=Yl;function sn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ba(t,e){return e instanceof re._CodeOrName?sn(t,e.names):t}function Hn(t,e,r){if(t instanceof re.Name)return n(t);if(!o(t))return t;return new re._Code(t._items.reduce((s,i)=>(i instanceof re.Name&&(i=n(i)),i instanceof re._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof re._Code&&s._items.some(i=>i instanceof re.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function rI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function s_(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,re._)`!${Xl(t)}`}K.not=s_;var nI=i_(K.operators.AND);function oI(...t){return t.reduce(nI)}K.and=oI;var sI=i_(K.operators.OR);function iI(...t){return t.reduce(sI)}K.or=iI;function i_(t){return(e,r)=>e===re.nil?r:r===re.nil?e:(0,re._)`${Xl(e)} ${t} ${Xl(r)}`}function Xl(t){return t instanceof re.Name?t:(0,re._)`(${t})`}});var ie=E(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var le=H(),aI=hs();function cI(t){let e={};for(let r of t)e[r]=!0;return e}J.toHash=cI;function uI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(u_(t,e),!l_(e,t.self.RULES.all))}J.alwaysValidSchema=uI;function u_(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]||f_(t,`unknown keyword: "${s}"`)}J.checkUnknownRules=u_;function l_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}J.schemaHasRules=l_;function lI(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=lI;function dI({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=dI;function pI(t){return d_(decodeURIComponent(t))}J.unescapeFragment=pI;function fI(t){return encodeURIComponent(ed(t))}J.escapeFragment=fI;function ed(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=ed;function d_(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=d_;function mI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}J.eachItem=mI;function a_({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:a_({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} || {}`),td(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:p_}),items:a_({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 p_(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&td(t,r,e),r}J.evaluatedPropsToName=p_;function td(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}J.setEvaluated=td;var c_={};function hI(t,e){return t.scopeValue("func",{ref:e,code:c_[e.code]||(c_[e.code]=new aI._Code(e.code))})}J.useFunc=hI;var Ql;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ql||(J.Type=Ql={}));function gI(t,e,r){if(t instanceof le.Name){let n=e===Ql.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():"/"+ed(t)}J.getErrorPath=gI;function f_(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=f_});var rr=E(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var Ue=H(),yI={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};rd.default=yI});var ws=E(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.extendErrors=qe.resetErrorsCount=qe.reportExtraError=qe.reportError=qe.keyword$DataError=qe.keywordError=void 0;var ne=H(),xa=ie(),Ge=rr();qe.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};qe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function vI(t,e=qe.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=g_(t,e,r);n??(i||a)?m_(s,c):h_(o,(0,ne._)`[${c}]`)}qe.reportError=vI;function _I(t,e=qe.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=g_(t,e,r);m_(o,a),s||i||h_(n,Ge.default.vErrors)}qe.reportExtraError=_I;function bI(t,e){t.assign(Ge.default.errors,e),t.if((0,ne._)`${Ge.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Ge.default.vErrors}.length`,e),()=>t.assign(Ge.default.vErrors,null)))}qe.resetErrorsCount=bI;function wI({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,Ge.default.errors,a=>{t.const(i,(0,ne._)`${Ge.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Ge.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}qe.extendErrors=wI;function m_(t,e){let r=t.const("err",e);t.if((0,ne._)`${Ge.default.vErrors} === null`,()=>t.assign(Ge.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Ge.default.vErrors}.push(${r})`),t.code((0,ne._)`${Ge.default.errors}++`)}function h_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var an={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function g_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:xI(t,e,r)}function xI(t,e,r={}){let{gen:n,it:o}=t,s=[SI(o,r),$I(t,r)];return kI(t,e,s),n.object(...s)}function SI({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,xa.getErrorPath)(e,xa.Type.Str)}`:t;return[Ge.default.instancePath,(0,ne.strConcat)(Ge.default.instancePath,r)]}function $I({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,xa.getErrorPath)(r,xa.Type.Str)}`),[an.schemaPath,o]}function kI(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([an.keyword,o],[an.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([an.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([an.schema,i],[an.parentSchema,(0,ne._)`${l}${d}`],[Ge.default.data,s]),u&&n.push([an.propertyName,u])}});var v_=E(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.boolOrEmptySchema=Kn.topBoolOrEmptySchema=void 0;var PI=ws(),TI=H(),EI=rr(),RI={message:"boolean schema is false"};function II(t){let{gen:e,schema:r,validateName:n}=t;r===!1?y_(t,!1):typeof r=="object"&&r.$async===!0?e.return(EI.default.data):(e.assign((0,TI._)`${n}.errors`,null),e.return(!0))}Kn.topBoolOrEmptySchema=II;function AI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),y_(t)):r.var(e,!0)}Kn.boolOrEmptySchema=AI;function y_(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,PI.reportError)(o,RI,void 0,e)}});var nd=E(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.getRules=Gn.isJSONType=void 0;var CI=["string","number","integer","boolean","null","object","array"],DI=new Set(CI);function zI(t){return typeof t=="string"&&DI.has(t)}Gn.isJSONType=zI;function OI(){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:{}}}Gn.getRules=OI});var od=E(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.shouldUseRule=_r.shouldUseGroup=_r.schemaHasRulesForType=void 0;function MI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&__(t,n)}_r.schemaHasRulesForType=MI;function __(t,e){return e.rules.some(r=>b_(t,r))}_r.shouldUseGroup=__;function b_(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}_r.shouldUseRule=b_});var xs=E(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.reportTypeError=Ve.checkDataTypes=Ve.checkDataType=Ve.coerceAndCheckDataType=Ve.getJSONTypes=Ve.getSchemaTypes=Ve.DataType=void 0;var NI=nd(),jI=od(),LI=ws(),q=H(),w_=ie(),Jn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Jn||(Ve.DataType=Jn={}));function FI(t){let e=x_(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}Ve.getSchemaTypes=FI;function x_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(NI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ve.getJSONTypes=x_;function ZI(t,e){let{gen:r,data:n,opts:o}=t,s=UI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,jI.schemaHasRulesForType)(t,e[0]));if(i){let a=id(e,n,o.strictNumbers,Jn.Wrong);r.if(a,()=>{s.length?qI(t,e,s):ad(t)})}return i}Ve.coerceAndCheckDataType=ZI;var S_=new Set(["string","number","integer","boolean","null"]);function UI(t,e){return e?t.filter(r=>S_.has(r)||e==="array"&&r==="array"):[]}function qI(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(id(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(S_.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),ad(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),VI(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
7
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,q._)`+${o}`);return;case"integer":n.elseIf((0,q._)`${i} === "boolean" || ${o} === null
8
+ || (${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"
9
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function VI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function sd(t,e,r,n=Jn.Correct){let o=n===Jn.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===Jn.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)}}Ve.checkDataType=sd;function id(t,e,r,n){if(t.length===1)return sd(t[0],e,r,n);let o,s=(0,w_.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,sd(i,e,r,n));return o}Ve.checkDataTypes=id;var BI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function ad(t){let e=WI(t);(0,LI.reportError)(e,BI)}Ve.reportTypeError=ad;function WI(t){let{gen:e,data:r,schema:n}=t,o=(0,w_.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var k_=E(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.assignDefaults=void 0;var Yn=H(),HI=ie();function KI(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)$_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>$_(t,s,o.default))}Sa.assignDefaults=KI;function $_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Yn._)`${s}${(0,Yn.getProperty)(e)}`;if(o){(0,HI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Yn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Yn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Yn._)`${a} = ${(0,Yn.stringify)(r)}`)}});var gt=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(),cd=ie(),br=rr(),GI=ie();function JI(t,e){let{gen:r,data:n,it:o}=t;r.if(ld(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=JI;function YI({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(ld(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=YI;function XI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=XI;function P_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=P_;function ud(t,e,r){return(0,ge._)`${P_(t)}.call(${e}, ${r})`}ue.isOwnProperty=ud;function QI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${ud(t,e,r)}`:o}ue.propertyInData=QI;function ld(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(ud(t,e,r))):o}ue.noPropertyInData=ld;function T_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=T_;function eA(t,e){return T_(e).filter(r=>!(0,cd.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=eA;function tA({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[br.default.instancePath,(0,ge.strConcat)(br.default.instancePath,s)],[br.default.parentData,i.parentData],[br.default.parentDataProperty,i.parentDataProperty],[br.default.rootData,br.default.rootData]];i.opts.dynamicRef&&d.push([br.default.dynamicAnchors,br.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=tA;var rA=(0,ge._)`new RegExp`;function nA({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"?rA:(0,GI.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=nA;function oA(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:cd.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=oA;function sA(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,cd.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=sA});var I_=E(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.validateKeywordUsage=jt.validSchemaType=jt.funcKeywordCode=jt.macroKeywordCode=void 0;var Je=H(),cn=rr(),iA=gt(),aA=ws();function cA(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=R_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Je.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}jt.macroKeywordCode=cA;function uA(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;dA(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=R_(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&&E_(t),y(()=>t.error());else{let v=e.async?f():m();e.modifying&&E_(t),y(()=>lA(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>g((0,Je._)`await `),S=>n.assign(d,!1).if((0,Je._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Je._)`${S}.errors`),()=>n.throw(S))),v}function m(){let v=(0,Je._)`${l}.errors`;return n.assign(v,null),g(Je.nil),v}function g(v=e.async?(0,Je._)`await `:Je.nil){let S=c.opts.passContext?cn.default.this:cn.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Je._)`${v}${(0,iA.callValidateCode)(t,l,S,w)}`,e.modifying)}function y(v){var S;n.if((0,Je.not)((S=e.valid)!==null&&S!==void 0?S:d),v)}}jt.funcKeywordCode=uA;function E_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Je._)`${n.parentData}[${n.parentDataProperty}]`))}function lA(t,e){let{gen:r}=t;r.if((0,Je._)`Array.isArray(${e})`,()=>{r.assign(cn.default.vErrors,(0,Je._)`${cn.default.vErrors} === null ? ${e} : ${cn.default.vErrors}.concat(${e})`).assign(cn.default.errors,(0,Je._)`${cn.default.vErrors}.length`),(0,aA.extendErrors)(t)},()=>t.error())}function dA({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function R_(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,Je.stringify)(r)})}function pA(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")}jt.validSchemaType=pA;function fA({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)}}jt.validateKeywordUsage=fA});var C_=E(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;var Lt=H(),A_=ie();function mA(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,Lt._)`${t.schemaPath}${(0,Lt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Lt._)`${t.schemaPath}${(0,Lt.getProperty)(e)}${(0,Lt.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')}wr.getSubschema=mA;function hA(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,Lt._)`${e.data}${(0,Lt.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Lt.str)`${u}${(0,A_.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Lt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Lt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}wr.extendSubschemaData=hA;function gA(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}wr.extendSubschemaMode=gA});var dd=E((mB,D_)=>{"use strict";D_.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 O_=E((hB,z_)=>{"use strict";var xr=z_.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};$a(e,n,o,t,"",t)};xr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};xr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};xr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};xr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function $a(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in xr.arrayKeywords)for(var p=0;p<d.length;p++)$a(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in xr.propsKeywords){if(d&&typeof d=="object")for(var f in d)$a(t,e,r,d[f],o+"/"+l+"/"+yA(f),s,o,l,n,f)}else(l in xr.keywords||t.allKeys&&!(l in xr.skipKeywords))&&$a(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function yA(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ss=E(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getSchemaRefs=rt.resolveUrl=rt.normalizeId=rt._getFullPath=rt.getFullPath=rt.inlineRef=void 0;var vA=ie(),_A=dd(),bA=O_(),wA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function xA(t,e=!0){return typeof t=="boolean"?!0:e===!0?!pd(t):e?M_(t)<=e:!1}rt.inlineRef=xA;var SA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function pd(t){for(let e in t){if(SA.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(pd)||typeof r=="object"&&pd(r))return!0}return!1}function M_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!wA.has(r)&&(typeof t[r]=="object"&&(0,vA.eachItem)(t[r],n=>e+=M_(n)),e===1/0))return 1/0}return e}function N_(t,e="",r){r!==!1&&(e=Xn(e));let n=t.parse(e);return j_(t,n)}rt.getFullPath=N_;function j_(t,e){return t.serialize(e).split("#")[0]+"#"}rt._getFullPath=j_;var $A=/#\/?$/;function Xn(t){return t?t.replace($A,""):""}rt.normalizeId=Xn;function kA(t,e,r){return r=Xn(r),t.resolve(e,r)}rt.resolveUrl=kA;var PA=/^[a-z_][-a-z0-9._]*$/i;function TA(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xn(t[r]||e),s={"":o},i=N_(n,o,!1),a={},c=new Set;return bA(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])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[p]=y;function v(w){let _=this.opts.uriResolver.resolve;if(w=Xn(y?_(y,w):w),c.has(w))throw l(w);c.add(w);let P=this.refs[w];return typeof P=="string"&&(P=this.refs[P]),typeof P=="object"?u(d,P.schema,w):w!==Xn(g)&&(w[0]==="#"?(u(d,a[w],w),a[w]=d):this.refs[w]=g),w}function S(w){if(typeof w=="string"){if(!PA.test(w))throw new Error(`invalid anchor "${w}"`);v.call(this,`#${w}`)}}}),a;function u(d,p,f){if(p!==void 0&&!_A(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}rt.getSchemaRefs=TA});var Ps=E(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.getData=Sr.KeywordCxt=Sr.validateFunctionCode=void 0;var q_=v_(),L_=xs(),md=od(),ka=xs(),EA=k_(),ks=I_(),fd=C_(),O=H(),F=rr(),RA=Ss(),nr=ie(),$s=ws();function IA(t){if(W_(t)&&(H_(t),B_(t))){DA(t);return}V_(t,()=>(0,q_.topBoolOrEmptySchema)(t))}Sr.validateFunctionCode=IA;function V_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,O._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,O._)`"use strict"; ${F_(r,o)}`),CA(t,o),t.code(s)}):t.func(e,(0,O._)`${F.default.data}, ${AA(o)}`,n.$async,()=>t.code(F_(r,o)).code(s))}function AA(t){return(0,O._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,O._)`, ${F.default.dynamicAnchors}={}`:O.nil}}={}`}function CA(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,O._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,O._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,O._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,O._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,O._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,O._)`""`),t.var(F.default.parentData,(0,O._)`undefined`),t.var(F.default.parentDataProperty,(0,O._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,O._)`{}`)})}function DA(t){let{schema:e,opts:r,gen:n}=t;V_(t,()=>{r.$comment&&e.$comment&&G_(t),jA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&zA(t),K_(t),ZA(t)})}function zA(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,O._)`${r}.evaluated`),e.if((0,O._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,O._)`${t.evaluated}.props`,(0,O._)`undefined`)),e.if((0,O._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,O._)`${t.evaluated}.items`,(0,O._)`undefined`))}function F_(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,O._)`/*# sourceURL=${r} */`:O.nil}function OA(t,e){if(W_(t)&&(H_(t),B_(t))){MA(t,e);return}(0,q_.boolOrEmptySchema)(t,e)}function B_({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 W_(t){return typeof t.schema!="boolean"}function MA(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&G_(t),LA(t),FA(t);let s=n.const("_errs",F.default.errors);K_(t,s),n.var(e,(0,O._)`${s} === ${F.default.errors}`)}function H_(t){(0,nr.checkUnknownRules)(t),NA(t)}function K_(t,e){if(t.opts.jtd)return Z_(t,[],!1,e);let r=(0,L_.getSchemaTypes)(t.schema),n=(0,L_.coerceAndCheckDataType)(t,r);Z_(t,r,!n,e)}function NA(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,nr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function jA(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,nr.checkStrictMode)(t,"default is ignored in the schema root")}function LA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,RA.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function FA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function G_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,O._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,O.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,O._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function ZA(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,O._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,O._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,O._)`${n}.errors`,F.default.vErrors),s.unevaluated&&UA(t),e.return((0,O._)`${F.default.errors} === 0`))}function UA({gen:t,evaluated:e,props:r,items:n}){r instanceof O.Name&&t.assign((0,O._)`${e}.props`,r),n instanceof O.Name&&t.assign((0,O._)`${e}.items`,n)}function Z_(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,nr.schemaHasRulesButRef)(s,l))){o.block(()=>Y_(t,"$ref",l.all.$ref.definition));return}c.jtd||qA(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,md.shouldUseGroup)(s,p)&&(p.type?(o.if((0,ka.checkDataType)(p.type,i,c.strictNumbers)),U_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,ka.reportTypeError)(t)),o.endIf()):U_(t,p),a||o.if((0,O._)`${F.default.errors} === ${n||0}`))}}function U_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,EA.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,md.shouldUseRule)(n,s)&&Y_(t,s.keyword,s.definition,e.type)})}function qA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(VA(t,e),t.opts.allowUnionTypes||BA(t,e),WA(t,t.dataTypes))}function VA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{J_(t.dataTypes,r)||hd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),KA(t,e)}}function BA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&hd(t,"use allowUnionTypes to allow union type keyword")}function WA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,md.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>HA(e,i))&&hd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function HA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function J_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function KA(t,e){let r=[];for(let n of t.dataTypes)J_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function hd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,nr.checkStrictMode)(t,e,t.opts.strictTypes)}var Pa=class{constructor(e,r,n){if((0,ks.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,nr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",X_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ks.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,O.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,O.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,O._)`${r} !== undefined && (${(0,O.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?$s.reportExtraError:$s.reportError)(this,this.def.error,r)}$dataError(){(0,$s.reportError)(this,this.def.$dataError||$s.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,$s.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=O.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=O.nil,r=O.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,O.or)((0,O._)`${o} === undefined`,r)),e!==O.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==O.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,O.or)(i(),a());function i(){if(n.length){if(!(r instanceof O.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,O._)`${(0,ka.checkDataTypes)(c,r,s.opts.strictNumbers,ka.DataType.Wrong)}`}return O.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,O._)`!${c}(${r})`}return O.nil}}subschema(e,r){let n=(0,fd.getSubschema)(this.it,e);(0,fd.extendSubschemaData)(n,this.it,e),(0,fd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return OA(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=nr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=nr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,O.Name)),!0}};Sr.KeywordCxt=Pa;function Y_(t,e,r,n){let o=new Pa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ks.funcKeywordCode)(o,r):"macro"in r?(0,ks.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ks.funcKeywordCode)(o,r)}var GA=/^\/(?:[^~]|~0|~1)*$/,JA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function X_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!GA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=JA.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,O._)`${s}${(0,O.getProperty)((0,nr.unescapeJsonPointer)(u))}`,i=(0,O._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Sr.getData=X_});var Ta=E(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var gd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};yd.default=gd});var Ts=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var vd=Ss(),_d=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,vd.resolveUrl)(e,r,n),this.missingSchema=(0,vd.normalizeId)((0,vd.getFullPath)(e,this.missingRef))}};bd.default=_d});var Ra=E(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var kt=H(),YA=Ta(),un=rr(),Pt=Ss(),Q_=ie(),XA=Ps(),Qn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Pt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};yt.SchemaEnv=Qn;function xd(t){let e=eb.call(this,t);if(e)return e;let r=(0,Pt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new kt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:YA.default,code:(0,kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:un.default.data,parentData:un.default.parentData,parentDataProperty:un.default.parentDataProperty,dataNames:[un.default.data],dataPathArr:[kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,kt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:kt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,kt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,XA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(un.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${un.default.self}`,`${un.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=u;f.evaluated={props:m instanceof kt.Name?void 0:m,items:g instanceof kt.Name?void 0:g,dynamicProps:m instanceof kt.Name,dynamicItems:g instanceof kt.Name},f.source&&(f.source.evaluated=(0,kt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}yt.compileSchema=xd;function QA(t,e,r){var n;r=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=rC.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Qn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=eC.call(this,s)}yt.resolveRef=QA;function eC(t){return(0,Pt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:xd.call(this,t)}function eb(t){for(let e of this._compilations)if(tC(e,t))return e}yt.getCompilingSchema=eb;function tC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function rC(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ea.call(this,t,e)}function Ea(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pt._getFullPath)(this.opts.uriResolver,r),o=(0,Pt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return wd.call(this,r,t);let s=(0,Pt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ea.call(this,t,i);return typeof a?.schema!="object"?void 0:wd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||xd.call(this,i),s===(0,Pt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pt.resolveUrl)(this.opts.uriResolver,o,u)),new Qn({schema:a,schemaId:c,root:t,baseId:o})}return wd.call(this,r,i)}}yt.resolveSchema=Ea;var nC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function wd(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,Q_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!nC.has(a)&&u&&(e=(0,Pt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Q_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ea.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Qn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var tb=E((wB,oC)=>{oC.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 $d=E((xB,sb)=>{"use strict";var sC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),nb=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 Sd(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 iC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function rb(t){return t.length=0,!0}function aC(t,e,r){if(t.length){let n=Sd(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function cC(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=aC;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=rb}else{o.push(u);continue}}return o.length&&(a===rb?r.zone=o.join(""):i?n.push(o.join("")):n.push(Sd(o))),r.address=n.join(""),r}function ob(t){if(uC(t,":")<2)return{host:t,isIPV6:!1};let e=cC(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 uC(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function lC(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 dC(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 pC(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!nb(r)){let n=ob(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}sb.exports={nonSimpleDomain:iC,recomposeAuthority:pC,normalizeComponentEncoding:dC,removeDotSegments:lC,isIPv4:nb,isUUID:sC,normalizeIPv6:ob,stringArrayToHexStripped:Sd}});var lb=E((SB,ub)=>{"use strict";var{isUUID:fC}=$d(),mC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,hC=["http","https","ws","wss","urn","urn:uuid"];function gC(t){return hC.indexOf(t)!==-1}function kd(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 ib(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function ab(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 yC(t){return t.secure=kd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function vC(t){if((t.port===(kd(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 _C(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(mC);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=Pd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function bC(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=Pd(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 wC(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!fC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function xC(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var cb={scheme:"http",domainHost:!0,parse:ib,serialize:ab},SC={scheme:"https",domainHost:cb.domainHost,parse:ib,serialize:ab},Ia={scheme:"ws",domainHost:!0,parse:yC,serialize:vC},$C={scheme:"wss",domainHost:Ia.domainHost,parse:Ia.parse,serialize:Ia.serialize},kC={scheme:"urn",parse:_C,serialize:bC,skipNormalize:!0},PC={scheme:"urn:uuid",parse:wC,serialize:xC,skipNormalize:!0},Aa={http:cb,https:SC,ws:Ia,wss:$C,urn:kC,"urn:uuid":PC};Object.setPrototypeOf(Aa,null);function Pd(t){return t&&(Aa[t]||Aa[t.toLowerCase()])||void 0}ub.exports={wsIsSecure:kd,SCHEMES:Aa,isValidSchemeName:gC,getSchemeHandler:Pd}});var fb=E(($B,Da)=>{"use strict";var{normalizeIPv6:TC,removeDotSegments:Es,recomposeAuthority:EC,normalizeComponentEncoding:Ca,isIPv4:RC,nonSimpleDomain:IC}=$d(),{SCHEMES:AC,getSchemeHandler:db}=lb();function CC(t,e){return typeof t=="string"?t=Ft(or(t,e),e):typeof t=="object"&&(t=or(Ft(t,e),e)),t}function DC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=pb(or(t,n),or(e,n),n,!0);return n.skipEscape=!0,Ft(o,n)}function pb(t,e,r,n){let o={};return n||(t=or(Ft(t,r),r),e=or(Ft(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=Es(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=Es(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Es(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=Es(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 zC(t,e,r){return typeof t=="string"?(t=unescape(t),t=Ft(Ca(or(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Ft(Ca(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Ft(Ca(or(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Ft(Ca(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Ft(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=db(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=EC(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=Es(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 OC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function or(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(OC);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(RC(n.host)===!1){let c=TC(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=db(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&IC(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Td={SCHEMES:AC,normalize:CC,resolve:DC,resolveComponent:pb,equal:zC,serialize:Ft,parse:or};Da.exports=Td;Da.exports.default=Td;Da.exports.fastUri=Td});var hb=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var mb=fb();mb.code='require("ajv/dist/runtime/uri").default';Ed.default=mb});var Sb=E(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.CodeGen=ze.Name=ze.nil=ze.stringify=ze.str=ze._=ze.KeywordCxt=void 0;var MC=Ps();Object.defineProperty(ze,"KeywordCxt",{enumerable:!0,get:function(){return MC.KeywordCxt}});var eo=H();Object.defineProperty(ze,"_",{enumerable:!0,get:function(){return eo._}});Object.defineProperty(ze,"str",{enumerable:!0,get:function(){return eo.str}});Object.defineProperty(ze,"stringify",{enumerable:!0,get:function(){return eo.stringify}});Object.defineProperty(ze,"nil",{enumerable:!0,get:function(){return eo.nil}});Object.defineProperty(ze,"Name",{enumerable:!0,get:function(){return eo.Name}});Object.defineProperty(ze,"CodeGen",{enumerable:!0,get:function(){return eo.CodeGen}});var NC=Ta(),bb=Ts(),jC=nd(),Rs=Ra(),LC=H(),Is=Ss(),za=xs(),Id=ie(),gb=tb(),FC=hb(),wb=(t,e)=>new RegExp(t,e);wb.code="new RegExp";var ZC=["removeAdditional","useDefaults","coerceTypes"],UC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),qC={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."},VC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},yb=200;function BC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,y,v,S,w,_,P,A,D,U,$e;let G=t.strict,_t=(e=t.code)===null||e===void 0?void 0:e.optimize,Te=_t===!0||_t===void 0?1:_t||0,Pr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:wb,fn=(o=t.uriResolver)!==null&&o!==void 0?o:FC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:G)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:G)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:G)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:G)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:G)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Te,regExp:Pr}:{optimize:Te,regExp:Pr},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:yb,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:yb,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(_=t.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(P=t.addUsedSchema)!==null&&P!==void 0?P:!0,validateSchema:(A=t.validateSchema)!==null&&A!==void 0?A:!0,validateFormats:(D=t.validateFormats)!==null&&D!==void 0?D:!0,unicodeRegExp:(U=t.unicodeRegExp)!==null&&U!==void 0?U:!0,int32range:($e=t.int32range)!==null&&$e!==void 0?$e:!0,uriResolver:fn}}var As=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...BC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new LC.ValueScope({scope:{},prefixes:UC,es5:r,lines:n}),this.logger=YC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,jC.getRules)(),vb.call(this,qC,e,"NOT SUPPORTED"),vb.call(this,VC,e,"DEPRECATED","warn"),this._metaOpts=GC.call(this),e.formats&&HC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&KC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),WC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=gb;n==="id"&&(o={...gb},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 bb.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,Is.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=_b.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Rs.SchemaEnv({schema:{},schemaId:n});if(r=Rs.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=_b.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,Is.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(QC.call(this,n,r),!r)return(0,Id.eachItem)(n,s=>Rd.call(this,s)),this;tD.call(this,r);let o={...r,type:(0,za.getJSONTypes)(r.type),schemaType:(0,za.getJSONTypes)(r.schemaType)};return(0,Id.eachItem)(n,o.type.length===0?s=>Rd.call(this,s,o):s=>o.type.forEach(i=>Rd.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]=xb(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,Is.normalizeId)(i||n);let u=Is.getSchemaRefs.call(this,e,n);return c=new Rs.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):Rs.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{Rs.compileSchema.call(this,e)}finally{this.opts=r}}};As.ValidationError=NC.default;As.MissingRefError=bb.default;ze.default=As;function vb(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 _b(t){return t=(0,Is.normalizeId)(t),this.schemas[t]||this.refs[t]}function WC(){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 HC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function KC(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 GC(){let t={...this.opts};for(let e of ZC)delete t[e];return t}var JC={log(){},warn(){},error(){}};function YC(t){if(t===!1)return JC;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var XC=/^[a-z_$][a-z0-9_$:-]*$/i;function QC(t,e){let{RULES:r}=this;if((0,Id.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 Rd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,za.getJSONTypes)(e.type),schemaType:(0,za.getJSONTypes)(e.schemaType)}};e.before?eD.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 eD(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 tD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=xb(e)),t.validateSchema=this.compile(e,!0))}var rD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xb(t){return{anyOf:[t,rD]}}});var $b=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var nD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ad.default=nD});var Eb=E(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.callRef=ln.getValidate=void 0;var oD=Ts(),kb=gt(),nt=H(),to=rr(),Pb=Ra(),Oa=ie(),sD={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=Pb.resolveRef.call(c,u,o,r);if(l===void 0)throw new oD.default(n.opts.uriResolver,o,r);if(l instanceof Pb.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Ma(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Ma(t,(0,nt._)`${m}.validate`,u,u.$async)}function p(m){let g=Tb(t,m);Ma(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,nt.stringify)(m)}:{ref:m}),y=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:nt.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function Tb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,nt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ln.getValidate=Tb;function Ma(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?to.default.this:nt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,nt._)`await ${(0,kb.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,nt._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,kb.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,nt._)`${m}.errors`;o.assign(to.default.vErrors,(0,nt._)`${to.default.vErrors} === null ? ${g} : ${to.default.vErrors}.concat(${g})`),o.assign(to.default.errors,(0,nt._)`${to.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let 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=Oa.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,nt._)`${m}.evaluated.props`);s.props=Oa.mergeEvaluated.props(o,v,s.props,nt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Oa.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,nt._)`${m}.evaluated.items`);s.items=Oa.mergeEvaluated.items(o,v,s.items,nt.Name)}}}ln.callRef=Ma;ln.default=sD});var Rb=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var iD=$b(),aD=Eb(),cD=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",iD.default,aD.default];Cd.default=cD});var Ib=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Na=H(),$r=Na.operators,ja={maximum:{okStr:"<=",ok:$r.LTE,fail:$r.GT},minimum:{okStr:">=",ok:$r.GTE,fail:$r.LT},exclusiveMaximum:{okStr:"<",ok:$r.LT,fail:$r.GTE},exclusiveMinimum:{okStr:">",ok:$r.GT,fail:$r.LTE}},uD={message:({keyword:t,schemaCode:e})=>(0,Na.str)`must be ${ja[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Na._)`{comparison: ${ja[t].okStr}, limit: ${e}}`},lD={keyword:Object.keys(ja),type:"number",schemaType:"number",$data:!0,error:uD,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Na._)`${r} ${ja[e].fail} ${n} || isNaN(${r})`)}};Dd.default=lD});var Ab=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var Cs=H(),dD={message:({schemaCode:t})=>(0,Cs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Cs._)`{multipleOf: ${t}}`},pD={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:dD,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Cs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Cs._)`${i} !== parseInt(${i})`;t.fail$data((0,Cs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};zd.default=pD});var Db=E(Od=>{"use strict";Object.defineProperty(Od,"__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}Od.default=Cb;Cb.code='require("ajv/dist/runtime/ucs2length").default'});var zb=E(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var dn=H(),fD=ie(),mD=Db(),hD={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,dn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,dn._)`{limit: ${t}}`},gD={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:hD,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?dn.operators.GT:dn.operators.LT,i=o.opts.unicode===!1?(0,dn._)`${r}.length`:(0,dn._)`${(0,fD.useFunc)(t.gen,mD.default)}(${r})`;t.fail$data((0,dn._)`${i} ${s} ${n}`)}};Md.default=gD});var Ob=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var yD=gt(),La=H(),vD={message:({schemaCode:t})=>(0,La.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,La._)`{pattern: ${t}}`},_D={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:vD,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,La._)`(new RegExp(${o}, ${i}))`:(0,yD.usePattern)(t,n);t.fail$data((0,La._)`!${a}.test(${e})`)}};Nd.default=_D});var Mb=E(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var Ds=H(),bD={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ds.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ds._)`{limit: ${t}}`},wD={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:bD,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ds.operators.GT:Ds.operators.LT;t.fail$data((0,Ds._)`Object.keys(${r}).length ${o} ${n}`)}};jd.default=wD});var Nb=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var zs=gt(),Os=H(),xD=ie(),SD={message:({params:{missingProperty:t}})=>(0,Os.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Os._)`{missingProperty: ${t}}`},$D={keyword:"required",type:"object",schemaType:"array",$data:!0,error:SD,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,xD.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Os.nil,d);else for(let f of r)(0,zs.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,zs.checkMissingProp)(t,r,f)),(0,zs.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,zs.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,zs.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Os.not)(m),()=>{t.error(),e.break()})},Os.nil)}}};Ld.default=$D});var jb=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Ms=H(),kD={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ms.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ms._)`{limit: ${t}}`},PD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kD,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ms.operators.GT:Ms.operators.LT;t.fail$data((0,Ms._)`${r}.length ${o} ${n}`)}};Fd.default=PD});var Fa=E(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});var Lb=dd();Lb.code='require("ajv/dist/runtime/equal").default';Zd.default=Lb});var Fb=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var Ud=xs(),Oe=H(),TD=ie(),ED=Fa(),RD={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},ID={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RD,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,Ud.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Oe._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Oe._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,Oe._)`${m} > 1`,()=>(d()?p:f)(m,g))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,g){let y=e.name("item"),v=(0,Ud.checkDataTypes)(u,y,a.opts.strictNumbers,Ud.DataType.Wrong),S=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${m}--;`,()=>{e.let(y,(0,Oe._)`${r}[${m}]`),e.if(v,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${y} == "string"`,(0,Oe._)`${y} += "_"`),e.if((0,Oe._)`typeof ${S}[${y}] == "number"`,()=>{e.assign(g,(0,Oe._)`${S}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${S}[${y}] = ${m}`)})}function f(m,g){let y=(0,TD.useFunc)(e,ED.default),v=e.name("outer");e.label(v).for((0,Oe._)`;${m}--;`,()=>e.for((0,Oe._)`${g} = ${m}; ${g}--;`,()=>e.if((0,Oe._)`${y}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};qd.default=ID});var Zb=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var Vd=H(),AD=ie(),CD=Fa(),DD={message:"must be equal to constant",params:({schemaCode:t})=>(0,Vd._)`{allowedValue: ${t}}`},zD={keyword:"const",$data:!0,error:DD,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Vd._)`!${(0,AD.useFunc)(e,CD.default)}(${r}, ${o})`):t.fail((0,Vd._)`${s} !== ${r}`)}};Bd.default=zD});var Ub=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var Ns=H(),OD=ie(),MD=Fa(),ND={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ns._)`{allowedValues: ${t}}`},jD={keyword:"enum",schemaType:"array",$data:!0,error:ND,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,OD.useFunc)(e,MD.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,Ns.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,Ns._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Ns._)`${u()}(${r}, ${f}[${m}])`:(0,Ns._)`${r} === ${g}`}}};Wd.default=jD});var qb=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var LD=Ib(),FD=Ab(),ZD=zb(),UD=Ob(),qD=Mb(),VD=Nb(),BD=jb(),WD=Fb(),HD=Zb(),KD=Ub(),GD=[LD.default,FD.default,ZD.default,UD.default,qD.default,VD.default,BD.default,WD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},HD.default,KD.default];Hd.default=GD});var Gd=E(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.validateAdditionalItems=void 0;var pn=H(),Kd=ie(),JD={message:({params:{len:t}})=>(0,pn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,pn._)`{limit: ${t}}`},YD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JD,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Kd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Vb(t,n)}};function Vb(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,pn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,pn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Kd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,pn._)`${a} <= ${e.length}`);r.if((0,pn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Kd.Type.Num},u),i.allErrors||r.if((0,pn.not)(u),()=>r.break())})}}js.validateAdditionalItems=Vb;js.default=YD});var Jd=E(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.validateTuple=void 0;var Bb=H(),Za=ie(),XD=gt(),QD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Wb(t,"additionalItems",e);r.items=!0,!(0,Za.alwaysValidSchema)(r,e)&&t.ok((0,XD.validateArray)(t))}};function Wb(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Za.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Bb._)`${s}.length`);r.forEach((d,p)=>{(0,Za.alwaysValidSchema)(a,d)||(n.if((0,Bb._)`${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,Za.checkStrictMode)(a,y,p.strictTuples)}}}Ls.validateTuple=Wb;Ls.default=QD});var Hb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var ez=Jd(),tz={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,ez.validateTuple)(t,"items")};Yd.default=tz});var Gb=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var Kb=H(),rz=ie(),nz=gt(),oz=Gd(),sz={message:({params:{len:t}})=>(0,Kb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Kb._)`{limit: ${t}}`},iz={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:sz,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,rz.alwaysValidSchema)(n,e)&&(o?(0,oz.validateAdditionalItems)(t,o):t.ok((0,nz.validateArray)(t)))}};Xd.default=iz});var Jb=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var vt=H(),Ua=ie(),az={message:({params:{min:t,max:e}})=>e===void 0?(0,vt.str)`must contain at least ${t} valid item(s)`:(0,vt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,vt._)`{minContains: ${t}}`:(0,vt._)`{minContains: ${t}, maxContains: ${e}}`},cz={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:az,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,vt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ua.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ua.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ua.alwaysValidSchema)(s,r)){let g=(0,vt._)`${l} >= ${i}`;a!==void 0&&(g=(0,vt._)`${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,vt._)`${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:Ua.Type.Num,compositeRule:!0},g),y()})}function m(g){e.code((0,vt._)`${g}++`),a===void 0?e.if((0,vt._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,vt._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,vt._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Qd.default=cz});var Qb=E(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.validateSchemaDeps=Zt.validatePropertyDeps=Zt.error=void 0;var ep=H(),uz=ie(),Fs=gt();Zt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ep.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ep._)`{property: ${t},
10
10
  missingProperty: ${n},
11
11
  depsCount: ${e},
12
- deps: ${r}}`};var uz={keyword:"dependencies",type:"object",schemaType:"object",error:Ft.error,code(t){let[e,r]=lz(t);Jb(t,e),Gb(t,r)}};function lz({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Jb(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ls.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Ls.checkReportMissingProp)(t,u)}):(r.if((0,Qd._)`${c} && (${(0,Ls.checkMissingProp)(t,a,s)})`),(0,Ls.reportMissingProp)(t,s),r.else())}}Ft.validatePropertyDeps=Jb;function Gb(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,cz.alwaysValidSchema)(s,e[a])||(r.if((0,Ls.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ft.validateSchemaDeps=Gb;Ft.default=uz});var Qb=E(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var Xb=W(),dz=ie(),pz={message:"property name must be valid",params:({params:t})=>(0,Xb._)`{propertyName: ${t.propertyName}}`},fz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:pz,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,dz.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Xb.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};ep.default=fz});var rp=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var qa=yt(),Tt=W(),mz=rr(),Va=ie(),hz={message:"must NOT have additional properties",params:({params:t})=>(0,Tt._)`{additionalProperty: ${t.additionalProperty}}`},gz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:hz,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Va.alwaysValidSchema)(i,r))return;let u=(0,qa.allSchemaProperties)(n.properties),l=(0,qa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Tt._)`${s} === ${mz.default.errors}`);function d(){e.forIn("key",o,v=>{!u.length&&!l.length?m(v):e.if(p(v),()=>m(v))})}function p(v){let _;if(u.length>8){let S=(0,Va.schemaRefOrVal)(i,n.properties,"properties");_=(0,qa.isOwnProperty)(e,S,v)}else u.length?_=(0,Tt.or)(...u.map(S=>(0,Tt._)`${v} === ${S}`)):_=Tt.nil;return l.length&&(_=(0,Tt.or)(_,...l.map(S=>(0,Tt._)`${(0,qa.usePattern)(t,S)}.test(${v})`))),(0,Tt.not)(_)}function f(v){e.code((0,Tt._)`delete ${o}[${v}]`)}function m(v){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Va.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(v,_,!1),e.if((0,Tt.not)(_),()=>{t.reset(),f(v)})):(g(v,_),a||e.if((0,Tt.not)(_),()=>e.break()))}}function g(v,_,S){let y={keyword:"additionalProperties",dataProp:v,dataPropType:Va.Type.Str};S===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(y,_)}}};tp.default=gz});var rw=E(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var yz=ks(),ew=yt(),np=ie(),tw=rp(),vz={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&tw.default.code(new yz.KeywordCxt(s,tw.default,"additionalProperties"));let i=(0,ew.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=np.mergeEvaluated.props(e,(0,np.toHash)(i),s.props));let a=i.filter(d=>!(0,np.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,ew.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};op.default=vz});var iw=E(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var nw=yt(),Ba=W(),ow=ie(),sw=ie(),_z={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,nw.allSchemaProperties)(r),c=a.filter(g=>(0,ow.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ba.Name)&&(s.props=(0,sw.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?m(g):(e.var(l,!0),m(g),e.if(l))}function f(g){for(let v in u)new RegExp(g).test(v)&&(0,ow.checkStrictMode)(s,`property ${v} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,v=>{e.if((0,Ba._)`${(0,nw.usePattern)(t,g)}.test(${v})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:v,dataPropType:sw.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ba._)`${d}[${v}]`,!0):!_&&!s.allErrors&&e.if((0,Ba.not)(l),()=>e.break())})})}}};sp.default=_z});var aw=E(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var bz=ie(),wz={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,bz.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};ip.default=wz});var cw=E(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var xz=yt(),Sz={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xz.validateUnion,error:{message:"must match a schema in anyOf"}};ap.default=Sz});var uw=E(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var Wa=W(),$z=ie(),kz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Wa._)`{passingSchemas: ${t.passing}}`},Pz={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kz,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,$z.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Wa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Wa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Wa.Name)})})}}};cp.default=Pz});var lw=E(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});var Tz=ie(),Ez={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,Tz.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};up.default=Ez});var fw=E(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});var Ha=W(),pw=ie(),Rz={message:({params:t})=>(0,Ha.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ha._)`{failingKeyword: ${t.ifClause}}`},Iz={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Rz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,pw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=dw(n,"then"),s=dw(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ha.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Ha._)`${l}`):t.setParams({ifClause:l})}}}};function dw(t,e){let r=t.schema[e];return r!==void 0&&!(0,pw.alwaysValidSchema)(t,r)}lp.default=Iz});var mw=E(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});var Az=ie(),Cz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Az.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};dp.default=Cz});var hw=E(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});var Dz=Kd(),zz=Bb(),Oz=Jd(),Mz=Hb(),Nz=Kb(),jz=Yb(),Lz=Qb(),Fz=rp(),Zz=rw(),Uz=iw(),qz=aw(),Vz=cw(),Bz=uw(),Wz=lw(),Hz=fw(),Kz=mw();function Jz(t=!1){let e=[qz.default,Vz.default,Bz.default,Wz.default,Hz.default,Kz.default,Lz.default,Fz.default,jz.default,Zz.default,Uz.default];return t?e.push(zz.default,Mz.default):e.push(Dz.default,Oz.default),e.push(Nz.default),e}pp.default=Jz});var gw=E(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var ke=W(),Gz={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},Yz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Gz,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,ke._)`${m}[${i}]`),v=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(v,(0,ke._)`${g}.type || "string"`).assign(_,(0,ke._)`${g}.validate`),()=>r.assign(v,(0,ke._)`"string"`).assign(_,g)),t.fail$data((0,ke.or)(S(),y()));function S(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function y(){let x=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,$=(0,ke._)`(typeof ${_} == "function" ? ${x} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${v} === ${e} && !${$}`}}function f(){let m=d.formats[s];if(!m){S();return}if(m===!0)return;let[g,v,_]=y(m);g===e&&t.pass(x());function S(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function y($){let M=$ instanceof RegExp?(0,ke.regexpCode)($):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:$,code:M});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,ke._)`${O}.validate`]:["string",$,O]}function x(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof v=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};fp.default=Yz});var yw=E(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var Xz=gw(),Qz=[Xz.default];mp.default=Qz});var vw=E(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.contentVocabulary=ro.metadataVocabulary=void 0;ro.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ro.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var bw=E(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var eO=Tb(),tO=Zb(),rO=hw(),nO=yw(),_w=vw(),oO=[eO.default,tO.default,(0,rO.default)(),nO.default,_w.metadataVocabulary,_w.contentVocabulary];hp.default=oO});var xw=E(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.DiscrError=void 0;var ww;(function(t){t.Tag="tag",t.Mapping="mapping"})(ww||(Ka.DiscrError=ww={}))});var $w=E(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});var no=W(),gp=xw(),Sw=Ra(),sO=Ps(),iO=ie(),aO={message:({params:{discrError:t,tagName:e}})=>t===gp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,no._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},cO={keyword:"discriminator",type:"object",schemaType:"object",error:aO,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,no._)`${r}${(0,no.getProperty)(a)}`);e.if((0,no._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:gp.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,no._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:gp.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(g,no.Name),m}function p(){var f;let m={},g=_(o),v=!0;for(let x=0;x<i.length;x++){let $=i[x];if($?.$ref&&!(0,iO.schemaHasRulesButRef)($,s.self.RULES)){let O=$.$ref;if($=Sw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),$ instanceof Sw.SchemaEnv&&($=$.schema),$===void 0)throw new sO.default(s.opts.uriResolver,s.baseId,O)}let M=(f=$?.properties)===null||f===void 0?void 0:f[a];if(typeof M!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(g||_($)),S(M,x)}if(!v)throw new Error(`discriminator: "${a}" must be required`);return m;function _({required:x}){return Array.isArray(x)&&x.includes(a)}function S(x,$){if(x.const)y(x.const,$);else if(x.enum)for(let M of x.enum)y(M,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(x,$){if(typeof x!="string"||x in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[x]=$}}}};yp.default=cO});var kw=E((c2,uO)=>{uO.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var _p=E((ye,vp)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var lO=wb(),dO=bw(),pO=$w(),Pw=kw(),fO=["/properties"],Ja="http://json-schema.org/draft-07/schema",oo=class extends lO.default{_addVocabularies(){super._addVocabularies(),dO.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(pO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Pw,fO):Pw;this.addMetaSchema(e,Ja,!1),this.refs["http://json-schema.org/schema"]=Ja}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ja)?Ja:void 0)}};ye.Ajv=oo;vp.exports=ye=oo;vp.exports.Ajv=oo;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=oo;var mO=ks();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return mO.KeywordCxt}});var so=W();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return so._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return so.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return so.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return so.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return so.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return so.CodeGen}});var hO=Ta();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return hO.default}});var gO=Ps();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return gO.default}})});var zw=E(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.formatNames=Ut.fastFormats=Ut.fullFormats=void 0;function Zt(t,e){return{validate:t,compare:e}}Ut.fullFormats={date:Zt(Iw,Sp),time:Zt(wp(!0),$p),"date-time":Zt(Tw(!0),Cw),"iso-time":Zt(wp(),Aw),"iso-date-time":Zt(Tw(),Dw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:xO,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:RO,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:SO,int32:{type:"number",validate:PO},int64:{type:"number",validate:TO},float:{type:"number",validate:Rw},double:{type:"number",validate:Rw},password:!0,binary:!0};Ut.fastFormats={...Ut.fullFormats,date:Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Sp),time:Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,$p),"date-time":Zt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Cw),"iso-time":Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Aw),"iso-date-time":Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Dw),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Ut.formatNames=Object.keys(Ut.fullFormats);function yO(t){return t%4===0&&(t%100!==0||t%400===0)}var vO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_O=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Iw(t){let e=vO.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&yO(r)?29:_O[n])}function Sp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var bp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function wp(t){return function(r){let n=bp.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function $p(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Aw(t,e){if(!(t&&e))return;let r=bp.exec(t),n=bp.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var xp=/t|\s/i;function Tw(t){let e=wp(t);return function(n){let o=n.split(xp);return o.length===2&&Iw(o[0])&&e(o[1])}}function Cw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Dw(t,e){if(!(t&&e))return;let[r,n]=t.split(xp),[o,s]=e.split(xp),i=Sp(r,o);if(i!==void 0)return i||$p(n,s)}var bO=/\/|:/,wO=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function xO(t){return bO.test(t)&&wO.test(t)}var Ew=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function SO(t){return Ew.lastIndex=0,Ew.test(t)}var $O=-(2**31),kO=2**31-1;function PO(t){return Number.isInteger(t)&&t<=kO&&t>=$O}function TO(t){return Number.isInteger(t)}function Rw(){return!0}var EO=/[^\\]\\Z/;function RO(t){if(EO.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ow=E(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.formatLimitDefinition=void 0;var IO=_p(),Et=W(),kr=Et.operators,Ga={formatMaximum:{okStr:"<=",ok:kr.LTE,fail:kr.GT},formatMinimum:{okStr:">=",ok:kr.GTE,fail:kr.LT},formatExclusiveMaximum:{okStr:"<",ok:kr.LT,fail:kr.GTE},formatExclusiveMinimum:{okStr:">",ok:kr.GT,fail:kr.LTE}},AO={message:({keyword:t,schemaCode:e})=>(0,Et.str)`should be ${Ga[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Et._)`{comparison: ${Ga[t].okStr}, limit: ${e}}`};io.formatLimitDefinition={keyword:Object.keys(Ga),type:"string",schemaType:"string",$data:!0,error:AO,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new IO.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,Et._)`${p}[${c.schemaCode}]`);t.fail$data((0,Et.or)((0,Et._)`typeof ${f} != "object"`,(0,Et._)`${f} instanceof RegExp`,(0,Et._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,Et._)`${i.code.formats}${(0,Et.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,Et._)`${p}.compare(${r}, ${n}) ${Ga[o].fail} 0`}},dependencies:["format"]};var CO=t=>(t.addKeyword(io.formatLimitDefinition),t);io.default=CO});var Lw=E((Fs,jw)=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var ao=zw(),DO=Ow(),kp=W(),Mw=new kp.Name("fullFormats"),zO=new kp.Name("fastFormats"),Pp=(t,e={keywords:!0})=>{if(Array.isArray(e))return Nw(t,e,ao.fullFormats,Mw),t;let[r,n]=e.mode==="fast"?[ao.fastFormats,zO]:[ao.fullFormats,Mw],o=e.formats||ao.formatNames;return Nw(t,o,r,n),e.keywords&&(0,DO.default)(t),t};Pp.get=(t,e="full")=>{let n=(e==="fast"?ao.fastFormats:ao.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Nw(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,kp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}jw.exports=Fs=Pp;Object.defineProperty(Fs,"__esModule",{value:!0});Fs.default=Pp});import{readFileSync as Fj}from"fs";import{join as cf}from"path";import{fileURLToPath as Zj}from"url";var mn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Ws=class extends mn{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},de=class extends mn{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var hn=class extends mn{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},Be=class extends mn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var Ef={ollama:{tier:"tool"},"claude-cli":{tier:"agent",maxComplexity:"complex"},"gemini-cli":{tier:"agent",maxComplexity:"complex"},"codex-cli":{tier:"agent",maxComplexity:"complex"},"claude-host":{tier:"agent",maxComplexity:"complex"},"codex-host":{tier:"agent",maxComplexity:"complex"},"gemini-host":{tier:"agent",maxComplexity:"complex"}},QS={ollama:{invocation:"http",roles:["participant","tool"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"claude-cli":{invocation:"cli",roles:["participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"codex-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"claude-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"codex-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0}};function Zc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Gs(t,e,r,n=t){let o=Ef[n]??Ef[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Zc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function ir(t,e){let r=QS[t.type],n=r?.roles?[...r.roles]:["participant"];return{id:t.id,type:t.type,invocation:r?.invocation??"unknown",roles:n,supportsAutonomousExecution:r?.supportsAutonomousExecution??!1,supportsReadOnlyChat:r?.supportsReadOnlyChat??!0,supportsToolUse:e?.supportsToolUse??r?.supportsToolUse??!1}}var Ys={low:0,medium:.5,high:.7},e$={chat:"low",simple_review:"low",code_review:"medium",code_generation:"medium",design:"medium",writing:"medium",analysis:"medium",ideation:"medium",debate_turn:"medium",architecture:"high",cross_validate:"high",complex_refactor:"high"};function Rf(t,e){return e?.[t]??e$[t]??"low"}function Xs(t,e,r=Ys){return t>=r[e]}var Qs=class{providers=new Map;resolveProvider(e){let r=this.providers.get(e);if(r)return r;if(e==="claude")return this.resolveClaudeAlias()}resolveClaudeAlias(){let e,r;for(let n of this.providers.values())n.type==="claude-host"?e=e??n:n.type==="claude-cli"&&(r=r??n);return e??r}register(e){this.providers.set(e.id,e)}get(e){let r=this.resolveProvider(e);if(!r)throw new Ws(e);return r}getAll(){return[...this.providers.values()]}getAvailable(){return this.getAll().filter(e=>e.isAvailable())}getAvailableDescriptors(){return this.getAvailable().map(e=>this.getDescriptor(e.id))}getByCapability(e){return this.getAvailable().filter(r=>r.getCapabilities().strengths.includes(e))}has(e){return this.providers.has(e)}getCapability(e){let r=this.get(e);return Gs(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??ir(r,r.getCapabilities())}getByTier(e){return this.getAvailable().filter(r=>this.getCapability(r.id).tier===e)}getByRole(e){return this.getAvailable().filter(r=>this.getDescriptor(r.id).roles.includes(e))}getBestForTask(e,r,n,o){let s=this.getAvailable();if(s.length===0)return;if(!r)return s[0];let i=n??Rf(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let m=p.split(":")[0],g=c.get(m)??{totalScore:0,count:0};g.totalScore+=f.avgScore*f.count,g.count+=f.count,c.set(m,g)}let u=s.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let m=f.totalScore/f.count;return Xs(m,i,o)});if(u.length===0)return;let l,d=-1;for(let p of u){let f=`${p.id}:${e}`,m=a.get(f);m&&m.avgScore>d&&(d=m.avgScore,l=p)}return l??u[0]}};var h={};Ve(h,{BRAND:()=>P$,DIRTY:()=>Ar,EMPTY_PATH:()=>o$,INVALID:()=>N,NEVER:()=>lk,OK:()=>Ne,ParseStatus:()=>Ie,Schema:()=>V,ZodAny:()=>ur,ZodArray:()=>Kt,ZodBigInt:()=>Dr,ZodBoolean:()=>zr,ZodBranded:()=>xo,ZodCatch:()=>Br,ZodDate:()=>Or,ZodDefault:()=>Vr,ZodDiscriminatedUnion:()=>ri,ZodEffects:()=>dt,ZodEnum:()=>Ur,ZodError:()=>Ye,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>oi,ZodIntersection:()=>Lr,ZodIssueCode:()=>k,ZodLazy:()=>Fr,ZodLiteral:()=>Zr,ZodMap:()=>Pn,ZodNaN:()=>En,ZodNativeEnum:()=>qr,ZodNever:()=>bt,ZodNull:()=>Nr,ZodNullable:()=>zt,ZodNumber:()=>Cr,ZodObject:()=>Xe,ZodOptional:()=>ut,ZodParsedType:()=>R,ZodPipeline:()=>So,ZodPromise:()=>lr,ZodReadonly:()=>Wr,ZodRecord:()=>ni,ZodSchema:()=>V,ZodSet:()=>Tn,ZodString:()=>cr,ZodSymbol:()=>$n,ZodTransformer:()=>dt,ZodTuple:()=>Dt,ZodType:()=>V,ZodUndefined:()=>Mr,ZodUnion:()=>jr,ZodUnknown:()=>Ht,ZodVoid:()=>kn,addIssueToContext:()=>T,any:()=>O$,array:()=>L$,bigint:()=>I$,boolean:()=>Ff,coerce:()=>uk,custom:()=>Nf,date:()=>A$,datetimeRegex:()=>Of,defaultErrorMap:()=>Bt,discriminatedUnion:()=>q$,effect:()=>tk,enum:()=>X$,function:()=>J$,getErrorMap:()=>wn,getParsedType:()=>Ct,instanceof:()=>E$,intersection:()=>V$,isAborted:()=>ei,isAsync:()=>xn,isDirty:()=>ti,isValid:()=>ar,late:()=>T$,lazy:()=>G$,literal:()=>Y$,makeIssue:()=>wo,map:()=>H$,nan:()=>R$,nativeEnum:()=>Q$,never:()=>N$,null:()=>z$,nullable:()=>nk,number:()=>Lf,object:()=>F$,objectUtil:()=>Uc,oboolean:()=>ck,onumber:()=>ak,optional:()=>rk,ostring:()=>ik,pipeline:()=>sk,preprocess:()=>ok,promise:()=>ek,quotelessJson:()=>t$,record:()=>W$,set:()=>K$,setErrorMap:()=>n$,strictObject:()=>Z$,string:()=>jf,symbol:()=>C$,transformer:()=>tk,tuple:()=>B$,undefined:()=>D$,union:()=>U$,unknown:()=>M$,util:()=>G,void:()=>j$});var G;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(G||(G={}));var Uc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Uc||(Uc={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ct=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var k=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),t$=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ye=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ye.create=t=>new Ye(t);var r$=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,G.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${G.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${G.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${G.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:G.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case k.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case k.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,G.assertNever(t)}return{message:r}},Bt=r$;var If=Bt;function n$(t){If=t}function wn(){return If}var wo=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},o$=[];function T(t,e){let r=wn(),n=wo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Bt?void 0:Bt].filter(o=>!!o)});t.common.issues.push(n)}var Ie=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return N;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return N;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},N=Object.freeze({status:"aborted"}),Ar=t=>({status:"dirty",value:t}),Ne=t=>({status:"valid",value:t}),ei=t=>t.status==="aborted",ti=t=>t.status==="dirty",ar=t=>t.status==="valid",xn=t=>typeof Promise<"u"&&t instanceof Promise;var A;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(A||(A={}));var lt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Af=(t,e)=>{if(ar(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ye(t.common.issues);return this._error=r,this._error}}};function Z(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var V=class{get description(){return this._def.description}_getType(e){return Ct(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(xn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Af(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ar(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ar(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(xn(o)?o:Promise.resolve(o));return Af(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:k.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new dt({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ut.create(this,this._def)}nullable(){return zt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return lr.create(this,this._def)}or(e){return jr.create([this,e],this._def)}and(e){return Lr.create(this,e,this._def)}transform(e){return new dt({...Z(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Vr({...Z(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new xo({typeName:P.ZodBranded,type:this,...Z(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Br({...Z(this._def),innerType:this,catchValue:r,typeName:P.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return So.create(this,e)}readonly(){return Wr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},s$=/^c[^\s-]{8,}$/i,i$=/^[0-9a-z]+$/,a$=/^[0-9A-HJKMNP-TV-Z]{26}$/i,c$=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,u$=/^[a-z0-9_-]{21}$/i,l$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,d$=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,p$=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,f$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qc,m$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,h$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,g$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,y$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,v$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Df="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",b$=new RegExp(`^${Df}$`);function zf(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function w$(t){return new RegExp(`^${zf(t)}$`)}function Of(t){let e=`${Df}T${zf(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function x$(t,e){return!!((e==="v4"||!e)&&m$.test(t)||(e==="v6"||!e)&&g$.test(t))}function S$(t,e){if(!l$.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function $$(t,e){return!!((e==="v4"||!e)&&h$.test(t)||(e==="v6"||!e)&&y$.test(t))}var cr=class t extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.string,received:s.parsedType}),N}let n=new Ie,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?T(o,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")p$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")qc||(qc=new RegExp(f$,"u")),qc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")c$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")u$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")s$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")i$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")a$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),T(o,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Of(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?b$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?w$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?d$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?x$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?S$(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?$$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?v$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?_$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):G.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:k.invalid_string,...A.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...A.errToObj(e)})}url(e){return this._addCheck({kind:"url",...A.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...A.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...A.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...A.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...A.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...A.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...A.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...A.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...A.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...A.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...A.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...A.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...A.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...A.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...A.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...A.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...A.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...A.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...A.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...A.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...A.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...A.errToObj(r)})}nonempty(e){return this.min(1,A.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};cr.create=t=>new cr({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...Z(t)});function k$(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Cr=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.number,received:s.parsedType}),N}let n,o=new Ie;for(let s of this._def.checks)s.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?k$(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_finite,message:s.message}),o.dirty()):G.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,A.toString(r))}gt(e,r){return this.setLimit("min",e,!1,A.toString(r))}lte(e,r){return this.setLimit("max",e,!0,A.toString(r))}lt(e,r){return this.setLimit("max",e,!1,A.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:A.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:A.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:A.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Cr.create=t=>new Cr({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...Z(t)});var Dr=class t extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,o=new Ie;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):G.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.bigint,received:r.parsedType}),N}gte(e,r){return this.setLimit("min",e,!0,A.toString(r))}gt(e,r){return this.setLimit("min",e,!1,A.toString(r))}lte(e,r){return this.setLimit("max",e,!0,A.toString(r))}lt(e,r){return this.setLimit("max",e,!1,A.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:A.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Dr.create=t=>new Dr({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...Z(t)});var zr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.boolean,received:n.parsedType}),N}return Ne(e.data)}};zr.create=t=>new zr({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...Z(t)});var Or=class t extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:R.date,received:s.parsedType}),N}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_date}),N}let n=new Ie,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):G.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:A.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:A.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Or.create=t=>new Or({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...Z(t)});var $n=class extends V{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.symbol,received:n.parsedType}),N}return Ne(e.data)}};$n.create=t=>new $n({typeName:P.ZodSymbol,...Z(t)});var Mr=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.undefined,received:n.parsedType}),N}return Ne(e.data)}};Mr.create=t=>new Mr({typeName:P.ZodUndefined,...Z(t)});var Nr=class extends V{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.null,received:n.parsedType}),N}return Ne(e.data)}};Nr.create=t=>new Nr({typeName:P.ZodNull,...Z(t)});var ur=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};ur.create=t=>new ur({typeName:P.ZodAny,...Z(t)});var Ht=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};Ht.create=t=>new Ht({typeName:P.ZodUnknown,...Z(t)});var bt=class extends V{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:R.never,received:r.parsedType}),N}};bt.create=t=>new bt({typeName:P.ZodNever,...Z(t)});var kn=class extends V{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.void,received:n.parsedType}),N}return Ne(e.data)}};kn.create=t=>new kn({typeName:P.ZodVoid,...Z(t)});var Kt=class t extends V{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:k.invalid_type,expected:R.array,received:r.parsedType}),N;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(r,{code:i?k.too_big:k.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(T(r,{code:k.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(T(r,{code:k.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new lt(r,i,r.path,a)))).then(i=>Ie.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new lt(r,i,r.path,a)));return Ie.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:A.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:A.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:A.toString(r)}})}nonempty(e){return this.min(1,e)}};Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...Z(e)});function Sn(t){if(t instanceof Xe){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ut.create(Sn(n))}return new Xe({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:Sn(t.element)}):t instanceof ut?ut.create(Sn(t.unwrap())):t instanceof zt?zt.create(Sn(t.unwrap())):t instanceof Dt?Dt.create(t.items.map(e=>Sn(e))):t}var Xe=class t extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=G.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:k.invalid_type,expected:R.object,received:u.parsedType}),N}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof bt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new lt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof bt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(T(o,{code:k.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new lt(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Ie.mergeObjectSync(n,u)):Ie.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return A.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:A.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:P.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of G.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Sn(this)}partial(e){let r={};for(let n of G.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ut;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Mf(G.objectKeys(this.shape))}};Xe.create=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:P.ZodObject,...Z(e)});Xe.strictCreate=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:P.ZodObject,...Z(e)});Xe.lazycreate=(t,e)=>new Xe({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:P.ZodObject,...Z(e)});var jr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ye(a.ctx.common.issues));return T(r,{code:k.invalid_union,unionErrors:i}),N}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ye(c));return T(r,{code:k.invalid_union,unionErrors:a}),N}}get options(){return this._def.options}};jr.create=(t,e)=>new jr({options:t,typeName:P.ZodUnion,...Z(e)});var Wt=t=>t instanceof Fr?Wt(t.schema):t instanceof dt?Wt(t.innerType()):t instanceof Zr?[t.value]:t instanceof Ur?t.options:t instanceof qr?G.objectValues(t.enum):t instanceof Vr?Wt(t._def.innerType):t instanceof Mr?[void 0]:t instanceof Nr?[null]:t instanceof ut?[void 0,...Wt(t.unwrap())]:t instanceof zt?[null,...Wt(t.unwrap())]:t instanceof xo||t instanceof Wr?Wt(t.unwrap()):t instanceof Br?Wt(t._def.innerType):[],ri=class t extends V{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:k.invalid_type,expected:R.object,received:r.parsedType}),N;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),N)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Wt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:P.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...Z(n)})}};function Vc(t,e){let r=Ct(t),n=Ct(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=G.objectKeys(e),s=G.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Vc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Vc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Lr=class extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ei(s)||ei(i))return N;let a=Vc(s.value,i.value);return a.valid?((ti(s)||ti(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:k.invalid_intersection_types}),N)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Lr.create=(t,e,r)=>new Lr({left:t,right:e,typeName:P.ZodIntersection,...Z(r)});var Dt=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:k.invalid_type,expected:R.array,received:n.parsedType}),N;if(n.data.length<this._def.items.length)return T(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),N;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new lt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ie.mergeArray(r,i)):Ie.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:t,typeName:P.ZodTuple,rest:null,...Z(e)})};var ni=class t extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:k.invalid_type,expected:R.object,received:n.parsedType}),N;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new lt(n,a,n.path,a)),value:i._parse(new lt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ie.mergeObjectAsync(r,o):Ie.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof V?new t({keyType:e,valueType:r,typeName:P.ZodRecord,...Z(n)}):new t({keyType:cr.create(),valueType:e,typeName:P.ZodRecord,...Z(r)})}},Pn=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:k.invalid_type,expected:R.map,received:n.parsedType}),N;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new lt(n,a,n.path,[u,"key"])),value:s._parse(new lt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return N;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return N;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Pn.create=(t,e,r)=>new Pn({valueType:e,keyType:t,typeName:P.ZodMap,...Z(r)});var Tn=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:k.invalid_type,expected:R.set,received:n.parsedType}),N;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:k.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(T(n,{code:k.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return N;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new lt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:A.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:A.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Tn.create=(t,e)=>new Tn({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...Z(e)});var oi=class t extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:k.invalid_type,expected:R.function,received:r.parsedType}),N;function n(a,c){return wo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wn(),Bt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function o(a,c){return wo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wn(),Bt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof lr){let a=this;return Ne(async function(...c){let u=new Ye([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return Ne(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ye([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ye([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Dt.create(e).rest(Ht.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Dt.create([]).rest(Ht.create()),returns:r||Ht.create(),typeName:P.ZodFunction,...Z(n)})}},Fr=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Fr.create=(t,e)=>new Fr({getter:t,typeName:P.ZodLazy,...Z(e)});var Zr=class extends V{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),N}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zr.create=(t,e)=>new Zr({value:t,typeName:P.ZodLiteral,...Z(e)});function Mf(t,e){return new Ur({values:t,typeName:P.ZodEnum,...Z(e)})}var Ur=class t extends V{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:G.joinValues(n),received:r.parsedType,code:k.invalid_type}),N}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:k.invalid_enum_value,options:n}),N}return Ne(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ur.create=Mf;var qr=class extends V{_parse(e){let r=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=G.objectValues(r);return T(n,{expected:G.joinValues(o),received:n.parsedType,code:k.invalid_type}),N}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=G.objectValues(r);return T(n,{received:n.data,code:k.invalid_enum_value,options:o}),N}return Ne(e.data)}get enum(){return this._def.values}};qr.create=(t,e)=>new qr({values:t,typeName:P.ZodNativeEnum,...Z(e)});var lr=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:k.invalid_type,expected:R.promise,received:r.parsedType}),N;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Ne(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};lr.create=(t,e)=>new lr({type:t,typeName:P.ZodPromise,...Z(e)});var dt=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return N;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?N:c.status==="dirty"?Ar(c.value):r.value==="dirty"?Ar(c.value):c});{if(r.value==="aborted")return N;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?N:a.status==="dirty"?Ar(a.value):r.value==="dirty"?Ar(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?N:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?N:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ar(i))return N;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ar(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):N);G.assertNever(o)}};dt.create=(t,e,r)=>new dt({schema:t,typeName:P.ZodEffects,effect:e,...Z(r)});dt.createWithPreprocess=(t,e,r)=>new dt({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...Z(r)});var ut=class extends V{_parse(e){return this._getType(e)===R.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ut.create=(t,e)=>new ut({innerType:t,typeName:P.ZodOptional,...Z(e)});var zt=class extends V{_parse(e){return this._getType(e)===R.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:P.ZodNullable,...Z(e)});var Vr=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Vr.create=(t,e)=>new Vr({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Br=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ye(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Br.create=(t,e)=>new Br({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var En=class extends V{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:R.nan,received:n.parsedType}),N}return{status:"valid",value:e.data}}};En.create=t=>new En({typeName:P.ZodNaN,...Z(t)});var P$=Symbol("zod_brand"),xo=class extends V{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},So=class t extends V{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?N:s.status==="dirty"?(r.dirty(),Ar(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?N:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:P.ZodPipeline})}},Wr=class extends V{_parse(e){let r=this._def.innerType._parse(e),n=o=>(ar(o)&&(o.value=Object.freeze(o.value)),o);return xn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Wr.create=(t,e)=>new Wr({innerType:t,typeName:P.ZodReadonly,...Z(e)});function Cf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Nf(t,e={},r){return t?ur.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Cf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Cf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):ur.create()}var T$={object:Xe.lazycreate},P;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(P||(P={}));var E$=(t,e={message:`Input not instance of ${t.name}`})=>Nf(r=>r instanceof t,e),jf=cr.create,Lf=Cr.create,R$=En.create,I$=Dr.create,Ff=zr.create,A$=Or.create,C$=$n.create,D$=Mr.create,z$=Nr.create,O$=ur.create,M$=Ht.create,N$=bt.create,j$=kn.create,L$=Kt.create,F$=Xe.create,Z$=Xe.strictCreate,U$=jr.create,q$=ri.create,V$=Lr.create,B$=Dt.create,W$=ni.create,H$=Pn.create,K$=Tn.create,J$=oi.create,G$=Fr.create,Y$=Zr.create,X$=Ur.create,Q$=qr.create,ek=lr.create,tk=dt.create,rk=ut.create,nk=zt.create,ok=dt.createWithPreprocess,sk=So.create,ik=()=>jf().optional(),ak=()=>Lf().optional(),ck=()=>Ff().optional(),uk={string:(t=>cr.create({...t,coerce:!0})),number:(t=>Cr.create({...t,coerce:!0})),boolean:(t=>zr.create({...t,coerce:!0})),bigint:(t=>Dr.create({...t,coerce:!0})),date:(t=>Or.create({...t,coerce:!0}))};var lk=N;qt();var dk=h.enum(["read-only","workspace-write","full-auto"]),pk=dk.default("read-only"),fk=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:pk,config:h.record(h.unknown()).default({})}),mk=h.enum(["default-only","auto"]).default("default-only"),hk=h.object({selectionPolicy:mk,locale:h.string().optional(),providers:h.array(fk).min(1,"At least one provider required")});function Jt(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":return"workspace-write";default:return"read-only"}}function si(t){return t==="workspace-write"||t==="full-auto"}function gk(t){return Js.includes(t)}function yk(t){if(t!==void 0)return gk(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${Rr}`),Rr)}function Zf(t){let e=hk.parse(t);return{selectionPolicy:e.selectionPolicy,locale:yk(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{mkdirSync as vk}from"fs";import{homedir as _k}from"os";import{dirname as bk,join as Uf}from"path";var qf="providers.config.json";function $o(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=process.env.CLAUDE_PLUGIN_ROOT;return e&&e.length>0?Uf(e,qf):Uf(_k(),".agestra",qf)}function Vf(t){vk(bk(t),{recursive:!0})}ci();Jc();To();bo();bn();qt();import{mkdirSync as rm,readFileSync as Te,readdirSync as Eo,existsSync as We,unlinkSync as Qk,rmdirSync as e0}from"fs";import{join as X}from"path";import{spawn as nm}from"child_process";import{randomUUID as t0}from"crypto";var r0=5e3,ru=["completed","error","timed_out","cancelled","missing_cli"];function Yt(t,e){let r=X(t,"status.json"),n=`${r}.lock`;Hr(n,()=>{let o=JSON.parse(Te(r,"utf-8"));je(r,{...o,...e})})}var li=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;completionHandler;saveInFlight=new Map;deferredSaveTimers=new Map;constructor(e=process.cwd(),r){this.jobsDir=X(e,pf),rm(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7,this.completionHandler=r?.completionHandler,this.submitCount=this.countExistingJobs()}countExistingJobs(){if(!We(this.jobsDir))return 0;try{return Eo(this.jobsDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).length}catch{return 0}}reconcileOrphans(){let e=0,r;try{r=Eo(this.jobsDir)}catch{return 0}for(let n of r){if(!dr(n))continue;let o=X(this.jobsDir,n,"status.json");if(!We(o))continue;let s;try{s=JSON.parse(Te(o,"utf-8"))}catch{continue}if(s.state!=="running"||s.pid!==void 0&&this.isPidAlive(s.pid))continue;let i=`${o}.lock`;try{let a=Hr(i,()=>{let c=JSON.parse(Te(o,"utf-8"));if(c.state!=="running"||c.pid!==void 0&&this.isPidAlive(c.pid))return null;let u={...c,state:"error",completedAt:new Date().toISOString()};return je(o,u),u});if(!a)continue;oe(X(this.jobsDir,n,"error.txt"),"orphaned (worker process died before completion)"),this.statusCache.set(n,a),e++}catch{}}return e}resolveCreatedAtMs(e){let r=X(this.jobsDir,e,"job.json");try{let o=JSON.parse(Te(r,"utf-8")),s=new Date(o.createdAt).getTime();if(Number.isFinite(s))return s}catch{}let n=e.split("-");for(let o=n.length-2;o>=0;o--)if(/^\d+$/.test(n[o])){let s=Number(n[o]);if(Number.isFinite(s)&&s>0)return s}return null}isPidAlive(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}submit(e){let r=`${e.provider}-${Date.now()}-${t0().slice(0,6)}`,n=X(this.jobsDir,r);rm(n,{recursive:!0});let o=e.timeout??3e5,s={id:r,provider:e.provider,prompt:e.prompt,timeout:o,createdAt:new Date().toISOString(),cwd:process.cwd(),saveAsDocument:e.saveAsDocument},i={id:r,state:"queued",provider:e.provider};if(je(X(n,"job.json"),s),je(X(n,"status.json"),i),oe(X(n,"prompt.txt"),e.prompt),this.statusCache.set(r,i),this.spawnWorker(n),e.saveAsDocument&&this.completionHandler){let a=setTimeout(()=>{this.deferredSaveTimers.delete(r),this.maybeTriggerCompletionSave(r).catch(()=>{})},o+r0);a.unref?.(),this.deferredSaveTimers.set(r,a)}return this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!dr(e))return null;let r=this.statusCache.get(e);if(r&&ru.includes(r.state)&&((r.savedDocumentId?!0:r.saveError!==void 0)||!this.completionHandler))return r;let n=X(this.jobsDir,e,"status.json");if(!We(n))return null;let o=JSON.parse(Te(n,"utf-8"));if(o.state==="queued"){let s=this.resolveCreatedAtMs(e);if(s!==null&&Date.now()-s>6e4){let a=`${n}.lock`;try{let c=Hr(a,()=>{let u=JSON.parse(Te(n,"utf-8"));if(u.state!=="queued")return null;let l={...u,state:"error",completedAt:new Date().toISOString()};return je(n,l),l});if(c)return oe(X(this.jobsDir,e,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(e,c),c}catch{}}}return this.statusCache.set(e,o),ru.includes(o.state)&&!o.savedDocumentId&&!o.saveError&&this.completionHandler&&this.maybeTriggerCompletionSave(e).catch(()=>{}),o}getResult(e){if(!dr(e))return null;let r=this.getStatus(e);if(!r)return null;let n=X(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode,savedDocumentId:r.savedDocumentId,saveError:r.saveError},s=X(n,"output.txt");We(s)&&(o.output=Te(s,"utf-8"));let i=X(n,"error.txt");return We(i)&&(o.error=Te(i,"utf-8")),o}async getResultAwaited(e){return dr(e)?(await this.maybeTriggerCompletionSave(e),this.getResult(e)):null}async maybeTriggerCompletionSave(e){if(!this.completionHandler||!dr(e))return;let r=X(this.jobsDir,e);if(!We(X(r,"status.json")))return;let n=this.saveInFlight.get(e);if(n)return n;let o=this.runCompletionSave(e).finally(()=>{this.saveInFlight.delete(e)});return this.saveInFlight.set(e,o),o}async runCompletionSave(e){if(!this.completionHandler||!dr(e))return;let r=X(this.jobsDir,e),n=X(r,"status.json"),o=X(r,"job.json");if(!We(n)||!We(o))return;let s=JSON.parse(Te(n,"utf-8"));if(!ru.includes(s.state)||s.savedDocumentId||s.saveError)return;let i=JSON.parse(Te(o,"utf-8"));if(!i.saveAsDocument)return;let a={id:e,state:s.state,exitCode:s.exitCode},c=X(r,"output.txt");We(c)&&(a.output=Te(c,"utf-8"));let u=X(r,"error.txt");We(u)&&(a.error=Te(u,"utf-8"));try{let l=await this.completionHandler({jobId:e,descriptor:i,result:a,saveAsDocument:i.saveAsDocument});if(l){let d={savedDocumentId:l.documentId};Yt(r,d),this.statusCache.set(e,{...s,...d})}else{let d={saveError:"skipped"};Yt(r,d),this.statusCache.set(e,{...s,...d})}}catch(l){let p={saveError:l instanceof Error?l.message:String(l)};try{Yt(r,p),this.statusCache.set(e,{...s,...p})}catch{}}}listJobs(){if(!We(this.jobsDir))return[];let e;try{e=Eo(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory())}catch{return[]}let r=[];for(let n of e)try{let o=X(this.jobsDir,n.name,"status.json");We(o)&&r.push(JSON.parse(Te(o,"utf-8")))}catch{}return r}cancel(e){if(!dr(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&vn(r.pid);let n=X(this.jobsDir,e),o=X(n,"status.json"),s=`${o}.lock`;try{let i=Hr(s,()=>{let a=JSON.parse(Te(o,"utf-8"));if(a.state!=="queued"&&a.state!=="running")return null;let c={...a,state:"cancelled",completedAt:new Date().toISOString()};return je(o,c),c});i&&this.statusCache.set(e,i)}catch{}return this.clearDeferredSaveTimer(e),!0}clearDeferredSaveTimer(e){let r=this.deferredSaveTimers.get(e);r&&(clearTimeout(r),this.deferredSaveTimers.delete(e))}shutdown(){for(let e of this.deferredSaveTimers.values())clearTimeout(e);this.deferredSaveTimers.clear()}cleanup(){if(!We(this.jobsDir))return 0;let e;try{e=Eo(this.jobsDir,{withFileTypes:!0}).filter(u=>u.isDirectory())}catch{return 0}let r=[];for(let u of e)try{let l=X(this.jobsDir,u.name,"status.json"),d=X(this.jobsDir,u.name,"job.json");if(!We(l))continue;let p=JSON.parse(Te(l,"utf-8")),f=null;try{f=JSON.parse(Te(d,"utf-8"))}catch{}r.push({name:u.name,status:p,descriptor:f})}catch{}let n=["completed","error","timed_out","cancelled","missing_cli"],o=r.filter(u=>n.includes(u.status.state)).sort((u,l)=>{let d=u.descriptor?.createdAt??"",p=l.descriptor?.createdAt??"";return d.localeCompare(p)}),s=0,i=Date.now(),a=this.maxAgeDays*24*60*60*1e3,c=r.length;for(let u of o){let d=(u.descriptor?.createdAt?i-new Date(u.descriptor.createdAt).getTime():1/0)>a,p=c-s>this.maxJobs;if(!d&&!p)continue;let f=X(this.jobsDir,u.name);try{let m=Eo(f);for(let g of m)Qk(X(f,g));e0(f),this.statusCache.delete(u.name),this.clearDeferredSaveTimer(u.name),s++}catch{}}return s}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(We(r)){let n=nm(process.execPath,[r,e],{detached:!0,stdio:"ignore"}),o=typeof n.pid=="number"&&n.pid>0;if(o)try{Yt(e,{pid:n.pid})}catch{}n.on("error",s=>{if(o)return;s.code==="ENOENT"?this.runInProcess(e):this.runInProcess(e)}),n.unref()}else this.runInProcess(e)}runInProcess(e){Promise.resolve().then(()=>(tm(),em)).then(({resolveCliConfig:r})=>{let n;try{n=JSON.parse(Te(X(e,"job.json"),"utf-8"))}catch{return}let o=r(n);if(!o){Yt(e,{state:"missing_cli",completedAt:new Date().toISOString()}),oe(X(e,"error.txt"),`No CLI mapping for provider: ${n.provider}`);return}let{command:s,buildArgs:i}=o,a=Te(X(e,"prompt.txt"),"utf-8"),c=i(a);Yt(e,{state:"running",startedAt:new Date().toISOString()});let u=Vt(s,c),l=nm(u.command,u.args,{cwd:n.cwd||void 0,stdio:["ignore","pipe","pipe"],windowsHide:!0});if(!l.stdout||!l.stderr){try{l.kill()}catch{}oe(X(e,"error.txt"),"Worker stdout/stderr streams unavailable (pipe allocation failed)"),Yt(e,{state:"error",completedAt:new Date().toISOString()});return}let d="",p="",f=0,m=0,g=!1,v=!1;l.stdout.on("data",y=>{f+=y.length,f<=10485760?d+=y.toString():g||(g=!0,At(l))}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let _=(y,x)=>{if(!v){v=!0,clearTimeout(S);try{oe(X(e,"output.txt"),d),x!==void 0?oe(X(e,"error.txt"),x):oe(X(e,"error.txt"),p),Yt(e,y)}catch{}}},S=setTimeout(()=>{v||(At(l),_({state:"timed_out",completedAt:new Date().toISOString()}))},n.timeout);l.on("close",y=>{if(v)return;let x=d.trim().length>0;_({state:y===0||x?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()})}),l.on("error",y=>{if(v)return;let x=y.code==="ENOENT"?"missing_cli":"error";_({state:x,completedAt:new Date().toISOString()},y.message)})}).catch(()=>{try{Yt(e,{state:"error",completedAt:new Date().toISOString()}),oe(X(e,"error.txt"),"Failed to load job worker module")}catch{}})}};ci();qt();import{mkdirSync as n0,readdirSync as om,readFileSync as o0,unlinkSync as s0}from"fs";import{join as Ro}from"path";function sm(t){let e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}function i0(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function a0(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var di=class{tracesDir;writer;constructor(e,r){this.tracesDir=Ro(e,ff),n0(this.tracesDir,{recursive:!0}),this.writer=new ii(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=sm(new Date(r.timestamp)),o=Ro(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
13
- `,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],o=[];for(let i of r){let a=o0(i,"utf-8").split(`
14
- `).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);a0(u)?o.push(u):i0(u)&&n.push(u)}catch{}}for(let i of o){let a=n.find(c=>c.traceId===i.traceId&&c.providerId===i.providerId);a&&(a.quality=i.quality)}let s=n;return e.providerId&&(s=s.filter(i=>i.providerId===e.providerId)),e.task&&(s=s.filter(i=>i.task===e.task)),e.traceId&&(s=s.filter(i=>i.traceId===e.traceId)),e.successOnly&&(s=s.filter(i=>i.response.success)),e.failedOnly&&(s=s.filter(i=>!i.response.success)),e.limit!==void 0&&(s=s.slice(0,e.limit)),s}updateQuality(e,r,n){let o=new Date,s={type:"quality_update",traceId:e,providerId:r,timestamp:o.toISOString(),quality:n},i=sm(o),a=Ro(this.tracesDir,`${i}.jsonl`);this.writer.append(a,JSON.stringify(s)+`
15
- `,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let s of r){if(!s.quality)continue;let i=`${s.providerId}:${s.task}`,a=n.get(i)??{totalScore:0,count:0,totalLatency:0};a.totalScore+=s.quality.score,a.count+=1,a.totalLatency+=s.latencyMs,n.set(i,a)}let o=new Map;for(let[s,i]of n)o.set(s,{avgScore:i.totalScore/i.count,count:i.count,avgLatencyMs:i.totalLatency/i.count});return o}cleanup(e){let r=new Date;r.setDate(r.getDate()-e);let n=0,o;try{o=om(this.tracesDir)}catch{return 0}for(let s of o){if(!s.endsWith(".jsonl"))continue;let i=s.replace(".jsonl",""),a=new Date(i+"T00:00:00.000Z");isNaN(a.getTime())||a<r&&(s0(Ro(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=om(this.tracesDir).filter(n=>n.endsWith(".jsonl")).sort()}catch{return[]}if(e!==void 0){let n=new Date;n.setDate(n.getDate()-e),r=r.filter(o=>{let s=o.replace(".jsonl",""),i=new Date(s+"T00:00:00.000Z");return!isNaN(i.getTime())&&i>=n})}return r.map(n=>Ro(this.tracesDir,n))}};var c0=/[;|&`$(){}!><\n\r\\]/,pi=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),u0=new Set(["rm","sudo","chmod","chown","mkfs","dd","curl","wget","kill","pkill","killall","mv","cp","sh","bash","zsh","python","perl","ruby","node","npm","npx","eval","exec","source"]);function im(t){if(c0.test(t))return{valid:!1,error:"Command contains shell metacharacters (piping, chaining, or subshell operators are not allowed)"};let e=t.split(/\s+/).filter(Boolean);if(e.length===0)return{valid:!1,error:"Empty command"};if(e[0].includes("/")||e[0].includes("\\"))return{valid:!1,error:"Command must not contain path separators (use bare command names only)"};for(let n=1;n<e.length;n++)if(e[n].includes("/")||e[n].includes("\\"))return{valid:!1,error:`Argument must not contain path separators: ${JSON.stringify(e[n])}`};let r=e[0];if(!pi.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...pi].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(u0.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}qt();var am=[{type:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/,description:"AWS Access Key ID"},{type:"private_key",regex:/-----BEGIN\s+(RSA|EC|DSA|OPENSSH)?\s*PRIVATE KEY-----/,description:"Private key header"},{type:"password_assignment",regex:/(?:password|passwd|pwd)\s*[:=]\s*["']?[^\s"',;]{4,}["']?/i,description:"Password assignment"},{type:"api_key_assignment",regex:/(?:api[_-]?key|apikey|secret[_-]?key)\s*[:=]\s*["']?[^\s"',;]{8,}["']?/i,description:"API key assignment"},{type:"bearer_token",regex:/Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/,description:"Bearer JWT token"},{type:"generic_secret",regex:/(?:token|secret|credential)\s*[:=]\s*["'][^"']{8,}["']/i,description:"Generic secret assignment"}],cm=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function um(t){let e=Array.isArray(t)?t:t.split(`
16
- `),r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let s of am){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!cm.some(u=>u.test(a))){r.push({type:s.type,pattern:s.description,line:n+1,excerpt:o.length>80?o.slice(0,80)+"...":o});break}}}return{clean:r.length===0,findings:r}}function nu(t){if(t.length===0)return t;let e=t.split(`
17
- `);for(let r=0;r<e.length;r++){let n=e[r];for(let o of am){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>cm.some(a=>a.test(i))?i:Pf)}e[r]=n}return e.join(`
18
- `)}qt();import{execFileSync as l0}from"child_process";import{existsSync as lm,rmSync as d0,mkdirSync as p0}from"fs";import{join as dm}from"path";var fi=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=dm(e,mf)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=dm(this.worktreeBaseDir,r);p0(this.worktreeBaseDir,{recursive:!0}),lm(o)&&this.forceRemoveWorktree(o),this.gitSafe(["branch","-D",n]),this.git(["worktree","add","-b",n,o,"HEAD"]);let s={id:e,path:o,branch:n};return this.worktrees.set(e,s),s}remove(e){let r=this.worktrees.get(e);r&&(this.forceRemoveWorktree(r.path),this.gitSafe(["branch","-D",r.branch]),this.worktrees.delete(e))}get(e){return this.worktrees.get(e)}list(){return[...this.worktrees.values()]}listOrphans(){let e=this.gitSafe(["worktree","list","--porcelain"]);if(!e)return[];let r=[],n="",o="",s=()=>{n.includes(".agestra/worktrees")&&o.startsWith("agestra-worker/")&&([...this.worktrees.values()].some(a=>a.path===n)||r.push({path:n,branch:o})),n="",o=""};for(let i of e.split(`
19
- `))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?o=i.slice(18):i===""&&s();return n&&s(),r}cleanOrphans(){let e=this.listOrphans(),r=0;for(let n of e)this.forceRemoveWorktree(n.path),this.gitSafe(["branch","-D",n.branch]),r++;return r}forceRemoveWorktree(e){this.gitSafe(["worktree","remove",e])===null&&this.gitSafe(["worktree","remove","--force",e])===null&&(lm(e)&&d0(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return l0("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var f0=["npm","node","git","tsc"];function pm(t){return{task:t.taskDescription,files:{readonly:t.filesToRead??[],readwrite:t.filesToModify??[]},constraints:t.constraints,success_criteria:t.successCriteria??[],permissions:{sandbox_root:t.workingDir,allowed_commands:[...f0]},timeout_minutes:t.timeoutMinutes??10}}function fm(t){let e=[];return(!t.task||t.task.trim().length===0)&&e.push("task must not be empty"),(!t.permissions.sandbox_root||t.permissions.sandbox_root.trim().length===0)&&e.push("permissions.sandbox_root must not be empty"),t.timeout_minutes<=0&&e.push("timeout_minutes must be positive"),{valid:e.length===0,errors:e}}var $e;(function(t){t.SPAWNING="SPAWNING",t.RUNNING="RUNNING",t.COLLECTING="COLLECTING",t.COMPLETED="COMPLETED",t.FAILED="FAILED",t.CANCELLING="CANCELLING",t.CANCELLED="CANCELLED",t.TIMEOUT="TIMEOUT"})($e||($e={}));var mi=10,ou=2e4;import{spawn as _0}from"child_process";import{writeFileSync as iu,mkdirSync as b0,readFileSync as ym,existsSync as vm}from"fs";import{isAbsolute as _m,join as Io,resolve as bm}from"path";import{randomBytes as w0}from"crypto";import{execFileSync as x0}from"child_process";qt();bn();bo();To();To();import{readFileSync as mm}from"fs";var su=class{builders=new Map;register(e,r){this.builders.set(e,r)}has(e){return this.builders.has(e)}build(e,r,n,o){let s=this.builders.get(e);if(!s){let i=[...this.builders.keys()];throw new Error(`No CLI launch builder registered for provider "${e}". Known: [${i.join(", ")}]`)}return s(r,n,o)}knownProviders(){return[...this.builders.keys()]}};function m0(t,e,r){let n=hm(t,e,r);return{command:"codex",args:["exec","--skip-git-repo-check","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function h0(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",hm(t,e,r)]}}function hm(t,e,r){let n=mm(t,"utf-8"),o=g0(r,e);return["You are an autonomous coding worker operating in the current workspace.","Execute the task manifest below without asking for confirmation.","Stay within the workspace, respect read-only vs read-write boundaries, and summarize changes plus verification at the end.","",n,o].join(`
20
- `)}function gm(){let t=new su;return t.register("codex",m0),t.register("gemini",h0),t}function g0(t,e){if(!t||t.length===0)return"";let r=t.filter(o=>!Qc(o,e));if(r.length===0)return"";let n=["Read-only file snapshots:","These files may live outside the worker sandbox root. Use the embedded contents below as authoritative context and do not attempt to edit them.",""];for(let o of r.slice(0,mi))try{let s=mm(o,"utf-8"),i=s.length>ou?`${s.slice(0,ou)}
12
+ deps: ${r}}`};var lz={keyword:"dependencies",type:"object",schemaType:"object",error:Zt.error,code(t){let[e,r]=dz(t);Yb(t,e),Xb(t,r)}};function dz({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 Yb(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,Fs.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,Fs.checkReportMissingProp)(t,u)}):(r.if((0,ep._)`${c} && (${(0,Fs.checkMissingProp)(t,a,s)})`),(0,Fs.reportMissingProp)(t,s),r.else())}}Zt.validatePropertyDeps=Yb;function Xb(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,uz.alwaysValidSchema)(s,e[a])||(r.if((0,Fs.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))}Zt.validateSchemaDeps=Xb;Zt.default=lz});var tw=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var ew=H(),pz=ie(),fz={message:"property name must be valid",params:({params:t})=>(0,ew._)`{propertyName: ${t.propertyName}}`},mz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fz,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,pz.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,ew.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};tp.default=mz});var np=E(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var qa=gt(),Tt=H(),hz=rr(),Va=ie(),gz={message:"must NOT have additional properties",params:({params:t})=>(0,Tt._)`{additionalProperty: ${t.additionalProperty}}`},yz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gz,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Va.alwaysValidSchema)(i,r))return;let u=(0,qa.allSchemaProperties)(n.properties),l=(0,qa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Tt._)`${s} === ${hz.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 S=(0,Va.schemaRefOrVal)(i,n.properties,"properties");v=(0,qa.isOwnProperty)(e,S,y)}else u.length?v=(0,Tt.or)(...u.map(S=>(0,Tt._)`${y} === ${S}`)):v=Tt.nil;return l.length&&(v=(0,Tt.or)(v,...l.map(S=>(0,Tt._)`${(0,qa.usePattern)(t,S)}.test(${y})`))),(0,Tt.not)(v)}function f(y){e.code((0,Tt._)`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,Va.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(g(y,v,!1),e.if((0,Tt.not)(v),()=>{t.reset(),f(y)})):(g(y,v),a||e.if((0,Tt.not)(v),()=>e.break()))}}function g(y,v,S){let w={keyword:"additionalProperties",dataProp:y,dataPropType:Va.Type.Str};S===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,v)}}};rp.default=yz});var ow=E(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var vz=Ps(),rw=gt(),op=ie(),nw=np(),_z={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&&nw.default.code(new vz.KeywordCxt(s,nw.default,"additionalProperties"));let i=(0,rw.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=op.mergeEvaluated.props(e,(0,op.toHash)(i),s.props));let a=i.filter(d=>!(0,op.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,rw.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)}}};sp.default=_z});var cw=E(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var sw=gt(),Ba=H(),iw=ie(),aw=ie(),bz={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,sw.allSchemaProperties)(r),c=a.filter(g=>(0,iw.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ba.Name)&&(s.props=(0,aw.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,iw.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,y=>{e.if((0,Ba._)`${(0,sw.usePattern)(t,g)}.test(${y})`,()=>{let v=c.includes(g);v||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:aw.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ba._)`${d}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Ba.not)(l),()=>e.break())})})}}};ip.default=bz});var uw=E(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var wz=ie(),xz={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,wz.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"}};ap.default=xz});var lw=E(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var Sz=gt(),$z={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Sz.validateUnion,error:{message:"must match a schema in anyOf"}};cp.default=$z});var dw=E(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});var Wa=H(),kz=ie(),Pz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Wa._)`{passingSchemas: ${t.passing}}`},Tz={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Pz,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,kz.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Wa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Wa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Wa.Name)})})}}};up.default=Tz});var pw=E(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});var Ez=ie(),Rz={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,Ez.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};lp.default=Rz});var hw=E(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});var Ha=H(),mw=ie(),Iz={message:({params:t})=>(0,Ha.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ha._)`{failingKeyword: ${t.ifClause}}`},Az={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Iz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,mw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=fw(n,"then"),s=fw(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ha.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Ha._)`${l}`):t.setParams({ifClause:l})}}}};function fw(t,e){let r=t.schema[e];return r!==void 0&&!(0,mw.alwaysValidSchema)(t,r)}dp.default=Az});var gw=E(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});var Cz=ie(),Dz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Cz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};pp.default=Dz});var yw=E(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var zz=Gd(),Oz=Hb(),Mz=Jd(),Nz=Gb(),jz=Jb(),Lz=Qb(),Fz=tw(),Zz=np(),Uz=ow(),qz=cw(),Vz=uw(),Bz=lw(),Wz=dw(),Hz=pw(),Kz=hw(),Gz=gw();function Jz(t=!1){let e=[Vz.default,Bz.default,Wz.default,Hz.default,Kz.default,Gz.default,Fz.default,Zz.default,Lz.default,Uz.default,qz.default];return t?e.push(Oz.default,Nz.default):e.push(zz.default,Mz.default),e.push(jz.default),e}fp.default=Jz});var vw=E(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var Pe=H(),Yz={message:({schemaCode:t})=>(0,Pe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Pe._)`{format: ${t}}`},Xz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Yz,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,Pe._)`${m}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,Pe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,Pe._)`${g}.type || "string"`).assign(v,(0,Pe._)`${g}.validate`),()=>r.assign(y,(0,Pe._)`"string"`).assign(v,g)),t.fail$data((0,Pe.or)(S(),w()));function S(){return c.strictSchema===!1?Pe.nil:(0,Pe._)`${i} && !${v}`}function w(){let _=l.$async?(0,Pe._)`(${g}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Pe._)`${v}(${n})`,P=(0,Pe._)`(typeof ${v} == "function" ? ${_} : ${v}.test(${n}))`;return(0,Pe._)`${v} && ${v} !== true && ${y} === ${e} && !${P}`}}function f(){let m=d.formats[s];if(!m){S();return}if(m===!0)return;let[g,y,v]=w(m);g===e&&t.pass(_());function S(){if(c.strictSchema===!1){d.logger.warn(P());return}throw new Error(P());function P(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(P){let A=P instanceof RegExp?(0,Pe.regexpCode)(P):c.code.formats?(0,Pe._)`${c.code.formats}${(0,Pe.getProperty)(s)}`:void 0,D=r.scopeValue("formats",{key:s,ref:P,code:A});return typeof P=="object"&&!(P instanceof RegExp)?[P.type||"string",P.validate,(0,Pe._)`${D}.validate`]:["string",P,D]}function _(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Pe._)`await ${v}(${n})`}return typeof y=="function"?(0,Pe._)`${v}(${n})`:(0,Pe._)`${v}.test(${n})`}}}};mp.default=Xz});var _w=E(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var Qz=vw(),eO=[Qz.default];hp.default=eO});var bw=E(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.contentVocabulary=ro.metadataVocabulary=void 0;ro.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ro.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var xw=E(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});var tO=Rb(),rO=qb(),nO=yw(),oO=_w(),ww=bw(),sO=[tO.default,rO.default,(0,nO.default)(),oO.default,ww.metadataVocabulary,ww.contentVocabulary];gp.default=sO});var $w=E(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.DiscrError=void 0;var Sw;(function(t){t.Tag="tag",t.Mapping="mapping"})(Sw||(Ka.DiscrError=Sw={}))});var Pw=E(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var no=H(),yp=$w(),kw=Ra(),iO=Ts(),aO=ie(),cO={message:({params:{discrError:t,tagName:e}})=>t===yp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,no._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},uO={keyword:"discriminator",type:"object",schemaType:"object",error:cO,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,no._)`${r}${(0,no.getProperty)(a)}`);e.if((0,no._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:yp.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,no._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:yp.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(g,no.Name),m}function p(){var f;let m={},g=v(o),y=!0;for(let _=0;_<i.length;_++){let P=i[_];if(P?.$ref&&!(0,aO.schemaHasRulesButRef)(P,s.self.RULES)){let D=P.$ref;if(P=kw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,D),P instanceof kw.SchemaEnv&&(P=P.schema),P===void 0)throw new iO.default(s.opts.uriResolver,s.baseId,D)}let A=(f=P?.properties)===null||f===void 0?void 0:f[a];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||v(P)),S(A,_)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:_}){return Array.isArray(_)&&_.includes(a)}function S(_,P){if(_.const)w(_.const,P);else if(_.enum)for(let A of _.enum)w(A,P);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(_,P){if(typeof _!="string"||_ in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[_]=P}}}};vp.default=uO});var Tw=E((p2,lO)=>{lO.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 bp=E((ye,_p)=>{"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 dO=Sb(),pO=xw(),fO=Pw(),Ew=Tw(),mO=["/properties"],Ga="http://json-schema.org/draft-07/schema",oo=class extends dO.default{_addVocabularies(){super._addVocabularies(),pO.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(fO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ew,mO):Ew;this.addMetaSchema(e,Ga,!1),this.refs["http://json-schema.org/schema"]=Ga}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ga)?Ga:void 0)}};ye.Ajv=oo;_p.exports=ye=oo;_p.exports.Ajv=oo;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=oo;var hO=Ps();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return hO.KeywordCxt}});var so=H();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return so._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return so.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return so.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return so.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return so.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return so.CodeGen}});var gO=Ta();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return gO.default}});var yO=Ts();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return yO.default}})});var Mw=E(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.formatNames=qt.fastFormats=qt.fullFormats=void 0;function Ut(t,e){return{validate:t,compare:e}}qt.fullFormats={date:Ut(Cw,$p),time:Ut(xp(!0),kp),"date-time":Ut(Rw(!0),zw),"iso-time":Ut(xp(),Dw),"iso-date-time":Ut(Rw(),Ow),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:SO,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:IO,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:$O,int32:{type:"number",validate:TO},int64:{type:"number",validate:EO},float:{type:"number",validate:Aw},double:{type:"number",validate:Aw},password:!0,binary:!0};qt.fastFormats={...qt.fullFormats,date:Ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,$p),time:Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,kp),"date-time":Ut(/^\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,zw),"iso-time":Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Dw),"iso-date-time":Ut(/^\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,Ow),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};qt.formatNames=Object.keys(qt.fullFormats);function vO(t){return t%4===0&&(t%100!==0||t%400===0)}var _O=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bO=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Cw(t){let e=_O.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&&vO(r)?29:bO[n])}function $p(t,e){if(t&&e)return t>e?1:t<e?-1:0}var wp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function xp(t){return function(r){let n=wp.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 kp(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 Dw(t,e){if(!(t&&e))return;let r=wp.exec(t),n=wp.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 Sp=/t|\s/i;function Rw(t){let e=xp(t);return function(n){let o=n.split(Sp);return o.length===2&&Cw(o[0])&&e(o[1])}}function zw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Ow(t,e){if(!(t&&e))return;let[r,n]=t.split(Sp),[o,s]=e.split(Sp),i=$p(r,o);if(i!==void 0)return i||kp(n,s)}var wO=/\/|:/,xO=/^(?:[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 SO(t){return wO.test(t)&&xO.test(t)}var Iw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function $O(t){return Iw.lastIndex=0,Iw.test(t)}var kO=-(2**31),PO=2**31-1;function TO(t){return Number.isInteger(t)&&t<=PO&&t>=kO}function EO(t){return Number.isInteger(t)}function Aw(){return!0}var RO=/[^\\]\\Z/;function IO(t){if(RO.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Nw=E(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.formatLimitDefinition=void 0;var AO=bp(),Et=H(),kr=Et.operators,Ja={formatMaximum:{okStr:"<=",ok:kr.LTE,fail:kr.GT},formatMinimum:{okStr:">=",ok:kr.GTE,fail:kr.LT},formatExclusiveMaximum:{okStr:"<",ok:kr.LT,fail:kr.GTE},formatExclusiveMinimum:{okStr:">",ok:kr.GT,fail:kr.LTE}},CO={message:({keyword:t,schemaCode:e})=>(0,Et.str)`should be ${Ja[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Et._)`{comparison: ${Ja[t].okStr}, limit: ${e}}`};io.formatLimitDefinition={keyword:Object.keys(Ja),type:"string",schemaType:"string",$data:!0,error:CO,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new AO.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,Et._)`${p}[${c.schemaCode}]`);t.fail$data((0,Et.or)((0,Et._)`typeof ${f} != "object"`,(0,Et._)`${f} instanceof RegExp`,(0,Et._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,Et._)`${i.code.formats}${(0,Et.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,Et._)`${p}.compare(${r}, ${n}) ${Ja[o].fail} 0`}},dependencies:["format"]};var DO=t=>(t.addKeyword(io.formatLimitDefinition),t);io.default=DO});var Zw=E((Zs,Fw)=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var ao=Mw(),zO=Nw(),Pp=H(),jw=new Pp.Name("fullFormats"),OO=new Pp.Name("fastFormats"),Tp=(t,e={keywords:!0})=>{if(Array.isArray(e))return Lw(t,e,ao.fullFormats,jw),t;let[r,n]=e.mode==="fast"?[ao.fastFormats,OO]:[ao.fullFormats,jw],o=e.formats||ao.formatNames;return Lw(t,o,r,n),e.keywords&&(0,zO.default)(t),t};Tp.get=(t,e="full")=>{let n=(e==="fast"?ao.fastFormats:ao.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Lw(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Pp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Fw.exports=Zs=Tp;Object.defineProperty(Zs,"__esModule",{value:!0});Zs.default=Tp});import{readFileSync as Vj}from"fs";import{join as uf}from"path";import{fileURLToPath as Bj}from"url";var mn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Ws=class extends mn{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},de=class extends mn{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var hn=class extends mn{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},We=class extends mn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var If={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"}},e$={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 Uc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Js(t,e,r,n=t){let o=If[n]??If[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Uc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function ir(t,e){let r=e$[t.type],n=r?.roles?[...r.roles]:["participant"];return{id:t.id,type:t.type,invocation:r?.invocation??"unknown",roles:n,supportsAutonomousExecution:r?.supportsAutonomousExecution??!1,supportsReadOnlyChat:r?.supportsReadOnlyChat??!0,supportsToolUse:e?.supportsToolUse??r?.supportsToolUse??!1}}var Ys={low:0,medium:.5,high:.7},t$={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 Af(t,e){return e?.[t]??t$[t]??"low"}function Xs(t,e,r=Ys){return t>=r[e]}var Qs=class{providers=new Map;resolveProvider(e){let r=this.providers.get(e);if(r)return r;if(e==="claude")return this.resolveClaudeAlias()}resolveClaudeAlias(){let e,r;for(let n of this.providers.values())n.type==="claude-host"?e=e??n:n.type==="claude-cli"&&(r=r??n);return e??r}register(e){this.providers.set(e.id,e)}get(e){let r=this.resolveProvider(e);if(!r)throw new Ws(e);return r}getAll(){return[...this.providers.values()]}getAvailable(){return this.getAll().filter(e=>e.isAvailable())}getAvailableDescriptors(){return this.getAvailable().map(e=>this.getDescriptor(e.id))}getByCapability(e){return this.getAvailable().filter(r=>r.getCapabilities().strengths.includes(e))}has(e){return this.providers.has(e)}getCapability(e){let r=this.get(e);return Js(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??ir(r,r.getCapabilities())}getByTier(e){return this.getAvailable().filter(r=>this.getCapability(r.id).tier===e)}getByRole(e){return this.getAvailable().filter(r=>this.getDescriptor(r.id).roles.includes(e))}getBestForTask(e,r,n,o){let s=this.getAvailable();if(s.length===0)return;if(!r)return s[0];let i=n??Af(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let m=p.split(":")[0],g=c.get(m)??{totalScore:0,count:0};g.totalScore+=f.avgScore*f.count,g.count+=f.count,c.set(m,g)}let u=s.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let m=f.totalScore/f.count;return Xs(m,i,o)});if(u.length===0)return;let l,d=-1;for(let p of u){let f=`${p.id}:${e}`,m=a.get(f);m&&m.avgScore>d&&(d=m.avgScore,l=p)}return l??u[0]}};var h={};Be(h,{BRAND:()=>T$,DIRTY:()=>Ir,EMPTY_PATH:()=>s$,INVALID:()=>N,NEVER:()=>dk,OK:()=>Ne,ParseStatus:()=>Ie,Schema:()=>B,ZodAny:()=>ur,ZodArray:()=>Gt,ZodBigInt:()=>Cr,ZodBoolean:()=>Dr,ZodBranded:()=>So,ZodCatch:()=>Vr,ZodDate:()=>zr,ZodDefault:()=>qr,ZodDiscriminatedUnion:()=>ri,ZodEffects:()=>lt,ZodEnum:()=>Zr,ZodError:()=>Ye,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>oi,ZodIntersection:()=>jr,ZodIssueCode:()=>$,ZodLazy:()=>Lr,ZodLiteral:()=>Fr,ZodMap:()=>Pn,ZodNaN:()=>En,ZodNativeEnum:()=>Ur,ZodNever:()=>bt,ZodNull:()=>Mr,ZodNullable:()=>zt,ZodNumber:()=>Ar,ZodObject:()=>Xe,ZodOptional:()=>ct,ZodParsedType:()=>R,ZodPipeline:()=>$o,ZodPromise:()=>lr,ZodReadonly:()=>Br,ZodRecord:()=>ni,ZodSchema:()=>B,ZodSet:()=>Tn,ZodString:()=>cr,ZodSymbol:()=>$n,ZodTransformer:()=>lt,ZodTuple:()=>Dt,ZodType:()=>B,ZodUndefined:()=>Or,ZodUnion:()=>Nr,ZodUnknown:()=>Kt,ZodVoid:()=>kn,addIssueToContext:()=>T,any:()=>M$,array:()=>F$,bigint:()=>A$,boolean:()=>Uf,coerce:()=>lk,custom:()=>Lf,date:()=>C$,datetimeRegex:()=>Nf,defaultErrorMap:()=>Wt,discriminatedUnion:()=>V$,effect:()=>rk,enum:()=>Q$,function:()=>J$,getErrorMap:()=>wn,getParsedType:()=>Ct,instanceof:()=>R$,intersection:()=>B$,isAborted:()=>ei,isAsync:()=>xn,isDirty:()=>ti,isValid:()=>ar,late:()=>E$,lazy:()=>Y$,literal:()=>X$,makeIssue:()=>xo,map:()=>K$,nan:()=>I$,nativeEnum:()=>ek,never:()=>j$,null:()=>O$,nullable:()=>ok,number:()=>Zf,object:()=>Z$,objectUtil:()=>qc,oboolean:()=>uk,onumber:()=>ck,optional:()=>nk,ostring:()=>ak,pipeline:()=>ik,preprocess:()=>sk,promise:()=>tk,quotelessJson:()=>r$,record:()=>H$,set:()=>G$,setErrorMap:()=>o$,strictObject:()=>U$,string:()=>Ff,symbol:()=>D$,transformer:()=>rk,tuple:()=>W$,undefined:()=>z$,union:()=>q$,unknown:()=>N$,util:()=>Y,void:()=>L$});var Y;(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})(Y||(Y={}));var qc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(qc||(qc={}));var R=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ct=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var $=Y.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),r$=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ye=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ye.create=t=>new Ye(t);var n$=(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,Y.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${Y.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}"`:Y.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,Y.assertNever(t)}return{message:r}},Wt=n$;var Cf=Wt;function o$(t){Cf=t}function wn(){return Cf}var xo=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}},s$=[];function T(t,e){let r=wn(),n=xo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Wt?void 0:Wt].filter(o=>!!o)});t.common.issues.push(n)}var Ie=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return N;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return N;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},N=Object.freeze({status:"aborted"}),Ir=t=>({status:"dirty",value:t}),Ne=t=>({status:"valid",value:t}),ei=t=>t.status==="aborted",ti=t=>t.status==="dirty",ar=t=>t.status==="valid",xn=t=>typeof Promise<"u"&&t instanceof Promise;var C;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(C||(C={}));var ut=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}},Df=(t,e)=>{if(ar(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ye(t.common.issues);return this._error=r,this._error}}};function Z(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var B=class{get description(){return this._def.description}_getType(e){return Ct(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(xn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Df(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ar(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ar(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(xn(o)?o:Promise.resolve(o));return Df(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 lt({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 ct.create(this,this._def)}nullable(){return zt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gt.create(this)}promise(){return lr.create(this,this._def)}or(e){return Nr.create([this,e],this._def)}and(e){return jr.create(this,e,this._def)}transform(e){return new lt({...Z(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new qr({...Z(this._def),innerType:this,defaultValue:r,typeName:k.ZodDefault})}brand(){return new So({typeName:k.ZodBranded,type:this,...Z(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Vr({...Z(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 $o.create(this,e)}readonly(){return Br.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},i$=/^c[^\s-]{8,}$/i,a$=/^[0-9a-z]+$/,c$=/^[0-9A-HJKMNP-TV-Z]{26}$/i,u$=/^[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,l$=/^[a-z0-9_-]{21}$/i,d$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,p$=/^[-+]?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)?)??$/,f$=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,m$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Vc,h$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,g$=/^(?:(?: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])$/,y$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,v$=/^(([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])$/,_$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,b$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Of="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",w$=new RegExp(`^${Of}$`);function Mf(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 x$(t){return new RegExp(`^${Mf(t)}$`)}function Nf(t){let e=`${Of}T${Mf(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 S$(t,e){return!!((e==="v4"||!e)&&h$.test(t)||(e==="v6"||!e)&&y$.test(t))}function $$(t,e){if(!d$.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 k$(t,e){return!!((e==="v4"||!e)&&g$.test(t)||(e==="v6"||!e)&&v$.test(t))}var cr=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 Ie,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.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")f$.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")Vc||(Vc=new RegExp(m$,"u")),Vc.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")u$.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")l$.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")i$.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")a$.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")c$.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"?Nf(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?w$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?x$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?p$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?S$(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.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?k$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?_$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?b$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):Y.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:$.invalid_string,...C.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...C.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...C.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...C.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...C.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...C.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...C.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...C.errToObj(r)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};cr.create=t=>new cr({checks:[],typeName:k.ZodString,coerce:t?.coerce??!1,...Z(t)});function P$(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Ar=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 Ie;for(let s of this._def.checks)s.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?P$(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_finite,message:s.message}),o.dirty()):Y.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,C.toString(r))}gt(e,r){return this.setLimit("min",e,!1,C.toString(r))}lte(e,r){return this.setLimit("max",e,!0,C.toString(r))}lt(e,r){return this.setLimit("max",e,!1,C.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:C.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Y.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)}};Ar.create=t=>new Ar({checks:[],typeName:k.ZodNumber,coerce:t?.coerce||!1,...Z(t)});var Cr=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 Ie;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.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()):Y.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,C.toString(r))}gt(e,r){return this.setLimit("min",e,!1,C.toString(r))}lte(e,r){return this.setLimit("max",e,!0,C.toString(r))}lt(e,r){return this.setLimit("max",e,!1,C.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:C.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Cr.create=t=>new Cr({checks:[],typeName:k.ZodBigInt,coerce:t?.coerce??!1,...Z(t)});var Dr=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 Ne(e.data)}};Dr.create=t=>new Dr({typeName:k.ZodBoolean,coerce:t?.coerce||!1,...Z(t)});var zr=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 Ie,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.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()):Y.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};zr.create=t=>new zr({checks:[],coerce:t?.coerce||!1,typeName:k.ZodDate,...Z(t)});var $n=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 Ne(e.data)}};$n.create=t=>new $n({typeName:k.ZodSymbol,...Z(t)});var Or=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 Ne(e.data)}};Or.create=t=>new Or({typeName:k.ZodUndefined,...Z(t)});var Mr=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 Ne(e.data)}};Mr.create=t=>new Mr({typeName:k.ZodNull,...Z(t)});var ur=class extends B{constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};ur.create=t=>new ur({typeName:k.ZodAny,...Z(t)});var Kt=class extends B{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};Kt.create=t=>new Kt({typeName:k.ZodUnknown,...Z(t)});var bt=class extends B{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.never,received:r.parsedType}),N}};bt.create=t=>new bt({typeName:k.ZodNever,...Z(t)});var kn=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 Ne(e.data)}};kn.create=t=>new kn({typeName:k.ZodVoid,...Z(t)});var Gt=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 ut(r,i,r.path,a)))).then(i=>Ie.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ut(r,i,r.path,a)));return Ie.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:C.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:C.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:C.toString(r)}})}nonempty(e){return this.min(1,e)}};Gt.create=(t,e)=>new Gt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...Z(e)});function Sn(t){if(t instanceof Xe){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ct.create(Sn(n))}return new Xe({...t._def,shape:()=>e})}else return t instanceof Gt?new Gt({...t._def,type:Sn(t.element)}):t instanceof ct?ct.create(Sn(t.unwrap())):t instanceof zt?zt.create(Sn(t.unwrap())):t instanceof Dt?Dt.create(t.items.map(e=>Sn(e))):t}var Xe=class t extends 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=Y.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 bt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ut(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof bt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(T(o,{code:$.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 ut(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Ie.mergeObjectSync(n,u)):Ie.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:C.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName: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 Y.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 Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Sn(this)}partial(e){let r={};for(let n of Y.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 Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ct;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return jf(Y.objectKeys(this.shape))}};Xe.create=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:k.ZodObject,...Z(e)});Xe.strictCreate=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:k.ZodObject,...Z(e)});Xe.lazycreate=(t,e)=>new Xe({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:k.ZodObject,...Z(e)});var Nr=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 Ye(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 Ye(c));return T(r,{code:$.invalid_union,unionErrors:a}),N}}get options(){return this._def.options}};Nr.create=(t,e)=>new Nr({options:t,typeName:k.ZodUnion,...Z(e)});var Ht=t=>t instanceof Lr?Ht(t.schema):t instanceof lt?Ht(t.innerType()):t instanceof Fr?[t.value]:t instanceof Zr?t.options:t instanceof Ur?Y.objectValues(t.enum):t instanceof qr?Ht(t._def.innerType):t instanceof Or?[void 0]:t instanceof Mr?[null]:t instanceof ct?[void 0,...Ht(t.unwrap())]:t instanceof zt?[null,...Ht(t.unwrap())]:t instanceof So||t instanceof Br?Ht(t.unwrap()):t instanceof Vr?Ht(t._def.innerType):[],ri=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=Ht(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,...Z(n)})}};function Bc(t,e){let r=Ct(t),n=Ct(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=Y.objectKeys(e),s=Y.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Bc(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=Bc(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 jr=class extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ei(s)||ei(i))return N;let a=Bc(s.value,i.value);return a.valid?((ti(s)||ti(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}))}};jr.create=(t,e,r)=>new jr({left:t,right:e,typeName:k.ZodIntersection,...Z(r)});var Dt=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 ut(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ie.mergeArray(r,i)):Ie.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:t,typeName:k.ZodTuple,rest:null,...Z(e)})};var ni=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 ut(n,a,n.path,a)),value:i._parse(new ut(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ie.mergeObjectAsync(r,o):Ie.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof B?new t({keyType:e,valueType:r,typeName:k.ZodRecord,...Z(n)}):new t({keyType:cr.create(),valueType:e,typeName:k.ZodRecord,...Z(r)})}},Pn=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 ut(n,a,n.path,[u,"key"])),value:s._parse(new ut(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return N;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return N;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Pn.create=(t,e,r)=>new Pn({valueType:e,keyType:t,typeName:k.ZodMap,...Z(r)});var Tn=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 ut(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:C.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:C.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Tn.create=(t,e)=>new Tn({valueType:t,minSize:null,maxSize:null,typeName:k.ZodSet,...Z(e)});var oi=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 xo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wn(),Wt].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function o(a,c){return xo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wn(),Wt].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof lr){let a=this;return Ne(async function(...c){let u=new Ye([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return Ne(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ye([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ye([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Dt.create(e).rest(Kt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Dt.create([]).rest(Kt.create()),returns:r||Kt.create(),typeName:k.ZodFunction,...Z(n)})}},Lr=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})}};Lr.create=(t,e)=>new Lr({getter:t,typeName:k.ZodLazy,...Z(e)});var Fr=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}};Fr.create=(t,e)=>new Fr({value:t,typeName:k.ZodLiteral,...Z(e)});function jf(t,e){return new Zr({values:t,typeName:k.ZodEnum,...Z(e)})}var Zr=class t extends B{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:Y.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 Ne(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Zr.create=jf;var Ur=class extends B{_parse(e){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=Y.objectValues(r);return T(n,{expected:Y.joinValues(o),received:n.parsedType,code:$.invalid_type}),N}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=Y.objectValues(r);return T(n,{received:n.data,code:$.invalid_enum_value,options:o}),N}return Ne(e.data)}get enum(){return this._def.values}};Ur.create=(t,e)=>new Ur({values:t,typeName:k.ZodNativeEnum,...Z(e)});var lr=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 Ne(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};lr.create=(t,e)=>new lr({type:t,typeName:k.ZodPromise,...Z(e)});var lt=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"?Ir(c.value):r.value==="dirty"?Ir(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"?Ir(a.value):r.value==="dirty"?Ir(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?N:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?N:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ar(i))return N;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ar(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):N);Y.assertNever(o)}};lt.create=(t,e,r)=>new lt({schema:t,typeName:k.ZodEffects,effect:e,...Z(r)});lt.createWithPreprocess=(t,e,r)=>new lt({schema:e,effect:{type:"preprocess",transform:t},typeName:k.ZodEffects,...Z(r)});var ct=class extends B{_parse(e){return this._getType(e)===R.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(t,e)=>new ct({innerType:t,typeName:k.ZodOptional,...Z(e)});var zt=class extends B{_parse(e){return this._getType(e)===R.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:k.ZodNullable,...Z(e)});var qr=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}};qr.create=(t,e)=>new qr({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Vr=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 xn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ye(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Vr.create=(t,e)=>new Vr({innerType:t,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var En=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}}};En.create=t=>new En({typeName:k.ZodNaN,...Z(t)});var T$=Symbol("zod_brand"),So=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}},$o=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(),Ir(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})}},Br=class extends B{_parse(e){let r=this._def.innerType._parse(e),n=o=>(ar(o)&&(o.value=Object.freeze(o.value)),o);return xn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Br.create=(t,e)=>new Br({innerType:t,typeName:k.ZodReadonly,...Z(e)});function zf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Lf(t,e={},r){return t?ur.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=zf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=zf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):ur.create()}var E$={object:Xe.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 R$=(t,e={message:`Input not instance of ${t.name}`})=>Lf(r=>r instanceof t,e),Ff=cr.create,Zf=Ar.create,I$=En.create,A$=Cr.create,Uf=Dr.create,C$=zr.create,D$=$n.create,z$=Or.create,O$=Mr.create,M$=ur.create,N$=Kt.create,j$=bt.create,L$=kn.create,F$=Gt.create,Z$=Xe.create,U$=Xe.strictCreate,q$=Nr.create,V$=ri.create,B$=jr.create,W$=Dt.create,H$=ni.create,K$=Pn.create,G$=Tn.create,J$=oi.create,Y$=Lr.create,X$=Fr.create,Q$=Zr.create,ek=Ur.create,tk=lr.create,rk=lt.create,nk=ct.create,ok=zt.create,sk=lt.createWithPreprocess,ik=$o.create,ak=()=>Ff().optional(),ck=()=>Zf().optional(),uk=()=>Uf().optional(),lk={string:(t=>cr.create({...t,coerce:!0})),number:(t=>Ar.create({...t,coerce:!0})),boolean:(t=>Dr.create({...t,coerce:!0})),bigint:(t=>Cr.create({...t,coerce:!0})),date:(t=>zr.create({...t,coerce:!0}))};var dk=N;Vt();var pk=h.enum(["read-only","workspace-write","full-auto"]),fk=pk.default("read-only"),mk=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:fk,config:h.record(h.unknown()).default({})}),hk=h.enum(["default-only","auto"]).default("default-only"),gk=h.object({selectionPolicy:hk,locale:h.string().optional(),providers:h.array(mk).min(1,"At least one provider required")});function Jt(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":case"claude-cli":return"workspace-write";default:return"read-only"}}function si(t){return t==="workspace-write"||t==="full-auto"}function yk(t){return Gs.includes(t)}function vk(t){if(t!==void 0)return yk(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${Er}`),Er)}function qf(t){let e=gk.parse(t);return{selectionPolicy:e.selectionPolicy,locale:vk(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{mkdirSync as _k}from"fs";import{homedir as bk}from"os";import{dirname as wk,join as Vf}from"path";var Bf="providers.config.json";function ko(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=process.env.CLAUDE_PLUGIN_ROOT;return e&&e.length>0?Vf(e,Bf):Vf(bk(),".agestra",Bf)}function Wf(t){_k(wk(t),{recursive:!0})}ci();Jc();Eo();wo();bn();Vt();import{mkdirSync as om,readFileSync as Ee,readdirSync as Ro,existsSync as Fe,unlinkSync as e0,rmdirSync as t0}from"fs";import{join as X}from"path";import{spawn as sm}from"child_process";import{randomUUID as r0}from"crypto";var n0=5e3,nu=["completed","error","timed_out","cancelled","missing_cli"];function Ot(t,e){let r=X(t,"status.json"),n=`${r}.lock`;Wr(n,()=>{let o=JSON.parse(Ee(r,"utf-8"));je(r,{...o,...e})})}var li=class{jobsDir;workspaceDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;completionHandler;saveInFlight=new Map;deferredSaveTimers=new Map;constructor(e=process.cwd(),r){this.workspaceDir=e,this.jobsDir=X(e,mf),om(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7,this.completionHandler=r?.completionHandler,this.submitCount=this.countExistingJobs()}countExistingJobs(){if(!Fe(this.jobsDir))return 0;try{return Ro(this.jobsDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).length}catch{return 0}}reconcileOrphans(){let e=0,r;try{r=Ro(this.jobsDir)}catch{return 0}for(let n of r){if(!dr(n))continue;let o=X(this.jobsDir,n,"status.json");if(!Fe(o))continue;let s;try{s=JSON.parse(Ee(o,"utf-8"))}catch{continue}if(s.state!=="running"||s.pid!==void 0&&this.isPidAlive(s.pid))continue;let i=`${o}.lock`;try{let a=Wr(i,()=>{let c=JSON.parse(Ee(o,"utf-8"));if(c.state!=="running"||c.pid!==void 0&&this.isPidAlive(c.pid))return null;let u={...c,state:"error",completedAt:new Date().toISOString()};return je(o,u),u});if(!a)continue;oe(X(this.jobsDir,n,"error.txt"),"orphaned (worker process died before completion)"),this.statusCache.set(n,a),e++}catch{}}return e}resolveCreatedAtMs(e){let r=X(this.jobsDir,e,"job.json");try{let o=JSON.parse(Ee(r,"utf-8")),s=new Date(o.createdAt).getTime();if(Number.isFinite(s))return s}catch{}let n=e.split("-");for(let o=n.length-2;o>=0;o--)if(/^\d+$/.test(n[o])){let s=Number(n[o]);if(Number.isFinite(s)&&s>0)return s}return null}isPidAlive(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}submit(e){let r=`${e.provider}-${Date.now()}-${r0().slice(0,6)}`,n=X(this.jobsDir,r);om(n,{recursive:!0});let o=e.timeout??3e5,s={id:r,provider:e.provider,prompt:e.prompt,timeout:o,createdAt:new Date().toISOString(),cwd:this.workspaceDir,saveAsDocument:e.saveAsDocument},i={id:r,state:"queued",provider:e.provider};if(je(X(n,"job.json"),s),je(X(n,"status.json"),i),oe(X(n,"prompt.txt"),e.prompt),this.statusCache.set(r,i),this.spawnWorker(n),e.saveAsDocument&&this.completionHandler){let a=setTimeout(()=>{this.deferredSaveTimers.delete(r),this.maybeTriggerCompletionSave(r).catch(()=>{})},o+n0);a.unref?.(),this.deferredSaveTimers.set(r,a)}return this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!dr(e))return null;let r=this.statusCache.get(e);if(r&&nu.includes(r.state)&&((r.savedDocumentId?!0:r.saveError!==void 0)||!this.completionHandler))return r;let n=X(this.jobsDir,e,"status.json");if(!Fe(n))return null;let o=JSON.parse(Ee(n,"utf-8"));if(o.state==="queued"){let s=this.resolveCreatedAtMs(e);if(s!==null&&Date.now()-s>6e4){let a=`${n}.lock`;try{let c=Wr(a,()=>{let u=JSON.parse(Ee(n,"utf-8"));if(u.state!=="queued")return null;let l={...u,state:"error",completedAt:new Date().toISOString()};return je(n,l),l});if(c)return oe(X(this.jobsDir,e,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(e,c),c}catch{}}}return this.statusCache.set(e,o),nu.includes(o.state)&&!o.savedDocumentId&&!o.saveError&&this.completionHandler&&this.maybeTriggerCompletionSave(e).catch(()=>{}),o}getResult(e){if(!dr(e))return null;let r=this.getStatus(e);if(!r)return null;let n=X(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode,savedDocumentId:r.savedDocumentId,saveError:r.saveError},s=X(n,"output.txt");Fe(s)&&(o.output=Ee(s,"utf-8"));let i=X(n,"error.txt");return Fe(i)&&(o.error=Ee(i,"utf-8")),o}async getResultAwaited(e){return dr(e)?(await this.maybeTriggerCompletionSave(e),this.getResult(e)):null}async invokeHandlerWithRetry(e,r){let n=[200,600],o;for(let s=0;s<n.length+1;s++){if(!Fe(X(r,"status.json")))throw o||new Error("job directory removed during completion save");try{return await e()}catch(i){if(o=i,s>=n.length)break;await new Promise(a=>setTimeout(a,n[s]))}}throw o}async maybeTriggerCompletionSave(e){if(!this.completionHandler||!dr(e))return;let r=X(this.jobsDir,e);if(!Fe(X(r,"status.json")))return;let n=this.saveInFlight.get(e);if(n)return n;let o=this.runCompletionSave(e).finally(()=>{this.saveInFlight.delete(e)});return this.saveInFlight.set(e,o),o}async runCompletionSave(e){if(!this.completionHandler||!dr(e))return;let r=X(this.jobsDir,e),n=X(r,"status.json"),o=X(r,"job.json");if(!Fe(n)||!Fe(o))return;let s=JSON.parse(Ee(n,"utf-8"));if(!nu.includes(s.state)||s.savedDocumentId||s.saveError)return;let i=JSON.parse(Ee(o,"utf-8"));if(!i.saveAsDocument)return;let a={id:e,state:s.state,exitCode:s.exitCode},c=X(r,"output.txt");Fe(c)&&(a.output=Ee(c,"utf-8"));let u=X(r,"error.txt");Fe(u)&&(a.error=Ee(u,"utf-8"));try{let l=await this.invokeHandlerWithRetry(()=>this.completionHandler({jobId:e,descriptor:i,result:a,saveAsDocument:i.saveAsDocument}),r);if(l){let d={savedDocumentId:l.documentId};Ot(r,d),this.statusCache.set(e,{...s,...d})}else{let d={saveError:`skipped (state=${s.state})`};Ot(r,d),this.statusCache.set(e,{...s,...d})}}catch(l){let p={saveError:l instanceof Error?l.message:String(l)};try{Ot(r,p),this.statusCache.set(e,{...s,...p})}catch{}}}listJobs(){if(!Fe(this.jobsDir))return[];let e;try{e=Ro(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory())}catch{return[]}let r=[];for(let n of e)try{let o=X(this.jobsDir,n.name,"status.json");Fe(o)&&r.push(JSON.parse(Ee(o,"utf-8")))}catch{}return r}cancel(e){if(!dr(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&vn(r.pid);let n=X(this.jobsDir,e),o=X(n,"status.json"),s=`${o}.lock`;try{let i=Wr(s,()=>{let a=JSON.parse(Ee(o,"utf-8"));if(a.state!=="queued"&&a.state!=="running")return null;let c={...a,state:"cancelled",completedAt:new Date().toISOString()};return je(o,c),c});i&&this.statusCache.set(e,i)}catch{}return this.clearDeferredSaveTimer(e),!0}clearDeferredSaveTimer(e){let r=this.deferredSaveTimers.get(e);r&&(clearTimeout(r),this.deferredSaveTimers.delete(e))}shutdown(){for(let e of this.deferredSaveTimers.values())clearTimeout(e);this.deferredSaveTimers.clear()}cleanup(){if(!Fe(this.jobsDir))return 0;let e;try{e=Ro(this.jobsDir,{withFileTypes:!0}).filter(u=>u.isDirectory())}catch{return 0}let r=[];for(let u of e)try{let l=X(this.jobsDir,u.name,"status.json"),d=X(this.jobsDir,u.name,"job.json");if(!Fe(l))continue;let p=JSON.parse(Ee(l,"utf-8")),f=null;try{f=JSON.parse(Ee(d,"utf-8"))}catch{}r.push({name:u.name,status:p,descriptor:f})}catch{}let n=["completed","error","timed_out","cancelled","missing_cli"],o=r.filter(u=>n.includes(u.status.state)).sort((u,l)=>{let d=u.descriptor?.createdAt??"",p=l.descriptor?.createdAt??"";return d.localeCompare(p)}),s=0,i=Date.now(),a=this.maxAgeDays*24*60*60*1e3,c=r.length;for(let u of o){let d=(u.descriptor?.createdAt?i-new Date(u.descriptor.createdAt).getTime():1/0)>a,p=c-s>this.maxJobs;if(!d&&!p)continue;let f=X(this.jobsDir,u.name);try{let m=Ro(f);for(let g of m)e0(X(f,g));t0(f),this.statusCache.delete(u.name),this.clearDeferredSaveTimer(u.name),s++}catch{}}return s}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(Fe(r)){let n=sm(process.execPath,[r,e],{detached:!0,stdio:"ignore",cwd:this.workspaceDir}),o=typeof n.pid=="number"&&n.pid>0;if(o)try{Ot(e,{pid:n.pid})}catch{}n.on("error",s=>{if(o)return;s.code==="ENOENT"?this.runInProcess(e):this.runInProcess(e)}),n.unref()}else this.runInProcess(e)}runInProcess(e){Promise.resolve().then(()=>(nm(),rm)).then(({resolveCliConfig:r})=>{let n;try{n=JSON.parse(Ee(X(e,"job.json"),"utf-8"))}catch{return}let o=r(n);if(!o){Ot(e,{state:"missing_cli",completedAt:new Date().toISOString()}),oe(X(e,"error.txt"),`No CLI mapping for provider: ${n.provider}`);return}let{command:s,buildArgs:i}=o,a=Ee(X(e,"prompt.txt"),"utf-8"),c=i(a);Ot(e,{state:"running",startedAt:new Date().toISOString()});let u=Bt(s,c),l=sm(u.command,u.args,{cwd:n.cwd||void 0,stdio:["ignore","pipe","pipe"],windowsHide:!0});if(typeof l.pid=="number"&&l.pid>0)try{Ot(e,{pid:l.pid})}catch{}if(!l.stdout||!l.stderr){try{l.kill()}catch{}oe(X(e,"error.txt"),"Worker stdout/stderr streams unavailable (pipe allocation failed)"),Ot(e,{state:"error",completedAt:new Date().toISOString()});return}let d="",p="",f=0,m=0,g=!1,y=!1;l.stdout.on("data",w=>{f+=w.length,f<=10485760?d+=w.toString():g||(g=!0,At(l))}),l.stderr.on("data",w=>{m+=w.length,m<=10485760&&(p+=w.toString())});let v=(w,_)=>{if(!y){y=!0,clearTimeout(S);try{oe(X(e,"output.txt"),d),_!==void 0?oe(X(e,"error.txt"),_):oe(X(e,"error.txt"),p),Ot(e,w)}catch{}}},S=setTimeout(()=>{y||(At(l),v({state:"timed_out",completedAt:new Date().toISOString()}))},n.timeout);l.on("close",w=>{if(y)return;let _=d.trim().length>0;v({state:w===0||_?"completed":"error",exitCode:w??1,completedAt:new Date().toISOString()})}),l.on("error",w=>{if(y)return;let _=w.code==="ENOENT"?"missing_cli":"error";v({state:_,completedAt:new Date().toISOString()},w.message)})}).catch(()=>{try{Ot(e,{state:"error",completedAt:new Date().toISOString()}),oe(X(e,"error.txt"),"Failed to load job worker module")}catch{}})}};ci();Vt();import{mkdirSync as o0,readdirSync as im,readFileSync as s0,unlinkSync as i0}from"fs";import{join as Io}from"path";function am(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 a0(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function c0(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var di=class{tracesDir;writer;constructor(e,r){this.tracesDir=Io(e,hf),o0(this.tracesDir,{recursive:!0}),this.writer=new ii(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=am(new Date(r.timestamp)),o=Io(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
13
+ `,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],o=[];for(let i of r){let a=s0(i,"utf-8").split(`
14
+ `).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);c0(u)?o.push(u):a0(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=am(o),a=Io(this.tracesDir,`${i}.jsonl`);this.writer.append(a,JSON.stringify(s)+`
15
+ `,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let s of r){if(!s.quality)continue;let i=`${s.providerId}:${s.task}`,a=n.get(i)??{totalScore:0,count:0,totalLatency:0};a.totalScore+=s.quality.score,a.count+=1,a.totalLatency+=s.latencyMs,n.set(i,a)}let o=new Map;for(let[s,i]of n)o.set(s,{avgScore:i.totalScore/i.count,count:i.count,avgLatencyMs:i.totalLatency/i.count});return o}cleanup(e){let r=new Date;r.setDate(r.getDate()-e);let n=0,o;try{o=im(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&&(i0(Io(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=im(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=>Io(this.tracesDir,n))}};var u0=/[;|&`$(){}!><\n\r\\]/,pi=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),l0=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 cm(t){if(u0.test(t))return{valid:!1,error:"Command contains shell metacharacters (piping, chaining, or subshell operators are not allowed)"};let e=t.split(/\s+/).filter(Boolean);if(e.length===0)return{valid:!1,error:"Empty command"};if(e[0].includes("/")||e[0].includes("\\"))return{valid:!1,error:"Command must not contain path separators (use bare command names only)"};for(let n=1;n<e.length;n++)if(e[n].includes("/")||e[n].includes("\\"))return{valid:!1,error:`Argument must not contain path separators: ${JSON.stringify(e[n])}`};let r=e[0];if(!pi.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...pi].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(l0.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}Vt();var um=[{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"}],lm=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function dm(t){let e=Array.isArray(t)?t:t.split(`
16
+ `),r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let s of um){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!lm.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 ou(t){if(t.length===0)return t;let e=t.split(`
17
+ `);for(let r=0;r<e.length;r++){let n=e[r];for(let o of um){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>lm.some(a=>a.test(i))?i:Ef)}e[r]=n}return e.join(`
18
+ `)}Vt();import{execFileSync as d0}from"child_process";import{existsSync as pm,rmSync as p0,mkdirSync as f0}from"fs";import{join as fm}from"path";var fi=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=fm(e,gf)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=fm(this.worktreeBaseDir,r);f0(this.worktreeBaseDir,{recursive:!0}),pm(o)&&this.forceRemoveWorktree(o),this.gitSafe(["branch","-D",n]),this.git(["worktree","add","-b",n,o,"HEAD"]);let s={id:e,path:o,branch:n};return this.worktrees.set(e,s),s}remove(e){let r=this.worktrees.get(e);r&&(this.forceRemoveWorktree(r.path),this.gitSafe(["branch","-D",r.branch]),this.worktrees.delete(e))}get(e){return this.worktrees.get(e)}list(){return[...this.worktrees.values()]}listOrphans(){let e=this.gitSafe(["worktree","list","--porcelain"]);if(!e)return[];let r=[],n="",o="",s=()=>{n.includes(".agestra/worktrees")&&o.startsWith("agestra-worker/")&&([...this.worktrees.values()].some(a=>a.path===n)||r.push({path:n,branch:o})),n="",o=""};for(let i of e.split(`
19
+ `))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?o=i.slice(18):i===""&&s();return n&&s(),r}cleanOrphans(){let e=this.listOrphans(),r=0;for(let n of e)this.forceRemoveWorktree(n.path),this.gitSafe(["branch","-D",n.branch]),r++;return r}forceRemoveWorktree(e){this.gitSafe(["worktree","remove",e])===null&&this.gitSafe(["worktree","remove","--force",e])===null&&(pm(e)&&p0(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return d0("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var m0=["npm","node","git","tsc"];function mm(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:[...m0]},timeout_minutes:t.timeoutMinutes??10}}function hm(t){let e=[];return(!t.task||t.task.trim().length===0)&&e.push("task must not be empty"),(!t.permissions.sandbox_root||t.permissions.sandbox_root.trim().length===0)&&e.push("permissions.sandbox_root must not be empty"),t.timeout_minutes<=0&&e.push("timeout_minutes must be positive"),{valid:e.length===0,errors:e}}var ke;(function(t){t.SPAWNING="SPAWNING",t.RUNNING="RUNNING",t.COLLECTING="COLLECTING",t.COMPLETED="COMPLETED",t.FAILED="FAILED",t.CANCELLING="CANCELLING",t.CANCELLED="CANCELLED",t.TIMEOUT="TIMEOUT"})(ke||(ke={}));var mi=10,su=2e4;import{spawn as b0}from"child_process";import{writeFileSync as au,mkdirSync as w0,readFileSync as _m,existsSync as bm}from"fs";import{isAbsolute as wm,join as Ao,resolve as xm}from"path";import{randomBytes as x0}from"crypto";import{execFileSync as S0}from"child_process";Vt();bn();wo();Eo();Eo();import{readFileSync as gm}from"fs";var iu=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 h0(t,e,r){let n=ym(t,e,r);return{command:"codex",args:["exec","--skip-git-repo-check","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function g0(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",ym(t,e,r)]}}function ym(t,e,r){let n=gm(t,"utf-8"),o=y0(r,e);return["You are an autonomous coding worker operating in the current workspace.","Execute the task manifest below without asking for confirmation.","Stay within the workspace, respect read-only vs read-write boundaries, and summarize changes plus verification at the end.","",n,o].join(`
20
+ `)}function vm(){let t=new iu;return t.register("codex",h0),t.register("gemini",g0),t}function y0(t,e){if(!t||t.length===0)return"";let r=t.filter(o=>!eu(o,e));if(r.length===0)return"";let n=["Read-only file snapshots:","These files may live outside the worker sandbox root. Use the embedded contents below as authoritative context and do not attempt to edit them.",""];for(let o of r.slice(0,mi))try{let s=gm(o,"utf-8"),i=s.length>su?`${s.slice(0,su)}
21
21
  ...[truncated]`:s;n.push(`### File: ${o}`),n.push("```"),n.push(i),n.push("```"),n.push("")}catch(s){let i=s instanceof Error?s.message:String(s);n.push(`### File: ${o}`),n.push(`[unavailable: ${i}]`),n.push("")}return r.length>mi&&(n.push(`...[${r.length-mi} additional read-only files omitted]`),n.push("")),n.join(`
22
- `)}var Ao=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=Io(e,_f),this.worktreeManager=new fi(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??gm()}knownProviders(){let e=new Set;for(let r of this.cliBuilderRegistry.knownProviders())e.add(r);for(let r of this.providerPolicies.keys())e.add(r);return[...e]}activeWorkerCount(){let e=0;for(let r of this.workers.values()){let n=r.info.state;(n===$e.RUNNING||n===$e.COLLECTING)&&e++}return e}spawn(e){if(this.activeWorkerCount()>=3)throw new Error(`Worker quota exceeded: ${this.activeWorkerCount()}/${3} workers already active. Wait for existing workers to complete or call stop() before spawning a new one.`);let r=this.validateWorkingDirectory(e.workingDir),n=this.normalizeReadablePaths(e.filesToRead,r),o=this.normalizeWritablePaths(e.filesToModify,r);this.assertAutonomousExecutionAllowed(e.provider);let s=[e.taskDescription,e.constraints??""],i=um(s);if(!i.clean){let Y=i.findings.map(Pe=>Pe.pattern).join(", ");throw new Error(`Secret detected in task input \u2014 spawn blocked. Found: ${Y}`)}let a=w0(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=Io(this.workersBaseDir,c);b0(u,{recursive:!0});let l=pm({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=fm(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=Io(u,"task-manifest.json");iu(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=Io(u,"stdout.log"),g=Io(u,"stderr.log"),v=f?.path??r,_=this.cliBuilderRegistry.build(e.provider,p,v,n),S=Vt(_.command,_.args),y=_0(S.command,S.args,{cwd:v,env:t.buildWorkerEnv(),detached:!0,stdio:[_.stdin?"pipe":"ignore","pipe","pipe"]}),x=[],$=[];y.stdout?.on("data",Y=>x.push(Y)),y.stderr?.on("data",Y=>$.push(Y)),_.stdin!==void 0&&y.stdin?.end(_.stdin),y.unref();let M={workerId:c,provider:e.provider,state:$e.RUNNING,pid:y.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},O={info:M,process:y,workerDir:u,manifestPath:p,outputPath:m,errorPath:g};if(this.workers.set(c,O),e.timeoutMinutes){let Y=e.timeoutMinutes*6e4,Pe=setTimeout(()=>{if(O.info.state===$e.RUNNING&&O.process===y){O.info.state=$e.TIMEOUT,O.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let K=y.pid;K&&vn(K)}},Y);Pe.unref(),O.timeoutTimer=Pe}return y.on("close",Y=>{O.timeoutTimer&&(clearTimeout(O.timeoutTimer),O.timeoutTimer=void 0),O.info.exitCode=Y;try{iu(m,Buffer.concat(x).toString("utf-8")),iu(g,Buffer.concat($).toString("utf-8"))}catch{}O.info.state===$e.CANCELLING?O.info.state=$e.CANCELLED:Y===0?O.info.state=$e.COLLECTING:(O.info.state=$e.FAILED,O.info.error=`Process exited with code ${Y}`)}),M}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{vm(r.outputPath)&&(o=ym(r.outputPath,"utf-8").split(`
22
+ `)}var Co=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=Ao(e,wf),this.worktreeManager=new fi(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??vm()}knownProviders(){let e=new Set;for(let r of this.cliBuilderRegistry.knownProviders())e.add(r);for(let r of this.providerPolicies.keys())e.add(r);return[...e]}activeWorkerCount(){let e=0;for(let r of this.workers.values()){let n=r.info.state;(n===ke.RUNNING||n===ke.COLLECTING)&&e++}return e}spawn(e){if(this.activeWorkerCount()>=3)throw new Error(`Worker quota exceeded: ${this.activeWorkerCount()}/${3} workers already active. Wait for existing workers to complete or call stop() before spawning a new one.`);let r=this.validateWorkingDirectory(e.workingDir),n=this.normalizeReadablePaths(e.filesToRead,r),o=this.normalizeWritablePaths(e.filesToModify,r);this.assertAutonomousExecutionAllowed(e.provider);let s=[e.taskDescription,e.constraints??""],i=dm(s);if(!i.clean){let U=i.findings.map($e=>$e.pattern).join(", ");throw new Error(`Secret detected in task input \u2014 spawn blocked. Found: ${U}`)}let a=x0(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=Ao(this.workersBaseDir,c);w0(u,{recursive:!0});let l=mm({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=hm(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=Ao(u,"task-manifest.json");au(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=Ao(u,"stdout.log"),g=Ao(u,"stderr.log"),y=f?.path??r,v=this.cliBuilderRegistry.build(e.provider,p,y,n),S=Bt(v.command,v.args),w=b0(S.command,S.args,{cwd:y,env:t.buildWorkerEnv(),detached:!0,stdio:[v.stdin?"pipe":"ignore","pipe","pipe"]}),_=[],P=[];w.stdout?.on("data",U=>_.push(U)),w.stderr?.on("data",U=>P.push(U)),v.stdin!==void 0&&w.stdin?.end(v.stdin),w.unref();let A={workerId:c,provider:e.provider,state:ke.RUNNING,pid:w.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},D={info:A,process:w,workerDir:u,manifestPath:p,outputPath:m,errorPath:g};if(this.workers.set(c,D),e.timeoutMinutes){let U=e.timeoutMinutes*6e4,$e=setTimeout(()=>{if(D.info.state===ke.RUNNING&&D.process===w){D.info.state=ke.TIMEOUT,D.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let G=w.pid;G&&vn(G)}},U);$e.unref(),D.timeoutTimer=$e}return w.on("close",U=>{D.timeoutTimer&&(clearTimeout(D.timeoutTimer),D.timeoutTimer=void 0),D.info.exitCode=U;try{au(m,Buffer.concat(_).toString("utf-8")),au(g,Buffer.concat(P).toString("utf-8"))}catch{}D.info.state===ke.CANCELLING?D.info.state=ke.CANCELLED:U===0?D.info.state=ke.COLLECTING:(D.info.state=ke.FAILED,D.info.error=`Process exited with code ${U}`)}),A}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{bm(r.outputPath)&&(o=_m(r.outputPath,"utf-8").split(`
23
23
  `).slice(-20).join(`
24
- `))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:nu(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{vm(r.outputPath)&&(n=ym(r.outputPath,"utf-8"))}catch{}n=nu(n);let o=null;try{r.info.worktreePath&&(o=this.reviewChanges(r.info.workerId))}catch{o=null}return r.info.state===$e.COLLECTING&&(r.info.state=$e.COMPLETED),{workerId:r.info.workerId,state:r.info.state,exitCode:r.info.exitCode,outputFull:n,gitDiff:o?.fullDiff??"",filesChanged:o?.filesChanged??[],worktreeBranch:r.info.worktreeBranch}}stop(e){let r=this.workers.get(e);if(!r||!r.process||r.info.state!==$e.RUNNING)return;r.info.state=$e.CANCELLING;let n=r.process.pid;if(n)vn(n);else try{r.process.kill("SIGTERM")}catch{}setTimeout(()=>{if(r.info.state===$e.CANCELLING){try{r.process?.kill("SIGKILL")}catch{}r.info.state=$e.CANCELLED}},5e3)}listAll(){return[...this.workers.values()].map(e=>({...e.info}))}reviewChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);if(!r.info.worktreePath)throw new Error(`Worker ${e} has no isolated worktree`);let n=r.info.worktreePath;return this.execGitSafe(["add","-N","."],n),{workerId:r.info.workerId,provider:r.info.provider,worktreePath:r.info.worktreePath,branch:r.info.worktreeBranch,filesChanged:this.listChangedFiles(n),diffStat:this.execGit(["diff","--stat","HEAD"],n),fullDiff:this.execGit(["diff","HEAD"],n)}}acceptChanges(e,r){let n=this.workers.get(e);if(!n)throw new Error(`Worker not found: ${e}`);if(!n.info.worktreePath||!n.info.worktreeBranch)throw new Error(`Worker ${e} has no isolated worktree`);let o=n.info.worktreePath,s=r??`agestra: worker ${e}`;this.execGit(["add","-A"],o);let i=this.execGit(["status","--porcelain"],o),a=i.trim()?i.trim().split(`
25
- `).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",s],o),this.execGit(["merge",n.info.worktreeBranch,"--no-edit"],this.baseDir)),this.worktreeManager.remove(n.info.workerId),n.info.worktreePath=null,n.info.worktreeBranch=null,{merged:a}}rejectChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);r.info.worktreePath&&this.worktreeManager.remove(r.info.workerId),r.info.worktreePath=null,r.info.worktreeBranch=null}tryCreateWorktree(e){try{return this.worktreeManager.create(e)}catch(r){let n=r instanceof Error?r.message:String(r);return console.warn(`[CliWorkerManager] Worker ${e} failed to create isolated worktree: ${n} \u2014 falling back to shared base directory.`),null}}execGit(e,r){return x0("git",e,{cwd:r,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}execGitSafe(e,r){try{return this.execGit(e,r)}catch{return null}}listChangedFiles(e){let r=this.execGitSafe(["status","--porcelain"],e);return r?.trim()?r.trim().split(`
26
- `).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of bf){let n=process.env[r];n!==void 0&&(e[r]=n)}for(let[r,n]of Object.entries(process.env))r.startsWith("AGESTRA_")&&n!==void 0&&(e[r]=n);return e}getProviderPolicy(e){let r=this.providerPolicies.get(e);if(r===void 0){let n=[...this.providerPolicies.keys()];throw new Error(`No execution policy configured for provider "${e}". Known: [${n.join(", ")}]`)}return r}assertAutonomousExecutionAllowed(e){let r=this.getProviderPolicy(e);if(!si(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return pt(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let o=_m(n)?n:bm(r,n);return Gt(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=_m(n)?n:bm(r,n);return pt(o,this.baseDir)})}};var gi=class{upstream;cached=null;cachedAt=0;cachedDaysBack=0;ttlMs;constructor(e,r){this.upstream=e,this.ttlMs=r?.ttlMs??6e4}getQualityStats(e){let r=Date.now();return this.cached!==null&&this.cachedDaysBack===e&&r-this.cachedAt<this.ttlMs?this.cached:(this.cached=this.upstream.getQualityStats(e),this.cachedAt=r,this.cachedDaysBack=e,this.cached)}invalidate(){this.cached=null,this.cachedAt=0}};var Rn=class{maxConcurrent;maxQueueSize;running=0;queue=[];constructor(e,r=16){this.maxConcurrent=e,this.maxQueueSize=r}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}if(this.queue.length>=this.maxQueueSize)throw new Error(`ConcurrencyLimiter queue full (max ${this.maxQueueSize})`);return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}async run(e){await this.acquire();try{return await e()}finally{this.release()}}};bn();qt();import{spawn as S0}from"child_process";var $0=3e5,k0=3,P0=15e3,T0=3e3,wm=10*1024*1024,E0=6e5,yi=class{state="idle";process=null;consecutiveFailures=0;lastFailureTime=0;idleTimer=null;pendingRequests=new Map;command;commandPrefix;commandArgs;idleTimeoutMs;maxConsecutiveFailures;startupTimeoutMs;stdoutBuffer="";startupResolve=null;startupReject=null;constructor(e){this.command=e.command,this.commandPrefix=e.commandPrefix??[],this.commandArgs=e.commandArgs??[],this.idleTimeoutMs=e.idleTimeoutMs??$0,this.maxConsecutiveFailures=e.maxConsecutiveFailures??k0,this.startupTimeoutMs=e.startupTimeoutMs??P0}async request(e,r,n){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if(n?.aborted)throw new ct(n.reason);if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),n?.aborted)throw new ct(n.reason);if(this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??E0,n)}isAlive(){return this.process!==null&&!this.process.killed&&(this.state==="ready"||this.state==="busy"||this.state==="starting")}getState(){return this.state}shouldFallback(){return this.consecutiveFailures<this.maxConsecutiveFailures?!1:Date.now()-this.lastFailureTime>xf?(this.consecutiveFailures=0,!1):!0}resetFailures(){this.consecutiveFailures=0}async shutdown(){if(!this.process||this.state==="shutdown"||this.state==="idle")return;this.state="shutdown",this.clearIdleTimer();for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error("App server shutting down"));this.pendingRequests.clear(),this.startupReject&&(this.startupReject(new Error("App server shutting down")),this.startupResolve=null,this.startupReject=null);let e=this.process;this.process=null;try{e.kill("SIGTERM")}catch{this.state="idle";return}let r=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},T0);await new Promise(n=>{e.on("close",()=>{clearTimeout(r),n()}),(e.exitCode!==null||e.signalCode!==null)&&(clearTimeout(r),n())}),this.state="idle"}async start(){if(this.state!=="idle"&&this.state!=="error")return;this.state="starting",this.stdoutBuffer="";let e=[...this.commandPrefix,...this.commandArgs,"app-server"],r=Vt(this.command,e),n=S0(r.command,r.args,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0});this.process=n;let o=c=>this.handleStdout(c.toString()),s=c=>{process.stderr.write(`[codex-app-server] ${c.toString()}`)},i=(c,u)=>{n.stdout?.off("data",o),n.stderr?.off("data",s),n.off("error",a),this.handleProcessClose(c,u)},a=c=>{n.stdout?.off("data",o),n.stderr?.off("data",s),n.off("close",i),this.handleProcessError(c)};return n.stdout.on("data",o),n.stderr.on("data",s),n.on("close",i),n.on("error",a),this.waitForReady()}waitForReady(){return this.state==="ready"?Promise.resolve():new Promise((e,r)=>{let n=setTimeout(()=>{this.startupResolve=null,this.startupReject=null,this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",r(new Error(`CodexAppServer startup timeout (${this.startupTimeoutMs}ms)`))},this.startupTimeoutMs);this.startupResolve=()=>{clearTimeout(n),e()},this.startupReject=o=>{clearTimeout(n),r(o)}})}handleStdout(e){if(this.stdoutBuffer+=e,this.stdoutBuffer.length>wm){if(process.stderr.write(`[codex-app-server] stdoutBuffer exceeded ${wm} bytes \u2014 dropping and restarting
24
+ `))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:ou(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{bm(r.outputPath)&&(n=_m(r.outputPath,"utf-8"))}catch{}n=ou(n);let o=null;try{r.info.worktreePath&&(o=this.reviewChanges(r.info.workerId))}catch{o=null}return r.info.state===ke.COLLECTING&&(r.info.state=ke.COMPLETED),{workerId:r.info.workerId,state:r.info.state,exitCode:r.info.exitCode,outputFull:n,gitDiff:o?.fullDiff??"",filesChanged:o?.filesChanged??[],worktreeBranch:r.info.worktreeBranch}}stop(e){let r=this.workers.get(e);if(!r||!r.process||r.info.state!==ke.RUNNING)return;r.info.state=ke.CANCELLING;let n=r.process.pid;if(n)vn(n);else try{r.process.kill("SIGTERM")}catch{}setTimeout(()=>{if(r.info.state===ke.CANCELLING){try{r.process?.kill("SIGKILL")}catch{}r.info.state=ke.CANCELLED}},5e3)}listAll(){return[...this.workers.values()].map(e=>({...e.info}))}reviewChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);if(!r.info.worktreePath)throw new Error(`Worker ${e} has no isolated worktree`);let n=r.info.worktreePath;return this.execGitSafe(["add","-N","."],n),{workerId:r.info.workerId,provider:r.info.provider,worktreePath:r.info.worktreePath,branch:r.info.worktreeBranch,filesChanged:this.listChangedFiles(n),diffStat:this.execGit(["diff","--stat","HEAD"],n),fullDiff:this.execGit(["diff","HEAD"],n)}}acceptChanges(e,r){let n=this.workers.get(e);if(!n)throw new Error(`Worker not found: ${e}`);if(!n.info.worktreePath||!n.info.worktreeBranch)throw new Error(`Worker ${e} has no isolated worktree`);let o=n.info.worktreePath,s=r??`agestra: worker ${e}`;this.execGit(["add","-A"],o);let i=this.execGit(["status","--porcelain"],o),a=i.trim()?i.trim().split(`
25
+ `).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",s],o),this.execGit(["merge",n.info.worktreeBranch,"--no-edit"],this.baseDir)),this.worktreeManager.remove(n.info.workerId),n.info.worktreePath=null,n.info.worktreeBranch=null,{merged:a}}rejectChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);r.info.worktreePath&&this.worktreeManager.remove(r.info.workerId),r.info.worktreePath=null,r.info.worktreeBranch=null}tryCreateWorktree(e){try{return this.worktreeManager.create(e)}catch(r){let n=r instanceof Error?r.message:String(r);return console.warn(`[CliWorkerManager] Worker ${e} failed to create isolated worktree: ${n} \u2014 falling back to shared base directory.`),null}}execGit(e,r){return S0("git",e,{cwd:r,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}execGitSafe(e,r){try{return this.execGit(e,r)}catch{return null}}listChangedFiles(e){let r=this.execGitSafe(["status","--porcelain"],e);return r?.trim()?r.trim().split(`
26
+ `).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of xf){let n=process.env[r];n!==void 0&&(e[r]=n)}for(let[r,n]of Object.entries(process.env))r.startsWith("AGESTRA_")&&n!==void 0&&(e[r]=n);return e}getProviderPolicy(e){let r=this.providerPolicies.get(e);if(r===void 0){let n=[...this.providerPolicies.keys()];throw new Error(`No execution policy configured for provider "${e}". Known: [${n.join(", ")}]`)}return r}assertAutonomousExecutionAllowed(e){let r=this.getProviderPolicy(e);if(!si(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return dt(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let o=wm(n)?n:xm(r,n);return Yt(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=wm(n)?n:xm(r,n);return dt(o,this.baseDir)})}};var gi=class{upstream;cached=null;cachedAt=0;cachedDaysBack=0;ttlMs;constructor(e,r){this.upstream=e,this.ttlMs=r?.ttlMs??6e4}getQualityStats(e){let r=Date.now();return this.cached!==null&&this.cachedDaysBack===e&&r-this.cachedAt<this.ttlMs?this.cached:(this.cached=this.upstream.getQualityStats(e),this.cachedAt=r,this.cachedDaysBack=e,this.cached)}invalidate(){this.cached=null,this.cachedAt=0}};var Rn=class{maxConcurrent;maxQueueSize;running=0;queue=[];constructor(e,r=16){this.maxConcurrent=e,this.maxQueueSize=r}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}if(this.queue.length>=this.maxQueueSize)throw new Error(`ConcurrencyLimiter queue full (max ${this.maxQueueSize})`);return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}async run(e){await this.acquire();try{return await e()}finally{this.release()}}};bn();Vt();import{spawn as $0}from"child_process";var k0=3e5,P0=3,T0=15e3,E0=3e3,Sm=10*1024*1024,R0=6e5,yi=class{state="idle";process=null;consecutiveFailures=0;lastFailureTime=0;idleTimer=null;pendingRequests=new Map;command;commandPrefix;commandArgs;idleTimeoutMs;maxConsecutiveFailures;startupTimeoutMs;stdoutBuffer="";startupResolve=null;startupReject=null;constructor(e){this.command=e.command,this.commandPrefix=e.commandPrefix??[],this.commandArgs=e.commandArgs??[],this.idleTimeoutMs=e.idleTimeoutMs??k0,this.maxConsecutiveFailures=e.maxConsecutiveFailures??P0,this.startupTimeoutMs=e.startupTimeoutMs??T0}async request(e,r,n){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if(n?.aborted)throw new at(n.reason);if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),n?.aborted)throw new at(n.reason);if(this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??R0,n)}isAlive(){return this.process!==null&&!this.process.killed&&(this.state==="ready"||this.state==="busy"||this.state==="starting")}getState(){return this.state}shouldFallback(){return this.consecutiveFailures<this.maxConsecutiveFailures?!1:Date.now()-this.lastFailureTime>$f?(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{}},E0);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=Bt(this.command,e),n=$0(r.command,r.args,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0});this.process=n;let o=c=>this.handleStdout(c.toString()),s=c=>{process.stderr.write(`[codex-app-server] ${c.toString()}`)},i=(c,u)=>{n.stdout?.off("data",o),n.stderr?.off("data",s),n.off("error",a),this.handleProcessClose(c,u)},a=c=>{n.stdout?.off("data",o),n.stderr?.off("data",s),n.off("close",i),this.handleProcessError(c)};return n.stdout.on("data",o),n.stderr.on("data",s),n.on("close",i),n.on("error",a),this.waitForReady()}waitForReady(){return this.state==="ready"?Promise.resolve():new Promise((e,r)=>{let n=setTimeout(()=>{this.startupResolve=null,this.startupReject=null,this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",r(new Error(`CodexAppServer startup timeout (${this.startupTimeoutMs}ms)`))},this.startupTimeoutMs);this.startupResolve=()=>{clearTimeout(n),e()},this.startupReject=o=>{clearTimeout(n),r(o)}})}handleStdout(e){if(this.stdoutBuffer+=e,this.stdoutBuffer.length>Sm){if(process.stderr.write(`[codex-app-server] stdoutBuffer exceeded ${Sm} bytes \u2014 dropping and restarting
27
27
  `),this.stdoutBuffer="",this.state!=="shutdown"){this.state="error",this.consecutiveFailures++,this.lastFailureTime=Date.now();for(let[,o]of this.pendingRequests)clearTimeout(o.timer),o.reject(new Error("App server stdout buffer overflow"));this.pendingRequests.clear();try{this.process?.kill("SIGTERM")}catch{}}return}for(let o of this.pendingRequests.values())o.resetTimer();let r=()=>{this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null)},n;for(;(n=this.stdoutBuffer.indexOf(`
28
- `))!==-1;){let o=this.stdoutBuffer.slice(0,n).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(n+1),!!o){if(this.state==="starting"&&(o.includes("ready")||o.includes("initialized"))){r();continue}try{let s=JSON.parse(o);if(this.state==="starting"&&r(),s.id&&this.pendingRequests.has(s.id)){let i=this.pendingRequests.get(s.id);this.pendingRequests.delete(s.id),clearTimeout(i.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),i.resolve(s)}}catch{this.state==="starting"&&r()}}}}sendRequest(e,r,n){return new Promise((o,s)=>{if(!this.process||!this.process.stdin){s(new Error("App server process not available"));return}let i=null,a=()=>{i&&n&&(n.removeEventListener("abort",i),i=null)},c=()=>{this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="error"),s(new Error(`App server request timeout (${r}ms of inactivity)`))},u=setTimeout(c,r),l=()=>{clearTimeout(u),u=setTimeout(c,r)},d=f=>{a(),o(f)},p=f=>{a(),s(f)};this.pendingRequests.set(e.id,{resolve:d,reject:p,timer:u,resetTimer:l}),this.state="busy",this.clearIdleTimer(),n&&(i=()=>{let f=this.pendingRequests.get(e.id);f&&(this.pendingRequests.delete(e.id),clearTimeout(f.timer),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="ready",this.resetIdleTimer()),a(),s(new ct(n.reason)))},n.addEventListener("abort",i));try{this.process.stdin.write(JSON.stringify(e)+`
29
- `)}catch(f){clearTimeout(u),this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",s(new Error(`Failed to write to app server: ${f.message}`))}})}handleProcessClose(e,r){for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error(`App server process exited (code=${e}, signal=${r})`));this.pendingRequests.clear(),this.startupReject&&(this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject(new Error(`App server process exited during startup (code=${e})`)),this.startupResolve=null,this.startupReject=null),this.process=null,this.clearIdleTimer(),this.state!=="shutdown"&&(this.state=this.state==="starting"?"error":"idle")}handleProcessError(e){this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject&&(this.startupReject(new Error(`App server spawn error: ${e.message}`)),this.startupResolve=null,this.startupReject=null),this.state="error",this.process=null,this.clearIdleTimer()}resetIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.state==="ready"&&this.pendingRequests.size===0&&this.shutdown().catch(()=>{})},this.idleTimeoutMs),this.idleTimer&&typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};function z(t){return t instanceof Error?t.message:String(t)}function In(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}bn();async function An(t,e){try{if((await Me({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await Me({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function xm(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await Me({command:t==="npx"?"npx":e,args:t==="npx"?[r,"--version"]:["--version"],timeout:1e4});return i.exitCode===0?{status:"ok",message:`${n} CLI available`}:{status:"error",message:`Exit code: ${i.exitCode}`}}catch(o){return{status:"error",message:o.message}}}function Cn(t,e,r){let n=e.trim()||`Exit code ${t}`,o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("quota")){let s=new de(r,`Rate limited: ${n}`);throw s.markUnavailable=!0,s}throw o.includes("auth")||o.includes("credential")||o.includes("login")||o.includes("api key")?new de(r,`Authentication issue: ${n}`):new Be(r,n)}function Sm(t){let e="",r=!1;return{feed(n){if(r)return null;e+=n;let o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("rate-limit")||o.includes("resource_exhausted")||o.includes("quota")){r=!0;let s=new de(t,`Rate limited (detected in stream): ${n.trim().slice(0,200)}`);return s.markUnavailable=!0,s}return o.includes("authentication")||o.includes("credential")||o.includes("api key")?(r=!0,new de(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Jr(t){let e=t.prompt;if(t.system&&(e=`${t.system}
28
+ `))!==-1;){let o=this.stdoutBuffer.slice(0,n).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(n+1),!!o){if(this.state==="starting"&&(o.includes("ready")||o.includes("initialized"))){r();continue}try{let s=JSON.parse(o);if(this.state==="starting"&&r(),s.id&&this.pendingRequests.has(s.id)){let i=this.pendingRequests.get(s.id);this.pendingRequests.delete(s.id),clearTimeout(i.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),i.resolve(s)}}catch{this.state==="starting"&&r()}}}}sendRequest(e,r,n){return new Promise((o,s)=>{if(!this.process||!this.process.stdin){s(new Error("App server process not available"));return}let i=null,a=()=>{i&&n&&(n.removeEventListener("abort",i),i=null)},c=()=>{this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="error"),s(new Error(`App server request timeout (${r}ms of inactivity)`))},u=setTimeout(c,r),l=()=>{clearTimeout(u),u=setTimeout(c,r)},d=f=>{a(),o(f)},p=f=>{a(),s(f)};this.pendingRequests.set(e.id,{resolve:d,reject:p,timer:u,resetTimer:l}),this.state="busy",this.clearIdleTimer(),n&&(i=()=>{let f=this.pendingRequests.get(e.id);f&&(this.pendingRequests.delete(e.id),clearTimeout(f.timer),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="ready",this.resetIdleTimer()),a(),s(new at(n.reason)))},n.addEventListener("abort",i));try{this.process.stdin.write(JSON.stringify(e)+`
29
+ `)}catch(f){clearTimeout(u),this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",s(new Error(`Failed to write to app server: ${f.message}`))}})}handleProcessClose(e,r){for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error(`App server process exited (code=${e}, signal=${r})`));this.pendingRequests.clear(),this.startupReject&&(this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject(new Error(`App server process exited during startup (code=${e})`)),this.startupResolve=null,this.startupReject=null),this.process=null,this.clearIdleTimer(),this.state!=="shutdown"&&(this.state=this.state==="starting"?"error":"idle")}handleProcessError(e){this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject&&(this.startupReject(new Error(`App server spawn error: ${e.message}`)),this.startupResolve=null,this.startupReject=null),this.state="error",this.process=null,this.clearIdleTimer()}resetIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.state==="ready"&&this.pendingRequests.size===0&&this.shutdown().catch(()=>{})},this.idleTimeoutMs),this.idleTimer&&typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};function M(t){return t instanceof Error?t.message:String(t)}function In(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}bn();async function An(t,e){try{if((await Me({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await Me({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function $m(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await Me({command:t==="npx"?"npx":e,args:t==="npx"?[r,"--version"]:["--version"],timeout:1e4});return i.exitCode===0?{status:"ok",message:`${n} CLI available`}:{status:"error",message:`Exit code: ${i.exitCode}`}}catch(o){return{status:"error",message:o.message}}}function Cn(t,e,r){let n=e.trim()||`Exit code ${t}`,o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("quota")){let s=new de(r,`Rate limited: ${n}`);throw s.markUnavailable=!0,s}throw o.includes("auth")||o.includes("credential")||o.includes("login")||o.includes("api key")?new de(r,`Authentication issue: ${n}`):new We(r,n)}function km(t){let e="",r=!1;return{feed(n){if(r)return null;e+=n;let o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("rate-limit")||o.includes("resource_exhausted")||o.includes("quota")){r=!0;let s=new de(t,`Rate limited (detected in stream): ${n.trim().slice(0,200)}`);return s.markUnavailable=!0,s}return o.includes("authentication")||o.includes("credential")||o.includes("api key")?(r=!0,new de(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Kr(t){let e=t.prompt;if(t.system&&(e=`${t.system}
30
30
 
31
31
  ${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
32
32
 
33
33
  ### File: ${r.path}
34
34
  \`\`\`
35
35
  ${r.content}
36
- \`\`\``);return e}function vi(t,e){return!!t.files?.length||e.length>4e3}function au(t){let e=0;return t.replace(/^### File: .+$/gm,()=>(e+=1,`### File ${e}`))}function pr(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function Dn(t,e,r){if(t instanceof de||t instanceof Be||t instanceof ct)throw t;let n=t?.message??"";throw n.startsWith("CLI timeout after ")?new hn(e,r):new Be(e,n)}function R0(t){let e=t.prompt;if(t.system&&(e=`${t.system}
36
+ \`\`\``);return e}function vi(t,e){return!!t.files?.length||e.length>4e3}function cu(t){let e=0;return t.replace(/^### File: .+$/gm,()=>(e+=1,`### File ${e}`))}function pr(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function Dn(t,e,r){if(t instanceof de||t instanceof We||t instanceof at)throw t;let n=t?.message??"";throw n.startsWith("CLI timeout after ")?new hn(e,r):new We(e,n)}function I0(t){let e=t.prompt;if(t.system&&(e=`${t.system}
37
37
 
38
38
  ${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
39
39
 
40
40
  ### File: ${r.path}
41
41
  \`\`\`
42
42
  ${r.content}
43
- \`\`\``);return e}function I0(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var fr=class{id;type;bridge;modelName;displayName;capabilities;constructor(e){this.id=e.id??e.bridge.providerId,this.type=e.type,this.bridge=e.bridge,this.modelName=e.modelName??e.type,this.displayName=e.displayName,this.capabilities=e.capabilities}async initialize(){}async healthCheck(){return this.bridge.healthCheck?this.bridge.healthCheck():this.bridge.isAvailable()?{status:"ok",message:`${this.displayName} host bridge available`}:{status:"error",message:`${this.displayName} host bridge unavailable`}}getCapabilities(){return{...this.capabilities,models:this.capabilities.models.map((e,r)=>r===0?{...e,name:this.modelName}:{...e})}}getDescriptor(){return ir(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new de(this.id,`${this.displayName} host bridge is not available`);try{let r=R0(e),n={...e.extra??{}};e.model&&(n.model=e.model),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.maxTokens=="number"&&(n.maxTokens=e.maxTokens);let o=await this.bridge.runTurn({prompt:r,system:e.system,metadata:n});return{text:o.text,model:I0(this.modelName,o.metadata),provider:this.id,metadata:o.metadata}}catch(r){let n=r instanceof Error?r.message:String(r);throw/sampling|host bridge unavailable|does not support/i.test(n)?new de(this.id,n):new Be(this.id,n)}}};var A0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude-host",description:"Claude host model via MCP sampling bridge",strengths:["reasoning","review","synthesis"]}]},_i=class extends fr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:A0,modelName:e.modelName??"claude-host"})}};var C0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["coding","reasoning","review","implementation"],models:[{name:"codex-host",description:"Codex host model via MCP sampling bridge",strengths:["coding","implementation","review"]}]},bi=class extends fr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:C0,modelName:e.modelName??"codex-host"})}};var D0={maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["analysis","reasoning","research","review"],models:[{name:"gemini-host",description:"Gemini host model via MCP sampling bridge",strengths:["analysis","research","review"]}]},wi=class extends fr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:D0,modelName:e.modelName??"gemini-host"})}};qt();var $m={"report.header.topic":"Topic","report.header.participants":"Participants","report.header.individualDocs":"Individual documents","report.table.proposer":"Proposer","report.table.opinion":"Opinion","report.table.severity":"Severity","report.table.agreement":"Agreement","report.section.mainTable":"Proposal ledger","report.section.dissentDetail":"Dissenting items","report.section.contributionSummary":"AI contribution summary","report.contribution.ai":"AI","report.contribution.proposed":"Proposed","report.contribution.accepted":"Accepted","report.contribution.revises":"Revises issued","report.contribution.abstains":"Abstains","report.footer.synthesisPath":"Final synthesis document","report.footer.debatePath":"Debate transcript","report.footer.pendingSynthesis":"(pending leader approval)","report.status.running":"running","report.status.readyForApproval":"ready for approval","report.status.consensus":"consensus","report.status.escalated":"escalated","report.status.approved":"approved","report.status.rejected":"rejected","report.status.leaderTimeout":"leader timeout","report.status.error":"error","synthesis.status.consensus":"Consensus reached","synthesis.status.escalated":"Partial / escalated","synthesis.section.acceptedItems":"Accepted Items","synthesis.section.rejectedItems":"Rejected / Withdrawn Items","synthesis.section.openItems":"Open Items","synthesis.section.sources":"Sources","synthesis.narration.consensusIn":"Consensus reached in round {round} of {max}.","synthesis.narration.escalated":"Session escalated by user after {round} rounds without consensus.","synthesis.narration.leaderNote":"Leader note","approval.pending":"Awaiting leader approval. Call `agent_debate_approve`, `agent_debate_continue`, or `agent_debate_reject`.","approval.timeout":"Session timed out waiting for leader decision ({hours}h).","moderator.narration.roundHeader":"Round {round} of {max}","moderator.narration.consensusInRound":"Consensus reached after {round} round(s).","moderator.narration.dissentDetailHeader":"Unresolved items","moderator.narration.noInterest":"No interest from participants","moderator.narration.participantDropout":"Participant `{participantId}` marked unavailable after repeated failures.","moderator.narration.participantTimeout":"Participant `{participantId}` did not respond in this round.","moderator.narration.leaderTimeoutFooter":"Leader Timeout","moderator.narration.rejected":"Session rejected by leader.","moderator.narration.approved":"Session approved by leader.","moderator.narration.aliasClarification":"Alias clarification phase","prompt.system.moderator":"You are the moderator of a structured multi-AI debate. You do not author proposals; you aggregate structured votes and produce a neutral synthesis. Respond only in the channels the protocol defines.","error.participantTimeout":"Participant `{participantId}` timed out after {seconds}s.","error.parseFailure":"Could not parse `<{tag}>` block from `{participantId}`.","error.sessionNotFound":"Debate session `{sessionId}` was not found.","error.invalidState":"Operation `{operation}` is not allowed in state `{state}`.","error.unknownLocaleFallback":"Unknown locale `{locale}`; falling back to `{fallback}`.","askUser.escalation.header":"Maximum rounds reached without consensus","askUser.escalation.question":"How would you like to proceed?","askUser.escalation.continue":"Continue +{rounds} rounds","askUser.escalation.escalate":"Escalate without consensus","askUser.escalation.stop":"Stop the debate"};var km={"report.header.topic":"\uC8FC\uC81C","report.header.participants":"\uCC38\uAC00\uC790","report.header.individualDocs":"\uAC1C\uBCC4 \uAC80\uD1A0 \uBB38\uC11C","report.table.proposer":"\uC81C\uC548\uC790","report.table.opinion":"\uC758\uACAC","report.table.severity":"\uC911\uC694\uB3C4","report.table.agreement":"\uB3D9\uC758\uC728","report.section.mainTable":"\uC81C\uC548 \uC6D0\uC7A5","report.section.dissentDetail":"\uBBF8\uD569\uC758 \uD56D\uBAA9 \uC0C1\uC138","report.section.contributionSummary":"AI \uAE30\uC5EC\uB3C4 \uC694\uC57D","report.contribution.ai":"AI","report.contribution.proposed":"\uC81C\uC548","report.contribution.accepted":"\uCC44\uD0DD","report.contribution.revises":"\uC218\uC815 \uC694\uCCAD","report.contribution.abstains":"\uAE30\uAD8C","report.footer.synthesisPath":"\uCD5C\uC885 \uD569\uC758 \uBB38\uC11C","report.footer.debatePath":"\uD1A0\uB860 \uAE30\uB85D","report.footer.pendingSynthesis":"(\uB9AC\uB354 \uC2B9\uC778 \uB300\uAE30 \uC911)","report.status.running":"\uC9C4\uD589 \uC911","report.status.readyForApproval":"\uC2B9\uC778 \uB300\uAE30","report.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","report.status.escalated":"\uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","report.status.approved":"\uC2B9\uC778\uB428","report.status.rejected":"\uAE30\uAC01\uB428","report.status.leaderTimeout":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","report.status.error":"\uC624\uB958","synthesis.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","synthesis.status.escalated":"\uBD80\uBD84 \uD569\uC758 / \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","synthesis.section.acceptedItems":"\uCC44\uD0DD \uD56D\uBAA9","synthesis.section.rejectedItems":"\uAE30\uAC01 / \uCCA0\uD68C \uD56D\uBAA9","synthesis.section.openItems":"\uBBF8\uACB0 \uD56D\uBAA9","synthesis.section.sources":"\uADFC\uAC70","synthesis.narration.consensusIn":"\uC804\uCCB4 {max}\uB77C\uC6B4\uB4DC \uC911 {round}\uB77C\uC6B4\uB4DC\uC5D0\uC11C \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","synthesis.narration.escalated":"{round}\uB77C\uC6B4\uB4DC \uB3D9\uC548 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD558\uC5EC \uC0AC\uC6A9\uC790 \uD310\uB2E8\uC73C\uB85C \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","synthesis.narration.leaderNote":"\uB9AC\uB354 \uBA54\uBAA8","approval.pending":"\uB9AC\uB354 \uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uACE0 \uC788\uC2B5\uB2C8\uB2E4. `agent_debate_approve`, `agent_debate_continue`, `agent_debate_reject` \uC911 \uD558\uB098\uB97C \uD638\uCD9C\uD574 \uC8FC\uC2ED\uC2DC\uC624.","approval.timeout":"\uB9AC\uB354 \uACB0\uC815\uC744 \uAE30\uB2E4\uB9AC\uB2E4 \uC138\uC158\uC774 \uC2DC\uAC04 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4({hours}\uC2DC\uAC04).","moderator.narration.roundHeader":"{round}/{max} \uB77C\uC6B4\uB4DC","moderator.narration.consensusInRound":"{round}\uB77C\uC6B4\uB4DC \uB9CC\uC5D0 \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","moderator.narration.dissentDetailHeader":"\uBBF8\uD574\uACB0 \uD56D\uBAA9","moderator.narration.noInterest":"\uCC38\uAC00\uC790 \uAD00\uC2EC \uC5C6\uC74C","moderator.narration.participantDropout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uBC18\uBCF5\uC801 \uC2E4\uD328\uB85C \uC778\uD574 \uC0AC\uC6A9 \uBD88\uAC00 \uC0C1\uD0DC\uB85C \uD45C\uC2DC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uC774\uBC88 \uB77C\uC6B4\uB4DC\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","moderator.narration.leaderTimeoutFooter":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","moderator.narration.rejected":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uAE30\uAC01\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.approved":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uC2B9\uC778\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.aliasClarification":"\uBCC4\uCE6D \uD655\uC778 \uB2E8\uACC4","prompt.system.moderator":"\uB2F9\uC2E0\uC740 \uAD6C\uC870\uD654\uB41C \uB2E4\uC911 AI \uD1A0\uB860\uC758 \uC911\uC7AC\uC790\uC785\uB2C8\uB2E4. \uC81C\uC548\uC744 \uC9C1\uC811 \uC791\uC131\uD558\uC9C0 \uC54A\uC73C\uBA70, \uAD6C\uC870\uD654\uB41C \uD22C\uD45C\uB97C \uC9D1\uACC4\uD558\uACE0 \uC911\uB9BD\uC801\uC778 \uD569\uC758\uC548\uC744 \uC0B0\uCD9C\uD569\uB2C8\uB2E4. \uD504\uB85C\uD1A0\uCF5C\uC774 \uC815\uC758\uD55C \uCC44\uB110 \uC548\uC5D0\uC11C\uB9CC \uC751\uB2F5\uD558\uC2ED\uC2DC\uC624.","error.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 {seconds}\uCD08 \uB0B4\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","error.parseFailure":"\uCC38\uAC00\uC790 `{participantId}`\uC758 `<{tag}>` \uBE14\uB85D\uC744 \uD574\uC11D\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.","error.sessionNotFound":"\uD1A0\uB860 \uC138\uC158 `{sessionId}`\uC744(\uB97C) \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.invalidState":"\uC0C1\uD0DC `{state}`\uC5D0\uC11C\uB294 `{operation}` \uC791\uC5C5\uC744 \uC218\uD589\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.unknownLocaleFallback":"\uC54C \uC218 \uC5C6\uB294 \uB85C\uCF00\uC77C `{locale}`; \uAE30\uBCF8\uAC12 `{fallback}`(\uC73C)\uB85C \uB300\uCCB4\uD569\uB2C8\uB2E4.","askUser.escalation.header":"\uCD5C\uB300 \uB77C\uC6B4\uB4DC\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC73C\uB098 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4","askUser.escalation.question":"\uC5B4\uB5BB\uAC8C \uC9C4\uD589\uD558\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?","askUser.escalation.continue":"{rounds}\uB77C\uC6B4\uB4DC \uCD94\uAC00 \uC9C4\uD589","askUser.escalation.escalate":"\uD569\uC758 \uC5C6\uC774 \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","askUser.escalation.stop":"\uD1A0\uB860 \uC885\uB8CC"};var Pm={"report.header.topic":"\u30C6\u30FC\u30DE","report.header.participants":"\u53C2\u52A0\u8005","report.header.individualDocs":"\u500B\u5225\u30EC\u30D3\u30E5\u30FC\u6587\u66F8","report.table.proposer":"\u63D0\u6848\u8005","report.table.opinion":"\u610F\u898B","report.table.severity":"\u91CD\u5927\u5EA6","report.table.agreement":"\u5408\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u5E33","report.section.dissentDetail":"\u672A\u5408\u610F\u9805\u76EE\u306E\u8A73\u7D30","report.section.contributionSummary":"AI \u8CA2\u732E\u5EA6\u30B5\u30DE\u30EA\u30FC","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u6848","report.contribution.accepted":"\u63A1\u629E","report.contribution.revises":"\u4FEE\u6B63\u8981\u8ACB","report.contribution.abstains":"\u68C4\u6A29","report.footer.synthesisPath":"\u6700\u7D42\u5408\u610F\u6587\u66F8","report.footer.debatePath":"\u8A0E\u8B70\u8A18\u9332","report.footer.pendingSynthesis":"(\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u5F85\u3061)","report.status.running":"\u9032\u884C\u4E2D","report.status.readyForApproval":"\u627F\u8A8D\u5F85\u3061","report.status.consensus":"\u5408\u610F\u5F62\u6210","report.status.escalated":"\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","report.status.approved":"\u627F\u8A8D\u6E08\u307F","report.status.rejected":"\u5374\u4E0B","report.status.leaderTimeout":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","report.status.error":"\u30A8\u30E9\u30FC","synthesis.status.consensus":"\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F","synthesis.status.escalated":"\u90E8\u5206\u5408\u610F / \u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","synthesis.section.acceptedItems":"\u63A1\u629E\u9805\u76EE","synthesis.section.rejectedItems":"\u5374\u4E0B / \u53D6\u308A\u4E0B\u3052\u9805\u76EE","synthesis.section.openItems":"\u672A\u6C7A\u9805\u76EE","synthesis.section.sources":"\u6839\u62E0","synthesis.narration.consensusIn":"\u5168 {max} \u30E9\u30A6\u30F3\u30C9\u4E2D {round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","synthesis.narration.escalated":"{round} \u30E9\u30A6\u30F3\u30C9\u7D4C\u904E\u3057\u3066\u3082\u5408\u610F\u306B\u81F3\u3089\u305A\u3001\u30E6\u30FC\u30B6\u30FC\u5224\u65AD\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3\u3055\u308C\u307E\u3057\u305F\u3002","synthesis.narration.leaderNote":"\u30EA\u30FC\u30C0\u30FC\u30E1\u30E2","approval.pending":"\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u3092\u5F85\u6A5F\u3057\u3066\u3044\u307E\u3059\u3002`agent_debate_approve`\u3001`agent_debate_continue`\u3001`agent_debate_reject` \u306E\u3044\u305A\u308C\u304B\u3092\u547C\u3073\u51FA\u3057\u3066\u304F\u3060\u3055\u3044\u3002","approval.timeout":"\u30EA\u30FC\u30C0\u30FC\u5224\u65AD\u3092\u5F85\u6A5F\u4E2D\u306B\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F({hours} \u6642\u9593)\u3002","moderator.narration.roundHeader":"\u30E9\u30A6\u30F3\u30C9 {round}/{max}","moderator.narration.consensusInRound":"{round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u6C7A\u9805\u76EE","moderator.narration.noInterest":"\u53C2\u52A0\u8005\u306E\u95A2\u5FC3\u306A\u3057","moderator.narration.participantDropout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u7E70\u308A\u8FD4\u3057\u306E\u5931\u6557\u306B\u3088\u308A\u5229\u7528\u4E0D\u53EF\u3068\u3057\u3066\u30DE\u30FC\u30AF\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u4ECA\u56DE\u306E\u30E9\u30A6\u30F3\u30C9\u3067\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","moderator.narration.leaderTimeoutFooter":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","moderator.narration.rejected":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u5374\u4E0B\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.approved":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u627F\u8A8D\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.aliasClarification":"\u5225\u540D\u78BA\u8A8D\u30D5\u30A7\u30FC\u30BA","prompt.system.moderator":"\u3042\u306A\u305F\u306F\u69CB\u9020\u5316\u30DE\u30EB\u30C1 AI \u8A0E\u8B70\u306E\u30E2\u30C7\u30EC\u30FC\u30BF\u30FC\u3067\u3059\u3002\u63D0\u6848\u3092\u81EA\u3089\u8D77\u6848\u305B\u305A\u3001\u69CB\u9020\u5316\u6295\u7968\u3092\u96C6\u8A08\u3057\u3066\u4E2D\u7ACB\u7684\u306A\u5408\u610F\u6848\u3092\u63D0\u793A\u3057\u307E\u3059\u3002\u30D7\u30ED\u30C8\u30B3\u30EB\u304C\u5B9A\u7FA9\u3059\u308B\u30C1\u30E3\u30CD\u30EB\u306E\u7BC4\u56F2\u5185\u3067\u306E\u307F\u5FDC\u7B54\u3057\u3066\u304F\u3060\u3055\u3044\u3002","error.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F {seconds} \u79D2\u4EE5\u5185\u306B\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.parseFailure":"\u53C2\u52A0\u8005 `{participantId}` \u306E `<{tag}>` \u30D6\u30ED\u30C3\u30AF\u3092\u89E3\u6790\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.sessionNotFound":"\u8A0E\u8B70\u30BB\u30C3\u30B7\u30E7\u30F3 `{sessionId}` \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.invalidState":"\u72B6\u614B `{state}` \u3067\u306F\u64CD\u4F5C `{operation}` \u3092\u5B9F\u884C\u3067\u304D\u307E\u305B\u3093\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u306E\u30ED\u30B1\u30FC\u30EB `{locale}`\u3002\u65E2\u5B9A\u5024 `{fallback}` \u306B\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u307E\u3059\u3002","askUser.escalation.header":"\u6700\u5927\u30E9\u30A6\u30F3\u30C9\u306B\u9054\u3057\u307E\u3057\u305F\u304C\u5408\u610F\u306B\u81F3\u308A\u307E\u305B\u3093\u3067\u3057\u305F","askUser.escalation.question":"\u3069\u306E\u3088\u3046\u306B\u9032\u3081\u307E\u3059\u304B?","askUser.escalation.continue":"{rounds} \u30E9\u30A6\u30F3\u30C9\u8FFD\u52A0\u3057\u3066\u7D9A\u884C","askUser.escalation.escalate":"\u5408\u610F\u306A\u3057\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","askUser.escalation.stop":"\u8A0E\u8B70\u3092\u7D42\u4E86"};var Tm={"report.header.topic":"\u4E3B\u9898","report.header.participants":"\u53C2\u4E0E\u8005","report.header.individualDocs":"\u4E2A\u4EBA\u8BC4\u5BA1\u6587\u6863","report.table.proposer":"\u63D0\u8BAE\u8005","report.table.opinion":"\u610F\u89C1","report.table.severity":"\u4E25\u91CD\u7A0B\u5EA6","report.table.agreement":"\u540C\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u8D26","report.section.dissentDetail":"\u672A\u8FBE\u6210\u4E00\u81F4\u9879\u8BE6\u60C5","report.section.contributionSummary":"AI \u8D21\u732E\u6C47\u603B","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u51FA","report.contribution.accepted":"\u91C7\u7EB3","report.contribution.revises":"\u4FEE\u8BA2\u8BF7\u6C42","report.contribution.abstains":"\u5F03\u6743","report.footer.synthesisPath":"\u6700\u7EC8\u5171\u8BC6\u6587\u6863","report.footer.debatePath":"\u8FA9\u8BBA\u8BB0\u5F55","report.footer.pendingSynthesis":"(\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6)","report.status.running":"\u8FDB\u884C\u4E2D","report.status.readyForApproval":"\u5F85\u6279\u51C6","report.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","report.status.escalated":"\u5DF2\u5347\u7EA7","report.status.approved":"\u5DF2\u6279\u51C6","report.status.rejected":"\u5DF2\u62D2\u7EDD","report.status.leaderTimeout":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","report.status.error":"\u9519\u8BEF","synthesis.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","synthesis.status.escalated":"\u90E8\u5206\u5171\u8BC6 / \u5DF2\u5347\u7EA7","synthesis.section.acceptedItems":"\u91C7\u7EB3\u9879","synthesis.section.rejectedItems":"\u62D2\u7EDD / \u64A4\u56DE\u9879","synthesis.section.openItems":"\u672A\u51B3\u9879","synthesis.section.sources":"\u4F9D\u636E","synthesis.narration.consensusIn":"\u5728\u5168\u90E8 {max} \u8F6E\u4E2D\u7684\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","synthesis.narration.escalated":"\u7ECF\u8FC7 {round} \u8F6E\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6,\u7531\u7528\u6237\u51B3\u5B9A\u5347\u7EA7\u5904\u7406\u3002","synthesis.narration.leaderNote":"\u8D1F\u8D23\u4EBA\u5907\u6CE8","approval.pending":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6\u3002\u8BF7\u8C03\u7528 `agent_debate_approve`\u3001`agent_debate_continue` \u6216 `agent_debate_reject`\u3002","approval.timeout":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u51B3\u7B56\u671F\u95F4\u4F1A\u8BDD\u5DF2\u8D85\u65F6({hours} \u5C0F\u65F6)\u3002","moderator.narration.roundHeader":"\u7B2C {round}/{max} \u8F6E","moderator.narration.consensusInRound":"\u5728\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u51B3\u9879","moderator.narration.noInterest":"\u53C2\u4E0E\u8005\u65E0\u5174\u8DA3","moderator.narration.participantDropout":"\u53C2\u4E0E\u8005 `{participantId}` \u56E0\u591A\u6B21\u5931\u8D25\u88AB\u6807\u8BB0\u4E3A\u4E0D\u53EF\u7528\u3002","moderator.narration.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728\u672C\u8F6E\u672A\u4F5C\u51FA\u54CD\u5E94\u3002","moderator.narration.leaderTimeoutFooter":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","moderator.narration.rejected":"\u8D1F\u8D23\u4EBA\u5DF2\u62D2\u7EDD\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.approved":"\u8D1F\u8D23\u4EBA\u5DF2\u6279\u51C6\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.aliasClarification":"\u522B\u540D\u6F84\u6E05\u9636\u6BB5","prompt.system.moderator":"\u4F60\u662F\u7ED3\u6784\u5316\u591A AI \u8FA9\u8BBA\u7684\u4E3B\u6301\u4EBA\u3002\u4F60\u4E0D\u64B0\u5199\u63D0\u6848,\u800C\u662F\u6C47\u603B\u7ED3\u6784\u5316\u6295\u7968\u5E76\u4EA7\u51FA\u4E2D\u7ACB\u7684\u5171\u8BC6\u65B9\u6848\u3002\u4EC5\u5728\u534F\u8BAE\u5B9A\u4E49\u7684\u901A\u9053\u8303\u56F4\u5185\u4F5C\u51FA\u54CD\u5E94\u3002","error.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728 {seconds} \u79D2\u5185\u672A\u54CD\u5E94\u3002","error.parseFailure":"\u65E0\u6CD5\u89E3\u6790\u53C2\u4E0E\u8005 `{participantId}` \u7684 `<{tag}>` \u5757\u3002","error.sessionNotFound":"\u672A\u627E\u5230\u8FA9\u8BBA\u4F1A\u8BDD `{sessionId}`\u3002","error.invalidState":"\u5728\u72B6\u6001 `{state}` \u4E0B\u4E0D\u5141\u8BB8\u6267\u884C\u64CD\u4F5C `{operation}`\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u533A\u57DF `{locale}`,\u56DE\u9000\u5230 `{fallback}`\u3002","askUser.escalation.header":"\u5DF2\u8FBE\u6700\u5927\u8F6E\u6B21\u4F46\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6","askUser.escalation.question":"\u60A8\u5E0C\u671B\u5982\u4F55\u7EE7\u7EED?","askUser.escalation.continue":"\u518D\u8FDB\u884C {rounds} \u8F6E","askUser.escalation.escalate":"\u4E0D\u8FBE\u6210\u5171\u8BC6\u5373\u5347\u7EA7","askUser.escalation.stop":"\u7ED3\u675F\u8FA9\u8BBA"};var Em=Object.freeze({en:$m,ko:km,ja:Pm,zh:Tm});function j0(t){return typeof t=="string"&&Js.includes(t)}function cu(t,e){return e===void 0?t:t.replace(/\{(\w+)\}/g,(r,n)=>{if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];return typeof o=="number"?String(o):o}return r})}function lu(t){return t===void 0?uu(Rr):j0(t)?uu(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${Rr}`),uu(Rr))}function L0(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return cu(i,s);let a=r[o];return a!==void 0?(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in locale '${t}', falling back to ${Fc}`)),cu(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),cu(o,s))}}}function uu(t){return L0(t,Em[t],Em[Fc])}async function Rm(t){let e=await fetch(`${t}/api/tags`);if(!e.ok)throw new Error(`Ollama API error: ${e.status}`);return((await e.json()).models||[]).map(n=>({name:n.name||"unknown",size:n.size||0,strengths:F0(n.name||"")}))}function F0(t){let e=["chat"],r=t.toLowerCase();return(r.includes("coder")||r.includes("code"))&&e.push("code_review","code_generation"),r.includes("instruct")&&e.push("instruction_following"),r.includes("embed")&&e.push("embedding"),e}var Gr=class t{id;type="ollama";host;defaultModel;maxContext;available=!1;unavailableUntil=0;models=[];timeouts;static RATE_LIMIT_BACKOFF_MS=6e4;constructor(e){this.id=e.id,this.host=e.host,this.defaultModel=e.defaultModel||"auto",this.maxContext=e.maxContext??32768,this.timeouts={default:e.timeouts?.default??3e4,generate:e.timeouts?.generate??3e5,chat:e.timeouts?.chat??3e5}}async initialize(){try{this.models=await Rm(this.host),this.available=this.models.length>0,this.available&&(this.unavailableUntil=0)}catch{this.available=!1}}async healthCheck(){try{let e=await fetch(`${this.host}/api/tags`);if(!e.ok)return{status:"error",message:`HTTP ${e.status}`};let r=await e.json(),n=r.models?.length??0;return{status:n>0?"ok":"degraded",message:`${n} models available`,details:{models:r.models?.map(o=>o.name)}}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:this.maxContext,supportsSystemPrompt:!0,supportsFiles:!1,supportsStreaming:!0,supportsJsonOutput:!1,supportsToolUse:!0,strengths:[...new Set(this.models.flatMap(e=>e.strengths))],models:this.models.map(e=>({name:e.name,description:`Ollama model (${Math.round(e.size/1e9)}GB)`,strengths:e.strengths,sizeGb:e.size/1e9}))}}isAvailable(){return this.unavailableUntil>0&&Date.now()<this.unavailableUntil?!1:(this.unavailableUntil>0&&Date.now()>=this.unavailableUntil&&(this.unavailableUntil=0),this.available)}async chat(e){if(!this.available)throw new de(this.id,"Ollama not running or no models installed");let r=e.model||this.selectModel(),n={model:r,prompt:e.prompt,system:e.system||"You are a helpful assistant.",stream:!1,...e.extra||{}},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeouts.generate),i=()=>o.abort(e.signal.reason);e.signal&&(e.signal.aborted?o.abort(e.signal.reason):e.signal.addEventListener("abort",i));try{let a=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(a.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new de(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!a.ok)throw new Be(this.id,`HTTP ${a.status}: ${a.statusText}`);let c=await a.json();return{text:c.response||"",model:c.model||r,provider:this.id}}catch(a){throw a.name==="AbortError"?new hn(this.id,this.timeouts.generate):a instanceof Be||a instanceof de?a:new Be(this.id,a.message)}finally{clearTimeout(s),e.signal&&e.signal.removeEventListener("abort",i)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new de(this.id,`No models detected. Install a model first (ollama pull ${df})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var U0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function Im(t){return t.split(`
44
- `).filter(n=>{let o=n.trim();return o?!U0.some(s=>s.test(o)):!1}).join(`
45
- `).trim()}function Am(t){try{let e=JSON.parse(t.trim());if(e&&typeof e.response=="string")return e.response}catch{let e=t.split(`
46
- `);for(let r=e.length-1;r>=0;r--){let n=e[r].trim();if(n.startsWith("{"))try{let o=JSON.parse(n);if(o&&typeof o.response=="string")return o.response}catch{}}}return null}var du="gemini",pu="@google/gemini-cli",Yr=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;limiter=new Rn(wf);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await An(du,pu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){if(!this.available)return{status:"error",message:"Gemini CLI not installed"};try{let{command:e,cliArgs:r}=pr(this.cliPath,du,pu,["--version"]),n=await Me({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Gemini CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["long_context","file_analysis","translation","summarization"],models:[{name:"gemini-2.5-pro",description:"Google Gemini 2.5 Pro via CLI",strengths:["long_context","reasoning"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available)throw new de(this.id,"Gemini CLI not installed");let r=Jr(e),n=vi(e,r),s=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=pr(this.cliPath,du,pu,s),c=Sm(this.id);try{let u=await Me({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,onStderrChunk:p=>c.feed(p),signal:e.signal});if(u.exitCode!==0)try{Cn(u.exitCode,u.stderr,this.id)}catch(p){throw p.markUnavailable&&(this.available=!1),p}let l=Am(u.stdout);if(l!==null){let p=q0(u.stdout);return{text:l,model:p,provider:this.id}}return{text:Im(u.stdout),model:"gemini",provider:this.id}}catch(u){if(u instanceof de)throw u.markUnavailable&&(this.available=!1),u;Dn(u,this.id,this.timeout)}}};function q0(t){try{let e=JSON.parse(t.trim());if(e?.stats?.models){for(let[n,o]of Object.entries(e.stats.models))if(o?.roles?.main)return n;let r=Object.keys(e.stats.models);if(r.length>0)return r[0]}}catch{}return"gemini"}import{randomUUID as V0}from"crypto";function fu(t){let e=t.trim().split(`
43
+ \`\`\``);return e}function A0(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var fr=class{id;type;bridge;modelName;displayName;capabilities;constructor(e){this.id=e.id??e.bridge.providerId,this.type=e.type,this.bridge=e.bridge,this.modelName=e.modelName??e.type,this.displayName=e.displayName,this.capabilities=e.capabilities}async initialize(){}async healthCheck(){return this.bridge.healthCheck?this.bridge.healthCheck():this.bridge.isAvailable()?{status:"ok",message:`${this.displayName} host bridge available`}:{status:"error",message:`${this.displayName} host bridge unavailable`}}getCapabilities(){return{...this.capabilities,models:this.capabilities.models.map((e,r)=>r===0?{...e,name:this.modelName}:{...e})}}getDescriptor(){return ir(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new de(this.id,`${this.displayName} host bridge is not available`);try{let r=I0(e),n={...e.extra??{}};e.model&&(n.model=e.model),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.maxTokens=="number"&&(n.maxTokens=e.maxTokens);let o=await this.bridge.runTurn({prompt:r,system:e.system,metadata:n});return{text:o.text,model:A0(this.modelName,o.metadata),provider:this.id,metadata:o.metadata}}catch(r){let n=r instanceof Error?r.message:String(r);throw/sampling|host bridge unavailable|does not support/i.test(n)?new de(this.id,n):new We(this.id,n)}}};var C0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude-host",description:"Claude host model via MCP sampling bridge",strengths:["reasoning","review","synthesis"]}]},_i=class extends fr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:C0,modelName:e.modelName??"claude-host"})}};var D0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["coding","reasoning","review","implementation"],models:[{name:"codex-host",description:"Codex host model via MCP sampling bridge",strengths:["coding","implementation","review"]}]},bi=class extends fr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:D0,modelName:e.modelName??"codex-host"})}};var z0={maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["analysis","reasoning","research","review"],models:[{name:"gemini-host",description:"Gemini host model via MCP sampling bridge",strengths:["analysis","research","review"]}]},wi=class extends fr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:z0,modelName:e.modelName??"gemini-host"})}};Vt();var Pm={"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 Tm={"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 Em={"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 Rm={"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 Im=Object.freeze({en:Pm,ko:Tm,ja:Em,zh:Rm});function L0(t){return typeof t=="string"&&Gs.includes(t)}function uu(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 du(t){return t===void 0?lu(Er):L0(t)?lu(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${Er}`),lu(Er))}function F0(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return uu(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 ${Zc}`)),uu(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),uu(o,s))}}}function lu(t){return F0(t,Im[t],Im[Zc])}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:Z0(n.name||"")}))}function Z0(t){let e=["chat"],r=t.toLowerCase();return(r.includes("coder")||r.includes("code"))&&e.push("code_review","code_generation"),r.includes("instruct")&&e.push("instruction_following"),r.includes("embed")&&e.push("embedding"),e}var Gr=class t{id;type="ollama";host;defaultModel;maxContext;available=!1;unavailableUntil=0;models=[];timeouts;static RATE_LIMIT_BACKOFF_MS=6e4;constructor(e){this.id=e.id,this.host=e.host,this.defaultModel=e.defaultModel||"auto",this.maxContext=e.maxContext??32768,this.timeouts={default:e.timeouts?.default??3e4,generate:e.timeouts?.generate??3e5,chat:e.timeouts?.chat??3e5}}async initialize(){try{this.models=await Am(this.host),this.available=this.models.length>0,this.available&&(this.unavailableUntil=0)}catch{this.available=!1}}async healthCheck(){try{let e=await fetch(`${this.host}/api/tags`);if(!e.ok)return{status:"error",message:`HTTP ${e.status}`};let r=await e.json(),n=r.models?.length??0;return{status:n>0?"ok":"degraded",message:`${n} models available`,details:{models:r.models?.map(o=>o.name)}}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:this.maxContext,supportsSystemPrompt:!0,supportsFiles:!1,supportsStreaming:!0,supportsJsonOutput:!1,supportsToolUse:!0,strengths:[...new Set(this.models.flatMap(e=>e.strengths))],models:this.models.map(e=>({name:e.name,description:`Ollama model (${Math.round(e.size/1e9)}GB)`,strengths:e.strengths,sizeGb:e.size/1e9}))}}isAvailable(){return this.unavailableUntil>0&&Date.now()<this.unavailableUntil?!1:(this.unavailableUntil>0&&Date.now()>=this.unavailableUntil&&(this.unavailableUntil=0),this.available)}async chat(e){if(!this.available)throw new de(this.id,"Ollama not running or no models installed");let r=e.model||this.selectModel(),n={model:r,prompt:e.prompt,system:e.system||"You are a helpful assistant.",stream:!1,...e.extra||{}},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeouts.generate),i=()=>o.abort(e.signal.reason);e.signal&&(e.signal.aborted?o.abort(e.signal.reason):e.signal.addEventListener("abort",i));try{let a=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(a.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new de(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!a.ok)throw new We(this.id,`HTTP ${a.status}: ${a.statusText}`);let c=await a.json();return{text:c.response||"",model:c.model||r,provider:this.id}}catch(a){throw a.name==="AbortError"?new hn(this.id,this.timeouts.generate):a instanceof We||a instanceof de?a:new We(this.id,a.message)}finally{clearTimeout(s),e.signal&&e.signal.removeEventListener("abort",i)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new de(this.id,`No models detected. Install a model first (ollama pull ${ff})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var q0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function Cm(t){return t.split(`
44
+ `).filter(n=>{let o=n.trim();return o?!q0.some(s=>s.test(o)):!1}).join(`
45
+ `).trim()}function Dm(t){try{let e=JSON.parse(t.trim());if(e&&typeof e.response=="string")return e.response}catch{let e=t.split(`
46
+ `);for(let r=e.length-1;r>=0;r--){let n=e[r].trim();if(n.startsWith("{"))try{let o=JSON.parse(n);if(o&&typeof o.response=="string")return o.response}catch{}}}return null}var pu="gemini",fu="@google/gemini-cli",Jr=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;limiter=new Rn(Sf);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await An(pu,fu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){if(!this.available)return{status:"error",message:"Gemini CLI not installed"};try{let{command:e,cliArgs:r}=pr(this.cliPath,pu,fu,["--version"]),n=await Me({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Gemini CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["long_context","file_analysis","translation","summarization"],models:[{name:"gemini-2.5-pro",description:"Google Gemini 2.5 Pro via CLI",strengths:["long_context","reasoning"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available)throw new de(this.id,"Gemini CLI not installed");let r=Kr(e),n=vi(e,r),s=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=pr(this.cliPath,pu,fu,s),c=km(this.id);try{let u=await Me({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,onStderrChunk:p=>c.feed(p),signal:e.signal});if(u.exitCode!==0)try{Cn(u.exitCode,u.stderr,this.id)}catch(p){throw p.markUnavailable&&(this.available=!1),p}let l=Dm(u.stdout);if(l!==null){let p=V0(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 de)throw u.markUnavailable&&(this.available=!1),u;Dn(u,this.id,this.timeout)}}};function V0(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 B0}from"crypto";function mu(t){let e=t.trim().split(`
47
47
  `),r=[];for(let n of e)try{let o=JSON.parse(n);o.type==="item.completed"&&o.item?.type==="agent_message"&&o.item.text&&r.push(o.item.text)}catch{n.trim()&&r.push(n.trim())}return r.join(`
48
- `)||t.trim()}var xi="codex",Si="@openai/codex";function B0(t){return["-C",t]}function W0(t,e,r){return["exec","--skip-git-repo-check","-C",r,"--full-auto","--ephemeral","--json","--",e?"-":t]}var Xr=class{id;type="codex-cli";timeout;available=!1;cliPath=null;appServer=null;defaultCwd;constructor(e){this.id=e.id,this.timeout=e.timeout??6e5,this.defaultCwd=e.workspaceBaseDir??process.cwd()}async initialize(){let e=await An(xi,Si);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new yi({command:this.cliPath==="npx"?"npx":xi,commandPrefix:this.cliPath==="npx"?[Si]:void 0,commandArgs:B0(this.defaultCwd)}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=pr(this.cliPath,xi,Si,["--version"]),n=await Me({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Codex CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:128e3,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!0,strengths:["code_generation","code_review","autonomous_execution"],models:[{name:"codex",description:"OpenAI Codex CLI",strengths:["code_generation"]}]}}isAvailable(){return this.available}async chat(e){if(!this.available)throw new de(this.id,"Codex CLI not installed");if(this.appServer&&!this.appServer.shouldFallback())try{return await this.chatViaAppServer(e)}catch(r){if(!this.shouldFallbackFrom(r))throw r}return this.chatViaCli(e)}shouldFallbackFrom(e){return!(e instanceof ct||e instanceof de||e instanceof Be)}async shutdown(){this.appServer&&await this.appServer.shutdown()}async chatViaAppServer(e){let r={method:"exec",params:{prompt:au(Jr(e)),fullAuto:!0,ephemeral:!0},id:V0()},n=await this.appServer.request(r,this.timeout,e.signal);if(n.error)throw new Be(this.id,n.error.message);return{text:fu(JSON.stringify(n.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=au(Jr(e)),n=process.platform==="win32"||vi(e,r),o=e.workspaceBaseDir??this.defaultCwd,s=W0(r,n,o),{command:i,cliArgs:a}=pr(this.cliPath,xi,Si,s);try{let c=await Me({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,signal:e.signal});if(c.exitCode!==0)try{Cn(c.exitCode,c.stderr,this.id)}catch(l){throw l.markUnavailable&&(this.available=!1),l}return{text:fu(c.stdout),model:"codex",provider:this.id}}catch(c){Dn(c,this.id,this.timeout)}}};function Cm(t){try{return JSON.parse(t.trim())}catch{return null}}function Dm(t){let e=Cm(t);if(e)return e;let r=t.split(`
49
- `);for(let n=r.length-1;n>=0;n--){let o=r[n].trim();if(!o.startsWith("{"))continue;let s=Cm(o);if(s)return s}return null}function zm(t){let e=Dm(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function Om(t){let e=Dm(t);return typeof e?.model=="string"?e.model:"claude"}var H0=1,mu="claude",hu="@anthropic-ai/claude-code",Qr=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new Rn(H0);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await An(mu,hu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return xm(this.cliPath,mu,hu,"Claude")}getCapabilities(){return{maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude",description:"Anthropic Claude Code CLI",strengths:["reasoning","review","synthesis"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available||!this.cliPath)throw new de(this.id,"Claude CLI not installed");let r=Jr(e),n=["-p","--output-format","json"];e.model&&n.push("--model",e.model),n.push(r);let{command:o,cliArgs:s}=pr(this.cliPath,mu,hu,n);try{let i=await Me({command:o,args:s,timeout:this.timeout,signal:e.signal});if(i.exitCode!==0){let c=[i.stderr,i.stdout].filter(Boolean).join(`
50
- `).trim();try{Cn(i.exitCode,c,this.id)}catch(u){throw(u.markUnavailable||/auth|credential|login|api key|oauth|token|401/i.test(c))&&(this.available=!1),u}}return{text:zm(i.stdout)??i.stdout.trim(),model:Om(i.stdout),provider:this.id}}catch(i){Dn(i,this.id,this.timeout)}}};import{randomUUID as K0}from"crypto";var J0=7200*1e3,Do=class{debates=new Map;create(e){this.purgeStaleDebates();let r=K0(),n=new Date().toISOString(),o={id:r,topic:e.topic,goal:e.goal,providerIds:e.providerIds,turns:[],status:"active",documentId:e.documentId,createdAt:n};return this.debates.set(r,o),o}addTurn(e,r,n){let o=this.getState(e);if(!o)throw new Error(`Debate not found: ${e}`);if(o.status==="concluded")throw new Error(`Debate already concluded: ${e}`);let s={turnNumber:o.turns.length+1,speaker:r,content:n,timestamp:new Date().toISOString()};return o.turns.push(s),o}buildPromptForProvider(e,r){let n=this.getState(e);if(!n)throw new Error(`Debate not found: ${e}`);let o=`Topic: ${n.topic}
48
+ `)||t.trim()}var xi="codex",Si="@openai/codex";function W0(t){return["-C",t]}function H0(t,e,r){return["exec","--skip-git-repo-check","-C",r,"--full-auto","--ephemeral","--json","--",e?"-":t]}var Yr=class{id;type="codex-cli";timeout;available=!1;cliPath=null;appServer=null;defaultCwd;constructor(e){this.id=e.id,this.timeout=e.timeout??6e5,this.defaultCwd=e.workspaceBaseDir??process.cwd()}async initialize(){let e=await An(xi,Si);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new yi({command:this.cliPath==="npx"?"npx":xi,commandPrefix:this.cliPath==="npx"?[Si]:void 0,commandArgs:W0(this.defaultCwd)}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=pr(this.cliPath,xi,Si,["--version"]),n=await Me({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Codex CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:128e3,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!0,strengths:["code_generation","code_review","autonomous_execution"],models:[{name:"codex",description:"OpenAI Codex CLI",strengths:["code_generation"]}]}}isAvailable(){return this.available}async chat(e){if(!this.available)throw new de(this.id,"Codex CLI not installed");let r=e.workspaceBaseDir,n=typeof r=="string"&&r.length>0&&r!==this.defaultCwd;if(this.appServer&&!this.appServer.shouldFallback()&&!n)try{return await this.chatViaAppServer(e)}catch(o){if(!this.shouldFallbackFrom(o))throw o}return this.chatViaCli(e)}shouldFallbackFrom(e){return!(e instanceof at||e instanceof de||e instanceof We)}async shutdown(){this.appServer&&await this.appServer.shutdown()}async chatViaAppServer(e){let r={method:"exec",params:{prompt:cu(Kr(e)),fullAuto:!0,ephemeral:!0},id:B0()},n=await this.appServer.request(r,this.timeout,e.signal);if(n.error)throw new We(this.id,n.error.message);return{text:mu(JSON.stringify(n.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=cu(Kr(e)),n=process.platform==="win32"||vi(e,r),o=e.workspaceBaseDir??this.defaultCwd,s=H0(r,n,o),{command:i,cliArgs:a}=pr(this.cliPath,xi,Si,s);try{let c=await Me({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,signal:e.signal});if(c.exitCode!==0)try{Cn(c.exitCode,c.stderr,this.id)}catch(l){throw l.markUnavailable&&(this.available=!1),l}return{text:mu(c.stdout),model:"codex",provider:this.id}}catch(c){Dn(c,this.id,this.timeout)}}};function zm(t){try{return JSON.parse(t.trim())}catch{return null}}function Om(t){let e=zm(t);if(e)return e;let r=t.split(`
49
+ `);for(let n=r.length-1;n>=0;n--){let o=r[n].trim();if(!o.startsWith("{"))continue;let s=zm(o);if(s)return s}return null}function Mm(t){let e=Om(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function Nm(t){let e=Om(t);return typeof e?.model=="string"?e.model:"claude"}var K0=1,hu="claude",gu="@anthropic-ai/claude-code",Xr=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new Rn(K0);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await An(hu,gu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return $m(this.cliPath,hu,gu,"Claude")}getCapabilities(){return{maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude",description:"Anthropic Claude Code CLI",strengths:["reasoning","review","synthesis"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available||!this.cliPath)throw new de(this.id,"Claude CLI not installed");let r=Kr(e),n=["-p","--output-format","json"];e.model&&n.push("--model",e.model),n.push(r);let{command:o,cliArgs:s}=pr(this.cliPath,hu,gu,n);try{let i=await Me({command:o,args:s,timeout:this.timeout,signal:e.signal});if(i.exitCode!==0){let c=[i.stderr,i.stdout].filter(Boolean).join(`
50
+ `).trim();try{Cn(i.exitCode,c,this.id)}catch(u){throw(u.markUnavailable||/auth|credential|login|api key|oauth|token|401/i.test(c))&&(this.available=!1),u}}return{text:Mm(i.stdout)??i.stdout.trim(),model:Nm(i.stdout),provider:this.id}}catch(i){Dn(i,this.id,this.timeout)}}};import{randomUUID as G0}from"crypto";var J0=7200*1e3,zo=class{debates=new Map;create(e){this.purgeStaleDebates();let r=G0(),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}
51
51
  `;if(n.goal&&(o+=`Goal: ${n.goal}
52
52
  `),n.turns.length>0){o+=`
53
53
  === Conversation History ===
@@ -57,7 +57,7 @@ ${r.content}
57
57
  `}let a=n.turns.slice(-Ks),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
58
58
  ${u.content}
59
59
 
60
- `;if(c.length+l.length>Mc){c+=`[... history truncated at ${Mc} characters]
60
+ `;if(c.length+l.length>Nc){c+=`[... history truncated at ${Nc} characters]
61
61
 
62
62
  `;break}c+=l}o+=c,o+=`===
63
63
 
@@ -93,31 +93,31 @@ Evaluation goal: ${n.goal}
93
93
 
94
94
  ${o.content}
95
95
 
96
- `;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let o=new Date(n.createdAt).getTime();e-o>J0&&this.debates.delete(r)}}};import{mkdirSync as G0,readFileSync as Mm,readdirSync as gu,existsSync as $i,renameSync as Y0,rmdirSync as X0}from"fs";import{join as Q0}from"path";import{randomUUID as eP}from"crypto";function yu(t){if(t.providers<=0)throw new Error(`deriveTerminalStatus: providers must be positive, got ${t.providers}`);if(t.failed<0||t.failed>t.providers)throw new Error(`deriveTerminalStatus: failed (${t.failed}) out of range [0, ${t.providers}]`);return t.failed===0?"completed":t.failed===t.providers?"failed":"completed_with_errors"}var Nm=new Set(["completed","completed_with_errors","failed"]);function jm(t,e){return Nm.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&Nm.has(e)||t==="in_progress"&&e==="in_progress")}function Lm(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}var zo=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,G0(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=Q0(this.sessionDir,"sessions");if(!$i(e))return;let r;try{r=gu(e)}catch(o){console.warn(`[SessionManager] failed to read legacy nested dir ${e}: ${String(o)}`);return}let n=r.filter(o=>o.endsWith(".json"));for(let o of n){let s,i;try{s=Le(o,e),i=Le(o,this.sessionDir)}catch(a){console.warn(`[SessionManager] skipped legacy file ${JSON.stringify(o)}: ${String(a)}`);continue}if($i(i)){console.warn(`[SessionManager] migration skipped ${o}: destination already exists at ${i}`);continue}try{Y0(s,i)}catch(a){console.warn(`[SessionManager] migration failed for ${o}: ${String(a)}`)}}try{gu(e).length===0&&X0(e)}catch(o){console.warn(`[SessionManager] could not remove legacy nested dir ${e}: ${String(o)}`)}}createSession(e,r){let n=new Date().toISOString(),o={id:eP(),type:e,status:"pending",config:r,createdAt:n,updatedAt:n};return this.sessions.set(o.id,o),this.persist(o),o}getSession(e){let r=this.sessions.get(e);if(r)return r;if(!this.fullyLoaded){let n;try{n=Le(`${e}.json`,this.sessionDir)}catch{return}if($i(n))try{let o=Mm(n,"utf-8"),s=JSON.parse(o);return Lm(s)?(this.sessions.set(s.id,s),s):void 0}catch{}}}listSessions(){return this.ensureFullyLoaded(),[...this.sessions.values()]}updateSessionStatus(e,r){let n=this.getSession(e);if(!n)throw new Error(`Session not found: ${e}`);if(!jm(n.status,r))throw new Error(`Illegal session transition: ${n.id} ${n.status} -> ${r}`);n.status=r,n.updatedAt=new Date().toISOString(),this.persist(n)}transitionSession(e,r,n){let o=this.getSession(e);if(!o)throw new Error(`Session not found: ${e}`);if(!jm(o.status,r))throw new Error(`Illegal session transition: ${o.id} ${o.status} -> ${r}`);o.status=r,n!==void 0&&(o.result=n),o.updatedAt=new Date().toISOString(),this.persist(o)}completeSession(e,r){this.transitionSession(e,"completed",r)}persist(e){let r=Le(`${e.id}.json`,this.sessionDir);je(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!$i(this.sessionDir)){this.fullyLoaded=!0;return}let e=gu(this.sessionDir).filter(r=>r.endsWith(".json"));for(let r of e){let n=r.replace(/\.json$/,"");if(!this.sessions.has(n))try{let o=Le(r,this.sessionDir),s=Mm(o,"utf-8"),i=JSON.parse(s);if(!Lm(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function zn(t){if(!t||!t.trim())return null;try{return JSON.parse(t.trim())}catch{}let e=[],r=0,n=-1;for(let o=0;o<t.length;o++){let s=t[o];s==="{"?(r===0&&(n=o),r++):s==="}"&&(r--,r===0&&n>=0&&(e.push(t.slice(n,o+1)),n=-1),r<0&&(r=0))}if(e.length===0)return null;for(let o=e.length-1;o>=0;o--)try{return JSON.parse(e[o])}catch{continue}return null}function Fm(t,e,r){try{let n=zn(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var Oo=class{registry;chatAdapter;constructor(e,r){this.registry=e,this.chatAdapter=r}async chatWith(e,r){return this.chatAdapter?this.chatAdapter.chat(e,r):e.chat(r)}canValidate(e){if(this.chatAdapter){let r=this.registry.getCapability(e);return r.tier==="agent"||r.tier==="tool"}return this.isAgentTier(e)}async validate(e){let{items:r,criteria:n}=e,o=this.resolveValidators(e),s=[];for(let l of r)for(let d of o)d.id!==l.providerId&&s.push(this.reviewItem(l,d,n));let i=await Promise.all(s),a=this.detectConflicts(i),c=i.length>0&&i.every(l=>l.passed),u=i.length===0?this.chatAdapter?"No validators available for cross-validation.":"No agent-tier validators available for cross-validation.":void 0;return{reviews:i,overallPass:c,conflicts:a,message:u}}resolveValidators(e){if(e.validators)return e.validators.filter(o=>this.canValidate(o.id));let r=new Set,n=[];for(let o of e.items)r.has(o.providerId)||(r.add(o.providerId),this.canValidate(o.providerId)&&n.push(this.registry.get(o.providerId)));return n}isAgentTier(e){return this.registry.getCapability(e).tier==="agent"}async reviewItem(e,r,n){let o=n?`
96
+ `;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let o=new Date(n.createdAt).getTime();e-o>J0&&this.debates.delete(r)}}};import{mkdirSync as Y0,readFileSync as jm,readdirSync as yu,existsSync as $i,renameSync as X0,rmdirSync as Q0}from"fs";import{join as eP}from"path";import{randomUUID as tP}from"crypto";function vu(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 Lm=new Set(["completed","completed_with_errors","failed"]);function Fm(t,e){return Lm.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&Lm.has(e)||t==="in_progress"&&e==="in_progress")}function Zm(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 Oo=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,Y0(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=eP(this.sessionDir,"sessions");if(!$i(e))return;let r;try{r=yu(e)}catch(o){console.warn(`[SessionManager] failed to read legacy nested dir ${e}: ${String(o)}`);return}let n=r.filter(o=>o.endsWith(".json"));for(let o of n){let s,i;try{s=Le(o,e),i=Le(o,this.sessionDir)}catch(a){console.warn(`[SessionManager] skipped legacy file ${JSON.stringify(o)}: ${String(a)}`);continue}if($i(i)){console.warn(`[SessionManager] migration skipped ${o}: destination already exists at ${i}`);continue}try{X0(s,i)}catch(a){console.warn(`[SessionManager] migration failed for ${o}: ${String(a)}`)}}try{yu(e).length===0&&Q0(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:tP(),type:e,status:"pending",config:r,createdAt:n,updatedAt:n};return this.sessions.set(o.id,o),this.persist(o),o}getSession(e){let r=this.sessions.get(e);if(r)return r;if(!this.fullyLoaded){let n;try{n=Le(`${e}.json`,this.sessionDir)}catch{return}if($i(n))try{let o=jm(n,"utf-8"),s=JSON.parse(o);return Zm(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(!Fm(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(!Fm(o.status,r))throw new Error(`Illegal session transition: ${o.id} ${o.status} -> ${r}`);o.status=r,n!==void 0&&(o.result=n),o.updatedAt=new Date().toISOString(),this.persist(o)}completeSession(e,r){this.transitionSession(e,"completed",r)}persist(e){let r=Le(`${e.id}.json`,this.sessionDir);je(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!$i(this.sessionDir)){this.fullyLoaded=!0;return}let e=yu(this.sessionDir).filter(r=>r.endsWith(".json"));for(let r of e){let n=r.replace(/\.json$/,"");if(!this.sessions.has(n))try{let o=Le(r,this.sessionDir),s=jm(o,"utf-8"),i=JSON.parse(s);if(!Zm(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function zn(t){if(!t||!t.trim())return null;try{return JSON.parse(t.trim())}catch{}let e=[],r=0,n=-1;for(let o=0;o<t.length;o++){let s=t[o];s==="{"?(r===0&&(n=o),r++):s==="}"&&(r--,r===0&&n>=0&&(e.push(t.slice(n,o+1)),n=-1),r<0&&(r=0))}if(e.length===0)return null;for(let o=e.length-1;o>=0;o--)try{return JSON.parse(e[o])}catch{continue}return null}function Um(t,e,r){try{let n=zn(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var Mo=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?`
97
97
  Additional criteria: ${n}`:"",s=[`You are a cross-validator reviewing work from provider "${e.providerId}".`,`Task: ${e.task}`,`Content to review:
98
98
  ${e.content}`,o,"",'Respond with JSON only: { "passed": boolean, "feedback": "string", "suggestedFixes": "string or omit" }'].join(`
99
- `),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return Fm(n,o=>({targetProvider:e,reviewerProvider:r,passed:!!o.passed,feedback:String(o.feedback??""),suggestedFixes:o.suggestedFixes?String(o.suggestedFixes):void 0}),o=>({targetProvider:e,reviewerProvider:r,passed:!1,feedback:o}))}detectConflicts(e){let r=[],n=new Map;for(let o of e){let s=o.targetProvider;n.has(s)||n.set(s,[]),n.get(s).push(o)}for(let[o,s]of n){if(s.length<2)continue;let i=s.filter(c=>c.passed),a=s.filter(c=>!c.passed);if(i.length>0&&a.length>0){let c=i.map(l=>l.reviewerProvider).join(", "),u=a.map(l=>l.reviewerProvider).join(", ");r.push(`Conflict on "${o}": passed by [${c}], failed by [${u}]`)}}return r}};import{readFileSync as qm,readdirSync as Vm,statSync as Pi}from"fs";import{join as Bm,relative as nP}from"path";var Zm=50*1024,ki=500,Um=100;function oP(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function sP(t,e){let r=[],n=o=>{let s=Pi(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of Vm(o)){let a=Bm(o,i),c=Pi(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function iP(t,e){if(process.platform!=="win32")return{command:t,args:e};let r=n=>`'${n.replace(/'/g,"''")}'`;switch(t){case"ls":{let n=e.length>0?r(e[0]):".",o=e.slice(1).map(r);return{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-ChildItem -Name -LiteralPath ${n}${o.length?" "+o.join(" "):""}`]}}case"cat":return e.length===0?{command:t,args:e}:{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-Content -LiteralPath ${e.map(r).join(",")}`]};default:return{command:t,args:e}}}var Wm={name:"file_read",description:"Read the contents of a file. Returns the text content.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},offset:{type:"number",description:"Line offset to start reading from (0-based)"},limit:{type:"number",description:"Maximum number of lines to read"}},async execute(t,e){let r=Gt(String(t.path??""),e),n=qm(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
99
+ `),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return Um(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 Bm,readdirSync as Wm,statSync as Pi}from"fs";import{join as Hm,relative as oP}from"path";var qm=50*1024,ki=500,Vm=100;function sP(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function iP(t,e){let r=[],n=o=>{let s=Pi(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of Wm(o)){let a=Hm(o,i),c=Pi(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function aP(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 Km={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=Yt(String(t.path??""),e),n=Bm(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
100
100
  `),s=Number(t.offset??0),i=Number(t.limit??o.length);n=o.slice(s,s+i).join(`
101
- `)}return Buffer.byteLength(n,"utf-8")>Zm&&(n=In(n,Zm,`
102
- ... [truncated]`)),n}},aP={name:"file_write",description:"Write content to a file. Creates parent directories if needed. Overwrites existing files.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},content:{type:"string",description:"Content to write",required:!0}},async execute(t,e){let r=pt(String(t.path??""),e),n=String(t.content??"");return oe(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},Hm={name:"file_list",description:"List files and directories at the given path.",parameters:{path:{type:"string",description:"Directory path relative to workspace (default: '.')"},recursive:{type:"boolean",description:"List recursively (default: false)"}},async execute(t,e){let r=Gt(String(t.path??"."),e),n=!!t.recursive,o=[];function s(a,c){if(o.length>=ki)return;let u=Vm(a);for(let l of u){if(o.length>=ki)break;let d=Bm(a,l),p=c?`${c}/${l}`:l;try{let f=Pi(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=ki?`
101
+ `)}return Buffer.byteLength(n,"utf-8")>qm&&(n=In(n,qm,`
102
+ ... [truncated]`)),n}},cP={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=dt(String(t.path??""),e),n=String(t.content??"");return oe(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},Gm={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=Yt(String(t.path??"."),e),n=!!t.recursive,o=[];function s(a,c){if(o.length>=ki)return;let u=Wm(a);for(let l of u){if(o.length>=ki)break;let d=Hm(a,l),p=c?`${c}/${l}`:l;try{let f=Pi(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=ki?`
103
103
  ... [truncated at ${ki} entries]`:"";return o.join(`
104
- `)+i}},Km={name:"grep_search",description:"Search file contents with a regex pattern. Returns matching lines with file paths and line numbers.",parameters:{pattern:{type:"string",description:"Regular expression pattern to search for",required:!0},path:{type:"string",description:"Directory or file path to search in (default: '.')"},glob:{type:"string",description:"Glob pattern to filter files (e.g., '*.ts')"}},async execute(t,e){let r=String(t.pattern??""),n=Gt(String(t.path??"."),e),o=t.glob?oP(String(t.glob)):null,s=Pi(n).isDirectory(),i=sP(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=nP(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=qm(u,"utf-8")}catch{continue}let p=d.split(/\r?\n/);for(let f=0;f<p.length;f++)if(a.test(p[f])&&(c.push(`${l}:${f+1}:${p[f]}`),c.length>=Um))return c.join(`
104
+ `)+i}},Jm={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=Yt(String(t.path??"."),e),o=t.glob?sP(String(t.glob)):null,s=Pi(n).isDirectory(),i=iP(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=oP(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=Bm(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>=Vm))return c.join(`
105
105
  `)+`
106
- ... [truncated at ${Um} matches]`}return c.join(`
107
- `)||"No matches found."}catch{return"No matches found."}}},cP={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...pi].join(", ")}). Shell operators (pipes, chaining, subshells) are blocked.`,parameters:{command:{type:"string",description:"Shell command to execute",required:!0}},async execute(t,e){let r=String(t.command??"").trim();if(!r)return"Error: empty command";let n=im(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=iP(s,i);try{let c=await Me({command:a.command,args:a.args,timeout:3e4,cwd:e,maxBuffer:102400}),u=c.stdout;return c.stderr&&(u+=(u?`
106
+ ... [truncated at ${Vm} matches]`}return c.join(`
107
+ `)||"No matches found."}catch{return"No matches found."}}},uP={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...pi].join(", ")}). Shell operators (pipes, chaining, subshells) are blocked.`,parameters:{command:{type:"string",description:"Shell command to execute",required:!0}},async execute(t,e){let r=String(t.command??"").trim();if(!r)return"Error: empty command";let n=cm(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=aP(s,i);try{let c=await Me({command:a.command,args:a.args,timeout:3e4,cwd:e,maxBuffer:102400}),u=c.stdout;return c.stderr&&(u+=(u?`
108
108
  `:"")+`[stderr] ${c.stderr}`),c.exitCode!==0&&(u+=`
109
109
  [exit code: ${c.exitCode}]`),c.truncated&&(u+=`
110
- ... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${z(c)}`}}};function vu(){return[Wm,aP,Hm,Km,cP]}function Ti(){return[Wm,Hm,Km]}function _u(t){return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:e.parameters,required:Object.entries(e.parameters).filter(([,r])=>r.required===!0).map(([r])=>r)}}}))}var uP=15,lP=30,dP=3e5,pP=2e3,fP=`You are a coding assistant with access to tools for reading, writing, and searching files in a workspace. Use the provided tools when you need to inspect or modify code. When your task is complete, respond with your final answer without making any tool calls.
110
+ ... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${M(c)}`}}};function _u(){return[Km,cP,Gm,Jm,uP]}function Ti(){return[Km,Gm,Jm]}function bu(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 lP=15,dP=30,pP=3e5,fP=2e3,mP=`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.
111
111
 
112
112
  Guidelines:
113
113
  - Read files before modifying them to understand the existing code.
114
114
  - Use grep_search to find relevant code across the workspace.
115
115
  - Write complete file contents when using file_write (not just diffs).
116
- - Provide a clear summary of what you did when finished.`,Ei=class{host;model;baseDir;maxIterations;timeoutMs;systemPrompt;tools;toolDefs;toolMap;constructor(e){this.host=e.providerHost.replace(/\/$/,""),this.model=e.model,this.baseDir=e.baseDir,this.maxIterations=Math.min(e.maxIterations??uP,lP),this.timeoutMs=e.timeoutMs??dP,this.systemPrompt=e.systemPrompt??fP,this.tools=e.tools??vu(),this.toolDefs=_u(this.tools),this.toolMap=new Map(this.tools.map(r=>[r.name,r]))}async run(e){let r=Date.now(),n=[],o="",s=[{role:"system",content:this.systemPrompt},{role:"user",content:e}];for(let i=0;i<this.maxIterations;i++){if(Date.now()-r>this.timeoutMs)return{success:!1,output:o||"Agent loop timed out before completion.",iterations:i,toolCalls:n,error:`Timed out after ${this.timeoutMs}ms`};let a;try{a=await this.callOllama(s)}catch(u){let l=z(u);return{success:!1,output:o||"",iterations:i,toolCalls:n,error:`Ollama API error: ${l}`}}let c=a.message;if(c.content&&(o=c.content),!c.tool_calls||c.tool_calls.length===0)return{success:!0,output:o,iterations:i+1,toolCalls:n};s.push(c);for(let u of c.tool_calls){let l=u.function.name,d=u.function.arguments,p;if(typeof d=="string"){let v=zn(d);p=v&&typeof v=="object"&&!Array.isArray(v)?v:{}}else p=d??{};let f=this.toolMap.get(l),m=Date.now(),g;if(!f)g=`Error: unknown tool '${l}'. Available tools: ${[...this.toolMap.keys()].join(", ")}`;else try{g=await f.execute(p,this.baseDir)}catch(v){g=`Error: ${z(v)}`}n.push({iteration:i,toolName:l,arguments:p,result:In(g,pP,"... [truncated in log]"),durationMs:Date.now()-m}),s.push({role:"tool",content:g})}}return{success:!1,output:o||"Agent loop reached max iterations without completing.",iterations:this.maxIterations,toolCalls:n,error:`Max iterations (${this.maxIterations}) reached`}}async callOllama(e){let r=`${this.host}/api/chat`,n={model:this.model,messages:e,tools:this.toolDefs,stream:!1},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`HTTP ${i.status}: ${a.slice(0,200)}`)}return await i.json()}finally{clearTimeout(s)}}};function Jm(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var On=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(Gs(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Jm(e);return o?{text:(await new Ei({providerHost:o.host,model:o.model,baseDir:this.baseDir,tools:this.tools}).run(r.prompt)).output,model:o.model,provider:e.id}:e.chat(r)}};import{existsSync as Mo,readFileSync as gP,readdirSync as yP}from"fs";import{join as Mn}from"path";var No=class{baseDir;constructor(e){this.baseDir=e}async run(e={}){let r=e.timeoutMs??12e4,n=e.buildProfile??"auto",o=this.resolveProfile(n),s=e.designDoc??this.detectDesignDoc(),i=o?await this.runProfile(o,r):{exitCode:0,output:"(no build profile resolved)"},a=i.exitCode===0,c=i.output,u=[];o?u.push(`${o.name}: ${a?"PASS":"FAIL"}`):u.push("No profile resolved"),s&&u.push(`Design doc: ${s}`);let d=`**AutoQA: ${a?"PASS":"FAIL"}**
116
+ - Provide a clear summary of what you did when finished.`,Ei=class{host;model;baseDir;maxIterations;timeoutMs;systemPrompt;tools;toolDefs;toolMap;constructor(e){this.host=e.providerHost.replace(/\/$/,""),this.model=e.model,this.baseDir=e.baseDir,this.maxIterations=Math.min(e.maxIterations??lP,dP),this.timeoutMs=e.timeoutMs??pP,this.systemPrompt=e.systemPrompt??mP,this.tools=e.tools??_u(),this.toolDefs=bu(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=zn(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:In(g,fP,"... [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 Ym(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var On=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(Js(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Ym(e);return o?{text:(await new Ei({providerHost:o.host,model:o.model,baseDir:this.baseDir,tools:this.tools}).run(r.prompt)).output,model:o.model,provider:e.id}:e.chat(r)}};import{existsSync as No,readFileSync as yP,readdirSync as vP}from"fs";import{join as Mn}from"path";var jo=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"}**
117
117
  ${u.join(`
118
- `)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:s??void 0,summary:d}}resolveProfile(e){if(e==="auto"){let n=this.detectBuildProfile();return n?{name:n.name,command:n.command,args:n.args}:null}let r=yn[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(Mo(Mn(this.baseDir,"tsconfig.json")))return yn.tsc;if(Mo(Mn(this.baseDir,"vitest.config.ts"))||Mo(Mn(this.baseDir,"vitest.config.js")))return yn.vitest;let e=this.getPackageScripts();return e?.build?yn["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?yn["npm-test"]:null}detectDesignDoc(){let e=Mn(this.baseDir,"docs","plans");if(!Mo(e))return null;try{let r=yP(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return Mn("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=Mn(this.baseDir,"package.json");if(!Mo(e))return null;try{return JSON.parse(gP(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{ui(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof st?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await Me({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),o=n.exitCode===0?n.stdout:`${n.stdout}
118
+ `)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:s??void 0,summary:d}}resolveProfile(e){if(e==="auto"){let n=this.detectBuildProfile();return n?{name:n.name,command:n.command,args:n.args}:null}let r=yn[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(No(Mn(this.baseDir,"tsconfig.json")))return yn.tsc;if(No(Mn(this.baseDir,"vitest.config.ts"))||No(Mn(this.baseDir,"vitest.config.js")))return yn.vitest;let e=this.getPackageScripts();return e?.build?yn["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?yn["npm-test"]:null}detectDesignDoc(){let e=Mn(this.baseDir,"docs","plans");if(!No(e))return null;try{let r=vP(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return Mn("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=Mn(this.baseDir,"package.json");if(!No(e))return null;try{return JSON.parse(yP(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{ui(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof ot?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await Me({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),o=n.exitCode===0?n.stdout:`${n.stdout}
119
119
  ${n.stderr}`.trim(),s=In(o,1e4,`
120
- ... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var vP=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),_P=/[\w./\\]+\.[a-z]{1,4}/gi,bP=/\b\d+\.?\d*\b/g,wP=/`[^`\n]+`/g,xP=/https?:\/\/\S+/g,SP=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function Ri(t){return Math.max(0,Math.min(1,t))}function Xt(t,e){return t.match(e)?.length??0}function $P(t){let r=t.split(/[.!?]+|\n+(?=\S)/g).map(n=>n.trim()).filter(n=>n.length>0);return r.length>0?r:t.trim().length>0?[t.trim()]:[]}function kP(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return vP.has(e)?!0:e.replace(/\s+/g,"").length<5}function PP(t){let e=$P(t);if(e.length===0)return .1;let r=e.filter(kP).length,n=(e.length-r)/e.length;return Math.max(.1,Ri(n))}function TP(t){let e=Xt(t,/^\s*#\s+/gm),r=Xt(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(Xt(t,/^\s*```/gm)/2),o=Xt(t,/^\s*.*\|.*\s*$/gm),s=e+r+n+o;return Ri(s/3)}function EP(t){let e=Xt(t,_P)+Xt(t,bP)+Xt(t,wP)+Xt(t,xP)+Xt(t,SP);return Ri(e/3)}function Gm(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function RP(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Gm(i.content))r.add(a);if(r.size===0)return 0;let n=Gm(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return Ri(o/s)}function jo(t,e,r){let n={substanceRatio:PP(t),structureScore:TP(t),specificityScore:EP(t),engagementScore:RP(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Ii,readFileSync as Ym,readdirSync as bu,existsSync as Lo,statSync as AP,unlinkSync as CP}from"fs";import{basename as Xm,join as Fo,relative as Qm,sep as eh}from"path";import{randomUUID as DP}from"crypto";var zP="reviews";function Nn(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function OP(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anonymous"}function jn(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}${r}${n}`}function th(t){return eh==="/"?t:t.split(eh).join("/")}var Zo=class{reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.reviewDir=Fo(e,zP),this.individualDir=Fo(e,gf),this.debateDir=Fo(e,Hs),this.synthesisDir=Fo(e,yf),Ii(this.reviewDir,{recursive:!0}),Ii(this.individualDir,{recursive:!0}),Ii(this.debateDir,{recursive:!0}),Ii(this.synthesisDir,{recursive:!0})}get allDirs(){return[this.individualDir,this.debateDir,this.synthesisDir,this.reviewDir]}nextSequenceGlobal(e){let r=0,n=new RegExp(`_${e}_(\\d{3})\\.md$`);for(let o of this.allDirs){if(!Lo(o))continue;let s;try{s=bu(o)}catch{continue}for(let i of s){let a=i.match(n);if(a){let c=parseInt(a[1],10);c>r&&(r=c)}}}return String(r+1).padStart(3,"0")}resolveDocPath(e){let r;for(let n of this.allDirs)try{let o=Le(`${e}.md`,n);if(Lo(o))return o}catch(o){r===void 0&&(r=o)}throw r!==void 0?r:new Error(`Document not found: ${e}`)}async createReview(e){let r=jn(),n=e.topic?Nn(e.topic):DP().slice(0,8),o=this.nextSequenceGlobal(r),s=e.provider?`${e.provider}_${n}_${r}_${o}`:`${n}_${r}_${o}`,i=Le(`${s}.md`,this.reviewDir),a=`# Review: ${e.topic??s}
120
+ ... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var _P=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),bP=/[\w./\\]+\.[a-z]{1,4}/gi,wP=/\b\d+\.?\d*\b/g,xP=/`[^`\n]+`/g,SP=/https?:\/\/\S+/g,$P=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function Ri(t){return Math.max(0,Math.min(1,t))}function Xt(t,e){return t.match(e)?.length??0}function kP(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 PP(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return _P.has(e)?!0:e.replace(/\s+/g,"").length<5}function TP(t){let e=kP(t);if(e.length===0)return .1;let r=e.filter(PP).length,n=(e.length-r)/e.length;return Math.max(.1,Ri(n))}function EP(t){let e=Xt(t,/^\s*#\s+/gm),r=Xt(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(Xt(t,/^\s*```/gm)/2),o=Xt(t,/^\s*.*\|.*\s*$/gm),s=e+r+n+o;return Ri(s/3)}function RP(t){let e=Xt(t,bP)+Xt(t,wP)+Xt(t,xP)+Xt(t,SP)+Xt(t,$P);return Ri(e/3)}function Xm(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function IP(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Xm(i.content))r.add(a);if(r.size===0)return 0;let n=Xm(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return Ri(o/s)}function Lo(t,e,r){let n={substanceRatio:TP(t),structureScore:EP(t),specificityScore:RP(t),engagementScore:IP(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Ii,readFileSync as Qm,readdirSync as wu,existsSync as Fo,statSync as CP,unlinkSync as DP}from"fs";import{basename as eh,join as Zo,relative as th,sep as rh}from"path";import{randomUUID as zP}from"crypto";var OP="reviews";function Nn(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function MP(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anonymous"}function jn(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}${r}${n}`}function nh(t){return rh==="/"?t:t.split(rh).join("/")}var Uo=class{reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.reviewDir=Zo(e,OP),this.individualDir=Zo(e,vf),this.debateDir=Zo(e,Hs),this.synthesisDir=Zo(e,_f),Ii(this.reviewDir,{recursive:!0}),Ii(this.individualDir,{recursive:!0}),Ii(this.debateDir,{recursive:!0}),Ii(this.synthesisDir,{recursive:!0})}get allDirs(){return[this.individualDir,this.debateDir,this.synthesisDir,this.reviewDir]}nextSequenceGlobal(e){let r=0,n=new RegExp(`_${e}_(\\d{3})\\.md$`);for(let o of this.allDirs){if(!Fo(o))continue;let s;try{s=wu(o)}catch{continue}for(let i of s){let a=i.match(n);if(a){let c=parseInt(a[1],10);c>r&&(r=c)}}}return String(r+1).padStart(3,"0")}resolveDocPath(e){let r;for(let n of this.allDirs)try{let o=Le(`${e}.md`,n);if(Fo(o))return o}catch(o){r===void 0&&(r=o)}throw r!==void 0?r:new Error(`Document not found: ${e}`)}async createReview(e){let r=jn(),n=e.topic?Nn(e.topic):zP().slice(0,8),o=this.nextSequenceGlobal(r),s=e.provider?`${e.provider}_${n}_${r}_${o}`:`${n}_${r}_${o}`,i=Le(`${s}.md`,this.reviewDir),a=`# Review: ${e.topic??s}
121
121
 
122
122
  `;a+=`**Date:** ${new Date().toISOString().slice(0,10)}
123
123
  `,e.provider&&(a+=`**Provider:** ${e.provider}
@@ -140,7 +140,7 @@ ${n.stderr}`.trim(),s=In(o,1e4,`
140
140
  `),a+=`
141
141
  ---
142
142
 
143
- `,oe(i,a),{id:s,content:a,path:i}}async createIndividualReview(e){let r=jn(),n=OP(e.participantId),o=Nn(e.topic),s=this.nextSequenceGlobal(r),i=`${n}_${o}_${r}_${s}`,a=Le(`${i}.md`,this.individualDir),c=`# ${e.topic} \u2014 ${e.participantId}
143
+ `,oe(i,a),{id:s,content:a,path:i}}async createIndividualReview(e){let r=jn(),n=MP(e.participantId),o=Nn(e.topic),s=this.nextSequenceGlobal(r),i=`${n}_${o}_${r}_${s}`,a=Le(`${i}.md`,this.individualDir),c=`# ${e.topic} \u2014 ${e.participantId}
144
144
 
145
145
  `;if(c+=`**Date:** ${new Date().toISOString().slice(0,10)}
146
146
  `,c+=`**Participant:** ${e.participantId}
@@ -155,7 +155,7 @@ ${n.stderr}`.trim(),s=In(o,1e4,`
155
155
  `,c+=e.content,c+=`
156
156
 
157
157
  ---
158
- `,oe(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=jn(),n=e.sessionId.slice(0,8),o=this.nextSequenceGlobal(r),s=`${vf}_${n}_${r}_${o}`,i=Le(`${s}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
158
+ `,oe(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=jn(),n=e.sessionId.slice(0,8),o=this.nextSequenceGlobal(r),s=`${bf}_${n}_${r}_${o}`,i=Le(`${s}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
159
159
 
160
160
  `;if(a+=`**Session:** ${e.sessionId}
161
161
  `,a+=`**Rejected at:** ${new Date().toISOString()}
@@ -174,7 +174,7 @@ ${n.stderr}`.trim(),s=In(o,1e4,`
174
174
  `}a+=`
175
175
  `}return a+=`
176
176
  ---
177
- `,oe(i,a),{id:s,content:a,path:i}}async createSynthesis(e){let r=jn(),n=Nn(e.topic),o=this.nextSequenceGlobal(r),s=`${n}_${r}_${o}`,i=Le(`${s}.md`,this.synthesisDir),a=th(Qm(this.synthesisDir,e.debatePath)),c=e.individualPaths.map(l=>th(Qm(this.synthesisDir,l))),u=`# Synthesis: ${e.topic}
177
+ `,oe(i,a),{id:s,content:a,path:i}}async createSynthesis(e){let r=jn(),n=Nn(e.topic),o=this.nextSequenceGlobal(r),s=`${n}_${r}_${o}`,i=Le(`${s}.md`,this.synthesisDir),a=nh(th(this.synthesisDir,e.debatePath)),c=e.individualPaths.map(l=>nh(th(this.synthesisDir,l))),u=`# Synthesis: ${e.topic}
178
178
 
179
179
  `;if(u+=`**Date:** ${new Date().toISOString().slice(0,10)}
180
180
  `,u+=`**Status:** ${e.status}
@@ -185,16 +185,16 @@ ${n.stderr}`.trim(),s=In(o,1e4,`
185
185
  `;if(u+=`
186
186
  ## Sources
187
187
 
188
- `,u+=`- Debate transcript: [${Xm(e.debatePath)}](${a})
188
+ `,u+=`- Debate transcript: [${eh(e.debatePath)}](${a})
189
189
  `,e.individualPaths.length>0){u+=`- Individual reviews:
190
- `;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${Xm(d)}](${c[l]})
190
+ `;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${eh(d)}](${c[l]})
191
191
  `}}return u+=`
192
192
  ---
193
193
 
194
194
  `,u+=e.body,u+=`
195
195
 
196
196
  ---
197
- `,oe(i,u),{id:s,content:u,path:i}}async appendToSynthesis(e,r){let n=Le(`${e}.md`,this.synthesisDir);if(!Lo(n))throw new Error(`Synthesis document not found: ${e}`);ai(n,`
197
+ `,oe(i,u),{id:s,content:u,path:i}}async appendToSynthesis(e,r){let n=Le(`${e}.md`,this.synthesisDir);if(!Fo(n))throw new Error(`Synthesis document not found: ${e}`);ai(n,`
198
198
  ${r}
199
199
  `)}async addComment(e,r){let n=this.resolveDocPath(e),o=`
200
200
  ## Comment by ${r.author}
@@ -202,78 +202,78 @@ ${r}
202
202
  ${r.content}
203
203
 
204
204
  ---
205
- `;ai(n,o)}async read(e){let r=this.resolveDocPath(e),n=Ym(r,"utf-8");return{id:e,content:n,path:r}}resolveKindDir(e){switch(e){case"individual":return this.individualDir;case"debate":return this.debateDir;case"synthesis":return this.synthesisDir;case"general":return this.reviewDir}}async createDocument(e){let r=e.kind??"general",n=this.resolveKindDir(r),o=jn(),s=e.topic?Nn(e.topic):Nn(e.title),i=this.nextSequenceGlobal(o),a=`${s}_${o}_${i}`,c=Le(`${a}.md`,n),u=`# ${e.title}
205
+ `;ai(n,o)}async read(e){let r=this.resolveDocPath(e),n=Qm(r,"utf-8");return{id:e,content:n,path:r}}resolveKindDir(e){switch(e){case"individual":return this.individualDir;case"debate":return this.debateDir;case"synthesis":return this.synthesisDir;case"general":return this.reviewDir}}async createDocument(e){let r=e.kind??"general",n=this.resolveKindDir(r),o=jn(),s=e.topic?Nn(e.topic):Nn(e.title),i=this.nextSequenceGlobal(o),a=`${s}_${o}_${i}`,c=Le(`${a}.md`,n),u=`# ${e.title}
206
206
 
207
207
  `;if(e.metadata){for(let[l,d]of Object.entries(e.metadata))u+=`**${l}:** ${d}
208
208
  `;u+=`
209
209
  `}return u+=e.content,u+=`
210
210
 
211
211
  ---
212
- `,oe(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!Lo(r))continue;let n=bu(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Le(o,r),a=Ym(i,"utf-8");e.push({id:s,content:a,path:i})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFilesPerDir??e.maxFiles??100,o=Date.now(),s=r*24*60*60*1e3,i=0;for(let a of this.allDirs){if(!Lo(a))continue;let c=bu(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Fo(a,u),d=AP(l);return{path:l,mtime:d.mtimeMs}}).sort((u,l)=>l.mtime-u.mtime);for(let u=0;u<c.length;u++){let l=o-c[u].mtime;if(u>=n||l>s)try{CP(c[u].path),i++}catch{}}}return{removed:i}}};var XZ=Object.freeze({status:"aborted"});function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Qt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ai={};function ft(t){return t&&Object.assign(Ai,t),Ai}var ae={};Ve(ae,{BIGINT_FORMAT_RANGES:()=>nh,Class:()=>xu,NUMBER_FORMAT_RANGES:()=>Iu,aborted:()=>tn,allowsEval:()=>Tu,assert:()=>FP,assertEqual:()=>MP,assertIs:()=>jP,assertNever:()=>LP,assertNotEqual:()=>NP,assignProp:()=>Pu,cached:()=>qo,captureStackTrace:()=>Di,cleanEnum:()=>QP,cleanRegex:()=>Bo,clone:()=>Ot,createTransparentProxy:()=>WP,defineLazy:()=>pe,esc:()=>en,escapeRegex:()=>mr,extend:()=>JP,finalizeIssue:()=>wt,floatSafeRemainder:()=>ku,getElementAtPath:()=>ZP,getEnumValues:()=>Su,getLengthableOrigin:()=>Wo,getParsedType:()=>BP,getSizableOrigin:()=>oh,isObject:()=>Ln,isPlainObject:()=>Fn,issue:()=>Au,joinValues:()=>Ci,jsonStringifyReplacer:()=>$u,merge:()=>GP,normalizeParams:()=>j,nullish:()=>Vo,numKeys:()=>VP,omit:()=>KP,optionalKeys:()=>Ru,partial:()=>YP,pick:()=>HP,prefixIssues:()=>Mt,primitiveTypes:()=>rh,promiseAllObject:()=>UP,propertyKeyTypes:()=>Eu,randomString:()=>qP,required:()=>XP,stringifyPrimitive:()=>zi,unwrapMessage:()=>Uo});function MP(t){return t}function NP(t){return t}function jP(t){}function LP(t){throw new Error}function FP(t){}function Su(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ci(t,e="|"){return t.map(r=>zi(r)).join(e)}function $u(t,e){return typeof e=="bigint"?e.toString():e}function qo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Vo(t){return t==null}function Bo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ku(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function pe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Pu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ZP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function UP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function qP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function en(t){return JSON.stringify(t)}var Di=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Tu=qo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Fn(t){if(Ln(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function VP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var BP=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Eu=new Set(["string","number","symbol"]),rh=new Set(["string","number","bigint","boolean","symbol","undefined"]);function mr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ot(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function j(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function WP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function zi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ru(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Iu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},nh={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function HP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Ot(t,{...t._zod.def,shape:r,checks:[]})}function KP(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Ot(t,{...t._zod.def,shape:r,checks:[]})}function JP(t,e){if(!Fn(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Pu(this,"shape",n),n},checks:[]};return Ot(t,r)}function GP(t,e){return Ot(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Pu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function YP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Ot(e,{...e._zod.def,shape:o,checks:[]})}function XP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Ot(e,{...e._zod.def,shape:o,checks:[]})}function tn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Mt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Uo(t){return typeof t=="string"?t:t?.message}function wt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Uo(t.inst?._zod.def?.error?.(t))??Uo(e?.error?.(t))??Uo(r.customError?.(t))??Uo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function oh(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Wo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Au(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function QP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var xu=class{constructor(...e){}};var sh=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,$u,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Oi=w("$ZodError",sh),Cu=w("$ZodError",sh,{Parent:Error});function ih(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function ah(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var ch=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Qt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>wt(c,s,ft())));throw Di(a,o?.callee),a}return i.value};var uh=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>wt(c,s,ft())));throw Di(a,o?.callee),a}return i.value};var Du=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Qt;return s.issues.length?{success:!1,error:new(t??Oi)(s.issues.map(i=>wt(i,o,ft())))}:{success:!0,data:s.value}},Ho=Du(Cu),zu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>wt(i,o,ft())))}:{success:!0,data:s.value}},Mi=zu(Cu);var lh=/^[cC][^\s-]{8,}$/,dh=/^[0-9a-z]+$/,ph=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fh=/^[0-9a-vA-V]{20}$/,mh=/^[A-Za-z0-9]{27}$/,hh=/^[a-zA-Z0-9_-]{21}$/,gh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var yh=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ou=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var vh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var tT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _h(){return new RegExp(tT,"u")}var bh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,wh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,xh=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Sh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$h=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mu=/^[A-Za-z0-9_-]*$/,kh=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Ph=/^\+(?:[0-9]){6,14}[0-9]$/,Th="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Eh=new RegExp(`^${Th}$`);function Rh(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ih(t){return new RegExp(`^${Rh(t)}$`)}function Ah(t){let e=Rh({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Th}T(?:${n})$`)}var Ch=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Dh=/^\d+$/,zh=/^-?\d+(?:\.\d+)?/i,Oh=/true|false/i,Mh=/null/i;var Nh=/^[^A-Z]*$/,jh=/^[^a-z]*$/;var Fe=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Lh={number:"number",bigint:"bigint",object:"date"},ju=w("$ZodCheckLessThan",(t,e)=>{Fe.init(t,e);let r=Lh[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Lu=w("$ZodCheckGreaterThan",(t,e)=>{Fe.init(t,e);let r=Lh[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Fh=w("$ZodCheckMultipleOf",(t,e)=>{Fe.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):ku(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Zh=w("$ZodCheckNumberFormat",(t,e)=>{Fe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Iu[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Dh)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var Uh=w("$ZodCheckMaxLength",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Vo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Wo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),qh=w("$ZodCheckMinLength",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Vo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Wo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Vh=w("$ZodCheckLengthEquals",(t,e)=>{var r;Fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Vo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Wo(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Ko=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Fe.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Bh=w("$ZodCheckRegex",(t,e)=>{Ko.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Wh=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Nh),Ko.init(t,e)}),Hh=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=jh),Ko.init(t,e)}),Kh=w("$ZodCheckIncludes",(t,e)=>{Fe.init(t,e);let r=mr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Jh=w("$ZodCheckStartsWith",(t,e)=>{Fe.init(t,e);let r=new RegExp(`^${mr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Gh=w("$ZodCheckEndsWith",(t,e)=>{Fe.init(t,e);let r=new RegExp(`.*${mr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Yh=w("$ZodCheckOverwrite",(t,e)=>{Fe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Ni=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
212
+ `,oe(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!Fo(r))continue;let n=wu(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Le(o,r),a=Qm(i,"utf-8");e.push({id:s,content:a,path:i})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFilesPerDir??e.maxFiles??100,o=Date.now(),s=r*24*60*60*1e3,i=0;for(let a of this.allDirs){if(!Fo(a))continue;let c=wu(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Zo(a,u),d=CP(l);return{path:l,mtime:d.mtimeMs}}).sort((u,l)=>l.mtime-u.mtime);for(let u=0;u<c.length;u++){let l=o-c[u].mtime;if(u>=n||l>s)try{DP(c[u].path),i++}catch{}}}return{removed:i}}};var rU=Object.freeze({status:"aborted"});function x(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Qt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ai={};function pt(t){return t&&Object.assign(Ai,t),Ai}var ae={};Be(ae,{BIGINT_FORMAT_RANGES:()=>sh,Class:()=>Su,NUMBER_FORMAT_RANGES:()=>Au,aborted:()=>en,allowsEval:()=>Eu,assert:()=>ZP,assertEqual:()=>NP,assertIs:()=>LP,assertNever:()=>FP,assertNotEqual:()=>jP,assignProp:()=>Tu,cached:()=>Vo,captureStackTrace:()=>Di,cleanEnum:()=>eT,cleanRegex:()=>Wo,clone:()=>Mt,createTransparentProxy:()=>HP,defineLazy:()=>pe,esc:()=>Qr,escapeRegex:()=>mr,extend:()=>JP,finalizeIssue:()=>wt,floatSafeRemainder:()=>Pu,getElementAtPath:()=>UP,getEnumValues:()=>$u,getLengthableOrigin:()=>Ho,getParsedType:()=>WP,getSizableOrigin:()=>ih,isObject:()=>Ln,isPlainObject:()=>Fn,issue:()=>Cu,joinValues:()=>Ci,jsonStringifyReplacer:()=>ku,merge:()=>YP,normalizeParams:()=>j,nullish:()=>Bo,numKeys:()=>BP,omit:()=>GP,optionalKeys:()=>Iu,partial:()=>XP,pick:()=>KP,prefixIssues:()=>Nt,primitiveTypes:()=>oh,promiseAllObject:()=>qP,propertyKeyTypes:()=>Ru,randomString:()=>VP,required:()=>QP,stringifyPrimitive:()=>zi,unwrapMessage:()=>qo});function NP(t){return t}function jP(t){return t}function LP(t){}function FP(t){throw new Error}function ZP(t){}function $u(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ci(t,e="|"){return t.map(r=>zi(r)).join(e)}function ku(t,e){return typeof e=="bigint"?e.toString():e}function Vo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Bo(t){return t==null}function Wo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Pu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function pe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Tu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function UP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function qP(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 VP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Qr(t){return JSON.stringify(t)}var Di=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Eu=Vo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Fn(t){if(Ln(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function BP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var WP=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}`)}},Ru=new Set(["string","number","symbol"]),oh=new Set(["string","number","bigint","boolean","symbol","undefined"]);function mr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mt(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 HP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function zi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Iu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Au={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]},sh={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function KP(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 Mt(t,{...t._zod.def,shape:r,checks:[]})}function GP(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 Mt(t,{...t._zod.def,shape:r,checks:[]})}function JP(t,e){if(!Fn(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Tu(this,"shape",n),n},checks:[]};return Mt(t,r)}function YP(t,e){return Mt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Tu(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 Mt(e,{...e._zod.def,shape:o,checks:[]})}function QP(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 Mt(e,{...e._zod.def,shape:o,checks:[]})}function en(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Nt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function qo(t){return typeof t=="string"?t:t?.message}function wt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=qo(t.inst?._zod.def?.error?.(t))??qo(e?.error?.(t))??qo(r.customError?.(t))??qo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function ih(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ho(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Cu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function eT(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Su=class{constructor(...e){}};var ah=(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,ku,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Oi=x("$ZodError",ah),Du=x("$ZodError",ah,{Parent:Error});function ch(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 uh(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 lh=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Qt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>wt(c,s,pt())));throw Di(a,o?.callee),a}return i.value};var dh=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>wt(c,s,pt())));throw Di(a,o?.callee),a}return i.value};var zu=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Qt;return s.issues.length?{success:!1,error:new(t??Oi)(s.issues.map(i=>wt(i,o,pt())))}:{success:!0,data:s.value}},Ko=zu(Du),Ou=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>wt(i,o,pt())))}:{success:!0,data:s.value}},Mi=Ou(Du);var ph=/^[cC][^\s-]{8,}$/,fh=/^[0-9a-z]+$/,mh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,hh=/^[0-9a-vA-V]{20}$/,gh=/^[A-Za-z0-9]{27}$/,yh=/^[a-zA-Z0-9_-]{21}$/,vh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _h=/^([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})$/,Mu=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 bh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var rT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function wh(){return new RegExp(rT,"u")}var xh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Sh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,$h=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,kh=/^(([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])$/,Ph=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Nu=/^[A-Za-z0-9_-]*$/,Th=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Eh=/^\+(?:[0-9]){6,14}[0-9]$/,Rh="(?:(?:\\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(`^${Rh}$`);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 Dh(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(`^${Rh}T(?:${n})$`)}var zh=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Oh=/^\d+$/,Mh=/^-?\d+(?:\.\d+)?/i,Nh=/true|false/i,jh=/null/i;var Lh=/^[^A-Z]*$/,Fh=/^[^a-z]*$/;var Ze=x("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Zh={number:"number",bigint:"bigint",object:"date"},Lu=x("$ZodCheckLessThan",(t,e)=>{Ze.init(t,e);let r=Zh[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})}}),Fu=x("$ZodCheckGreaterThan",(t,e)=>{Ze.init(t,e);let r=Zh[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})}}),Uh=x("$ZodCheckMultipleOf",(t,e)=>{Ze.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):Pu(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})}}),qh=x("$ZodCheckNumberFormat",(t,e)=>{Ze.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Au[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=Oh)}),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 Vh=x("$ZodCheckMaxLength",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Bo(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=Ho(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Bh=x("$ZodCheckMinLength",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Bo(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=Ho(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Wh=x("$ZodCheckLengthEquals",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Bo(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=Ho(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})}}),Go=x("$ZodCheckStringFormat",(t,e)=>{var r,n;Ze.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=()=>{})}),Hh=x("$ZodCheckRegex",(t,e)=>{Go.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})}}),Kh=x("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Lh),Go.init(t,e)}),Gh=x("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Fh),Go.init(t,e)}),Jh=x("$ZodCheckIncludes",(t,e)=>{Ze.init(t,e);let r=mr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Yh=x("$ZodCheckStartsWith",(t,e)=>{Ze.init(t,e);let r=new RegExp(`^${mr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Xh=x("$ZodCheckEndsWith",(t,e)=>{Ze.init(t,e);let r=new RegExp(`.*${mr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Qh=x("$ZodCheckOverwrite",(t,e)=>{Ze.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Ni=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
213
213
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
214
- `))}};var Qh={major:4,minor:0,patch:0};var fe=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Qh;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=tn(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Qt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=tn(s,d)))});else{if(s.issues.length===d)continue;c||(c=tn(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Qt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Ho(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Mi(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Li=w("$ZodString",(t,e)=>{fe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ch(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),he=w("$ZodStringFormat",(t,e)=>{Ko.init(t,e),Li.init(t,e)}),ug=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=yh),he.init(t,e)}),lg=w("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ou(n))}else e.pattern??(e.pattern=Ou());he.init(t,e)}),dg=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=vh),he.init(t,e)}),pg=w("$ZodURL",(t,e)=>{he.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:kh.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),fg=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=_h()),he.init(t,e)}),mg=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=hh),he.init(t,e)}),hg=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=lh),he.init(t,e)}),gg=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=dh),he.init(t,e)}),yg=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ph),he.init(t,e)}),vg=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=fh),he.init(t,e)}),_g=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=mh),he.init(t,e)}),bg=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ah(e)),he.init(t,e)}),wg=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Eh),he.init(t,e)}),xg=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ih(e)),he.init(t,e)}),Sg=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=gh),he.init(t,e)}),$g=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=bh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),kg=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=wh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Pg=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=xh),he.init(t,e)}),Tg=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Sh),he.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Eg(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Rg=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=$h),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Eg(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function rT(t){if(!Mu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Eg(r)}var Ig=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Mu),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{rT(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Ag=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ph),he.init(t,e)});function nT(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var Cg=w("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{nT(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Zu=w("$ZodNumber",(t,e)=>{fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??zh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Dg=w("$ZodNumber",(t,e)=>{Zh.init(t,e),Zu.init(t,e)}),zg=w("$ZodBoolean",(t,e)=>{fe.init(t,e),t._zod.pattern=Oh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var Og=w("$ZodNull",(t,e)=>{fe.init(t,e),t._zod.pattern=Mh,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var Mg=w("$ZodUnknown",(t,e)=>{fe.init(t,e),t._zod.parse=r=>r}),Ng=w("$ZodNever",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function eg(t,e,r){t.issues.length&&e.issues.push(...Mt(r,t.issues)),e.value[r]=t.value}var jg=w("$ZodArray",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>eg(u,r,i))):eg(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ji(t,e,r){t.issues.length&&e.issues.push(...Mt(r,t.issues)),e.value[r]=t.value}function tg(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Mt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var Lg=w("$ZodObject",(t,e)=>{fe.init(t,e);let r=qo(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof fe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Ru(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});pe(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let g of m.values)p[f].add(g)}}return p});let n=d=>{let p=new Ni(["shape","payload","ctx"]),f=r.value,m=S=>{let y=en(S);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),v=0;for(let S of f.keys)g[S]=`key_${v++}`;p.write("const newResult = {}");for(let S of f.keys)if(f.optionalKeys.has(S)){let y=g[S];p.write(`const ${y} = ${m(S)};`);let x=en(S);p.write(`
215
- if (${y}.issues.length) {
216
- if (input[${x}] === undefined) {
217
- if (${x} in input) {
218
- newResult[${x}] = undefined;
214
+ `))}};var tg={major:4,minor:0,patch:0};var fe=x("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=tg;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=en(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Qt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=en(s,d)))});else{if(s.issues.length===d)continue;c||(c=en(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Qt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Ko(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Mi(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Li=x("$ZodString",(t,e)=>{fe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??zh(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),he=x("$ZodStringFormat",(t,e)=>{Go.init(t,e),Li.init(t,e)}),dg=x("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=_h),he.init(t,e)}),pg=x("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Mu(n))}else e.pattern??(e.pattern=Mu());he.init(t,e)}),fg=x("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=bh),he.init(t,e)}),mg=x("$ZodURL",(t,e)=>{he.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Th.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})}}}),hg=x("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=wh()),he.init(t,e)}),gg=x("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=yh),he.init(t,e)}),yg=x("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ph),he.init(t,e)}),vg=x("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=fh),he.init(t,e)}),_g=x("$ZodULID",(t,e)=>{e.pattern??(e.pattern=mh),he.init(t,e)}),bg=x("$ZodXID",(t,e)=>{e.pattern??(e.pattern=hh),he.init(t,e)}),wg=x("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=gh),he.init(t,e)}),xg=x("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Dh(e)),he.init(t,e)}),Sg=x("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ih),he.init(t,e)}),$g=x("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ch(e)),he.init(t,e)}),kg=x("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=vh),he.init(t,e)}),Pg=x("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=xh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Tg=x("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Sh),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})}}}),Eg=x("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=$h),he.init(t,e)}),Rg=x("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=kh),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=x("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ph),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 nT(t){if(!Nu.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=x("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Nu),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{nT(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Dg=x("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Eh),he.init(t,e)});function oT(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 zg=x("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{oT(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Uu=x("$ZodNumber",(t,e)=>{fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Mh,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}}),Og=x("$ZodNumber",(t,e)=>{qh.init(t,e),Uu.init(t,e)}),Mg=x("$ZodBoolean",(t,e)=>{fe.init(t,e),t._zod.pattern=Nh,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 Ng=x("$ZodNull",(t,e)=>{fe.init(t,e),t._zod.pattern=jh,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 jg=x("$ZodUnknown",(t,e)=>{fe.init(t,e),t._zod.parse=r=>r}),Lg=x("$ZodNever",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function rg(t,e,r){t.issues.length&&e.issues.push(...Nt(r,t.issues)),e.value[r]=t.value}var Fg=x("$ZodArray",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>rg(u,r,i))):rg(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ji(t,e,r){t.issues.length&&e.issues.push(...Nt(r,t.issues)),e.value[r]=t.value}function ng(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(...Nt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var Zg=x("$ZodObject",(t,e)=>{fe.init(t,e);let r=Vo(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof fe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Iu(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});pe(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let g of m.values)p[f].add(g)}}return p});let n=d=>{let p=new Ni(["shape","payload","ctx"]),f=r.value,m=S=>{let w=Qr(S);return`shape[${w}]._zod.run({ value: input[${w}], 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 w=g[S];p.write(`const ${w} = ${m(S)};`);let _=Qr(S);p.write(`
215
+ if (${w}.issues.length) {
216
+ if (input[${_}] === undefined) {
217
+ if (${_} in input) {
218
+ newResult[${_}] = undefined;
219
219
  }
220
220
  } else {
221
221
  payload.issues = payload.issues.concat(
222
- ${y}.issues.map((iss) => ({
222
+ ${w}.issues.map((iss) => ({
223
223
  ...iss,
224
- path: iss.path ? [${x}, ...iss.path] : [${x}],
224
+ path: iss.path ? [${_}, ...iss.path] : [${_}],
225
225
  }))
226
226
  );
227
227
  }
228
- } else if (${y}.value === undefined) {
229
- if (${x} in input) newResult[${x}] = undefined;
228
+ } else if (${w}.value === undefined) {
229
+ if (${_} in input) newResult[${_}] = undefined;
230
230
  } else {
231
- newResult[${x}] = ${y}.value;
231
+ newResult[${_}] = ${w}.value;
232
232
  }
233
- `)}else{let y=g[S];p.write(`const ${y} = ${m(S)};`),p.write(`
234
- if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
233
+ `)}else{let w=g[S];p.write(`const ${w} = ${m(S)};`),p.write(`
234
+ if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
235
235
  ...iss,
236
- path: iss.path ? [${en(S)}, ...iss.path] : [${en(S)}]
237
- })));`),p.write(`newResult[${en(S)}] = ${y}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(S,y)=>_(d,S,y)},o,s=Ln,i=!Ai.jitless,c=i&&Tu.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let y=l.shape;for(let x of l.keys){let $=y[x],M=$._zod.run({value:f[x],issues:[]},p),O=$._zod.optin==="optional"&&$._zod.optout==="optional";M instanceof Promise?m.push(M.then(Y=>O?tg(Y,d,x,f):ji(Y,d,x))):O?tg(M,d,x,f):ji(M,d,x)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],v=l.keySet,_=u._zod,S=_.def.type;for(let y of Object.keys(f)){if(v.has(y))continue;if(S==="never"){g.push(y);continue}let x=_.run({value:f[y],issues:[]},p);x instanceof Promise?m.push(x.then($=>ji($,d,y))):ji(x,d,y)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function rg(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>wt(s,n,ft())))}),e}var Uu=w("$ZodUnion",(t,e)=>{fe.init(t,e),pe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),pe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),pe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),pe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Bo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>rg(i,r,t,n)):rg(s,r,t,n)}}),Fg=w("$ZodDiscriminatedUnion",(t,e)=>{Uu.init(t,e);let r=t._zod.parse;pe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=qo(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Ln(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Zg=w("$ZodIntersection",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>ng(r,c,u)):ng(r,s,i)}});function Fu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Fn(t)&&Fn(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Fu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Fu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function ng(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),tn(t))return t;let n=Fu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var Ug=w("$ZodRecord",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Fn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Mt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Mt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>wt(u,n,ft())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Mt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Mt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var qg=w("$ZodEnum",(t,e)=>{fe.init(t,e);let r=Su(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Eu.has(typeof n)).map(n=>typeof n=="string"?mr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Vg=w("$ZodLiteral",(t,e)=>{fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?mr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Bg=w("$ZodTransform",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Qt;return r.value=o,r}}),Wg=w("$ZodOptional",(t,e)=>{fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Bo(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Hg=w("$ZodNullable",(t,e)=>{fe.init(t,e),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Bo(r.source)}|null)$`):void 0}),pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Kg=w("$ZodDefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>og(s,e)):og(o,e)}});function og(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Jg=w("$ZodPrefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Gg=w("$ZodNonOptional",(t,e)=>{fe.init(t,e),pe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>sg(s,t)):sg(o,t)}});function sg(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Yg=w("$ZodCatch",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>wt(i,n,ft()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>wt(s,n,ft()))},input:r.value}),r.issues=[]),r)}});var Xg=w("$ZodPipe",(t,e)=>{fe.init(t,e),pe(t._zod,"values",()=>e.in._zod.values),pe(t._zod,"optin",()=>e.in._zod.optin),pe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ig(s,e,n)):ig(o,e,n)}});function ig(t,e,r){return tn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Qg=w("$ZodReadonly",(t,e)=>{fe.init(t,e),pe(t._zod,"propValues",()=>e.innerType._zod.propValues),pe(t._zod,"values",()=>e.innerType._zod.values),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(ag):ag(o)}});function ag(t){return t.value=Object.freeze(t.value),t}var ey=w("$ZodCustom",(t,e)=>{Fe.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>cg(s,r,n,t));cg(o,r,n,t)}});function cg(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Au(o))}}var oT=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},sT=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${oT(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${zi(n.values[0])}`:`Invalid option: expected one of ${Ci(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ci(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function ty(){return{localeError:sT()}}var qu=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function iT(){return new qu}var Jo=iT();function ry(t,e){return new t({type:"string",...j(e)})}function ny(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Vu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function oy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function sy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function iy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function ay(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function cy(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function uy(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function ly(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function dy(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function py(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function fy(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function my(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function hy(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function gy(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function yy(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function vy(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function _y(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function by(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function wy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function xy(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function Sy(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}function $y(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function ky(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function Py(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function Ty(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function Ey(t,e){return new t({type:"number",checks:[],...j(e)})}function Ry(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function Iy(t,e){return new t({type:"boolean",...j(e)})}function Ay(t,e){return new t({type:"null",...j(e)})}function Cy(t){return new t({type:"unknown"})}function Dy(t,e){return new t({type:"never",...j(e)})}function Fi(t,e){return new ju({check:"less_than",...j(e),value:t,inclusive:!1})}function Go(t,e){return new ju({check:"less_than",...j(e),value:t,inclusive:!0})}function Zi(t,e){return new Lu({check:"greater_than",...j(e),value:t,inclusive:!1})}function Yo(t,e){return new Lu({check:"greater_than",...j(e),value:t,inclusive:!0})}function Ui(t,e){return new Fh({check:"multiple_of",...j(e),value:t})}function qi(t,e){return new Uh({check:"max_length",...j(e),maximum:t})}function Zn(t,e){return new qh({check:"min_length",...j(e),minimum:t})}function Vi(t,e){return new Vh({check:"length_equals",...j(e),length:t})}function Bu(t,e){return new Bh({check:"string_format",format:"regex",...j(e),pattern:t})}function Wu(t){return new Wh({check:"string_format",format:"lowercase",...j(t)})}function Hu(t){return new Hh({check:"string_format",format:"uppercase",...j(t)})}function Ku(t,e){return new Kh({check:"string_format",format:"includes",...j(e),includes:t})}function Ju(t,e){return new Jh({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Gu(t,e){return new Gh({check:"string_format",format:"ends_with",...j(e),suffix:t})}function rn(t){return new Yh({check:"overwrite",tx:t})}function Yu(t){return rn(e=>e.normalize(t))}function Xu(){return rn(t=>t.trim())}function Qu(){return rn(t=>t.toLowerCase())}function el(){return rn(t=>t.toUpperCase())}function zy(t,e,r){return new t({type:"array",element:e,...j(r)})}function Oy(t,e,r){let n=j(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function My(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}function Un(t){return!!t._zod}function hr(t,e){return Un(t)?Ho(t,e):t.safeParse(e)}function Bi(t){if(!t)return;let e;if(Un(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ny(t){if(Un(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Qo={};Ve(Qo,{ZodISODate:()=>Ly,ZodISODateTime:()=>jy,ZodISODuration:()=>Zy,ZodISOTime:()=>Fy,date:()=>rl,datetime:()=>tl,duration:()=>ol,time:()=>nl});var jy=w("ZodISODateTime",(t,e)=>{bg.init(t,e),ve.init(t,e)});function tl(t){return $y(jy,t)}var Ly=w("ZodISODate",(t,e)=>{wg.init(t,e),ve.init(t,e)});function rl(t){return ky(Ly,t)}var Fy=w("ZodISOTime",(t,e)=>{xg.init(t,e),ve.init(t,e)});function nl(t){return Py(Fy,t)}var Zy=w("ZodISODuration",(t,e)=>{Sg.init(t,e),ve.init(t,e)});function ol(t){return Ty(Zy,t)}var Uy=(t,e)=>{Oi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>ah(t,r)},flatten:{value:r=>ih(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},BU=w("ZodError",Uy),es=w("ZodError",Uy,{Parent:Error});var qy=ch(es),Vy=uh(es),By=Du(es),Wy=zu(es);var Se=w("ZodType",(t,e)=>(fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>qy(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>By(t,r,n),t.parseAsync=async(r,n)=>Vy(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wy(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(nE(r,n)),t.superRefine=r=>t.check(oE(r)),t.overwrite=r=>t.check(rn(r)),t.optional=()=>xe(t),t.nullable=()=>Jy(t),t.nullish=()=>xe(Jy(t)),t.nonoptional=r=>GT(t,r),t.array=()=>Q(t),t.or=r=>me([t,r]),t.and=r=>Hi(t,r),t.transform=r=>il(t,ev(r)),t.default=r=>HT(t,r),t.prefault=r=>JT(t,r),t.catch=r=>XT(t,r),t.pipe=r=>il(t,r),t.readonly=()=>tE(t),t.describe=r=>{let n=t.clone();return Jo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Jo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Jo.get(t);let n=t.clone();return Jo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Gy=w("_ZodString",(t,e)=>{Li.init(t,e),Se.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Bu(...n)),t.includes=(...n)=>t.check(Ku(...n)),t.startsWith=(...n)=>t.check(Ju(...n)),t.endsWith=(...n)=>t.check(Gu(...n)),t.min=(...n)=>t.check(Zn(...n)),t.max=(...n)=>t.check(qi(...n)),t.length=(...n)=>t.check(Vi(...n)),t.nonempty=(...n)=>t.check(Zn(1,...n)),t.lowercase=n=>t.check(Wu(n)),t.uppercase=n=>t.check(Hu(n)),t.trim=()=>t.check(Xu()),t.normalize=(...n)=>t.check(Yu(...n)),t.toLowerCase=()=>t.check(Qu()),t.toUpperCase=()=>t.check(el())}),hT=w("ZodString",(t,e)=>{Li.init(t,e),Gy.init(t,e),t.email=r=>t.check(ny(gT,r)),t.url=r=>t.check(cy(yT,r)),t.jwt=r=>t.check(Sy(CT,r)),t.emoji=r=>t.check(uy(vT,r)),t.guid=r=>t.check(Vu(Hy,r)),t.uuid=r=>t.check(oy(Wi,r)),t.uuidv4=r=>t.check(sy(Wi,r)),t.uuidv6=r=>t.check(iy(Wi,r)),t.uuidv7=r=>t.check(ay(Wi,r)),t.nanoid=r=>t.check(ly(_T,r)),t.guid=r=>t.check(Vu(Hy,r)),t.cuid=r=>t.check(dy(bT,r)),t.cuid2=r=>t.check(py(wT,r)),t.ulid=r=>t.check(fy(xT,r)),t.base64=r=>t.check(by(RT,r)),t.base64url=r=>t.check(wy(IT,r)),t.xid=r=>t.check(my(ST,r)),t.ksuid=r=>t.check(hy($T,r)),t.ipv4=r=>t.check(gy(kT,r)),t.ipv6=r=>t.check(yy(PT,r)),t.cidrv4=r=>t.check(vy(TT,r)),t.cidrv6=r=>t.check(_y(ET,r)),t.e164=r=>t.check(xy(AT,r)),t.datetime=r=>t.check(tl(r)),t.date=r=>t.check(rl(r)),t.time=r=>t.check(nl(r)),t.duration=r=>t.check(ol(r))});function b(t){return ry(hT,t)}var ve=w("ZodStringFormat",(t,e)=>{he.init(t,e),Gy.init(t,e)}),gT=w("ZodEmail",(t,e)=>{dg.init(t,e),ve.init(t,e)});var Hy=w("ZodGUID",(t,e)=>{ug.init(t,e),ve.init(t,e)});var Wi=w("ZodUUID",(t,e)=>{lg.init(t,e),ve.init(t,e)});var yT=w("ZodURL",(t,e)=>{pg.init(t,e),ve.init(t,e)});var vT=w("ZodEmoji",(t,e)=>{fg.init(t,e),ve.init(t,e)});var _T=w("ZodNanoID",(t,e)=>{mg.init(t,e),ve.init(t,e)});var bT=w("ZodCUID",(t,e)=>{hg.init(t,e),ve.init(t,e)});var wT=w("ZodCUID2",(t,e)=>{gg.init(t,e),ve.init(t,e)});var xT=w("ZodULID",(t,e)=>{yg.init(t,e),ve.init(t,e)});var ST=w("ZodXID",(t,e)=>{vg.init(t,e),ve.init(t,e)});var $T=w("ZodKSUID",(t,e)=>{_g.init(t,e),ve.init(t,e)});var kT=w("ZodIPv4",(t,e)=>{$g.init(t,e),ve.init(t,e)});var PT=w("ZodIPv6",(t,e)=>{kg.init(t,e),ve.init(t,e)});var TT=w("ZodCIDRv4",(t,e)=>{Pg.init(t,e),ve.init(t,e)});var ET=w("ZodCIDRv6",(t,e)=>{Tg.init(t,e),ve.init(t,e)});var RT=w("ZodBase64",(t,e)=>{Rg.init(t,e),ve.init(t,e)});var IT=w("ZodBase64URL",(t,e)=>{Ig.init(t,e),ve.init(t,e)});var AT=w("ZodE164",(t,e)=>{Ag.init(t,e),ve.init(t,e)});var CT=w("ZodJWT",(t,e)=>{Cg.init(t,e),ve.init(t,e)});var Yy=w("ZodNumber",(t,e)=>{Zu.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(Zi(n,o)),t.gte=(n,o)=>t.check(Yo(n,o)),t.min=(n,o)=>t.check(Yo(n,o)),t.lt=(n,o)=>t.check(Fi(n,o)),t.lte=(n,o)=>t.check(Go(n,o)),t.max=(n,o)=>t.check(Go(n,o)),t.int=n=>t.check(Ky(n)),t.safe=n=>t.check(Ky(n)),t.positive=n=>t.check(Zi(0,n)),t.nonnegative=n=>t.check(Yo(0,n)),t.negative=n=>t.check(Fi(0,n)),t.nonpositive=n=>t.check(Go(0,n)),t.multipleOf=(n,o)=>t.check(Ui(n,o)),t.step=(n,o)=>t.check(Ui(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ce(t){return Ey(Yy,t)}var DT=w("ZodNumberFormat",(t,e)=>{Dg.init(t,e),Yy.init(t,e)});function Ky(t){return Ry(DT,t)}var zT=w("ZodBoolean",(t,e)=>{zg.init(t,e),Se.init(t,e)});function Ee(t){return Iy(zT,t)}var OT=w("ZodNull",(t,e)=>{Og.init(t,e),Se.init(t,e)});function al(t){return Ay(OT,t)}var MT=w("ZodUnknown",(t,e)=>{Mg.init(t,e),Se.init(t,e)});function _e(){return Cy(MT)}var NT=w("ZodNever",(t,e)=>{Ng.init(t,e),Se.init(t,e)});function jT(t){return Dy(NT,t)}var LT=w("ZodArray",(t,e)=>{jg.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Zn(r,n)),t.nonempty=r=>t.check(Zn(1,r)),t.max=(r,n)=>t.check(qi(r,n)),t.length=(r,n)=>t.check(Vi(r,n)),t.unwrap=()=>t.element});function Q(t,e){return zy(LT,t,e)}var Xy=w("ZodObject",(t,e)=>{Lg.init(t,e),Se.init(t,e),ae.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Qe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:_e()}),t.loose=()=>t.clone({...t._zod.def,catchall:_e()}),t.strict=()=>t.clone({...t._zod.def,catchall:jT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ae.extend(t,r),t.merge=r=>ae.merge(t,r),t.pick=r=>ae.pick(t,r),t.omit=r=>ae.omit(t,r),t.partial=(...r)=>ae.partial(tv,t,r[0]),t.required=(...r)=>ae.required(rv,t,r[0])});function I(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new Xy(r)}function He(t,e){return new Xy({type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ae.normalizeParams(e)})}var Qy=w("ZodUnion",(t,e)=>{Uu.init(t,e),Se.init(t,e),t.options=e.options});function me(t,e){return new Qy({type:"union",options:t,...ae.normalizeParams(e)})}var FT=w("ZodDiscriminatedUnion",(t,e)=>{Qy.init(t,e),Fg.init(t,e)});function cl(t,e,r){return new FT({type:"union",options:e,discriminator:t,...ae.normalizeParams(r)})}var ZT=w("ZodIntersection",(t,e)=>{Zg.init(t,e),Se.init(t,e)});function Hi(t,e){return new ZT({type:"intersection",left:t,right:e})}var UT=w("ZodRecord",(t,e)=>{Ug.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new UT({type:"record",keyType:t,valueType:e,...ae.normalizeParams(r)})}var sl=w("ZodEnum",(t,e)=>{qg.init(t,e),Se.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new sl({...e,checks:[],...ae.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new sl({...e,checks:[],...ae.normalizeParams(o),entries:s})}});function Qe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new sl({type:"enum",entries:r,...ae.normalizeParams(e)})}var qT=w("ZodLiteral",(t,e)=>{Vg.init(t,e),Se.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function C(t,e){return new qT({type:"literal",values:Array.isArray(t)?t:[t],...ae.normalizeParams(e)})}var VT=w("ZodTransform",(t,e)=>{Bg.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ae.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ae.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function ev(t){return new VT({type:"transform",transform:t})}var tv=w("ZodOptional",(t,e)=>{Wg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new tv({type:"optional",innerType:t})}var BT=w("ZodNullable",(t,e)=>{Hg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Jy(t){return new BT({type:"nullable",innerType:t})}var WT=w("ZodDefault",(t,e)=>{Kg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function HT(t,e){return new WT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var KT=w("ZodPrefault",(t,e)=>{Jg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function JT(t,e){return new KT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var rv=w("ZodNonOptional",(t,e)=>{Gg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function GT(t,e){return new rv({type:"nonoptional",innerType:t,...ae.normalizeParams(e)})}var YT=w("ZodCatch",(t,e)=>{Yg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function XT(t,e){return new YT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var QT=w("ZodPipe",(t,e)=>{Xg.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function il(t,e){return new QT({type:"pipe",in:t,out:e})}var eE=w("ZodReadonly",(t,e)=>{Qg.init(t,e),Se.init(t,e)});function tE(t){return new eE({type:"readonly",innerType:t})}var nv=w("ZodCustom",(t,e)=>{ey.init(t,e),Se.init(t,e)});function rE(t){let e=new Fe({check:"custom"});return e._zod.check=t,e}function ov(t,e){return Oy(nv,t??(()=>!0),e)}function nE(t,e={}){return My(nv,t,e)}function oE(t){let e=rE(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ae.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ae.issue(o))}},t(r.value,r)));return e}function ul(t,e){return il(ev(t),e)}ft(ty());var dl="2025-11-25";var sv=[dl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gr="io.modelcontextprotocol/related-task",Ji="2.0",Ae=ov(t=>t!==null&&(typeof t=="object"||typeof t=="function")),iv=me([b(),ce().int()]),av=b(),jq=He({ttl:me([ce(),al()]).optional(),pollInterval:ce().optional()}),sE=I({ttl:ce().optional()}),iE=I({taskId:b()}),pl=He({progressToken:iv.optional(),[gr]:iE.optional()}),at=I({_meta:pl.optional()}),ts=at.extend({task:sE.optional()}),cv=t=>ts.safeParse(t).success,Ce=I({method:b(),params:at.loose().optional()}),mt=I({_meta:pl.optional()}),ht=I({method:b(),params:mt.loose().optional()}),De=He({_meta:pl.optional()}),Gi=me([b(),ce().int()]),uv=I({jsonrpc:C(Ji),id:Gi,...Ce.shape}).strict(),fl=t=>uv.safeParse(t).success,lv=I({jsonrpc:C(Ji),...ht.shape}).strict(),dv=t=>lv.safeParse(t).success,ml=I({jsonrpc:C(Ji),id:Gi,result:De}).strict(),rs=t=>ml.safeParse(t).success;var ee;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ee||(ee={}));var hl=I({jsonrpc:C(Ji),id:Gi.optional(),error:I({code:ce().int(),message:b(),data:_e().optional()})}).strict();var pv=t=>hl.safeParse(t).success;var fv=me([uv,lv,ml,hl]),Lq=me([ml,hl]),Yi=De.strict(),aE=mt.extend({requestId:Gi.optional(),reason:b().optional()}),Xi=ht.extend({method:C("notifications/cancelled"),params:aE}),cE=I({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Qe(["light","dark"]).optional()}),ns=I({icons:Q(cE).optional()}),qn=I({name:b(),title:b().optional()}),mv=qn.extend({...qn.shape,...ns.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),uE=Hi(I({applyDefaults:Ee().optional()}),be(b(),_e())),lE=ul(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Hi(I({form:uE.optional(),url:Ae.optional()}),be(b(),_e()).optional())),dE=He({list:Ae.optional(),cancel:Ae.optional(),requests:He({sampling:He({createMessage:Ae.optional()}).optional(),elicitation:He({create:Ae.optional()}).optional()}).optional()}),pE=He({list:Ae.optional(),cancel:Ae.optional(),requests:He({tools:He({call:Ae.optional()}).optional()}).optional()}),fE=I({experimental:be(b(),Ae).optional(),sampling:I({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:lE.optional(),roots:I({listChanged:Ee().optional()}).optional(),tasks:dE.optional()}),mE=at.extend({protocolVersion:b(),capabilities:fE,clientInfo:mv}),gl=Ce.extend({method:C("initialize"),params:mE});var hE=I({experimental:be(b(),Ae).optional(),logging:Ae.optional(),completions:Ae.optional(),prompts:I({listChanged:Ee().optional()}).optional(),resources:I({subscribe:Ee().optional(),listChanged:Ee().optional()}).optional(),tools:I({listChanged:Ee().optional()}).optional(),tasks:pE.optional()}),gE=De.extend({protocolVersion:b(),capabilities:hE,serverInfo:mv,instructions:b().optional()}),yl=ht.extend({method:C("notifications/initialized"),params:mt.optional()});var Qi=Ce.extend({method:C("ping"),params:at.optional()}),yE=I({progress:ce(),total:xe(ce()),message:xe(b())}),vE=I({...mt.shape,...yE.shape,progressToken:iv}),ea=ht.extend({method:C("notifications/progress"),params:vE}),_E=at.extend({cursor:av.optional()}),os=Ce.extend({params:_E.optional()}),ss=De.extend({nextCursor:av.optional()}),bE=Qe(["working","input_required","completed","failed","cancelled"]),is=I({taskId:b(),status:bE,ttl:me([ce(),al()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ce()),statusMessage:xe(b())}),Vn=De.extend({task:is}),wE=mt.merge(is),as=ht.extend({method:C("notifications/tasks/status"),params:wE}),ta=Ce.extend({method:C("tasks/get"),params:at.extend({taskId:b()})}),ra=De.merge(is),na=Ce.extend({method:C("tasks/result"),params:at.extend({taskId:b()})}),Fq=De.loose(),oa=os.extend({method:C("tasks/list")}),sa=ss.extend({tasks:Q(is)}),ia=Ce.extend({method:C("tasks/cancel"),params:at.extend({taskId:b()})}),hv=De.merge(is),gv=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),yv=gv.extend({text:b()}),vl=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),vv=gv.extend({blob:vl}),cs=Qe(["user","assistant"]),Bn=I({audience:Q(cs).optional(),priority:ce().min(0).max(1).optional(),lastModified:Qo.datetime({offset:!0}).optional()}),_v=I({...qn.shape,...ns.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Bn.optional(),_meta:xe(He({}))}),xE=I({...qn.shape,...ns.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Bn.optional(),_meta:xe(He({}))}),SE=os.extend({method:C("resources/list")}),$E=ss.extend({resources:Q(_v)}),kE=os.extend({method:C("resources/templates/list")}),PE=ss.extend({resourceTemplates:Q(xE)}),_l=at.extend({uri:b()}),TE=_l,EE=Ce.extend({method:C("resources/read"),params:TE}),RE=De.extend({contents:Q(me([yv,vv]))}),IE=ht.extend({method:C("notifications/resources/list_changed"),params:mt.optional()}),AE=_l,CE=Ce.extend({method:C("resources/subscribe"),params:AE}),DE=_l,zE=Ce.extend({method:C("resources/unsubscribe"),params:DE}),OE=mt.extend({uri:b()}),ME=ht.extend({method:C("notifications/resources/updated"),params:OE}),NE=I({name:b(),description:xe(b()),required:xe(Ee())}),jE=I({...qn.shape,...ns.shape,description:xe(b()),arguments:xe(Q(NE)),_meta:xe(He({}))}),LE=os.extend({method:C("prompts/list")}),FE=ss.extend({prompts:Q(jE)}),ZE=at.extend({name:b(),arguments:be(b(),b()).optional()}),UE=Ce.extend({method:C("prompts/get"),params:ZE}),bl=I({type:C("text"),text:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),wl=I({type:C("image"),data:vl,mimeType:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),xl=I({type:C("audio"),data:vl,mimeType:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),qE=I({type:C("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),VE=I({type:C("resource"),resource:me([yv,vv]),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),BE=_v.extend({type:C("resource_link")}),Sl=me([bl,wl,xl,BE,VE]),WE=I({role:cs,content:Sl}),HE=De.extend({description:b().optional(),messages:Q(WE)}),KE=ht.extend({method:C("notifications/prompts/list_changed"),params:mt.optional()}),JE=I({title:b().optional(),readOnlyHint:Ee().optional(),destructiveHint:Ee().optional(),idempotentHint:Ee().optional(),openWorldHint:Ee().optional()}),GE=I({taskSupport:Qe(["required","optional","forbidden"]).optional()}),bv=I({...qn.shape,...ns.shape,description:b().optional(),inputSchema:I({type:C("object"),properties:be(b(),Ae).optional(),required:Q(b()).optional()}).catchall(_e()),outputSchema:I({type:C("object"),properties:be(b(),Ae).optional(),required:Q(b()).optional()}).catchall(_e()).optional(),annotations:JE.optional(),execution:GE.optional(),_meta:be(b(),_e()).optional()}),$l=os.extend({method:C("tools/list")}),YE=ss.extend({tools:Q(bv)}),aa=De.extend({content:Q(Sl).default([]),structuredContent:be(b(),_e()).optional(),isError:Ee().optional()}),Zq=aa.or(De.extend({toolResult:_e()})),XE=ts.extend({name:b(),arguments:be(b(),_e()).optional()}),us=Ce.extend({method:C("tools/call"),params:XE}),QE=ht.extend({method:C("notifications/tools/list_changed"),params:mt.optional()}),Uq=I({autoRefresh:Ee().default(!0),debounceMs:ce().int().nonnegative().default(300)}),ls=Qe(["debug","info","notice","warning","error","critical","alert","emergency"]),eR=at.extend({level:ls}),kl=Ce.extend({method:C("logging/setLevel"),params:eR}),tR=mt.extend({level:ls,logger:b().optional(),data:_e()}),rR=ht.extend({method:C("notifications/message"),params:tR}),nR=I({name:b().optional()}),oR=I({hints:Q(nR).optional(),costPriority:ce().min(0).max(1).optional(),speedPriority:ce().min(0).max(1).optional(),intelligencePriority:ce().min(0).max(1).optional()}),sR=I({mode:Qe(["auto","required","none"]).optional()}),iR=I({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(Sl).default([]),structuredContent:I({}).loose().optional(),isError:Ee().optional(),_meta:be(b(),_e()).optional()}),aR=cl("type",[bl,wl,xl]),Ki=cl("type",[bl,wl,xl,qE,iR]),cR=I({role:cs,content:me([Ki,Q(Ki)]),_meta:be(b(),_e()).optional()}),uR=ts.extend({messages:Q(cR),modelPreferences:oR.optional(),systemPrompt:b().optional(),includeContext:Qe(["none","thisServer","allServers"]).optional(),temperature:ce().optional(),maxTokens:ce().int(),stopSequences:Q(b()).optional(),metadata:Ae.optional(),tools:Q(bv).optional(),toolChoice:sR.optional()}),lR=Ce.extend({method:C("sampling/createMessage"),params:uR}),Pl=De.extend({model:b(),stopReason:xe(Qe(["endTurn","stopSequence","maxTokens"]).or(b())),role:cs,content:aR}),Tl=De.extend({model:b(),stopReason:xe(Qe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:cs,content:me([Ki,Q(Ki)])}),dR=I({type:C("boolean"),title:b().optional(),description:b().optional(),default:Ee().optional()}),pR=I({type:C("string"),title:b().optional(),description:b().optional(),minLength:ce().optional(),maxLength:ce().optional(),format:Qe(["email","uri","date","date-time"]).optional(),default:b().optional()}),fR=I({type:Qe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ce().optional(),maximum:ce().optional(),default:ce().optional()}),mR=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),hR=I({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Q(I({const:b(),title:b()})),default:b().optional()}),gR=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),yR=me([mR,hR]),vR=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:I({type:C("string"),enum:Q(b())}),default:Q(b()).optional()}),_R=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:I({anyOf:Q(I({const:b(),title:b()}))}),default:Q(b()).optional()}),bR=me([vR,_R]),wR=me([gR,yR,bR]),xR=me([wR,dR,pR,fR]),SR=ts.extend({mode:C("form").optional(),message:b(),requestedSchema:I({type:C("object"),properties:be(b(),xR),required:Q(b()).optional()})}),$R=ts.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),kR=me([SR,$R]),PR=Ce.extend({method:C("elicitation/create"),params:kR}),TR=mt.extend({elicitationId:b()}),ER=ht.extend({method:C("notifications/elicitation/complete"),params:TR}),ca=De.extend({action:Qe(["accept","decline","cancel"]),content:ul(t=>t===null?void 0:t,be(b(),me([b(),ce(),Ee(),Q(b())])).optional())}),RR=I({type:C("ref/resource"),uri:b()});var IR=I({type:C("ref/prompt"),name:b()}),AR=at.extend({ref:me([IR,RR]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),CR=Ce.extend({method:C("completion/complete"),params:AR});var DR=De.extend({completion:He({values:Q(b()).max(100),total:xe(ce().int()),hasMore:xe(Ee())})}),zR=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),OR=Ce.extend({method:C("roots/list"),params:at.optional()}),El=De.extend({roots:Q(zR)}),MR=ht.extend({method:C("notifications/roots/list_changed"),params:mt.optional()}),qq=me([Qi,gl,CR,kl,UE,LE,SE,kE,EE,CE,zE,us,$l,ta,na,oa,ia]),Vq=me([Xi,ea,yl,MR,as]),Bq=me([Yi,Pl,Tl,ca,El,ra,sa,Vn]),Wq=me([Qi,lR,PR,OR,ta,na,oa,ia]),Hq=me([Xi,ea,rR,ME,IE,QE,KE,as,ER]),Kq=me([Yi,gE,DR,HE,FE,$E,PE,RE,aa,YE,ra,sa,Vn]),B=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===ee.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ll(o.elicitations,r)}return new t(e,r,n)}},ll=class extends B{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ee.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function yr(t){return t==="completed"||t==="failed"||t==="cancelled"}var xv=Symbol("Let zodToJsonSchema decide on which parser to use");var wv={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Sv=t=>typeof t=="string"?{...wv,name:t}:{...wv,...t};var $v=t=>{let e=Sv(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Rl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function te(t,e,r,n,o){t[e]=r,Rl(t,e,n,o)}var ua=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ua(e,t.currentPath):e.join("/")}}function kv(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==P.ZodAny&&(r.items=L(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&te(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&te(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(te(r,"minItems",t.exactLength.value,t.exactLength.message,e),te(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Pv(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?te(r,"minimum",n.value,n.message,e):te(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),te(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?te(r,"maximum",n.value,n.message,e):te(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),te(r,"maximum",n.value,n.message,e));break;case"multipleOf":te(r,"multipleOf",n.value,n.message,e);break}return r}function Tv(){return{type:"boolean"}}function la(t,e){return L(t.type._def,e)}var Ev=(t,e)=>L(t.innerType._def,e);function Il(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Il(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return NR(t,e)}}var NR=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":te(r,"minimum",n.value,n.message,e);break;case"max":te(r,"maximum",n.value,n.message,e);break}return r};function Rv(t,e){return{...L(t.innerType._def,e),default:t.defaultValue()}}function Iv(t,e){return e.effectStrategy==="input"?L(t.schema._def,e):we(e)}function Av(t){return{type:"string",enum:Array.from(t.values)}}var jR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Cv(t,e){let r=[L(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),L(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(jR(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function Dv(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Al,xt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Al===void 0&&(Al=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Al),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function da(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":te(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":te(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":St(r,"email",n.message,e);break;case"format:idn-email":St(r,"idn-email",n.message,e);break;case"pattern:zod":Ke(r,xt.email,n.message,e);break}break;case"url":St(r,"uri",n.message,e);break;case"uuid":St(r,"uuid",n.message,e);break;case"regex":Ke(r,n.regex,n.message,e);break;case"cuid":Ke(r,xt.cuid,n.message,e);break;case"cuid2":Ke(r,xt.cuid2,n.message,e);break;case"startsWith":Ke(r,RegExp(`^${Cl(n.value,e)}`),n.message,e);break;case"endsWith":Ke(r,RegExp(`${Cl(n.value,e)}$`),n.message,e);break;case"datetime":St(r,"date-time",n.message,e);break;case"date":St(r,"date",n.message,e);break;case"time":St(r,"time",n.message,e);break;case"duration":St(r,"duration",n.message,e);break;case"length":te(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),te(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ke(r,RegExp(Cl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&St(r,"ipv4",n.message,e),n.version!=="v4"&&St(r,"ipv6",n.message,e);break}case"base64url":Ke(r,xt.base64url,n.message,e);break;case"jwt":Ke(r,xt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ke(r,xt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ke(r,xt.ipv6Cidr,n.message,e);break}case"emoji":Ke(r,xt.emoji(),n.message,e);break;case"ulid":{Ke(r,xt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{St(r,"binary",n.message,e);break}case"contentEncoding:base64":{te(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ke(r,xt.base64,n.message,e);break}}break}case"nanoid":Ke(r,xt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Cl(t,e){return e.patternStrategy==="escape"?FR(t):t}var LR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function FR(t){let e="";for(let r=0;r<t.length;r++)LR.has(t[r])||(e+="\\"),e+=t[r];return e}function St(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):te(t,"format",e,r,n)}function Ke(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:zv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):te(t,"pattern",zv(e,n),r,n)}function zv(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
236
+ path: iss.path ? [${Qr(S)}, ...iss.path] : [${Qr(S)}]
237
+ })));`),p.write(`newResult[${Qr(S)}] = ${w}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let v=p.compile();return(S,w)=>v(d,S,w)},o,s=Ln,i=!Ai.jitless,c=i&&Eu.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 w=l.shape;for(let _ of l.keys){let P=w[_],A=P._zod.run({value:f[_],issues:[]},p),D=P._zod.optin==="optional"&&P._zod.optout==="optional";A instanceof Promise?m.push(A.then(U=>D?ng(U,d,_,f):ji(U,d,_))):D?ng(A,d,_,f):ji(A,d,_)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],y=l.keySet,v=u._zod,S=v.def.type;for(let w of Object.keys(f)){if(y.has(w))continue;if(S==="never"){g.push(w);continue}let _=v.run({value:f[w],issues:[]},p);_ instanceof Promise?m.push(_.then(P=>ji(P,d,w))):ji(_,d,w)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function og(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>wt(s,n,pt())))}),e}var qu=x("$ZodUnion",(t,e)=>{fe.init(t,e),pe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),pe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),pe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),pe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Wo(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=>og(i,r,t,n)):og(s,r,t,n)}}),Ug=x("$ZodDiscriminatedUnion",(t,e)=>{qu.init(t,e);let r=t._zod.parse;pe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Vo(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Ln(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),qg=x("$ZodIntersection",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>sg(r,c,u)):sg(r,s,i)}});function Zu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Fn(t)&&Fn(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Zu(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=Zu(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 sg(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),en(t))return t;let n=Zu(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 Vg=x("$ZodRecord",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Fn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Nt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Nt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>wt(u,n,pt())),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(...Nt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Nt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Bg=x("$ZodEnum",(t,e)=>{fe.init(t,e);let r=$u(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Ru.has(typeof n)).map(n=>typeof n=="string"?mr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Wg=x("$ZodLiteral",(t,e)=>{fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?mr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Hg=x("$ZodTransform",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Qt;return r.value=o,r}}),Kg=x("$ZodOptional",(t,e)=>{fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Wo(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)}),Gg=x("$ZodNullable",(t,e)=>{fe.init(t,e),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Wo(r.source)}|null)$`):void 0}),pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Jg=x("$ZodDefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>ig(s,e)):ig(o,e)}});function ig(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Yg=x("$ZodPrefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Xg=x("$ZodNonOptional",(t,e)=>{fe.init(t,e),pe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>ag(s,t)):ag(o,t)}});function ag(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 Qg=x("$ZodCatch",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>wt(i,n,pt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>wt(s,n,pt()))},input:r.value}),r.issues=[]),r)}});var ey=x("$ZodPipe",(t,e)=>{fe.init(t,e),pe(t._zod,"values",()=>e.in._zod.values),pe(t._zod,"optin",()=>e.in._zod.optin),pe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>cg(s,e,n)):cg(o,e,n)}});function cg(t,e,r){return en(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var ty=x("$ZodReadonly",(t,e)=>{fe.init(t,e),pe(t._zod,"propValues",()=>e.innerType._zod.propValues),pe(t._zod,"values",()=>e.innerType._zod.values),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(ug):ug(o)}});function ug(t){return t.value=Object.freeze(t.value),t}var ry=x("$ZodCustom",(t,e)=>{Ze.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>lg(s,r,n,t));lg(o,r,n,t)}});function lg(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(Cu(o))}}var sT=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},iT=()=>{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 ${sT(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${zi(n.values[0])}`:`Invalid option: expected one of ${Ci(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ci(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function ny(){return{localeError:iT()}}var Vu=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 aT(){return new Vu}var Jo=aT();function oy(t,e){return new t({type:"string",...j(e)})}function sy(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Bu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function iy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function ay(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function cy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function uy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function ly(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function dy(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function py(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function fy(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function my(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function hy(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function gy(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function yy(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function vy(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function _y(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function by(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function wy(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function xy(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function Sy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function $y(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function ky(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}function Py(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function Ty(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function Ey(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function Ry(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 Dy(t,e){return new t({type:"null",...j(e)})}function zy(t){return new t({type:"unknown"})}function Oy(t,e){return new t({type:"never",...j(e)})}function Fi(t,e){return new Lu({check:"less_than",...j(e),value:t,inclusive:!1})}function Yo(t,e){return new Lu({check:"less_than",...j(e),value:t,inclusive:!0})}function Zi(t,e){return new Fu({check:"greater_than",...j(e),value:t,inclusive:!1})}function Xo(t,e){return new Fu({check:"greater_than",...j(e),value:t,inclusive:!0})}function Ui(t,e){return new Uh({check:"multiple_of",...j(e),value:t})}function qi(t,e){return new Vh({check:"max_length",...j(e),maximum:t})}function Zn(t,e){return new Bh({check:"min_length",...j(e),minimum:t})}function Vi(t,e){return new Wh({check:"length_equals",...j(e),length:t})}function Wu(t,e){return new Hh({check:"string_format",format:"regex",...j(e),pattern:t})}function Hu(t){return new Kh({check:"string_format",format:"lowercase",...j(t)})}function Ku(t){return new Gh({check:"string_format",format:"uppercase",...j(t)})}function Gu(t,e){return new Jh({check:"string_format",format:"includes",...j(e),includes:t})}function Ju(t,e){return new Yh({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Yu(t,e){return new Xh({check:"string_format",format:"ends_with",...j(e),suffix:t})}function tn(t){return new Qh({check:"overwrite",tx:t})}function Xu(t){return tn(e=>e.normalize(t))}function Qu(){return tn(t=>t.trim())}function el(){return tn(t=>t.toLowerCase())}function tl(){return tn(t=>t.toUpperCase())}function My(t,e,r){return new t({type:"array",element:e,...j(r)})}function Ny(t,e,r){let n=j(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function jy(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}function Un(t){return!!t._zod}function hr(t,e){return Un(t)?Ko(t,e):t.safeParse(e)}function Bi(t){if(!t)return;let e;if(Un(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ly(t){if(Un(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var es={};Be(es,{ZodISODate:()=>Zy,ZodISODateTime:()=>Fy,ZodISODuration:()=>qy,ZodISOTime:()=>Uy,date:()=>nl,datetime:()=>rl,duration:()=>sl,time:()=>ol});var Fy=x("ZodISODateTime",(t,e)=>{xg.init(t,e),ve.init(t,e)});function rl(t){return Py(Fy,t)}var Zy=x("ZodISODate",(t,e)=>{Sg.init(t,e),ve.init(t,e)});function nl(t){return Ty(Zy,t)}var Uy=x("ZodISOTime",(t,e)=>{$g.init(t,e),ve.init(t,e)});function ol(t){return Ey(Uy,t)}var qy=x("ZodISODuration",(t,e)=>{kg.init(t,e),ve.init(t,e)});function sl(t){return Ry(qy,t)}var Vy=(t,e)=>{Oi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>uh(t,r)},flatten:{value:r=>ch(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},GU=x("ZodError",Vy),ts=x("ZodError",Vy,{Parent:Error});var By=lh(ts),Wy=dh(ts),Hy=zu(ts),Ky=Ou(ts);var Se=x("ZodType",(t,e)=>(fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Mt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>By(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Hy(t,r,n),t.parseAsync=async(r,n)=>Wy(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ky(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(oE(r,n)),t.superRefine=r=>t.check(sE(r)),t.overwrite=r=>t.check(tn(r)),t.optional=()=>xe(t),t.nullable=()=>Yy(t),t.nullish=()=>xe(Yy(t)),t.nonoptional=r=>YT(t,r),t.array=()=>Q(t),t.or=r=>me([t,r]),t.and=r=>Hi(t,r),t.transform=r=>al(t,rv(r)),t.default=r=>KT(t,r),t.prefault=r=>JT(t,r),t.catch=r=>QT(t,r),t.pipe=r=>al(t,r),t.readonly=()=>rE(t),t.describe=r=>{let n=t.clone();return Jo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Jo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Jo.get(t);let n=t.clone();return Jo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Xy=x("_ZodString",(t,e)=>{Li.init(t,e),Se.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Wu(...n)),t.includes=(...n)=>t.check(Gu(...n)),t.startsWith=(...n)=>t.check(Ju(...n)),t.endsWith=(...n)=>t.check(Yu(...n)),t.min=(...n)=>t.check(Zn(...n)),t.max=(...n)=>t.check(qi(...n)),t.length=(...n)=>t.check(Vi(...n)),t.nonempty=(...n)=>t.check(Zn(1,...n)),t.lowercase=n=>t.check(Hu(n)),t.uppercase=n=>t.check(Ku(n)),t.trim=()=>t.check(Qu()),t.normalize=(...n)=>t.check(Xu(...n)),t.toLowerCase=()=>t.check(el()),t.toUpperCase=()=>t.check(tl())}),gT=x("ZodString",(t,e)=>{Li.init(t,e),Xy.init(t,e),t.email=r=>t.check(sy(yT,r)),t.url=r=>t.check(ly(vT,r)),t.jwt=r=>t.check(ky(DT,r)),t.emoji=r=>t.check(dy(_T,r)),t.guid=r=>t.check(Bu(Gy,r)),t.uuid=r=>t.check(iy(Wi,r)),t.uuidv4=r=>t.check(ay(Wi,r)),t.uuidv6=r=>t.check(cy(Wi,r)),t.uuidv7=r=>t.check(uy(Wi,r)),t.nanoid=r=>t.check(py(bT,r)),t.guid=r=>t.check(Bu(Gy,r)),t.cuid=r=>t.check(fy(wT,r)),t.cuid2=r=>t.check(my(xT,r)),t.ulid=r=>t.check(hy(ST,r)),t.base64=r=>t.check(xy(IT,r)),t.base64url=r=>t.check(Sy(AT,r)),t.xid=r=>t.check(gy($T,r)),t.ksuid=r=>t.check(yy(kT,r)),t.ipv4=r=>t.check(vy(PT,r)),t.ipv6=r=>t.check(_y(TT,r)),t.cidrv4=r=>t.check(by(ET,r)),t.cidrv6=r=>t.check(wy(RT,r)),t.e164=r=>t.check($y(CT,r)),t.datetime=r=>t.check(rl(r)),t.date=r=>t.check(nl(r)),t.time=r=>t.check(ol(r)),t.duration=r=>t.check(sl(r))});function b(t){return oy(gT,t)}var ve=x("ZodStringFormat",(t,e)=>{he.init(t,e),Xy.init(t,e)}),yT=x("ZodEmail",(t,e)=>{fg.init(t,e),ve.init(t,e)});var Gy=x("ZodGUID",(t,e)=>{dg.init(t,e),ve.init(t,e)});var Wi=x("ZodUUID",(t,e)=>{pg.init(t,e),ve.init(t,e)});var vT=x("ZodURL",(t,e)=>{mg.init(t,e),ve.init(t,e)});var _T=x("ZodEmoji",(t,e)=>{hg.init(t,e),ve.init(t,e)});var bT=x("ZodNanoID",(t,e)=>{gg.init(t,e),ve.init(t,e)});var wT=x("ZodCUID",(t,e)=>{yg.init(t,e),ve.init(t,e)});var xT=x("ZodCUID2",(t,e)=>{vg.init(t,e),ve.init(t,e)});var ST=x("ZodULID",(t,e)=>{_g.init(t,e),ve.init(t,e)});var $T=x("ZodXID",(t,e)=>{bg.init(t,e),ve.init(t,e)});var kT=x("ZodKSUID",(t,e)=>{wg.init(t,e),ve.init(t,e)});var PT=x("ZodIPv4",(t,e)=>{Pg.init(t,e),ve.init(t,e)});var TT=x("ZodIPv6",(t,e)=>{Tg.init(t,e),ve.init(t,e)});var ET=x("ZodCIDRv4",(t,e)=>{Eg.init(t,e),ve.init(t,e)});var RT=x("ZodCIDRv6",(t,e)=>{Rg.init(t,e),ve.init(t,e)});var IT=x("ZodBase64",(t,e)=>{Ag.init(t,e),ve.init(t,e)});var AT=x("ZodBase64URL",(t,e)=>{Cg.init(t,e),ve.init(t,e)});var CT=x("ZodE164",(t,e)=>{Dg.init(t,e),ve.init(t,e)});var DT=x("ZodJWT",(t,e)=>{zg.init(t,e),ve.init(t,e)});var Qy=x("ZodNumber",(t,e)=>{Uu.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(Zi(n,o)),t.gte=(n,o)=>t.check(Xo(n,o)),t.min=(n,o)=>t.check(Xo(n,o)),t.lt=(n,o)=>t.check(Fi(n,o)),t.lte=(n,o)=>t.check(Yo(n,o)),t.max=(n,o)=>t.check(Yo(n,o)),t.int=n=>t.check(Jy(n)),t.safe=n=>t.check(Jy(n)),t.positive=n=>t.check(Zi(0,n)),t.nonnegative=n=>t.check(Xo(0,n)),t.negative=n=>t.check(Fi(0,n)),t.nonpositive=n=>t.check(Yo(0,n)),t.multipleOf=(n,o)=>t.check(Ui(n,o)),t.step=(n,o)=>t.check(Ui(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ce(t){return Iy(Qy,t)}var zT=x("ZodNumberFormat",(t,e)=>{Og.init(t,e),Qy.init(t,e)});function Jy(t){return Ay(zT,t)}var OT=x("ZodBoolean",(t,e)=>{Mg.init(t,e),Se.init(t,e)});function Re(t){return Cy(OT,t)}var MT=x("ZodNull",(t,e)=>{Ng.init(t,e),Se.init(t,e)});function cl(t){return Dy(MT,t)}var NT=x("ZodUnknown",(t,e)=>{jg.init(t,e),Se.init(t,e)});function _e(){return zy(NT)}var jT=x("ZodNever",(t,e)=>{Lg.init(t,e),Se.init(t,e)});function LT(t){return Oy(jT,t)}var FT=x("ZodArray",(t,e)=>{Fg.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Zn(r,n)),t.nonempty=r=>t.check(Zn(1,r)),t.max=(r,n)=>t.check(qi(r,n)),t.length=(r,n)=>t.check(Vi(r,n)),t.unwrap=()=>t.element});function Q(t,e){return My(FT,t,e)}var ev=x("ZodObject",(t,e)=>{Zg.init(t,e),Se.init(t,e),ae.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Qe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:_e()}),t.loose=()=>t.clone({...t._zod.def,catchall:_e()}),t.strict=()=>t.clone({...t._zod.def,catchall:LT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ae.extend(t,r),t.merge=r=>ae.merge(t,r),t.pick=r=>ae.pick(t,r),t.omit=r=>ae.omit(t,r),t.partial=(...r)=>ae.partial(nv,t,r[0]),t.required=(...r)=>ae.required(ov,t,r[0])});function I(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new ev(r)}function He(t,e){return new ev({type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ae.normalizeParams(e)})}var tv=x("ZodUnion",(t,e)=>{qu.init(t,e),Se.init(t,e),t.options=e.options});function me(t,e){return new tv({type:"union",options:t,...ae.normalizeParams(e)})}var ZT=x("ZodDiscriminatedUnion",(t,e)=>{tv.init(t,e),Ug.init(t,e)});function ul(t,e,r){return new ZT({type:"union",options:e,discriminator:t,...ae.normalizeParams(r)})}var UT=x("ZodIntersection",(t,e)=>{qg.init(t,e),Se.init(t,e)});function Hi(t,e){return new UT({type:"intersection",left:t,right:e})}var qT=x("ZodRecord",(t,e)=>{Vg.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new qT({type:"record",keyType:t,valueType:e,...ae.normalizeParams(r)})}var il=x("ZodEnum",(t,e)=>{Bg.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 il({...e,checks:[],...ae.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new il({...e,checks:[],...ae.normalizeParams(o),entries:s})}});function Qe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new il({type:"enum",entries:r,...ae.normalizeParams(e)})}var VT=x("ZodLiteral",(t,e)=>{Wg.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 z(t,e){return new VT({type:"literal",values:Array.isArray(t)?t:[t],...ae.normalizeParams(e)})}var BT=x("ZodTransform",(t,e)=>{Hg.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ae.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ae.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function rv(t){return new BT({type:"transform",transform:t})}var nv=x("ZodOptional",(t,e)=>{Kg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new nv({type:"optional",innerType:t})}var WT=x("ZodNullable",(t,e)=>{Gg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Yy(t){return new WT({type:"nullable",innerType:t})}var HT=x("ZodDefault",(t,e)=>{Jg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function KT(t,e){return new HT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var GT=x("ZodPrefault",(t,e)=>{Yg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function JT(t,e){return new GT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var ov=x("ZodNonOptional",(t,e)=>{Xg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function YT(t,e){return new ov({type:"nonoptional",innerType:t,...ae.normalizeParams(e)})}var XT=x("ZodCatch",(t,e)=>{Qg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function QT(t,e){return new XT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var eE=x("ZodPipe",(t,e)=>{ey.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function al(t,e){return new eE({type:"pipe",in:t,out:e})}var tE=x("ZodReadonly",(t,e)=>{ty.init(t,e),Se.init(t,e)});function rE(t){return new tE({type:"readonly",innerType:t})}var sv=x("ZodCustom",(t,e)=>{ry.init(t,e),Se.init(t,e)});function nE(t){let e=new Ze({check:"custom"});return e._zod.check=t,e}function iv(t,e){return Ny(sv,t??(()=>!0),e)}function oE(t,e={}){return jy(sv,t,e)}function sE(t){let e=nE(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ae.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ae.issue(o))}},t(r.value,r)));return e}function ll(t,e){return al(rv(t),e)}pt(ny());var pl="2025-11-25";var av=[pl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gr="io.modelcontextprotocol/related-task",Gi="2.0",Ae=iv(t=>t!==null&&(typeof t=="object"||typeof t=="function")),cv=me([b(),ce().int()]),uv=b(),Uq=He({ttl:me([ce(),cl()]).optional(),pollInterval:ce().optional()}),iE=I({ttl:ce().optional()}),aE=I({taskId:b()}),fl=He({progressToken:cv.optional(),[gr]:aE.optional()}),it=I({_meta:fl.optional()}),rs=it.extend({task:iE.optional()}),lv=t=>rs.safeParse(t).success,Ce=I({method:b(),params:it.loose().optional()}),ft=I({_meta:fl.optional()}),mt=I({method:b(),params:ft.loose().optional()}),De=He({_meta:fl.optional()}),Ji=me([b(),ce().int()]),dv=I({jsonrpc:z(Gi),id:Ji,...Ce.shape}).strict(),ml=t=>dv.safeParse(t).success,pv=I({jsonrpc:z(Gi),...mt.shape}).strict(),fv=t=>pv.safeParse(t).success,hl=I({jsonrpc:z(Gi),id:Ji,result:De}).strict(),ns=t=>hl.safeParse(t).success;var ee;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ee||(ee={}));var gl=I({jsonrpc:z(Gi),id:Ji.optional(),error:I({code:ce().int(),message:b(),data:_e().optional()})}).strict();var mv=t=>gl.safeParse(t).success;var hv=me([dv,pv,hl,gl]),qq=me([hl,gl]),Yi=De.strict(),cE=ft.extend({requestId:Ji.optional(),reason:b().optional()}),Xi=mt.extend({method:z("notifications/cancelled"),params:cE}),uE=I({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Qe(["light","dark"]).optional()}),os=I({icons:Q(uE).optional()}),qn=I({name:b(),title:b().optional()}),gv=qn.extend({...qn.shape,...os.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),lE=Hi(I({applyDefaults:Re().optional()}),be(b(),_e())),dE=ll(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Hi(I({form:lE.optional(),url:Ae.optional()}),be(b(),_e()).optional())),pE=He({list:Ae.optional(),cancel:Ae.optional(),requests:He({sampling:He({createMessage:Ae.optional()}).optional(),elicitation:He({create:Ae.optional()}).optional()}).optional()}),fE=He({list:Ae.optional(),cancel:Ae.optional(),requests:He({tools:He({call:Ae.optional()}).optional()}).optional()}),mE=I({experimental:be(b(),Ae).optional(),sampling:I({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:dE.optional(),roots:I({listChanged:Re().optional()}).optional(),tasks:pE.optional()}),hE=it.extend({protocolVersion:b(),capabilities:mE,clientInfo:gv}),yl=Ce.extend({method:z("initialize"),params:hE});var gE=I({experimental:be(b(),Ae).optional(),logging:Ae.optional(),completions:Ae.optional(),prompts:I({listChanged:Re().optional()}).optional(),resources:I({subscribe:Re().optional(),listChanged:Re().optional()}).optional(),tools:I({listChanged:Re().optional()}).optional(),tasks:fE.optional()}),yE=De.extend({protocolVersion:b(),capabilities:gE,serverInfo:gv,instructions:b().optional()}),vl=mt.extend({method:z("notifications/initialized"),params:ft.optional()});var Qi=Ce.extend({method:z("ping"),params:it.optional()}),vE=I({progress:ce(),total:xe(ce()),message:xe(b())}),_E=I({...ft.shape,...vE.shape,progressToken:cv}),ea=mt.extend({method:z("notifications/progress"),params:_E}),bE=it.extend({cursor:uv.optional()}),ss=Ce.extend({params:bE.optional()}),is=De.extend({nextCursor:uv.optional()}),wE=Qe(["working","input_required","completed","failed","cancelled"]),as=I({taskId:b(),status:wE,ttl:me([ce(),cl()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ce()),statusMessage:xe(b())}),Vn=De.extend({task:as}),xE=ft.merge(as),cs=mt.extend({method:z("notifications/tasks/status"),params:xE}),ta=Ce.extend({method:z("tasks/get"),params:it.extend({taskId:b()})}),ra=De.merge(as),na=Ce.extend({method:z("tasks/result"),params:it.extend({taskId:b()})}),Vq=De.loose(),oa=ss.extend({method:z("tasks/list")}),sa=is.extend({tasks:Q(as)}),ia=Ce.extend({method:z("tasks/cancel"),params:it.extend({taskId:b()})}),yv=De.merge(as),vv=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),_v=vv.extend({text:b()}),_l=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bv=vv.extend({blob:_l}),us=Qe(["user","assistant"]),Bn=I({audience:Q(us).optional(),priority:ce().min(0).max(1).optional(),lastModified:es.datetime({offset:!0}).optional()}),wv=I({...qn.shape,...os.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Bn.optional(),_meta:xe(He({}))}),SE=I({...qn.shape,...os.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Bn.optional(),_meta:xe(He({}))}),$E=ss.extend({method:z("resources/list")}),kE=is.extend({resources:Q(wv)}),PE=ss.extend({method:z("resources/templates/list")}),TE=is.extend({resourceTemplates:Q(SE)}),bl=it.extend({uri:b()}),EE=bl,RE=Ce.extend({method:z("resources/read"),params:EE}),IE=De.extend({contents:Q(me([_v,bv]))}),AE=mt.extend({method:z("notifications/resources/list_changed"),params:ft.optional()}),CE=bl,DE=Ce.extend({method:z("resources/subscribe"),params:CE}),zE=bl,OE=Ce.extend({method:z("resources/unsubscribe"),params:zE}),ME=ft.extend({uri:b()}),NE=mt.extend({method:z("notifications/resources/updated"),params:ME}),jE=I({name:b(),description:xe(b()),required:xe(Re())}),LE=I({...qn.shape,...os.shape,description:xe(b()),arguments:xe(Q(jE)),_meta:xe(He({}))}),FE=ss.extend({method:z("prompts/list")}),ZE=is.extend({prompts:Q(LE)}),UE=it.extend({name:b(),arguments:be(b(),b()).optional()}),qE=Ce.extend({method:z("prompts/get"),params:UE}),wl=I({type:z("text"),text:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),xl=I({type:z("image"),data:_l,mimeType:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),Sl=I({type:z("audio"),data:_l,mimeType:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),VE=I({type:z("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),BE=I({type:z("resource"),resource:me([_v,bv]),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),WE=wv.extend({type:z("resource_link")}),$l=me([wl,xl,Sl,WE,BE]),HE=I({role:us,content:$l}),KE=De.extend({description:b().optional(),messages:Q(HE)}),GE=mt.extend({method:z("notifications/prompts/list_changed"),params:ft.optional()}),JE=I({title:b().optional(),readOnlyHint:Re().optional(),destructiveHint:Re().optional(),idempotentHint:Re().optional(),openWorldHint:Re().optional()}),YE=I({taskSupport:Qe(["required","optional","forbidden"]).optional()}),xv=I({...qn.shape,...os.shape,description:b().optional(),inputSchema:I({type:z("object"),properties:be(b(),Ae).optional(),required:Q(b()).optional()}).catchall(_e()),outputSchema:I({type:z("object"),properties:be(b(),Ae).optional(),required:Q(b()).optional()}).catchall(_e()).optional(),annotations:JE.optional(),execution:YE.optional(),_meta:be(b(),_e()).optional()}),kl=ss.extend({method:z("tools/list")}),XE=is.extend({tools:Q(xv)}),aa=De.extend({content:Q($l).default([]),structuredContent:be(b(),_e()).optional(),isError:Re().optional()}),Bq=aa.or(De.extend({toolResult:_e()})),QE=rs.extend({name:b(),arguments:be(b(),_e()).optional()}),ls=Ce.extend({method:z("tools/call"),params:QE}),eR=mt.extend({method:z("notifications/tools/list_changed"),params:ft.optional()}),Wq=I({autoRefresh:Re().default(!0),debounceMs:ce().int().nonnegative().default(300)}),ds=Qe(["debug","info","notice","warning","error","critical","alert","emergency"]),tR=it.extend({level:ds}),Pl=Ce.extend({method:z("logging/setLevel"),params:tR}),rR=ft.extend({level:ds,logger:b().optional(),data:_e()}),nR=mt.extend({method:z("notifications/message"),params:rR}),oR=I({name:b().optional()}),sR=I({hints:Q(oR).optional(),costPriority:ce().min(0).max(1).optional(),speedPriority:ce().min(0).max(1).optional(),intelligencePriority:ce().min(0).max(1).optional()}),iR=I({mode:Qe(["auto","required","none"]).optional()}),aR=I({type:z("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q($l).default([]),structuredContent:I({}).loose().optional(),isError:Re().optional(),_meta:be(b(),_e()).optional()}),cR=ul("type",[wl,xl,Sl]),Ki=ul("type",[wl,xl,Sl,VE,aR]),uR=I({role:us,content:me([Ki,Q(Ki)]),_meta:be(b(),_e()).optional()}),lR=rs.extend({messages:Q(uR),modelPreferences:sR.optional(),systemPrompt:b().optional(),includeContext:Qe(["none","thisServer","allServers"]).optional(),temperature:ce().optional(),maxTokens:ce().int(),stopSequences:Q(b()).optional(),metadata:Ae.optional(),tools:Q(xv).optional(),toolChoice:iR.optional()}),dR=Ce.extend({method:z("sampling/createMessage"),params:lR}),Tl=De.extend({model:b(),stopReason:xe(Qe(["endTurn","stopSequence","maxTokens"]).or(b())),role:us,content:cR}),El=De.extend({model:b(),stopReason:xe(Qe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:us,content:me([Ki,Q(Ki)])}),pR=I({type:z("boolean"),title:b().optional(),description:b().optional(),default:Re().optional()}),fR=I({type:z("string"),title:b().optional(),description:b().optional(),minLength:ce().optional(),maxLength:ce().optional(),format:Qe(["email","uri","date","date-time"]).optional(),default:b().optional()}),mR=I({type:Qe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ce().optional(),maximum:ce().optional(),default:ce().optional()}),hR=I({type:z("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),gR=I({type:z("string"),title:b().optional(),description:b().optional(),oneOf:Q(I({const:b(),title:b()})),default:b().optional()}),yR=I({type:z("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),vR=me([hR,gR]),_R=I({type:z("array"),title:b().optional(),description:b().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:I({type:z("string"),enum:Q(b())}),default:Q(b()).optional()}),bR=I({type:z("array"),title:b().optional(),description:b().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:I({anyOf:Q(I({const:b(),title:b()}))}),default:Q(b()).optional()}),wR=me([_R,bR]),xR=me([yR,vR,wR]),SR=me([xR,pR,fR,mR]),$R=rs.extend({mode:z("form").optional(),message:b(),requestedSchema:I({type:z("object"),properties:be(b(),SR),required:Q(b()).optional()})}),kR=rs.extend({mode:z("url"),message:b(),elicitationId:b(),url:b().url()}),PR=me([$R,kR]),TR=Ce.extend({method:z("elicitation/create"),params:PR}),ER=ft.extend({elicitationId:b()}),RR=mt.extend({method:z("notifications/elicitation/complete"),params:ER}),ca=De.extend({action:Qe(["accept","decline","cancel"]),content:ll(t=>t===null?void 0:t,be(b(),me([b(),ce(),Re(),Q(b())])).optional())}),IR=I({type:z("ref/resource"),uri:b()});var AR=I({type:z("ref/prompt"),name:b()}),CR=it.extend({ref:me([AR,IR]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),DR=Ce.extend({method:z("completion/complete"),params:CR});var zR=De.extend({completion:He({values:Q(b()).max(100),total:xe(ce().int()),hasMore:xe(Re())})}),OR=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),MR=Ce.extend({method:z("roots/list"),params:it.optional()}),Rl=De.extend({roots:Q(OR)}),NR=mt.extend({method:z("notifications/roots/list_changed"),params:ft.optional()}),Hq=me([Qi,yl,DR,Pl,qE,FE,$E,PE,RE,DE,OE,ls,kl,ta,na,oa,ia]),Kq=me([Xi,ea,vl,NR,cs]),Gq=me([Yi,Tl,El,ca,Rl,ra,sa,Vn]),Jq=me([Qi,dR,TR,MR,ta,na,oa,ia]),Yq=me([Xi,ea,nR,NE,AE,eR,GE,cs,RR]),Xq=me([Yi,yE,zR,KE,ZE,kE,TE,IE,aa,XE,ra,sa,Vn]),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===ee.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new dl(o.elicitations,r)}return new t(e,r,n)}},dl=class extends W{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ee.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function yr(t){return t==="completed"||t==="failed"||t==="cancelled"}var $v=Symbol("Let zodToJsonSchema decide on which parser to use");var Sv={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"},kv=t=>typeof t=="string"?{...Sv,name:t}:{...Sv,...t};var Pv=t=>{let e=kv(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 Il(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function te(t,e,r,n,o){t[e]=r,Il(t,e,n,o)}var ua=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ua(e,t.currentPath):e.join("/")}}function Tv(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&&te(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&te(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(te(r,"minItems",t.exactLength.value,t.exactLength.message,e),te(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Ev(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?te(r,"minimum",n.value,n.message,e):te(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),te(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?te(r,"maximum",n.value,n.message,e):te(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),te(r,"maximum",n.value,n.message,e));break;case"multipleOf":te(r,"multipleOf",n.value,n.message,e);break}return r}function Rv(){return{type:"boolean"}}function la(t,e){return L(t.type._def,e)}var Iv=(t,e)=>L(t.innerType._def,e);function Al(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Al(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 jR(t,e)}}var jR=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":te(r,"minimum",n.value,n.message,e);break;case"max":te(r,"maximum",n.value,n.message,e);break}return r};function 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 Dv(t){return{type:"string",enum:Array.from(t.values)}}var LR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function zv(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(LR(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 Ov(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 Cl,xt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Cl===void 0&&(Cl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Cl),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function da(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":te(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":te(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":St(r,"email",n.message,e);break;case"format:idn-email":St(r,"idn-email",n.message,e);break;case"pattern:zod":Ke(r,xt.email,n.message,e);break}break;case"url":St(r,"uri",n.message,e);break;case"uuid":St(r,"uuid",n.message,e);break;case"regex":Ke(r,n.regex,n.message,e);break;case"cuid":Ke(r,xt.cuid,n.message,e);break;case"cuid2":Ke(r,xt.cuid2,n.message,e);break;case"startsWith":Ke(r,RegExp(`^${Dl(n.value,e)}`),n.message,e);break;case"endsWith":Ke(r,RegExp(`${Dl(n.value,e)}$`),n.message,e);break;case"datetime":St(r,"date-time",n.message,e);break;case"date":St(r,"date",n.message,e);break;case"time":St(r,"time",n.message,e);break;case"duration":St(r,"duration",n.message,e);break;case"length":te(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),te(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ke(r,RegExp(Dl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&St(r,"ipv4",n.message,e),n.version!=="v4"&&St(r,"ipv6",n.message,e);break}case"base64url":Ke(r,xt.base64url,n.message,e);break;case"jwt":Ke(r,xt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ke(r,xt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ke(r,xt.ipv6Cidr,n.message,e);break}case"emoji":Ke(r,xt.emoji(),n.message,e);break;case"ulid":{Ke(r,xt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{St(r,"binary",n.message,e);break}case"contentEncoding:base64":{te(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ke(r,xt.base64,n.message,e);break}}break}case"nanoid":Ke(r,xt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Dl(t,e){return e.patternStrategy==="escape"?ZR(t):t}var FR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ZR(t){let e="";for(let r=0;r<t.length;r++)FR.has(t[r])||(e+="\\"),e+=t[r];return e}function St(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):te(t,"format",e,r,n)}function Ke(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Mv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):te(t,"pattern",Mv(e,n),r,n)}function Mv(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
238
238
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
239
239
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
240
240
  `:`[${n[c]}\r
241
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function pa(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===P.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===P.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=da(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===P.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===P.ZodBranded&&t.keyType._def.type._def.typeName===P.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=la(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Ov(t,e){if(e.mapStrategy==="record")return pa(t,e);let r=L(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Mv(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Nv(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function jv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ds={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Fv(t,e){if(e.target==="openApi3")return Lv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ds&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ds[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Lv(t,e)}var Lv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>L(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Zv(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ds[t.innerType._def.typeName],nullable:!0}:{type:[ds[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=L(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Uv(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Rl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?te(r,"minimum",n.value,n.message,e):te(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),te(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?te(r,"maximum",n.value,n.message,e):te(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),te(r,"maximum",n.value,n.message,e));break;case"multipleOf":te(r,"multipleOf",n.value,n.message,e);break}return r}function qv(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=UR(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=L(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=ZR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function ZR(t,e){if(t.catchall._def.typeName!=="ZodNever")return L(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function UR(t){try{return t.isOptional()}catch{return!0}}var Vv=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return L(t.innerType._def,e);let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Bv=(t,e)=>{if(e.pipeStrategy==="input")return L(t.in._def,e);if(e.pipeStrategy==="output")return L(t.out._def,e);let r=L(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=L(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Wv(t,e){return L(t.type._def,e)}function Hv(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&te(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&te(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Kv(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:L(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Jv(t){return{not:we(t)}}function Gv(t){return we(t)}var Yv=(t,e)=>L(t.innerType._def,e);var Xv=(t,e,r)=>{switch(e){case P.ZodString:return da(t,r);case P.ZodNumber:return Uv(t,r);case P.ZodObject:return qv(t,r);case P.ZodBigInt:return Pv(t,r);case P.ZodBoolean:return Tv();case P.ZodDate:return Il(t,r);case P.ZodUndefined:return Jv(r);case P.ZodNull:return jv(r);case P.ZodArray:return kv(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return Fv(t,r);case P.ZodIntersection:return Cv(t,r);case P.ZodTuple:return Kv(t,r);case P.ZodRecord:return pa(t,r);case P.ZodLiteral:return Dv(t,r);case P.ZodEnum:return Av(t);case P.ZodNativeEnum:return Mv(t);case P.ZodNullable:return Zv(t,r);case P.ZodOptional:return Vv(t,r);case P.ZodMap:return Ov(t,r);case P.ZodSet:return Hv(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return Wv(t,r);case P.ZodNaN:case P.ZodNever:return Nv(r);case P.ZodEffects:return Iv(t,r);case P.ZodAny:return we(r);case P.ZodUnknown:return Gv(r);case P.ZodDefault:return Rv(t,r);case P.ZodBranded:return la(t,r);case P.ZodReadonly:return Yv(t,r);case P.ZodCatch:return Ev(t,r);case P.ZodPipeline:return Bv(t,r);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(n=>{})(e)}};function L(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==xv)return a}if(n&&!r){let a=qR(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Xv(t,t.typeName,e),i=typeof s=="function"?L(s(),e):s;if(i&&VR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var qR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ua(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},VR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fa=(t,e)=>{let r=$v(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:L(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=L(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Dl(t){let r=Bi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ny(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zl(t,e){let r=hr(t,e);if(!r.success)throw r.error;return r.data}var BR=6e4,ma=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Xi,r=>{this._oncancel(r)}),this.setNotificationHandler(ea,r=>{this._onprogress(r)}),this.setRequestHandler(Qi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ta,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(na,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new B(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new B(ee.InvalidParams,`Task not found: ${s}`);if(!yr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(yr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[gr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(oa,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new B(ee.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ia,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(yr(o.status))throw new B(ee.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new B(ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof B?o:new B(ee.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),B.fromError(ee.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),rs(s)||pv(s)?this._onresponse(s):fl(s)?this._onrequest(s,i):dv(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=B.fromError(ee.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[gr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:ee.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=cv(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:ee.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),rs(e))n(e);else{let i=new B(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(rs(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),rs(e))o(e);else{let i=B.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof B?i:new B(ee.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Vn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new B(ee.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},yr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new B(ee.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(ee.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof B?i:new B(ee.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[gr]:c}});let m=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let y=S instanceof B?S:new B(ee.RequestTimeout,String(S));l(y)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let y=hr(r,S.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??BR,v=()=>m(B.fromError(ee.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let S=y=>{let x=this._responseHandlers.get(p);x?x(y):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(_,{type:"request",message:f,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(p),l(y)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ra,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},sa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},hv,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[gr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[gr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[gr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Dl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=zl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Dl(e);this._notificationHandlers.set(n,o=>{let s=zl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&fl(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new B(ee.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new B(ee.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new B(ee.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new B(ee.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=as.parse({method:"notifications/tasks/status",params:a});await this.notification(c),yr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new B(ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(yr(a.status))throw new B(ee.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=as.parse({method:"notifications/tasks/status",params:c});await this.notification(u),yr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Qv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function e_(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Qv(i)&&Qv(s)?r[o]={...i,...s}:r[o]=s}return r}var Fw=uf(_p(),1),Zw=uf(Lw(),1);function OO(){let t=new Fw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Zw.default)(t),t}var Ya=class{constructor(e){this._ajv=e??OO()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Xa=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Uw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function qw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Qa=class extends ma{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ls.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ya,this.setRequestHandler(gl,n=>this._oninitialize(n)),this.setNotificationHandler(yl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(kl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ls.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Xa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=e_(this._capabilities,e)}setRequestHandler(e,r){let o=Bi(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Un(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=hr(us,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new B(ee.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=hr(Vn,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new B(ee.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=hr(aa,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new B(ee.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){qw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Uw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:sv.includes(r)?r:dl,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Yi)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Tl,r):this.request({method:"sampling/createMessage",params:e},Pl,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},ca,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},ca,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new B(ee.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof B?i:new B(ee.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},El,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import Bw from"node:process";var ec=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
242
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),MO(r)}clear(){this._buffer=void 0}};function MO(t){return fv.parse(JSON.parse(t))}function Vw(t){return JSON.stringify(t)+`
243
- `}var tc=class{constructor(e=Bw.stdin,r=Bw.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new ec,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Vw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as $j}from"url";var Tp={};Ve(Tp,{AI_CHAT_TIMEOUT_MS:()=>Gw,getTools:()=>FO,handleTool:()=>VO});import{readFileSync as Ww}from"fs";import{join as NO}from"path";import{randomUUID as jO}from"crypto";function q(t){let e=fa(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var LO=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider initial analysis) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/.")}).optional(),Hw=h.object({provider:h.string().describe("Provider ID (e.g. 'ollama', 'gemini', 'codex', 'claude')"),prompt:h.string().describe("Chat prompt to send"),model:h.string().optional().describe("Model override"),system:h.string().optional().describe("System prompt"),files:h.array(h.string()).optional().describe("File paths to include as context"),allow_external_paths:h.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false. Relative paths remain sandboxed either way. Audit trail is the call log \u2014 use sparingly."),save_as_document:LO.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Kw=h.object({provider:h.string().describe("Provider ID"),file_paths:h.array(h.string()).min(1).describe("File paths to analyze"),question:h.string().describe("Question to ask about the files"),save_to_file:h.string().optional().describe("Path to save the analysis result"),allow_external_paths:h.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false.")}),Jw=h.object({providers:h.array(h.string()).min(1).describe("List of provider IDs to compare"),prompt:h.string().describe("Prompt to send to all providers"),aggregate_provider:h.string().optional().describe("Provider ID to synthesize all responses into a unified document. If omitted, returns raw comparisons only."),aggregate_prompt:h.string().optional().describe("Custom synthesis prompt. Default: synthesize and identify agreements/disagreements.")}),Gw=9e4;function Yw(t,e,r){let n=`${r.tool}-${Date.now()}-${jO().slice(0,8)}`,o=NO(t,".agestra","pending-saves",`${n}.md`),s=[["id",n],["tool",r.tool],["provider",e.provider],["model",e.model],["created_at",new Date().toISOString()]];if(r.title&&s.push(["title",r.title]),r.originalTarget&&s.push(["original_target",r.originalTarget]),r.extraMetadata)for(let[a,c]of Object.entries(r.extraMetadata))c!=null&&c!==""&&s.push([a,c]);let i=["---",...s.map(([a,c])=>`${a}: ${JSON.stringify(c)}`),"---",""].join(`
241
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function pa(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===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}=da(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}=la(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Nv(t,e){if(e.mapStrategy==="record")return pa(t,e);let r=L(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function jv(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 Lv(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function Fv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ps={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Uv(t,e){if(e.target==="openApi3")return Zv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ps&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ps[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 Zv(t,e)}var Zv=(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 qv(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:ps[t.innerType._def.typeName],nullable:!0}:{type:[ps[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 Vv(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",Il(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?te(r,"minimum",n.value,n.message,e):te(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),te(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?te(r,"maximum",n.value,n.message,e):te(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),te(r,"maximum",n.value,n.message,e));break;case"multipleOf":te(r,"multipleOf",n.value,n.message,e);break}return r}function Bv(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=qR(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=UR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function UR(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 qR(t){try{return t.isOptional()}catch{return!0}}var Wv=(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 Hv=(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 Kv(t,e){return L(t.type._def,e)}function Gv(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&te(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&te(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Jv(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 Yv(t){return{not:we(t)}}function Xv(t){return we(t)}var Qv=(t,e)=>L(t.innerType._def,e);var e_=(t,e,r)=>{switch(e){case k.ZodString:return da(t,r);case k.ZodNumber:return Vv(t,r);case k.ZodObject:return Bv(t,r);case k.ZodBigInt:return Ev(t,r);case k.ZodBoolean:return Rv();case k.ZodDate:return Al(t,r);case k.ZodUndefined:return Yv(r);case k.ZodNull:return Fv(r);case k.ZodArray:return Tv(t,r);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Uv(t,r);case k.ZodIntersection:return zv(t,r);case k.ZodTuple:return Jv(t,r);case k.ZodRecord:return pa(t,r);case k.ZodLiteral:return Ov(t,r);case k.ZodEnum:return Dv(t);case k.ZodNativeEnum:return jv(t);case k.ZodNullable:return qv(t,r);case k.ZodOptional:return Wv(t,r);case k.ZodMap:return Nv(t,r);case k.ZodSet:return Gv(t,r);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return Kv(t,r);case k.ZodNaN:case k.ZodNever:return Lv(r);case k.ZodEffects:return Cv(t,r);case k.ZodAny:return we(r);case k.ZodUnknown:return Xv(r);case k.ZodDefault:return Av(t,r);case k.ZodBranded:return la(t,r);case k.ZodReadonly:return Qv(t,r);case k.ZodCatch:return Iv(t,r);case k.ZodPipeline:return Hv(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!==$v)return a}if(n&&!r){let a=VR(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=e_(t,t.typeName,e),i=typeof s=="function"?L(s(),e):s;if(i&&BR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var VR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ua(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},BR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fa=(t,e)=>{let r=Pv(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 zl(t){let r=Bi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ly(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ol(t,e){let r=hr(t,e);if(!r.success)throw r.error;return r.data}var WR=6e4,ma=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Xi,r=>{this._oncancel(r)}),this.setNotificationHandler(ea,r=>{this._onprogress(r)}),this.setRequestHandler(Qi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ta,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(na,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new 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(ee.InvalidParams,`Task not found: ${s}`);if(!yr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(yr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[gr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(oa,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new W(ee.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ia,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(yr(o.status))throw new W(ee.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof W?o:new W(ee.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),W.fromError(ee.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),ns(s)||mv(s)?this._onresponse(s):ml(s)?this._onrequest(s,i):fv(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(ee.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[gr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:ee.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=lv(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:ee.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ns(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(ns(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),ns(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(ee.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Vn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new W(ee.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},yr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new W(ee.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new W(ee.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof W?i:new W(ee.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[gr]:c}});let m=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>this._onerror(new Error(`Failed to send cancellation: ${_}`)));let w=S instanceof W?S:new W(ee.RequestTimeout,String(S));l(w)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let w=hr(r,S.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??WR,y=()=>m(W.fromError(ee.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let S=w=>{let _=this._responseHandlers.get(p);_?_(w):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(p),l(w)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ra,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},sa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},yv,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[gr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[gr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[gr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=zl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ol(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=zl(e);this._notificationHandlers.set(n,o=>{let s=Ol(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"&&ml(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new W(ee.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new W(ee.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new W(ee.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new W(ee.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=cs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),yr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new W(ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(yr(a.status))throw new W(ee.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=cs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),yr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function t_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function r_(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];t_(i)&&t_(s)?r[o]={...i,...s}:r[o]=s}return r}var Uw=df(bp(),1),qw=df(Zw(),1);function MO(){let t=new Uw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,qw.default)(t),t}var Ya=class{constructor(e){this._ajv=e??MO()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Xa=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Vw(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 Bw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Qa=class extends ma{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ds.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ya,this.setRequestHandler(yl,n=>this._oninitialize(n)),this.setNotificationHandler(vl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Pl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ds.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Xa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=r_(this._capabilities,e)}setRequestHandler(e,r){let o=Bi(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Un(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=hr(ls,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new W(ee.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=hr(Vn,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new W(ee.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=hr(aa,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new W(ee.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Bw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Vw(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:av.includes(r)?r:pl,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Yi)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},El,r):this.request({method:"sampling/createMessage",params:e},Tl,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},ca,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},ca,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new W(ee.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof W?i:new W(ee.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Rl,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 Hw from"node:process";var ec=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
242
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),NO(r)}clear(){this._buffer=void 0}};function NO(t){return hv.parse(JSON.parse(t))}function Ww(t){return JSON.stringify(t)+`
243
+ `}var tc=class{constructor(e=Hw.stdin,r=Hw.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new ec,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Ww(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as Pj}from"url";var Ep={};Be(Ep,{AI_CHAT_TIMEOUT_MS:()=>Xw,getTools:()=>ZO,handleTool:()=>BO});import{readFileSync as Kw}from"fs";import{join as jO}from"path";import{randomUUID as LO}from"crypto";function V(t){let e=fa(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var FO=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider initial analysis) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/.")}).optional(),Gw=h.object({provider:h.string().describe("Provider ID (e.g. 'ollama', 'gemini', 'codex', 'claude')"),prompt:h.string().describe("Chat prompt to send"),model:h.string().optional().describe("Model override"),system:h.string().optional().describe("System prompt"),files:h.array(h.string()).optional().describe("File paths to include as context"),allow_external_paths:h.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false. Relative paths remain sandboxed either way. Audit trail is the call log \u2014 use sparingly."),save_as_document:FO.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Jw=h.object({provider:h.string().describe("Provider ID"),file_paths:h.array(h.string()).min(1).describe("File paths to analyze"),question:h.string().describe("Question to ask about the files"),save_to_file:h.string().optional().describe("Path to save the analysis result"),allow_external_paths:h.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false.")}),Yw=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.")}),Xw=9e4;function Qw(t,e,r){let n=`${r.tool}-${Date.now()}-${LO().slice(0,8)}`,o=jO(t,".agestra","pending-saves",`${n}.md`),s=[["id",n],["tool",r.tool],["provider",e.provider],["model",e.model],["created_at",new Date().toISOString()]];if(r.title&&s.push(["title",r.title]),r.originalTarget&&s.push(["original_target",r.originalTarget]),r.extraMetadata)for(let[a,c]of Object.entries(r.extraMetadata))c!=null&&c!==""&&s.push([a,c]);let i=["---",...s.map(([a,c])=>`${a}: ${JSON.stringify(c)}`),"---",""].join(`
244
244
  `);return oe(o,i+`
245
- `+e.text),o}function FO(){return[{name:"ai_chat",title:"AI Chat",description:"Chat with a specific AI provider. Sends a prompt and returns the response. Optionally saves the response as a workspace document.",inputSchema:q(Hw)},{name:"ai_analyze_files",title:"Analyze Files with AI",description:"Analyze files with an AI provider. Reads files from disk, sends contents with a question, and optionally saves the result.",inputSchema:q(Kw)},{name:"ai_compare",title:"Compare AI Providers",description:"Send the same prompt to multiple providers and return a comparison. Optionally aggregate results into a unified synthesis using a designated provider.",inputSchema:q(Jw)}]}async function ZO(t,e){let r=Hw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("chat",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=r.allow_external_paths?eu:Gt,a=e.aiChatTimeoutMs??Gw,c=new AbortController,u=!1,l,d=s.chat({prompt:r.prompt,model:r.model,system:r.system,workspaceBaseDir:n,signal:c.signal,files:r.files?.map(g=>{let v=i(g,n);return{path:v,content:Ww(v,"utf-8")}})});d.catch(()=>{});let p;try{p=await Promise.race([d,new Promise((g,v)=>{l=setTimeout(()=>{u=!0,c.abort(new Error("__AI_CHAT_TIMEOUT__")),v(new Error("__AI_CHAT_TIMEOUT__"))},a)})])}catch(g){if(u&&e.jobManager){let v=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5,saveAsDocument:r.save_as_document}),_=r.save_as_document?`
245
+ `+e.text),o}function ZO(){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(Gw)},{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(Jw)},{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(Yw)}]}async function UO(t,e){let r=Gw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("chat",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=r.allow_external_paths?tu:Yt,a=e.aiChatTimeoutMs??Xw,c=new AbortController,u=!1,l,d=s.chat({prompt:r.prompt,model:r.model,system:r.system,workspaceBaseDir:n,signal:c.signal,files:r.files?.map(g=>{let y=i(g,n);return{path:y,content:Kw(y,"utf-8")}})});d.catch(()=>{});let p;try{p=await Promise.race([d,new Promise((g,y)=>{l=setTimeout(()=>{u=!0,c.abort(new Error("__AI_CHAT_TIMEOUT__")),y(new Error("__AI_CHAT_TIMEOUT__"))},a)})])}catch(g){if(u&&e.jobManager){let y=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5,saveAsDocument:r.save_as_document}),v=r.save_as_document?`
246
246
  **Save on complete:** ${r.save_as_document.title}`:"";return{content:[{type:"text",text:`\u23F1 Provider "${r.provider}" timed out after ${a/1e3}s. Auto-submitted as background job.
247
247
 
248
- **Job ID:** ${v}${_}
248
+ **Job ID:** ${y}${v}
249
249
 
250
250
  Use \`cli_job_status\` to check progress.`}]}}throw g}finally{l!==void 0&&clearTimeout(l)}let f="",m=!1;if(r.save_as_document&&e.documentManager)try{f=`
251
- **Document ID:** ${(await e.documentManager.createDocument({title:r.save_as_document.title,content:p.text,metadata:{...r.save_as_document.metadata,Provider:p.provider,Model:p.model},kind:r.save_as_document.kind})).id}`}catch(g){m=!0;let v=z(g);try{let _=Yw(n,p,{tool:"ai_chat",title:r.save_as_document.title,extraMetadata:{kind:r.save_as_document.kind,...r.save_as_document.metadata}});f=`
252
- \u26A0 Document save failed: ${v}
253
- **Pending save:** ${_}`}catch(_){f=`
254
- \u26A0 Document save failed: ${v}
255
- \u26A0 Pending-save dump also failed: ${z(_)}`}}return{content:[{type:"text",text:`**Provider:** ${p.provider}
251
+ **Document ID:** ${(await e.documentManager.createDocument({title:r.save_as_document.title,content:p.text,metadata:{...r.save_as_document.metadata,Provider:p.provider,Model:p.model},kind:r.save_as_document.kind})).id}`}catch(g){m=!0;let y=M(g);try{let v=Qw(n,p,{tool:"ai_chat",title:r.save_as_document.title,extraMetadata:{kind:r.save_as_document.kind,...r.save_as_document.metadata}});f=`
252
+ \u26A0 Document save failed: ${y}
253
+ **Pending save:** ${v}`}catch(v){f=`
254
+ \u26A0 Document save failed: ${y}
255
+ \u26A0 Pending-save dump also failed: ${M(v)}`}}return{content:[{type:"text",text:`**Provider:** ${p.provider}
256
256
  **Model:** ${p.model}${f}
257
257
 
258
- ${p.text}`}],...m?{isError:!0}:{}}}async function UO(t,e){let r=Kw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("analysis",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=r.allow_external_paths?eu:Gt,c=`${r.file_paths.map(p=>{let f=i(p,n),m=Ww(f,"utf-8");return`--- ${f} ---
258
+ ${p.text}`}],...m?{isError:!0}:{}}}async function qO(t,e){let r=Jw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("analysis",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=r.allow_external_paths?tu:Yt,c=`${r.file_paths.map(p=>{let f=i(p,n),m=Kw(f,"utf-8");return`--- ${f} ---
259
259
  ${m}`}).join(`
260
260
 
261
261
  `)}
262
262
 
263
263
  ---
264
264
 
265
- Question: ${r.question}`,u=await s.chat({prompt:c,workspaceBaseDir:n}),l="",d=!1;if(r.save_to_file)try{let p=pt(r.save_to_file,n);oe(p,u.text),l=`
265
+ Question: ${r.question}`,u=await s.chat({prompt:c,workspaceBaseDir:n}),l="",d=!1;if(r.save_to_file)try{let p=dt(r.save_to_file,n);oe(p,u.text),l=`
266
266
 
267
- _Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=z(p);try{let m=Yw(n,u,{tool:"ai_analyze_files",originalTarget:r.save_to_file,extraMetadata:{question:r.question,file_paths:r.file_paths.join(", ")}});l=`
267
+ _Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=M(p);try{let m=Qw(n,u,{tool:"ai_analyze_files",originalTarget:r.save_to_file,extraMetadata:{question:r.question,file_paths:r.file_paths.join(", ")}});l=`
268
268
 
269
269
  \u26A0 Save to ${r.save_to_file} failed: ${f}
270
270
  **Pending save:** ${m}`}catch(m){l=`
271
271
 
272
272
  \u26A0 Save to ${r.save_to_file} failed: ${f}
273
- \u26A0 Pending-save dump also failed: ${z(m)}`}}return{content:[{type:"text",text:`**Provider:** ${u.provider}
273
+ \u26A0 Pending-save dump also failed: ${M(m)}`}}return{content:[{type:"text",text:`**Provider:** ${u.provider}
274
274
  **Files analyzed:** ${r.file_paths.join(", ")}
275
275
 
276
- ${u.text}${l}`}],...d?{isError:!0}:{}}}async function qO(t,e){let r=Jw.parse(t),n=r.providers.map(c=>e.registry.get(c)),o=await Promise.all(n.map(async c=>{try{let u=await c.chat({prompt:r.prompt});return{provider:c.id,text:u.text,error:null}}catch(u){return{provider:c.id,text:null,error:z(u)}}})),s=`# Comparison
276
+ ${u.text}${l}`}],...d?{isError:!0}:{}}}async function VO(t,e){let r=Yw.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
277
277
 
278
278
  **Prompt:** ${r.prompt}
279
279
 
@@ -288,48 +288,48 @@ ${u.text}${l}`}],...d?{isError:!0}:{}}}async function qO(t,e){let r=Jw.parse(t),
288
288
 
289
289
  ---
290
290
 
291
- ${s}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${z(p)}]`}}}let a=s;return i&&(a+=`---
291
+ ${s}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${M(p)}]`}}}let a=s;return i&&(a+=`---
292
292
 
293
293
  # Synthesis
294
294
 
295
- ${i}`),{content:[{type:"text",text:a}]}}async function VO(t,e,r){switch(t){case"ai_chat":return ZO(e,r);case"ai_analyze_files":return UO(e,r);case"ai_compare":return qO(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Up={};Ve(Up,{getTools:()=>Ep,handleTool:()=>Qx});var rc=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),max_rounds:h.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:h.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:h.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:h.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),nc=h.object({items:h.array(h.object({provider:h.string().describe("Provider that produced the content"),content:h.string().describe("Content to validate"),task:h.string().describe("Original task description")})).min(1).describe("Items to cross-validate"),validators:h.array(h.string()).optional().describe("Provider IDs to use as validators (agent-tier only)"),criteria:h.string().optional().describe("Custom validation criteria")}),oc=h.object({session_id:h.string().describe("Session ID to check")}),sc=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),goal:h.string().optional().describe("Quality goal for the debate"),save_document:h.boolean().optional().default(!0).describe("Save debate as a workspace document (default: true)")}),ic=h.object({debate_id:h.string().describe("Debate session ID"),provider:h.string().describe(`Provider ID to take this turn. Use "claude" to record Claude's own opinion as an independent turn (requires claude_comment).`),claude_comment:h.string().optional().describe(`Claude's opinion. When provider is "claude", this becomes the turn content. Otherwise, injected before the provider responds.`),auto_specialist:h.boolean().optional().default(!1).describe("When true with provider 'claude', automatically select and record a specialist agent recommendation based on the debate topic.")}),ac=h.object({debate_id:h.string().describe("Debate session ID to conclude"),summary:h.string().optional().describe("Claude's final summary of the debate"),quality_scores:h.array(h.object({provider:h.string(),score:h.number().min(0).max(1),feedback:h.string()})).optional().describe("Quality assessment of each provider's contribution")}),cc=h.object({document:h.string().describe("Document content to review"),providers:h.array(h.string()).min(1).describe("Provider IDs to review the document"),review_prompt:h.string().optional().describe("Custom review instructions (default: agree/disagree with feedback)"),debate_id:h.string().optional().describe("Link reviews to an existing debate session's workspace document")}),uc=h.object({task_id:h.string().describe("Task ID to review changes for")}),lc=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),dc=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),Xw=h.object({agrees:h.union([h.boolean(),h.enum(["true","false"])]).transform(t=>typeof t=="boolean"?t:t==="true"),feedback:h.string().optional().default(""),suggestions:h.string().optional()}),pc=h.object({topic:h.string().min(1).describe("Topic for the structured debate"),scope:h.string().optional().describe("What the leader wants debated (file list or task framing). Defaults to topic when omitted."),goal:h.string().optional().describe("Optional quality goal for the debate"),leader:h.string().optional().describe("Participant ID authorized to approve the final synthesis. Defaults to the session-context leader or the first participant."),participants:h.array(h.string()).min(1).describe("Participant IDs. When `auto_inject_specialists` is true (default), `claude-reviewer` and/or `claude-qa` may be added based on the topic."),exclude_participants:h.array(h.string()).optional().describe("Participant IDs to never inject/include. Applied regardless of `auto_inject_specialists`."),auto_inject_specialists:h.boolean().optional().default(!0).describe("When true (default), topic-matching Claude specialists are added to `participants` honoring `exclude_participants`. When false, `participants` is used verbatim."),max_rounds:h.number().int().positive().max(50).optional().describe("Maximum number of rounds. Default: STRUCTURED_DEBATE_DEFAULT_MAX_ROUNDS."),individual_review_prompt:h.string().optional().describe("Override the system prompt used for individual-review fan-out."),files:h.array(h.string()).optional().describe("Optional list of files to pass to participants as context."),locale:h.enum(["ko","zh","ja","en"]).optional().describe("Override config locale for moderator text in this debate only.")}),fc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),leader_note:h.string().optional().describe("Optional note appended to the synthesis footer under 'Leader approval notes'.")}),mc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),additional_rounds:h.union([h.literal(3),h.literal(5),h.literal(10)]).describe("How many extra rounds to run beyond the current round count. Choose one of 3, 5, or 10.")}),hc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),reason:h.string().optional().describe("Optional rejection reason, captured in the debate transcript footer."),spawn_issue:h.boolean().optional().default(!1).describe("If true, write an issue_{sessionIdShort}_{YYYYMMDD}_{seq}.md under individual/ listing all non-accepted proposals (rejected/withdrawn/open/inconclusive/superseded). Default false.")});var gc="agent_debate_structured",co="agent_debate_approve",uo="agent_debate_continue",lo="agent_debate_reject";function yc(t){return t.moderatorEngine?t.structuredSessionRegistry?null:{content:[{type:"text",text:"Structured session registry is not initialized for this workspace."}],isError:!0}:{content:[{type:"text",text:"Structured debate engine is not initialized for this workspace. Check MCP server wiring."}],isError:!0}}async function Qw(t,e){let r=yc(e);if(r)return r;let n;try{n=pc.parse(t)}catch(s){return sr(`Invalid arguments: ${z(s)}`)}let o=BO(n.leader,n.participants,e);if(!o)return sr("Cannot resolve a leader. Provide `leader` explicitly or ensure the session context exposes one.");try{let s=await e.moderatorEngine.startDebate({topic:n.topic,...n.scope!==void 0?{scope:n.scope}:{},...n.goal!==void 0?{goal:n.goal}:{},leader:o,participants:n.participants,...n.exclude_participants!==void 0?{excludeParticipants:n.exclude_participants}:{},...n.auto_inject_specialists!==void 0?{autoInjectSpecialists:n.auto_inject_specialists}:{},...n.max_rounds!==void 0?{maxRounds:n.max_rounds}:{},...n.locale!==void 0?{locale:n.locale}:{},...n.individual_review_prompt!==void 0?{individualReviewPrompt:n.individual_review_prompt}:{},...n.files!==void 0?{files:n.files}:{}}),i=[s.terminalReport];return i.push(nx(s.sessionId,s.snapshot.status)),s.snapshot.status==="escalated"?i.push(sx(s.sessionId)):s.snapshot.status==="ready-for-approval"?i.push(ox(s.sessionId)):s.snapshot.status==="error"&&i.push(`Engine reported an error: ${s.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
295
+ ${i}`),{content:[{type:"text",text:a}]}}async function BO(t,e,r){switch(t){case"ai_chat":return UO(e,r);case"ai_analyze_files":return qO(e,r);case"ai_compare":return VO(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var qp={};Be(qp,{getTools:()=>Rp,handleTool:()=>tS});var rc=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),max_rounds:h.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:h.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:h.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:h.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),nc=h.object({items:h.array(h.object({provider:h.string().describe("Provider that produced the content"),content:h.string().describe("Content to validate"),task:h.string().describe("Original task description")})).min(1).describe("Items to cross-validate"),validators:h.array(h.string()).optional().describe("Provider IDs to use as validators (agent-tier only)"),criteria:h.string().optional().describe("Custom validation criteria")}),oc=h.object({session_id:h.string().describe("Session ID to check")}),sc=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),goal:h.string().optional().describe("Quality goal for the debate"),save_document:h.boolean().optional().default(!0).describe("Save debate as a workspace document (default: true)")}),ic=h.object({debate_id:h.string().describe("Debate session ID"),provider:h.string().describe(`Provider ID to take this turn. Use "claude" to record Claude's own opinion as an independent turn (requires claude_comment).`),claude_comment:h.string().optional().describe(`Claude's opinion. When provider is "claude", this becomes the turn content. Otherwise, injected before the provider responds.`),auto_specialist:h.boolean().optional().default(!1).describe("When true with provider 'claude', automatically select and record a specialist agent recommendation based on the debate topic.")}),ac=h.object({debate_id:h.string().describe("Debate session ID to conclude"),summary:h.string().optional().describe("Claude's final summary of the debate"),quality_scores:h.array(h.object({provider:h.string(),score:h.number().min(0).max(1),feedback:h.string()})).optional().describe("Quality assessment of each provider's contribution")}),cc=h.object({document:h.string().describe("Document content to review"),providers:h.array(h.string()).min(1).describe("Provider IDs to review the document"),review_prompt:h.string().optional().describe("Custom review instructions (default: agree/disagree with feedback)"),debate_id:h.string().optional().describe("Link reviews to an existing debate session's workspace document")}),uc=h.object({task_id:h.string().describe("Task ID to review changes for")}),lc=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),dc=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),ex=h.object({agrees:h.union([h.boolean(),h.enum(["true","false"])]).transform(t=>typeof t=="boolean"?t:t==="true"),feedback:h.string().optional().default(""),suggestions:h.string().optional()}),pc=h.object({topic:h.string().min(1).describe("Topic for the structured debate"),scope:h.string().optional().describe("What the leader wants debated (file list or task framing). Defaults to topic when omitted."),goal:h.string().optional().describe("Optional quality goal for the debate"),leader:h.string().optional().describe("Participant ID authorized to approve the final synthesis. Defaults to the session-context leader or the first participant."),participants:h.array(h.string()).min(1).describe("Participant IDs. When `auto_inject_specialists` is true (default), `claude-reviewer` and/or `claude-qa` may be added based on the topic."),exclude_participants:h.array(h.string()).optional().describe("Participant IDs to never inject/include. Applied regardless of `auto_inject_specialists`."),auto_inject_specialists:h.boolean().optional().default(!0).describe("When true (default), topic-matching Claude specialists are added to `participants` honoring `exclude_participants`. When false, `participants` is used verbatim."),max_rounds:h.number().int().positive().max(50).optional().describe("Maximum number of rounds. Default: STRUCTURED_DEBATE_DEFAULT_MAX_ROUNDS."),individual_review_prompt:h.string().optional().describe("Override the system prompt used for individual-review fan-out."),files:h.array(h.string()).optional().describe("Optional list of files to pass to participants as context."),locale:h.enum(["ko","zh","ja","en"]).optional().describe("Override config locale for moderator text in this debate only.")}),fc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),leader_note:h.string().optional().describe("Optional note appended to the synthesis footer under 'Leader approval notes'.")}),mc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),additional_rounds:h.union([h.literal(3),h.literal(5),h.literal(10)]).describe("How many extra rounds to run beyond the current round count. Choose one of 3, 5, or 10.")}),hc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),reason:h.string().optional().describe("Optional rejection reason, captured in the debate transcript footer."),spawn_issue:h.boolean().optional().default(!1).describe("If true, write an issue_{sessionIdShort}_{YYYYMMDD}_{seq}.md under individual/ listing all non-accepted proposals (rejected/withdrawn/open/inconclusive/superseded). Default false.")});var gc="agent_debate_structured",co="agent_debate_approve",uo="agent_debate_continue",lo="agent_debate_reject";function yc(t){return t.moderatorEngine?t.structuredSessionRegistry?null:{content:[{type:"text",text:"Structured session registry is not initialized for this workspace."}],isError:!0}:{content:[{type:"text",text:"Structured debate engine is not initialized for this workspace. Check MCP server wiring."}],isError:!0}}async function tx(t,e){let r=yc(e);if(r)return r;let n;try{n=pc.parse(t)}catch(s){return sr(`Invalid arguments: ${M(s)}`)}let o=WO(n.leader,n.participants,e);if(!o)return sr("Cannot resolve a leader. Provide `leader` explicitly or ensure the session context exposes one.");try{let s=await e.moderatorEngine.startDebate({topic:n.topic,...n.scope!==void 0?{scope:n.scope}:{},...n.goal!==void 0?{goal:n.goal}:{},leader:o,participants:n.participants,...n.exclude_participants!==void 0?{excludeParticipants:n.exclude_participants}:{},...n.auto_inject_specialists!==void 0?{autoInjectSpecialists:n.auto_inject_specialists}:{},...n.max_rounds!==void 0?{maxRounds:n.max_rounds}:{},...n.locale!==void 0?{locale:n.locale}:{},...n.individual_review_prompt!==void 0?{individualReviewPrompt:n.individual_review_prompt}:{},...n.files!==void 0?{files:n.files}:{}}),i=[s.terminalReport];return i.push(sx(s.sessionId,s.snapshot.status)),s.snapshot.status==="escalated"?i.push(ax(s.sessionId)):s.snapshot.status==="ready-for-approval"?i.push(ix(s.sessionId)):s.snapshot.status==="error"&&i.push(`Engine reported an error: ${s.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
296
296
 
297
- `)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return sr(`Failed to start structured debate: ${z(s)}`)}}async function ex(t,e){let r=yc(e);if(r)return r;let n;try{n=fc.parse(t)}catch(o){return sr(`Invalid arguments: ${z(o)}`)}try{let o=await e.moderatorEngine.approve({sessionId:n.session_id,...n.leader_note!==void 0?{leaderNote:n.leader_note}:{}}),s=[o.terminalReport];return s.push(`Synthesis document: ${o.synthesisPath}`),s.push(`Status: ${o.snapshot.status} (session ${n.session_id})`),o.idempotentReplay&&s.push("(idempotent replay of existing approved state \u2014 no new synthesis written)"),{content:[{type:"text",text:s.join(`
297
+ `)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return sr(`Failed to start structured debate: ${M(s)}`)}}async function rx(t,e){let r=yc(e);if(r)return r;let n;try{n=fc.parse(t)}catch(o){return sr(`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(`
298
298
 
299
- `)}]}}catch(o){return sr(`Approve failed: ${z(o)}`)}}async function tx(t,e){let r=yc(e);if(r)return r;let n;try{n=mc.parse(t)}catch(o){return sr(`Invalid arguments: ${z(o)}`)}try{let o=await e.moderatorEngine.continueDebate({sessionId:n.session_id,additionalRounds:n.additional_rounds}),s=[o.terminalReport];return s.push(nx(n.session_id,o.snapshot.status)),o.snapshot.status==="escalated"?s.push(sx(n.session_id)):o.snapshot.status==="ready-for-approval"&&s.push(ox(n.session_id)),{content:[{type:"text",text:s.join(`
299
+ `)}]}}catch(o){return sr(`Approve failed: ${M(o)}`)}}async function nx(t,e){let r=yc(e);if(r)return r;let n;try{n=mc.parse(t)}catch(o){return sr(`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(sx(n.session_id,o.snapshot.status)),o.snapshot.status==="escalated"?s.push(ax(n.session_id)):o.snapshot.status==="ready-for-approval"&&s.push(ix(n.session_id)),{content:[{type:"text",text:s.join(`
300
300
 
301
- `)}]}}catch(o){return sr(`Continue failed: ${z(o)}`)}}async function rx(t,e){let r=yc(e);if(r)return r;let n;try{n=hc.parse(t)}catch(o){return sr(`Invalid arguments: ${z(o)}`)}try{let o=await e.moderatorEngine.reject({sessionId:n.session_id,...n.reason!==void 0?{reason:n.reason}:{},...n.spawn_issue!==void 0?{spawnIssue:n.spawn_issue}:{}}),s=o.snapshot.documentPaths.debate,i=[`Structured debate session ${n.session_id} rejected.`];return n.reason&&i.push(`Reason: ${n.reason}`),i.push(`Transcript: ${s}`),o.issuePath&&i.push(`Issue document: ${o.issuePath}`),o.idempotentReplay&&i.push("(idempotent replay of existing rejected state \u2014 no new artifacts written)"),{content:[{type:"text",text:i.join(`
302
- `)}]}}catch(o){return sr(`Reject failed: ${z(o)}`)}}function BO(t,e,r){if(t&&t.length>0)return t;let n=r.sessionContext?.leaderProviderId;return n&&e.includes(n)||n?n:e[0]}function nx(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function ox(t){return["Next step \u2014 choose one:",`- Approve synthesis: call \`${co}\` with { session_id: "${t}" }`,`- Extend debate: call \`${uo}\` with { session_id: "${t}", additional_rounds: 3 | 5 | 10 }`,`- Abandon session: call \`${lo}\` with { session_id: "${t}" }`].join(`
303
- `)}function sx(t){return["Debate escalated \u2014 max rounds exhausted with open proposals.","The leader should choose one of:",`- \`${uo}\` with additional_rounds = 3 | 5 | 10 to run more rounds.`,`- \`${co}\` to accept the current synthesis with open items captured.`,`- \`${lo}\` to abandon the session.`,`Session ID: ${t}`].join(`
304
- `)}function sr(t){return{content:[{type:"text",text:t}],isError:!0}}function Ep(){return[{name:"agent_debate_start",title:"Start AI Debate",description:"Start a multi-provider debate on a topic. Optionally enable enhanced mode with goal-based quality validation.",inputSchema:q(rc)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:q(oc)},{name:"agent_cross_validate",title:"Cross-Validate Outputs",description:"Cross-validate work outputs. Each item is reviewed by agent-tier providers. Tool-tier providers cannot be validators.",inputSchema:q(nc)},{name:"agent_debate_create",title:"Create Turn-Based Debate",description:"Create a turn-based debate session. Returns a debate ID for use with agent_debate_turn and agent_debate_conclude.",inputSchema:q(sc)},{name:"agent_debate_turn",title:"Execute Debate Turn",description:`Execute one provider's turn in a debate. Optionally inject Claude's comment before the provider responds. Returns the provider's response. Use provider: "claude" with claude_comment to record Claude's own independent opinion as a debate turn.`,inputSchema:q(ic)},{name:"agent_debate_conclude",title:"Conclude Debate",description:"End a debate session and generate the final transcript. Optionally add Claude's summary and quality scores for each provider.",inputSchema:q(ac)},{name:"agent_debate_review",title:"Review Document with Providers",description:"Send a document to multiple providers for structured review. Each provider responds with agree/disagree and feedback. Use iteratively: review \u2192 revise document based on feedback \u2192 review again until all agree.",inputSchema:q(cc)},{name:"agent_changes_review",title:"Review File Changes",description:"Review file changes made by an external AI in an isolated worktree. Shows diff stat and full diff.",inputSchema:q(uc)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:q(lc)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:q(dc)},{name:gc,title:"Start Structured Debate",description:"Start a structured, approval-gated debate. Each participant submits an individual review, then rounds run until consensus or max rounds. Output is a ready-for-approval session \u2014 call agent_debate_approve/continue/reject to finalize. No synthesis is written until approved.",inputSchema:q(pc)},{name:co,title:"Approve Structured Debate",description:"Leader-approve a ready-for-approval structured-debate session. Writes the synthesis document and marks the session approved.",inputSchema:q(fc)},{name:uo,title:"Continue Structured Debate",description:"Run additional rounds on a ready-for-approval (or escalated) structured-debate session. Choose 3, 5, or 10 extra rounds.",inputSchema:q(mc)},{name:lo,title:"Reject Structured Debate",description:"Reject a ready-for-approval (or escalated/leader-timeout) structured-debate session. Transcript is marked rejected; no synthesis is written.",inputSchema:q(hc)}]}import{readFileSync as HO}from"fs";import{join as dx}from"path";function ix(t,e){let r=`${t} ${e??""}`.toLowerCase(),n=[{patterns:[/\breview\b/,/\bcode\s*quality\b/,/\bsecurity\b/,/\baudit\b/,/리뷰/,/보안/,/코드\s*품질/],agent:"agestra-reviewer"},{patterns:[/\bdesign\b/,/\barchitect/,/\bstructur/,/설계/,/아키텍처/,/구조/],agent:"agestra-designer"},{patterns:[/\bidea\b/,/\bimprov/,/\bcompare\b/,/\balternativ/,/\bbrainstorm/,/개선/,/아이디어/,/비교/,/대안/],agent:"agestra-ideator"},{patterns:[/\bverif/,/\bvalidat/,/\bqa\b/,/\btest\b/,/\bcheck\b/,/검증/,/테스트/,/확인/],agent:"agestra-qa"}];for(let o of n)if(o.patterns.some(s=>s.test(r)))return o.agent;return null}var vc="claude-reviewer",_c="claude-qa",WO={"agestra-reviewer":vc,"agestra-qa":_c};function ax(t){let{topic:e,goal:r,participants:n,excludeParticipants:o,autoInjectSpecialists:s}=t,i=new Set(o),a=n.filter(d=>!i.has(d)),c=ix(e,r),u=c!==null?WO[c]??null:null,l=[];return u===null?{participants:a,skipped:l}:s?i.has(u)?(l.push({participantId:u,reason:"explicitly-excluded"}),{participants:a,skipped:l}):a.includes(u)?(l.push({participantId:u,reason:"already-listed"}),{participants:a,skipped:l}):{participants:[...a,u],skipped:l}:(l.push({participantId:u,reason:"auto-disabled"}),{participants:a,skipped:l})}var Ip="claude",Ap="claude-cli",KO=new Set([vc,_c]),Cp=Object.freeze({[vc]:"agestra-reviewer",[_c]:"agestra-qa"});function JO(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
301
+ `)}]}}catch(o){return sr(`Continue failed: ${M(o)}`)}}async function ox(t,e){let r=yc(e);if(r)return r;let n;try{n=hc.parse(t)}catch(o){return sr(`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(`
302
+ `)}]}}catch(o){return sr(`Reject failed: ${M(o)}`)}}function WO(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 sx(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function ix(t){return["Next step \u2014 choose one:",`- Approve synthesis: call \`${co}\` with { session_id: "${t}" }`,`- Extend debate: call \`${uo}\` with { session_id: "${t}", additional_rounds: 3 | 5 | 10 }`,`- Abandon session: call \`${lo}\` with { session_id: "${t}" }`].join(`
303
+ `)}function ax(t){return["Debate escalated \u2014 max rounds exhausted with open proposals.","The leader should choose one of:",`- \`${uo}\` with additional_rounds = 3 | 5 | 10 to run more rounds.`,`- \`${co}\` to accept the current synthesis with open items captured.`,`- \`${lo}\` to abandon the session.`,`Session ID: ${t}`].join(`
304
+ `)}function sr(t){return{content:[{type:"text",text:t}],isError:!0}}function Rp(){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(rc)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:V(oc)},{name:"agent_cross_validate",title:"Cross-Validate Outputs",description:"Cross-validate work outputs. Each item is reviewed by agent-tier providers. Tool-tier providers cannot be validators.",inputSchema:V(nc)},{name:"agent_debate_create",title:"Create Turn-Based Debate",description:"Create a turn-based debate session. Returns a debate ID for use with agent_debate_turn and agent_debate_conclude.",inputSchema:V(sc)},{name:"agent_debate_turn",title:"Execute Debate Turn",description:`Execute one provider's turn in a debate. Optionally inject Claude's comment before the provider responds. Returns the provider's response. Use provider: "claude" with claude_comment to record Claude's own independent opinion as a debate turn.`,inputSchema:V(ic)},{name:"agent_debate_conclude",title:"Conclude Debate",description:"End a debate session and generate the final transcript. Optionally add Claude's summary and quality scores for each provider.",inputSchema:V(ac)},{name:"agent_debate_review",title:"Review Document with Providers",description:"Send a document to multiple providers for structured review. Each provider responds with agree/disagree and feedback. Use iteratively: review \u2192 revise document based on feedback \u2192 review again until all agree.",inputSchema:V(cc)},{name:"agent_changes_review",title:"Review File Changes",description:"Review file changes made by an external AI in an isolated worktree. Shows diff stat and full diff.",inputSchema:V(uc)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:V(lc)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:V(dc)},{name:gc,title:"Start Structured Debate",description:"Start a structured, approval-gated debate. Each participant submits an individual review, then rounds run until consensus or max rounds. Output is a ready-for-approval session \u2014 call agent_debate_approve/continue/reject to finalize. No synthesis is written until approved.",inputSchema:V(pc)},{name:co,title:"Approve Structured Debate",description:"Leader-approve a ready-for-approval structured-debate session. Writes the synthesis document and marks the session approved.",inputSchema:V(fc)},{name:uo,title:"Continue Structured Debate",description:"Run additional rounds on a ready-for-approval (or escalated) structured-debate session. Choose 3, 5, or 10 extra rounds.",inputSchema:V(mc)},{name:lo,title:"Reject Structured Debate",description:"Reject a ready-for-approval (or escalated/leader-timeout) structured-debate session. Transcript is marked rejected; no synthesis is written.",inputSchema:V(hc)}]}import{join as dN}from"path";import{readFileSync as KO}from"fs";import{join as fx}from"path";function cx(t,e){let r=`${t} ${e??""}`.toLowerCase(),n=[{patterns:[/\breview\b/,/\bcode\s*quality\b/,/\bsecurity\b/,/\baudit\b/,/리뷰/,/보안/,/코드\s*품질/],agent:"agestra-reviewer"},{patterns:[/\bdesign\b/,/\barchitect/,/\bstructur/,/설계/,/아키텍처/,/구조/],agent:"agestra-designer"},{patterns:[/\bidea\b/,/\bimprov/,/\bcompare\b/,/\balternativ/,/\bbrainstorm/,/개선/,/아이디어/,/비교/,/대안/],agent:"agestra-ideator"},{patterns:[/\bverif/,/\bvalidat/,/\bqa\b/,/\btest\b/,/\bcheck\b/,/검증/,/테스트/,/확인/],agent:"agestra-qa"}];for(let o of n)if(o.patterns.some(s=>s.test(r)))return o.agent;return null}var vc="claude-reviewer",_c="claude-qa",HO={"agestra-reviewer":vc,"agestra-qa":_c};function ux(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=cx(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 Ap="claude",Cp="claude-cli",GO=new Set([vc,_c]),Dp=Object.freeze({[vc]:"agestra-reviewer",[_c]:"agestra-qa"});function JO(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
305
305
  `,3);if(e<0)return t;let r=t.indexOf(`
306
306
  ---`,e);if(r<0)return t;let n=t.indexOf(`
307
- `,r+4);return n<0?"":t.slice(n+1)}function GO(t,e){return KO.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:Cp[t]}:{transport:"cli-bridge",providerId:Ap,agentName:Cp[t]}:t===Ip?e==="claude-code"?{transport:"read-only-chat",providerId:Ip}:{transport:"cli-bridge",providerId:Ap}:{transport:"read-only-chat",providerId:t}}function cx(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var ux=18e4;function Rp(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${ux/1e3}s)`)),ux))])}function lx(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=Cp[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=dx(r,`${s}.md`);try{let a=JO(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var Dp=class{registry;readOnlyAdapter;hostKind;agentsDir;readFile;subagentSpawner;sysPromptCache=new Map;constructor(e){this.registry=e.registry,this.readOnlyAdapter=e.readOnlyAdapter,this.hostKind=e.hostKind,this.agentsDir=e.agentsDir??dx(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>HO(r,"utf-8")),this.subagentSpawner=e.subagentSpawner}describe(e){return this.resolveDescriptor(e)}async requestTurn(e,r){let n=this.resolveDescriptor(e),o=performance.now();try{switch(n.transport){case"task-subagent":{if(!this.subagentSpawner)return this.buildFailure(e,o,"subagent spawner not wired (integration pending \u2014 T10/T12)");let s=await Rp(this.subagentSpawner({agentName:n.agentName??e,prompt:r.prompt,system:r.system}),e);return this.buildSuccess(e,o,s.text)}case"cli-bridge":{let s=n.providerId??Ap,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=lx(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await Rp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:cx(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}case"read-only-chat":{let s=n.providerId??e,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`provider "${s}" not registered`);let a=n.agentName!==void 0?lx(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await Rp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:cx(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}default:{let s=n.transport;return this.buildFailure(e,o,`unknown transport: ${String(s)}`)}}}catch(s){return this.buildFailure(e,o,z(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}resolveDescriptor(e){let r=GO(e,this.hostKind);return r.transport==="task-subagent"&&!this.subagentSpawner&&this.hostKind==="claude-code"?{transport:"read-only-chat",providerId:Ip,agentName:r.agentName}:r}buildSuccess(e,r,n){return{participantId:e,text:n,latencyMs:Math.round(performance.now()-r),failed:!1}}buildFailure(e,r,n){return{participantId:e,text:"",latencyMs:Math.round(performance.now()-r),failed:!0,failureReason:n}}};function px(t){return new Dp(t)}function fx(t,e){return e(t)}var YO=/[.,!?;:]/g,XO=/\s+/g;function mx(t){return t.toLowerCase().replace(YO," ").replace(XO," ").trim()}function hx(t){return typeof t.location=="string"&&t.location.length>0}function gx(t,e){if(e.length===0)return t;let r=new Set(t),n=t.slice();for(let o of e)r.has(o)||(r.add(o),n.push(o));return n}function QO(t){let e={id:t.id,proposerIds:t.proposerIds.slice(),title:t.title,severity:t.severity,roundOpened:t.roundOpened,status:t.status,votes:new Map};t.location!==void 0&&(e.location=t.location),t.description!==void 0&&(e.description=t.description),t.supersededBy!==void 0&&(e.supersededBy=t.supersededBy),t.mergedInto!==void 0&&(e.mergedInto=t.mergedInto);for(let[r,n]of t.votes)e.votes.set(r,{...n});return e}function eM(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=mx(t.title)===mx(e.title),s=t.severity===e.severity,a=hx(t)&&hx(e)&&t.location===e.location,c=[];if(o&&c.push("title"),s&&c.push("severity"),a&&c.push("location"),c.length===0)return{kind:"unrelated"};if(o&&s&&a)return{kind:"hard-merge"};let l;return o?s?l="location":l="severity":l="title",{kind:"alias",pair:{proposalA:t.id,proposalB:e.id,matchedFields:c,missingField:l}}}var po=class t{_proposals=new Map;_aliasCandidates=[];get proposals(){return this._proposals}get aliasCandidates(){return this._aliasCandidates.slice()}addProposal(e){if(this._proposals.has(e.id))throw new Error(`ProposalLedger.addProposal: duplicate id "${e.id}"`);let r={id:e.id,proposerIds:e.proposerIds.slice(),title:e.title,severity:e.severity,roundOpened:e.roundOpened,status:e.status??"open",votes:new Map};e.location!==void 0&&(r.location=e.location),e.description!==void 0&&(r.description=e.description),this._proposals.set(r.id,r)}recordVote(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.recordVote: unknown proposal id "${e}"`);o.votes.set(r,{...n}),o.proposerIds.includes(r)&&n.vote==="revise"&&o.status==="open"&&(o.status="withdrawn-by-author")}countRevisesThisRound(e,r){let n=this._proposals.get(e);if(!n)return 0;let o=0;for(let[s,i]of n.votes)i.vote==="revise"&&i.roundRecorded===r&&(n.proposerIds.includes(s)||(o+=1));return o}markSuperseded(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.markSuperseded: unknown old id "${e}"`);if(!this._proposals.has(r))throw new Error(`ProposalLedger.markSuperseded: successor id "${r}" not registered`);o.status="superseded",o.supersededBy=r;for(let s of o.votes.values())s.supersededAt===void 0&&(s.supersededAt=n)}applyAliasMerge(e,r){if(e===r)throw new Error(`ProposalLedger.applyAliasMerge: cannot merge id "${e}" into itself`);let n=this._proposals.get(e),o=this._proposals.get(r);if(!n)throw new Error(`ProposalLedger.applyAliasMerge: unknown primary id "${e}"`);if(!o)throw new Error(`ProposalLedger.applyAliasMerge: unknown alias id "${r}"`);n.proposerIds=gx(n.proposerIds,o.proposerIds);for(let[s,i]of o.votes){let a=n.votes.get(s);if(!a){n.votes.set(s,{...i});continue}i.roundRecorded>a.roundRecorded&&n.votes.set(s,{...i})}o.status="merged",o.mergedInto=e;for(let s=this._aliasCandidates.length-1;s>=0;s-=1){let i=this._aliasCandidates[s];(i.proposalA===r||i.proposalB===r||i.proposalA===e||i.proposalB===e)&&this._aliasCandidates.splice(s,1)}}setStatus(e,r){let n=this._proposals.get(e);if(!n)throw new Error(`ProposalLedger.setStatus: unknown proposal id "${e}"`);n.status=r}aggregateRound(e,r,n=[]){let o=new Set(n),s=[];for(let i of this._proposals.values()){if(i.status!=="open")continue;let a={agree:0,disagree:0,abstain:0,revise:0,missing:0};for(let u of r){if(i.proposerIds.includes(u))continue;let l=i.votes.get(u);if(l===void 0||l.roundRecorded!==e){o.has(u)?a.abstain+=1:a.missing+=1;continue}switch(l.vote){case"agree":a.agree+=1;break;case"disagree":a.disagree+=1;break;case"abstain":a.abstain+=1;break;case"revise":a.revise+=1;break;default:{let d=l.vote}}}let c=tM(a);s.push({proposalId:i.id,tally:a,verdict:c})}return s}getOpenProposals(){return this.selectByStatus("open")}getConsensusProposals(){return this.selectByStatus("consensus")}getUnresolved(){return this.selectByStatus("unresolved")}selectByStatus(e){let r=[];for(let n of this._proposals.values())n.status===e&&r.push(QO(n));return r}toJSON(){let e=Array.from(this._proposals.values()).map(n=>{let o=[];for(let[i,a]of n.votes){let c={voter:i,vote:a.vote,roundRecorded:a.roundRecorded};a.reason!==void 0&&(c.reason=a.reason),a.supersededAt!==void 0&&(c.supersededAt=a.supersededAt),o.push(c)}let s={id:n.id,proposerIds:n.proposerIds.slice(),title:n.title,severity:n.severity,roundOpened:n.roundOpened,status:n.status,votes:o};return n.location!==void 0&&(s.location=n.location),n.description!==void 0&&(s.description=n.description),n.supersededBy!==void 0&&(s.supersededBy=n.supersededBy),n.mergedInto!==void 0&&(s.mergedInto=n.mergedInto),s}),r=this._aliasCandidates.map(n=>({proposalA:n.proposalA,proposalB:n.proposalB,matchedFields:n.matchedFields.slice(),missingField:n.missingField}));return{proposals:e,aliasCandidates:r}}static fromJSON(e){let r=new t,n=new Set;for(let o of e.proposals){if(n.has(o.id))throw new Error(`ProposalLedger.fromJSON: duplicate proposal id "${o.id}"`);n.add(o.id);let s={id:o.id,proposerIds:o.proposerIds.slice(),title:o.title,severity:o.severity,roundOpened:o.roundOpened,status:o.status,votes:new Map};o.location!==void 0&&(s.location=o.location),o.description!==void 0&&(s.description=o.description),o.supersededBy!==void 0&&(s.supersededBy=o.supersededBy),o.mergedInto!==void 0&&(s.mergedInto=o.mergedInto);for(let i of o.votes){let a={vote:i.vote,roundRecorded:i.roundRecorded};i.reason!==void 0&&(a.reason=i.reason),i.supersededAt!==void 0&&(a.supersededAt=i.supersededAt),s.votes.set(i.voter,a)}r._proposals.set(s.id,s)}for(let o of e.aliasCandidates)r._aliasCandidates.push({proposalA:o.proposalA,proposalB:o.proposalB,matchedFields:o.matchedFields.slice(),missingField:o.missingField});return r}_rawProposal(e){return this._proposals.get(e)}_pushAliasCandidate(e){this._aliasCandidates.push(e)}_extendProposers(e,r){let n=this._proposals.get(e);n&&(n.proposerIds=gx(n.proposerIds,r))}_maybeReplaceDescription(e,r){let n=this._proposals.get(e);if(!n||r===void 0)return;let o=n.description??"";r.length>o.length&&(n.description=r)}};function tM(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function yx(t){let e=new po,r=new Set;for(let s of t){if(r.has(s.id))throw new Error(`buildInitialLedger: duplicate proposal id "${s.id}"`);r.add(s.id),e.addProposal({id:s.id,proposerIds:[s.proposerId],title:s.title,severity:s.severity,...s.location!==void 0?{location:s.location}:{},...s.description!==void 0?{description:s.description}:{},roundOpened:s.roundOpened??1,status:"open"})}let n=new Set,o=t.map(s=>s.id);for(let s=0;s<o.length;s+=1){let i=o[s];if(n.has(i))continue;let a=e._rawProposal(i);if(a)for(let c=s+1;c<o.length;c+=1){let u=o[c];if(n.has(u))continue;let l=e._rawProposal(u);if(!l)continue;let d=eM(a,l);if(d.kind==="hard-merge"){e._extendProposers(i,l.proposerIds),e._maybeReplaceDescription(i,l.description),e._proposals.delete(u),n.add(u);continue}d.kind==="alias"&&e._pushAliasCandidate(d.pair)}}return{ledger:e,aliasCandidates:e.aliasCandidates}}var rM=new Set(Sf);function nM(t){return rM.has(t)}var oM=new Set(["disagree","revise"]);function sM(t){let e=`<${gn}>`,r=`</${gn}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function iM(t){let e=`<${gn}>`;return t.includes(e)}var aM=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function cM(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return aM[r]??e})}function uM(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=cM(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function zp(t,e){let r=sM(t);if(!r)return iM(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${gn}> without matching </${gn}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!vx(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!vx(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=uM(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.id,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({proposalId:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!nM(g)){l.push({proposalId:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({proposalId:m,reason:"unknown-id",raw:p.raw});continue}if(d.has(m)){l.push({proposalId:m,reason:"duplicate-id",raw:p.raw});continue}let v=f.reason,_=typeof v=="string"&&v.length>0?v:void 0;if(oM.has(g)&&_===void 0){d.add(m),l.push({proposalId:m,reason:"missing-reason",raw:p.raw});continue}d.add(m);let S={proposalId:m,vote:g};_!==void 0&&(S.reason=_),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}function vx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var lM=Object.freeze(["same","different","unsure"]),Zs="alias-votes",dM=new Set(lM);function pM(t){return dM.has(t)}function fM(t){let e=`<${Zs}>`,r=`</${Zs}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function mM(t){let e=`<${Zs}>`;return t.includes(e)}var hM=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function gM(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return hM[r]??e})}function yM(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=gM(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function _x(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Op(t,e){let r=fM(t);if(!r)return mM(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${Zs}> without matching </${Zs}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!_x(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!_x(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=yM(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.pair,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({pair:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!pM(g)){l.push({pair:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({pair:m,reason:"unknown-pair",raw:p.raw});continue}if(d.has(m)){l.push({pair:m,reason:"duplicate-pair",raw:p.raw});continue}let v=f.reason,_=typeof v=="string"&&v.length>0?v:void 0;d.add(m);let S={pair:m,vote:g};_!==void 0&&(S.reason=_),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}var vM="__";function _M(t){return`${t.proposalA}${vM}${t.proposalB}`}var bM=["You are participating in the alias clarification phase of a structured debate.","The moderator has detected the following proposal pairs that partially match","on title / severity / location but did not satisfy the automatic hard-merge","rule. For each pair, decide whether the two proposals describe the SAME","underlying issue or DIFFERENT issues. If you cannot tell from the material","given, answer `unsure` \u2014 there is no penalty for uncertainty here, this","phase is not the main debate."].join(" "),wM=["For every pair below, emit exactly one `<item>` element inside the","`<alias-votes>` block. The `pair` attribute must match the identifier","printed with each pair. The `vote` attribute must be one of:","`same`, `different`, `unsure`. A `reason` attribute is optional but","encouraged when you answer `different` or `unsure`."].join(" "),xM=["Response format \u2014 append the following block at the end of your reply","(moderator parses only this block; preamble is ignored):","","<alias-votes>",' <item pair="P1__P2" vote="same"/>',' <item pair="P3__P4" vote="different" reason="P3 concerns cache invalidation; P4 concerns read-through."/>',' <item pair="P5__P6" vote="unsure" reason="Insufficient detail on location."/>',"</alias-votes>"].join(`
308
- `),SM="Candidate pairs:";function $M(t,e){return["Your previous response did not include a valid `<alias-votes>` block.",`Problem: ${e}`,"Reply with ONLY the `<alias-votes>` block. Do not include prose.","<alias-votes>",...t.map(r=>` <item pair="${r}" vote="same|different|unsure" reason="optional"/>`),"</alias-votes>"].join(`
309
- `)}async function $x(t){let{ledger:e,participantIds:r,askParticipant:n}=t,o=e.aliasCandidates;if(o.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let s=o.map(_M),i=new Map;for(let f=0;f<o.length;f+=1)i.set(s[f],o[f]);let a=kM(e,o,s),c=await Promise.allSettled(r.map(async f=>{let m=await n(f,a);return{participantId:f,response:m}})),u=[],l=new Map;for(let f of s)l.set(f,{same:0,different:0,unsure:0,missing:0});for(let f=0;f<c.length;f+=1){let m=c[f],g=r[f];if(m.status==="rejected"){u.push({participantId:g,reason:Sx(m.reason)}),bc(l,s);continue}let{response:v}=m.value;if(v.failed===!0){u.push({participantId:g,reason:"askParticipant reported failed=true"}),bc(l,s);continue}let _=Op(v.text,s),S=new Set;if(!_.ok){let y=await n(g,$M(s,_.error.details!==void 0?`${_.error.kind}: ${_.error.details}`:_.error.kind)).catch($=>({text:"",failed:!0,reason:Sx($)}));if(y.failed===!0){u.push({participantId:g,reason:"reason"in y&&typeof y.reason=="string"?y.reason:"retry failed"}),bc(l,s);continue}let x=Op(y.text,s);if(!x.ok){u.push({participantId:g,reason:x.error.details!==void 0?`${x.error.kind}: ${x.error.details}`:x.error.kind}),bc(l,s);continue}for(let $ of x.entries)xx(l,$),S.add($.pair);for(let $ of s)if(!S.has($)){let M=l.get($);M!==void 0&&(M.missing+=1)}continue}for(let y of _.entries)xx(l,y),S.add(y.pair);for(let y of s)if(!S.has(y)){let x=l.get(y);x!==void 0&&(x.missing+=1)}}let d=[],p=[];for(let f of s){let m=i.get(f),g=l.get(f);if(m===void 0||g===void 0)continue;let v=TM(g);if(v.kind==="merge"){let _=m.proposalA,S=m.proposalB;if(e.proposals.get(_)===void 0||e.proposals.get(S)===void 0)continue;e.applyAliasMerge(_,S),d.push({primary:_,alias:S,voteBreakdown:{...g}});continue}p.push({pair:m,voteBreakdown:{...g},reason:v.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function kM(t,e,r){let n=[];n.push(bM),n.push(""),n.push(wM),n.push(""),n.push(SM),n.push("");for(let o=0;o<e.length;o+=1){let s=e[o],i=r[o],a=t.proposals.get(s.proposalA),c=t.proposals.get(s.proposalB);n.push(`Pair ${o+1} \u2014 pair="${i}"`),n.push(` matched fields: ${s.matchedFields.join(", ")||"(none)"}`),n.push(` blocking field: ${s.missingField}`),n.push(" Proposal A:"),bx(n,a),n.push(" Proposal B:"),bx(n,c),n.push("")}return n.push(xM),n.join(`
310
- `)}function bx(t,e){if(e===void 0){t.push(" (proposal unavailable \u2014 already removed from ledger)");return}if(t.push(` id: ${e.id}`),t.push(` title: ${e.title}`),t.push(` severity: ${e.severity}`),t.push(` location: ${e.location!==void 0&&e.location.length>0?e.location:"(empty)"}`),e.description!==void 0&&e.description.length>0){let r=PM(e.description);t.push(` description: ${r}`)}}var wx=400;function PM(t){return t.length<=wx?t:`${t.slice(0,wx)}\u2026`}function xx(t,e){let r=t.get(e.pair);if(r!==void 0)switch(e.vote){case"same":r.same+=1;break;case"different":r.different+=1;break;case"unsure":r.unsure+=1;break;default:{let n=e.vote}}}function bc(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function TM(t){return t.same===0&&t.different===0?{kind:"undecided",reason:"no-votes"}:t.same>t.different?{kind:"merge"}:t.same===t.different?{kind:"undecided",reason:"tie"}:{kind:"undecided",reason:"different-majority"}}function Sx(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as EM}from"fs/promises";import{readFileSync as RM,existsSync as Mp,unlinkSync as IM,mkdirSync as AM}from"fs";import{join as Us}from"path";var jp=".approval.json";function Np(t){return`${t}${jp}`}function CM(t){return t.endsWith(jp)?t.slice(0,t.length-jp.length):null}function kx(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+$f).toISOString()}var fo=class{debatesDir;cache=new Map;hydrated=!1;constructor(e){if(!e||typeof e!="string")throw new Error("StructuredSessionRegistry: baseDir is required");this.debatesDir=Us(e,Hs)}getDebatesDir(){return this.debatesDir}async persist(e){if(!e||!e.sessionId)throw new Error("StructuredSessionRegistry.persist: snapshot.sessionId is required");if(e.schemaVersion!==1)throw new Error(`StructuredSessionRegistry.persist: unsupported schemaVersion=${e.schemaVersion}`);AM(this.debatesDir,{recursive:!0});let r=Us(this.debatesDir,Np(e.sessionId));je(r,e),this.cache.set(e.sessionId,e)}async load(e){let r=this.cache.get(e);if(r)return r;let n=Us(this.debatesDir,Np(e));if(!Mp(n))return null;let o=this.readSnapshotFile(n);return o&&this.cache.set(e,o),o}async remove(e){this.cache.delete(e);let r=Us(this.debatesDir,Np(e));if(Mp(r))try{IM(r)}catch(n){if(n.code!=="ENOENT")throw n}}async hydrateFromDisk(){if(this.cache.clear(),!Mp(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await EM(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=CM(r);if(!n)continue;let o=this.readSnapshotFile(Us(this.debatesDir,r));o&&o.sessionId===n&&this.cache.set(n,o)}this.hydrated=!0}get(e){return this.cache.get(e)}getAll(){return Array.from(this.cache.values())}async sweepTimeouts(e=new Date){let r=e.getTime(),n=[],o=[];for(let s of this.cache.values()){if(s.status!=="ready-for-approval")continue;let i=Date.parse(s.deadline);if(Number.isNaN(i)||r<=i)continue;let a={...s,status:"leader-timeout",terminalNote:s.terminalNote??"leader-timeout after approval window"};try{await this.persist(a),n.push(a)}catch(c){o.push({sessionId:s.sessionId,error:c})}}return o.length>0&&console.warn(`[session-registry] sweepTimeouts: ${o.length} snapshot(s) failed to transition; will retry on next sweep`,o.map(s=>({sessionId:s.sessionId,message:s.error instanceof Error?s.error.message:String(s.error)}))),n}isHydrated(){return this.hydrated}readSnapshotFile(e){let r;try{r=RM(e,"utf-8")}catch(o){if(o.code==="ENOENT")return null;throw o}let n;try{n=JSON.parse(r)}catch{return console.warn(`[session-registry] skipping unparseable snapshot file: ${e}`),null}return DM(n)?n:(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function DM(t){if(!t||typeof t!="object")return!1;let e=t;return e.schemaVersion===1&&typeof e.sessionId=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.readyAt=="string"&&typeof e.deadline=="string"&&typeof e.config=="object"&&e.config!==null&&typeof e.rounds=="number"&&Array.isArray(e.aggregatedVotes)&&typeof e.documentPaths=="object"&&e.documentPaths!==null}function zM(t,e){let r=[];r.push(...NM(t,e)),r.push(""),r.push(...Tx(t,e));let n=Ex(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...Rx(t,e)),r.push(""),r.push(...LM(t,e)),r.join(`
311
- `)}function OM(t,e){let r=[];r.push(...Tx(t,e));let n=FM(t,e);n.length>0&&(r.push(""),r.push(...n));let o=ZM(t,e);o.length>0&&(r.push(""),r.push(...o));let s=UM(t,e);s.length>0&&(r.push(""),r.push(...s));let i=Ex(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...Rx(t,e)),r.join(`
312
- `)}function Px(){return{renderTerminal:zM,renderSynthesis:OM}}var MM=Object.freeze({running:"report.status.running","ready-for-approval":"report.status.readyForApproval",consensus:"report.status.consensus",escalated:"report.status.escalated",approved:"report.status.approved",rejected:"report.status.rejected","leader-timeout":"report.status.leaderTimeout",error:"report.status.error"});function NM(t,e){let r=e.t(MM[t.status]),n=e.t("report.header.topic"),o=e.t("report.header.participants"),s=e.t("report.header.individualDocs"),i=[`## ${n}: ${t.topic} (${t.rounds}/${t.maxRounds} \u2014 ${r})`,`## ${o}: ${t.participantIds.join(", ")}`,`## ${s}:`],a=Math.min(t.participantIds.length,t.individualPaths.length);for(let c=0;c<a;c+=1)i.push(` - ${t.participantIds[c]}: ${t.individualPaths[c]}`);return i}function Tx(t,e){let r=[`## ${e.t("report.section.mainTable")}`,"",`| ${e.t("report.table.proposer")} | ${e.t("report.table.opinion")} | ${e.t("report.table.severity")} | ${e.t("report.table.agreement")} |`,"|---|---|---|---|"];for(let n of t.proposals){let o=n.proposerIds.join(", "),s=jM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function jM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function Ex(t,e){if(t.dissentDetails.length===0)return[];let r=[`## ${e.t("report.section.dissentDetail")}`];for(let n of t.dissentDetails){r.push(""),r.push(`### ${n.proposalTitle} (${n.severity})`);for(let o of n.perParticipant)r.push(Lp(o))}return r}function Lp(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function Rx(t,e){let r=`| ${e.t("report.contribution.ai")} | ${e.t("report.contribution.proposed")} | ${e.t("report.contribution.accepted")} | ${e.t("report.contribution.revises")} | ${e.t("report.contribution.abstains")} |`,n=[`## ${e.t("report.section.contributionSummary")}`,"",r,"|---|---|---|---|---|"];for(let o of t.contributionSummary){let s=o.proposed===0?"\u2014":String(o.consensusReceived);n.push(`| ${o.participantId} | ${o.proposed} | ${s} | ${o.revisesProposed} | ${o.abstains} |`)}return n}function LM(t,e){let r=e.t("report.footer.synthesisPath"),n=e.t("report.footer.debatePath"),o=t.synthesisPath??e.t("report.footer.pendingSynthesis"),s=[`## ${r}: ${o}`,`## ${n}: ${t.debatePath}`];return t.status==="ready-for-approval"&&(s.push(""),s.push(e.t("approval.pending"))),s}function FM(t,e){let r=t.acceptedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.acceptedItems")}`];for(let o of r)n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.proposer")}:** ${o.proposerIds.join(", ")}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`),o.finalStatement.length>0&&(n.push(""),n.push(o.finalStatement));return n}function ZM(t,e){let r=t.rejectedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.rejectedItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),o.rejectionReason.length>0&&(n.push(""),n.push(o.rejectionReason));for(let s of o.dissentVotes)n.push(Lp(s))}return n}function UM(t,e){let r=t.openItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.openItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`);for(let s of o.perParticipant)n.push(Lp(s))}return n}var mo=class{deps;sessions=new Map;formatter=Px();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??qM)(),n=this.nowIso(),o=ax({topic:e.topic,...e.goal!==void 0?{goal:e.goal}:{},participants:e.participants,excludeParticipants:e.excludeParticipants??[],autoInjectSpecialists:e.autoInjectSpecialists??!0}),s=o.participants,i={topic:e.topic,scope:e.scope??e.topic,participants:s,excludeParticipants:e.excludeParticipants??[],leader:e.leader,maxRounds:e.maxRounds??Nc,locale:e.locale??this.deps.i18n.locale,autoInjectSpecialists:e.autoInjectSpecialists??!0},a=await this.deps.documentManager.createDebateDocument({topic:e.topic,providers:s.slice(),...e.goal!==void 0?{goal:e.goal}:{}}),c={sessionId:r,config:i,goal:e.goal,individualReviewPrompt:e.individualReviewPrompt,files:e.files??[],debateDocId:a.id,debateDocPath:a.path,individualPaths:{},createdAt:n,ledger:new po,rounds:0,maxRounds:i.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1};this.sessions.set(r,c);try{let u=await this.runIndividualPhase(c,o),{ledger:l}=yx(u);c.ledger=l,c.nextProposalIndex=GM(u),l.aliasCandidates.length>0&&await this.runAliasClarificationPhase(c),await this.runRoundLoop(c);let d=this.buildSnapshot(c,Ix(c));return await this.deps.registry.persist(d),this.emitTrace(c,"debate_rfa",{status:d.status}),{sessionId:r,status:d.status,snapshot:d,terminalReport:this.renderTerminal(c,d)}}catch(u){let l=this.buildSnapshot(c,"error",wc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:wc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:wc(u)}}}async approve(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="approved"){if(!r.documentPaths.synthesis)throw new Error(`approve: session "${e.sessionId}" is marked approved but has no synthesis path recorded. Snapshot is inconsistent.`);let u=this.sessions.get(e.sessionId);return{snapshot:r,synthesisPath:r.documentPaths.synthesis,terminalReport:this.renderTerminal(u??null,r),idempotentReplay:!0}}Fp(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),o=n?this.buildReportData(n,r,e.leaderNote):Cx(r,e.leaderNote),s=this.formatter.renderSynthesis(o,this.deps.i18n),i=(r.status==="escalated"||r.status==="ready-for-approval")&&r.status==="escalated"?"escalated":"consensus",a=await this.deps.documentManager.createSynthesis({sessionId:r.sessionId,topic:r.config.topic,status:i,rounds:r.rounds,maxRounds:r.config.maxRounds,participantIds:r.config.participants,individualPaths:Object.values(r.documentPaths.individual),debatePath:r.documentPaths.debate,body:s,...e.leaderNote!==void 0?{metadata:{"Leader Note":e.leaderNote}}:{}});await this.deps.documentManager.addComment(n?.debateDocId??xc(r),{author:"moderator",content:this.formatApprovalFooter(e.leaderNote)});let c={...r,status:"approved",documentPaths:{...r.documentPaths,synthesis:a.path}};return await this.deps.registry.persist(c),this.emitTrace(n??null,"debate_approved",{sessionId:r.sessionId,synthesisPath:a.path}),{snapshot:c,synthesisPath:a.path,terminalReport:this.renderTerminal(n??null,c)}}async continueDebate(e){if(!Number.isInteger(e.additionalRounds)||e.additionalRounds<=0)throw new Error(`continueDebate: additionalRounds must be a positive integer (got ${e.additionalRounds})`);let r=await this.loadSnapshotOrThrow(e.sessionId);Fp(r,["ready-for-approval","escalated"],"continue");let n=this.sessions.get(e.sessionId);if(!n){if(!r.ledgerState)throw new Error(`continueDebate: snapshot for session "${e.sessionId}" is too old to resume after restart \u2014 missing ledgerState. Use approve or reject instead, or rerun the debate.`);n=this.rehydrateSessionContext(r),this.sessions.set(e.sessionId,n)}n.maxRounds=r.config.maxRounds+e.additionalRounds;for(let i of n.ledger.proposals.values())i.status;await this.runRoundLoop(n);let o=Ix(n),s=this.buildSnapshot(n,o);return await this.deps.registry.persist(s),this.emitTrace(n,"debate_continued",{additionalRounds:e.additionalRounds,status:s.status}),{snapshot:s,terminalReport:this.renderTerminal(n,s)}}async reject(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="rejected")return{snapshot:r,idempotentReplay:!0,...r.documentPaths.issue!==void 0?{issuePath:r.documentPaths.issue}:{}};Fp(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??xc(r);await this.deps.documentManager.addComment(o,{author:"moderator",content:this.formatRejectionFooter(e.reason)});let s;e.spawnIssue===!0&&(s=(await this.deps.documentManager.createIssueDocument({sessionId:r.sessionId,topic:r.config.topic,...e.reason!==void 0?{reason:e.reason}:{},items:JM(r)})).path);let i={...r,status:"rejected",terminalNote:e.reason??r.terminalNote,documentPaths:{...r.documentPaths,...s!==void 0?{issue:s}:{}}};return await this.deps.registry.persist(i),this.emitTrace(n??null,"debate_rejected",{sessionId:r.sessionId,...s!==void 0?{issuePath:s}:{}}),{snapshot:i,...s!==void 0?{issuePath:s}:{}}}async handleTimedOutSnapshots(e){for(let r of e){if(r.status!=="leader-timeout")continue;let n=xc(r);try{await this.deps.documentManager.addComment(n,{author:"moderator",content:this.formatLeaderTimeoutFooter(r)})}catch{}this.emitTrace(this.sessions.get(r.sessionId)??null,"debate_leader_timeout",{sessionId:r.sessionId})}}async runIndividualPhase(e,r){let n=nN(),o=oN(e),s=await Promise.allSettled(e.config.participants.map(async a=>{let c=await this.deps.bridge.requestTurn(a,{prompt:o,system:e.individualReviewPrompt??n,round:0,...e.files.length>0?{files:e.files}:{}});return{participantId:a,resp:c}})),i=[];for(let a of s){if(a.status==="rejected")continue;let{participantId:c,resp:u}=a.value,l=u.failed?`(no response: ${u.failureReason??"unknown"})`:u.text,d=await this.deps.documentManager.createIndividualReview({participantId:c,topic:e.config.topic,content:l,...e.files.length>0?{files:e.files}:{}});if(e.individualPaths[c]=d.path,u.failed)continue;let p=rN(u.text);for(let f of p){let m=Ax(e,f.id);i.push({id:m,proposerId:c,title:f.title,severity:f.severity,...f.location!==void 0?{location:f.location}:{},...f.description!==void 0?{description:f.description}:{},roundOpened:1})}}return i}async runAliasClarificationPhase(e){let r=await $x({ledger:e.ledger,participantIds:e.config.participants,askParticipant:async(o,s)=>{let i=await this.deps.bridge.requestTurn(o,{prompt:s,round:0,...e.files.length>0?{files:e.files}:{}});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=uN(r,this.deps.i18n);n.length>0&&await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:n})}async runRoundLoop(e){for(;e.rounds<e.maxRounds;){if(e.ledger.getOpenProposals().map(p=>p.id).length===0)return;e.rounds+=1;let n=e.rounds,o=e.config.participants.filter(p=>!e.unavailableParticipants.has(p)),s=e.ledger.getOpenProposals(),i=e.pendingVoteWarnings,a=new Map,c=await Promise.allSettled(o.map(async p=>{let f={prompt:sN({round:n,maxRounds:e.maxRounds,topic:e.config.topic,scope:e.config.scope,openProposals:s,previousVoteIssues:i.get(p)}),round:n,...e.files.length>0?{files:e.files}:{}},m=await this.deps.bridge.requestTurn(p,f);return{participantId:p,request:f,resp:m}})),u=[],l=new Set;for(let p=0;p<c.length;p+=1){let f=c[p],m=o[p];if(f.status==="rejected"||f.value.resp.failed){this.registerFailure(e,m);let v=f.status==="rejected"?wc(f.reason):f.value.resp.failureReason??"unknown";u.push({participantId:m,text:`(no response: ${v})`,failed:!0});continue}l.add(m);let g=await this.parseVotesWithRetry(m,f.value.request,f.value.resp.text,s,n);if(u.push({participantId:m,text:g.displayText,failed:!g.ok}),!g.ok){this.registerFailure(e,m),a.set(m,g.warnings);continue}this.clearFailure(e,m);for(let v of g.parsed.entries)e.ledger.recordVote(v.proposalId,m,{vote:v.vote,roundRecorded:n,...v.reason!==void 0?{reason:v.reason}:{}});g.parsed.entryErrors.length>0&&a.set(m,aN(g.parsed.entryErrors))}e.pendingVoteWarnings=a;let d=e.ledger.aggregateRound(n,e.config.participants,Array.from(e.unavailableParticipants));for(let p of d){let f=e.ledger.proposals.get(p.proposalId);if(!f)continue;let m=e.config.participants.filter(g=>!f.proposerIds.includes(g)).length;if(BM(p.tally,m)){e.ledger.setStatus(p.proposalId,"consensus"),e.allAbstainCount.delete(p.proposalId);continue}if(WM(p.tally,m)){e.ledger.setStatus(p.proposalId,"rejected"),e.allAbstainCount.delete(p.proposalId);continue}if(HM(p.tally)){let g=(e.allAbstainCount.get(p.proposalId)??0)+1;e.allAbstainCount.set(p.proposalId,g),g>=Lc&&(e.ledger.setStatus(p.proposalId,"unresolved"),e.allAbstainCount.delete(p.proposalId));continue}e.allAbstainCount.delete(p.proposalId)}for(let p of d){if(p.tally.revise===0)continue;let f=e.ledger.proposals.get(p.proposalId);if(!f||f.status!=="open"||e.ledger.countRevisesThisRound(p.proposalId,n)===0)continue;let g=this.synthesizeReviseSuccessor(e,f,n);e.reviseSuccessors.set(f.id,g)}if(await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:cN({round:n,maxRounds:e.maxRounds,openProposals:s,turns:u,aggregation:d,ledger:e.ledger})}),l.size===0)return}}async parseVotesWithRetry(e,r,n,o,s){let i=o.map(p=>p.id),a=zp(n,i);if(a.ok)return{ok:!0,parsed:a,displayText:n};let c={prompt:iN({openProposals:o,errorKind:a.error.kind,errorDetails:a.error.details}),round:s,...r.files!==void 0?{files:r.files}:{}},u=await this.deps.bridge.requestTurn(e,c);if(u.failed)return{ok:!1,displayText:`${n}
307
+ `,r+4);return n<0?"":t.slice(n+1)}function YO(t,e){return GO.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:Dp[t]}:{transport:"cli-bridge",providerId:Cp,agentName:Dp[t]}:t===Ap?e==="claude-code"?{transport:"read-only-chat",providerId:Ap}:{transport:"cli-bridge",providerId:Cp}:{transport:"read-only-chat",providerId:t}}function lx(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var dx=18e4;function Ip(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${dx/1e3}s)`)),dx))])}function px(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=Dp[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=fx(r,`${s}.md`);try{let a=JO(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var zp=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??fx(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>KO(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 Ip(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??Cp,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=px(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await Ip(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:lx(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?px(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await Ip(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:lx(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=YO(e,this.hostKind);return r.transport==="task-subagent"&&!this.subagentSpawner&&this.hostKind==="claude-code"?{transport:"read-only-chat",providerId:Ap,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 mx(t){return new zp(t)}function hx(t,e){return e(t)}var XO=/[.,!?;:]/g,QO=/\s+/g;function gx(t){return t.toLowerCase().replace(XO," ").replace(QO," ").trim()}function yx(t){return typeof t.location=="string"&&t.location.length>0}function vx(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 eM(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 tM(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=gx(t.title)===gx(e.title),s=t.severity===e.severity,a=yx(t)&&yx(e)&&t.location===e.location,c=[];if(o&&c.push("title"),s&&c.push("severity"),a&&c.push("location"),c.length===0)return{kind:"unrelated"};if(o&&s&&a)return{kind:"hard-merge"};let l;return o?s?l="location":l="severity":l="title",{kind:"alias",pair:{proposalA:t.id,proposalB:e.id,matchedFields:c,missingField:l}}}var po=class t{_proposals=new Map;_aliasCandidates=[];get proposals(){return this._proposals}get aliasCandidates(){return this._aliasCandidates.slice()}addProposal(e){if(this._proposals.has(e.id))throw new Error(`ProposalLedger.addProposal: duplicate id "${e.id}"`);let r={id:e.id,proposerIds:e.proposerIds.slice(),title:e.title,severity:e.severity,roundOpened:e.roundOpened,status:e.status??"open",votes:new Map};e.location!==void 0&&(r.location=e.location),e.description!==void 0&&(r.description=e.description),this._proposals.set(r.id,r)}recordVote(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.recordVote: unknown proposal id "${e}"`);o.votes.set(r,{...n}),o.proposerIds.includes(r)&&n.vote==="revise"&&o.status==="open"&&(o.status="withdrawn-by-author")}countRevisesThisRound(e,r){let n=this._proposals.get(e);if(!n)return 0;let o=0;for(let[s,i]of n.votes)i.vote==="revise"&&i.roundRecorded===r&&(n.proposerIds.includes(s)||(o+=1));return o}markSuperseded(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.markSuperseded: unknown old id "${e}"`);if(!this._proposals.has(r))throw new Error(`ProposalLedger.markSuperseded: successor id "${r}" not registered`);o.status="superseded",o.supersededBy=r;for(let s of o.votes.values())s.supersededAt===void 0&&(s.supersededAt=n)}applyAliasMerge(e,r){if(e===r)throw new Error(`ProposalLedger.applyAliasMerge: cannot merge id "${e}" into itself`);let n=this._proposals.get(e),o=this._proposals.get(r);if(!n)throw new Error(`ProposalLedger.applyAliasMerge: unknown primary id "${e}"`);if(!o)throw new Error(`ProposalLedger.applyAliasMerge: unknown alias id "${r}"`);n.proposerIds=vx(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=rM(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(eM(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=vx(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 rM(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function _x(t){let e=new po,r=new Set;for(let s of t){if(r.has(s.id))throw new Error(`buildInitialLedger: duplicate proposal id "${s.id}"`);r.add(s.id),e.addProposal({id:s.id,proposerIds:[s.proposerId],title:s.title,severity:s.severity,...s.location!==void 0?{location:s.location}:{},...s.description!==void 0?{description:s.description}:{},roundOpened:s.roundOpened??1,status:"open"})}let n=new Set,o=t.map(s=>s.id);for(let s=0;s<o.length;s+=1){let i=o[s];if(n.has(i))continue;let a=e._rawProposal(i);if(a)for(let c=s+1;c<o.length;c+=1){let u=o[c];if(n.has(u))continue;let l=e._rawProposal(u);if(!l)continue;let d=tM(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 nM=new Set(kf);function oM(t){return nM.has(t)}var sM=new Set(["disagree","revise"]);function iM(t){let e=`<${gn}>`,r=`</${gn}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function aM(t){let e=`<${gn}>`;return t.includes(e)}var cM=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function uM(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 cM[r]??e})}function lM(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]=uM(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function Op(t,e){let r=iM(t);if(!r)return aM(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${gn}> without matching </${gn}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!bx(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(!bx(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=lM(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(!oM(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(sM.has(g)&&v===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};v!==void 0&&(S.reason=v),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}function bx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var dM=Object.freeze(["same","different","unsure"]),Us="alias-votes",pM=new Set(dM);function fM(t){return pM.has(t)}function mM(t){let e=`<${Us}>`,r=`</${Us}>`,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 hM(t){let e=`<${Us}>`;return t.includes(e)}var gM=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function yM(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 gM[r]??e})}function vM(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]=yM(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function wx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Mp(t,e){let r=mM(t);if(!r)return hM(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${Us}> without matching </${Us}>`}}:{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(!wx(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(!wx(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=vM(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(!fM(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 S={pair:m,vote:g};v!==void 0&&(S.reason=v),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}var _M="__";function bM(t){return`${t.proposalA}${_M}${t.proposalB}`}var wM=["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(" "),xM=["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(" "),SM=["Response format \u2014 append the following block at the end of your reply","(moderator parses only this block; preamble is ignored):","","<alias-votes>",' <item pair="P1__P2" vote="same"/>',' <item pair="P3__P4" vote="different" reason="P3 concerns cache invalidation; P4 concerns read-through."/>',' <item pair="P5__P6" vote="unsure" reason="Insufficient detail on location."/>',"</alias-votes>"].join(`
308
+ `),$M="Candidate pairs:";function kM(t,e){return["Your previous response did not include a valid `<alias-votes>` block.",`Problem: ${e}`,"Reply with ONLY the `<alias-votes>` block. Do not include prose.","<alias-votes>",...t.map(r=>` <item pair="${r}" vote="same|different|unsure" reason="optional"/>`),"</alias-votes>"].join(`
309
+ `)}async function Px(t){let{ledger:e,participantIds:r,askParticipant:n}=t,o=e.aliasCandidates;if(o.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let s=o.map(bM),i=new Map;for(let f=0;f<o.length;f+=1)i.set(s[f],o[f]);let a=PM(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:kx(m.reason)}),bc(l,s);continue}let{response:y}=m.value;if(y.failed===!0){u.push({participantId:g,reason:"askParticipant reported failed=true"}),bc(l,s);continue}let v=Mp(y.text,s),S=new Set;if(!v.ok){let w=await n(g,kM(s,v.error.details!==void 0?`${v.error.kind}: ${v.error.details}`:v.error.kind)).catch(P=>({text:"",failed:!0,reason:kx(P)}));if(w.failed===!0){u.push({participantId:g,reason:"reason"in w&&typeof w.reason=="string"?w.reason:"retry failed"}),bc(l,s);continue}let _=Mp(w.text,s);if(!_.ok){u.push({participantId:g,reason:_.error.details!==void 0?`${_.error.kind}: ${_.error.details}`:_.error.kind}),bc(l,s);continue}for(let P of _.entries)$x(l,P),S.add(P.pair);for(let P of s)if(!S.has(P)){let A=l.get(P);A!==void 0&&(A.missing+=1)}continue}for(let w of v.entries)$x(l,w),S.add(w.pair);for(let w of s)if(!S.has(w)){let _=l.get(w);_!==void 0&&(_.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=EM(g);if(y.kind==="merge"){let v=m.proposalA,S=m.proposalB;if(e.proposals.get(v)===void 0||e.proposals.get(S)===void 0)continue;e.applyAliasMerge(v,S),d.push({primary:v,alias:S,voteBreakdown:{...g}});continue}p.push({pair:m,voteBreakdown:{...g},reason:y.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function PM(t,e,r){let n=[];n.push(wM),n.push(""),n.push(xM),n.push(""),n.push($M),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:"),xx(n,a),n.push(" Proposal B:"),xx(n,c),n.push("")}return n.push(SM),n.join(`
310
+ `)}function xx(t,e){if(e===void 0){t.push(" (proposal unavailable \u2014 already removed from ledger)");return}if(t.push(` id: ${e.id}`),t.push(` title: ${e.title}`),t.push(` severity: ${e.severity}`),t.push(` location: ${e.location!==void 0&&e.location.length>0?e.location:"(empty)"}`),e.description!==void 0&&e.description.length>0){let r=TM(e.description);t.push(` description: ${r}`)}}var Sx=400;function TM(t){return t.length<=Sx?t:`${t.slice(0,Sx)}\u2026`}function $x(t,e){let r=t.get(e.pair);if(r!==void 0)switch(e.vote){case"same":r.same+=1;break;case"different":r.different+=1;break;case"unsure":r.unsure+=1;break;default:{let n=e.vote}}}function bc(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function EM(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 kx(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as RM}from"fs/promises";import{readFileSync as IM,existsSync as Np,unlinkSync as AM,mkdirSync as CM}from"fs";import{join as qs}from"path";var Lp=".approval.json";function jp(t){return`${t}${Lp}`}function DM(t){return t.endsWith(Lp)?t.slice(0,t.length-Lp.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+Pf).toISOString()}var fo=class{debatesDir;cache=new Map;hydrated=!1;constructor(e){if(!e||typeof e!="string")throw new Error("StructuredSessionRegistry: baseDir is required");this.debatesDir=qs(e,Hs)}getDebatesDir(){return this.debatesDir}async persist(e){if(!e||!e.sessionId)throw new Error("StructuredSessionRegistry.persist: snapshot.sessionId is required");if(e.schemaVersion!==1)throw new Error(`StructuredSessionRegistry.persist: unsupported schemaVersion=${e.schemaVersion}`);CM(this.debatesDir,{recursive:!0});let r=qs(this.debatesDir,jp(e.sessionId));je(r,e),this.cache.set(e.sessionId,e)}async load(e){let r=this.cache.get(e);if(r)return r;let n=qs(this.debatesDir,jp(e));if(!Np(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=qs(this.debatesDir,jp(e));if(Np(r))try{AM(r)}catch(n){if(n.code!=="ENOENT")throw n}}async hydrateFromDisk(){if(this.cache.clear(),!Np(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await RM(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=DM(r);if(!n)continue;let o=this.readSnapshotFile(qs(this.debatesDir,r));o&&o.sessionId===n&&this.cache.set(n,o)}this.hydrated=!0}get(e){return this.cache.get(e)}getAll(){return Array.from(this.cache.values())}async sweepTimeouts(e=new Date){let r=e.getTime(),n=[],o=[];for(let s of this.cache.values()){if(s.status!=="ready-for-approval")continue;let i=Date.parse(s.deadline);if(Number.isNaN(i)||r<=i)continue;let a={...s,status:"leader-timeout",terminalNote:s.terminalNote??"leader-timeout after approval window"};try{await this.persist(a),n.push(a)}catch(c){o.push({sessionId:s.sessionId,error:c})}}return o.length>0&&console.warn(`[session-registry] sweepTimeouts: ${o.length} snapshot(s) failed to transition; will retry on next sweep`,o.map(s=>({sessionId:s.sessionId,message:s.error instanceof Error?s.error.message:String(s.error)}))),n}isHydrated(){return this.hydrated}readSnapshotFile(e){let r;try{r=IM(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 zM(n)?n:(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function zM(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 OM(t,e){let r=[];r.push(...jM(t,e)),r.push(""),r.push(...Rx(t,e));let n=Ix(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...Ax(t,e)),r.push(""),r.push(...FM(t,e)),r.join(`
311
+ `)}function MM(t,e){let r=[];r.push(...Rx(t,e));let n=ZM(t,e);n.length>0&&(r.push(""),r.push(...n));let o=UM(t,e);o.length>0&&(r.push(""),r.push(...o));let s=qM(t,e);s.length>0&&(r.push(""),r.push(...s));let i=Ix(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...Ax(t,e)),r.join(`
312
+ `)}function Ex(){return{renderTerminal:OM,renderSynthesis:MM}}var NM=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 jM(t,e){let r=e.t(NM[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 Rx(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=LM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function LM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function Ix(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(Fp(o))}return r}function Fp(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function Ax(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 FM(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 ZM(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 UM(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(Fp(s))}return n}function qM(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(Fp(s))}return n}var mo=class{deps;sessions=new Map;formatter=Ex();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??VM)(),n=this.nowIso(),o=ux({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??jc,locale:e.locale??this.deps.i18n.locale,autoInjectSpecialists:e.autoInjectSpecialists??!0},a=await this.deps.documentManager.createDebateDocument({topic:e.topic,providers:s.slice(),...e.goal!==void 0?{goal:e.goal}:{}}),c={sessionId:r,config:i,goal:e.goal,individualReviewPrompt:e.individualReviewPrompt,files:e.files??[],debateDocId:a.id,debateDocPath:a.path,individualPaths:{},createdAt:n,ledger:new po,rounds:0,maxRounds:i.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1};this.sessions.set(r,c);try{let u=await this.runIndividualPhase(c,o),{ledger:l}=_x(u);c.ledger=l,c.nextProposalIndex=YM(u),l.aliasCandidates.length>0&&await this.runAliasClarificationPhase(c),await this.runRoundLoop(c);let d=this.buildSnapshot(c,Cx(c));return await this.deps.registry.persist(d),this.emitTrace(c,"debate_rfa",{status:d.status}),{sessionId:r,status:d.status,snapshot:d,terminalReport:this.renderTerminal(c,d)}}catch(u){let l=this.buildSnapshot(c,"error",wc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:wc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:wc(u)}}}async approve(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="approved"){if(!r.documentPaths.synthesis)throw new Error(`approve: session "${e.sessionId}" is marked approved but has no synthesis path recorded. Snapshot is inconsistent.`);let u=this.sessions.get(e.sessionId);return{snapshot:r,synthesisPath:r.documentPaths.synthesis,terminalReport:this.renderTerminal(u??null,r),idempotentReplay:!0}}Zp(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),o=n?this.buildReportData(n,r,e.leaderNote):zx(r,e.leaderNote),s=this.formatter.renderSynthesis(o,this.deps.i18n),i=(r.status==="escalated"||r.status==="ready-for-approval")&&r.status==="escalated"?"escalated":"consensus",a=await this.deps.documentManager.createSynthesis({sessionId:r.sessionId,topic:r.config.topic,status:i,rounds:r.rounds,maxRounds:r.config.maxRounds,participantIds:r.config.participants,individualPaths:Object.values(r.documentPaths.individual),debatePath:r.documentPaths.debate,body:s,...e.leaderNote!==void 0?{metadata:{"Leader Note":e.leaderNote}}:{}});await this.deps.documentManager.addComment(n?.debateDocId??xc(r),{author:"moderator",content:this.formatApprovalFooter(e.leaderNote)});let c={...r,status:"approved",documentPaths:{...r.documentPaths,synthesis:a.path}};return await this.deps.registry.persist(c),this.emitTrace(n??null,"debate_approved",{sessionId:r.sessionId,synthesisPath:a.path}),{snapshot:c,synthesisPath:a.path,terminalReport:this.renderTerminal(n??null,c)}}async continueDebate(e){if(!Number.isInteger(e.additionalRounds)||e.additionalRounds<=0)throw new Error(`continueDebate: additionalRounds must be a positive integer (got ${e.additionalRounds})`);let r=await this.loadSnapshotOrThrow(e.sessionId);Zp(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=Cx(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}:{}};Zp(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??xc(r);await this.deps.documentManager.addComment(o,{author:"moderator",content:this.formatRejectionFooter(e.reason)});let s;e.spawnIssue===!0&&(s=(await this.deps.documentManager.createIssueDocument({sessionId:r.sessionId,topic:r.config.topic,...e.reason!==void 0?{reason:e.reason}:{},items:JM(r)})).path);let i={...r,status:"rejected",terminalNote:e.reason??r.terminalNote,documentPaths:{...r.documentPaths,...s!==void 0?{issue:s}:{}}};return await this.deps.registry.persist(i),this.emitTrace(n??null,"debate_rejected",{sessionId:r.sessionId,...s!==void 0?{issuePath:s}:{}}),{snapshot:i,...s!==void 0?{issuePath:s}:{}}}async handleTimedOutSnapshots(e){for(let r of e){if(r.status!=="leader-timeout")continue;let n=xc(r);try{await this.deps.documentManager.addComment(n,{author:"moderator",content:this.formatLeaderTimeoutFooter(r)})}catch{}this.emitTrace(this.sessions.get(r.sessionId)??null,"debate_leader_timeout",{sessionId:r.sessionId})}}async runIndividualPhase(e,r){let n=oN(),o=sN(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=nN(u.text);for(let f of p){let m=Dx(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 Px({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=lN(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:iN({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"?wc(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,cN(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(WM(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(KM(p.tally)){let g=(e.allAbstainCount.get(p.proposalId)??0)+1;e.allAbstainCount.set(p.proposalId,g),g>=Fc&&(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:uN({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=Op(n,i);if(a.ok)return{ok:!0,parsed:a,displayText:n};let c={prompt:aN({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}
313
313
 
314
- [retry failed: ${u.failureReason??"unknown"}]`,warnings:[`Missing or malformed <votes> block (${a.error.kind}). Retry failed: ${u.failureReason??"unknown"}.`]};let l=zp(u.text,i),d=`${n}
314
+ [retry failed: ${u.failureReason??"unknown"}]`,warnings:[`Missing or malformed <votes> block (${a.error.kind}). Retry failed: ${u.failureReason??"unknown"}.`]};let l=Op(u.text,i),d=`${n}
315
315
 
316
316
  [retry response]
317
- ${u.text}`;return l.ok?{ok:!0,parsed:l,displayText:d}:{ok:!1,displayText:d,warnings:[`Missing or malformed <votes> block (${l.error.kind}).${l.error.details?` ${l.error.details}`:""}`]}}registerFailure(e,r){let n=(e.consecutiveFailures.get(r)??0)+1;e.consecutiveFailures.set(r,n),n>=jc&&e.unavailableParticipants.add(r)}clearFailure(e,r){e.consecutiveFailures.delete(r)}synthesizeReviseSuccessor(e,r,n){let o=Ax(e),s=[];for(let[,a]of r.votes)a.vote==="revise"&&a.roundRecorded===n&&a.reason&&s.push(a.reason);let i=s.length>0?`Revised from ${r.id}: ${s.join(" / ")}`:`Revised from ${r.id}`;return e.ledger.addProposal({id:o,proposerIds:r.proposerIds,title:`${r.title} (revised)`,severity:r.severity,...r.location!==void 0?{location:r.location}:{},description:i,roundOpened:n+1}),e.ledger.markSuperseded(r.id,o,n),o}rehydrateSessionContext(e){if(!e.ledgerState)throw new Error(`rehydrateSessionContext: snapshot "${e.sessionId}" has no ledgerState`);let r=po.fromJSON(e.ledgerState),n=new Map;if(e.consecutiveFailuresByParticipant)for(let[a,c]of Object.entries(e.consecutiveFailuresByParticipant))c>0&&n.set(a,c);let o=new Set(e.unavailableParticipants??[]),s=0;for(let a of e.ledgerState.proposals.map(c=>c.id)){let c=a.match(/^P(\d+)$/);if(c){let u=Number.parseInt(c[1],10);Number.isFinite(u)&&u>s&&(s=u)}}return{sessionId:e.sessionId,config:e.config,goal:void 0,individualReviewPrompt:void 0,files:[],debateDocId:xc(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:r,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:n,unavailableParticipants:o,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:s+1}}buildSnapshot(e,r,n){let o=this.nowIso(),s=VM(r)?fx(o,kx):o,i=this.snapshotAggregatedVotes(e),a={};for(let[u,l]of e.consecutiveFailures)l>0&&(a[u]=l);return{schemaVersion:1,sessionId:e.sessionId,status:r,createdAt:e.createdAt,readyAt:o,deadline:s,config:{...e.config,maxRounds:e.maxRounds},rounds:e.rounds,aggregatedVotes:i,documentPaths:{individual:{...e.individualPaths},debate:e.debateDocPath},ledgerState:e.ledger.toJSON(),...Object.keys(a).length>0?{consecutiveFailuresByParticipant:a}:{},...e.unavailableParticipants.size>0?{unavailableParticipants:Array.from(e.unavailableParticipants)}:{},...n!==void 0?{terminalNote:n}:{}}}snapshotAggregatedVotes(e){let r=[];for(let n of e.ledger.proposals.values()){if(n.status==="merged")continue;let o={};for(let[s,i]of n.votes)o[s]={vote:i.vote,roundRecorded:i.roundRecorded,...i.reason!==void 0?{reason:i.reason}:{}};r.push({proposalId:n.id,title:n.title,severity:n.severity,...n.location!==void 0?{location:n.location}:{},proposers:n.proposerIds,status:KM(n.status),votes:o,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){let n=e?this.buildReportData(e,r):Cx(r);return this.formatter.renderTerminal(n,this.deps.i18n)}buildReportData(e,r,n){let o=[],s=[],i=[],a=[],c=[];for(let l of e.ledger.proposals.values()){if(l.status==="merged"||l.status==="superseded")continue;let d=e.config.participants.filter(f=>!l.proposerIds.includes(f)),p=YM(l,d);o.push({proposerIds:l.proposerIds,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,accepted:l.status==="consensus",...p.dissentSummary!==void 0?{dissentSummary:p.dissentSummary}:{}}),p.perParticipant.length>0&&l.status!=="consensus"&&s.push({proposalTitle:l.title,severity:l.severity,perParticipant:p.perParticipant}),l.status==="consensus"?i.push({id:l.id,proposerIds:l.proposerIds,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,finalStatement:l.description??""}):l.status==="rejected"||l.status==="withdrawn-by-author"?a.push({id:l.id,title:l.title,severity:l.severity,rejectionReason:l.status==="withdrawn-by-author"?"Withdrawn by author":"Rejected by tally",dissentVotes:p.perParticipant}):(l.status==="open"||l.status==="unresolved")&&c.push({id:l.id,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,perParticipant:p.perParticipant})}let u=XM(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:Dx(r.status),participantIds:e.config.participants,individualPaths:Object.values(e.individualPaths),debatePath:e.debateDocPath,...r.documentPaths.synthesis!==void 0?{synthesisPath:r.documentPaths.synthesis}:{},proposals:o,contributionSummary:u,dissentDetails:s,acceptedItems:i,rejectedItems:a,openItems:c,...n!==void 0?{leaderNote:n}:{}}}nowIso(){return(this.deps.now?this.deps.now():new Date).toISOString()}async loadSnapshotOrThrow(e){let r=await this.deps.registry.load(e);if(!r)throw new Error(`Structured debate session "${e}" not found`);return r}formatApprovalFooter(e){let r=this.deps.i18n.t("moderator.narration.approved");if(!e)return r;let n=this.deps.i18n.t("synthesis.narration.leaderNote");return`${r}
317
+ ${u.text}`;return l.ok?{ok:!0,parsed:l,displayText:d}:{ok:!1,displayText:d,warnings:[`Missing or malformed <votes> block (${l.error.kind}).${l.error.details?` ${l.error.details}`:""}`]}}registerFailure(e,r){let n=(e.consecutiveFailures.get(r)??0)+1;e.consecutiveFailures.set(r,n),n>=Lc&&e.unavailableParticipants.add(r)}clearFailure(e,r){e.consecutiveFailures.delete(r)}synthesizeReviseSuccessor(e,r,n){let o=Dx(e),s=[];for(let[,a]of r.votes)a.vote==="revise"&&a.roundRecorded===n&&a.reason&&s.push(a.reason);let i=s.length>0?`Revised from ${r.id}: ${s.join(" / ")}`:`Revised from ${r.id}`;return e.ledger.addProposal({id:o,proposerIds:r.proposerIds,title:`${r.title} (revised)`,severity:r.severity,...r.location!==void 0?{location:r.location}:{},description:i,roundOpened:n+1}),e.ledger.markSuperseded(r.id,o,n),o}rehydrateSessionContext(e){if(!e.ledgerState)throw new Error(`rehydrateSessionContext: snapshot "${e.sessionId}" has no ledgerState`);let r=po.fromJSON(e.ledgerState),n=new Map;if(e.consecutiveFailuresByParticipant)for(let[a,c]of Object.entries(e.consecutiveFailuresByParticipant))c>0&&n.set(a,c);let o=new Set(e.unavailableParticipants??[]),s=0;for(let a of e.ledgerState.proposals.map(c=>c.id)){let c=a.match(/^P(\d+)$/);if(c){let u=Number.parseInt(c[1],10);Number.isFinite(u)&&u>s&&(s=u)}}return{sessionId:e.sessionId,config:e.config,goal:void 0,individualReviewPrompt:void 0,files:[],debateDocId:xc(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:r,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:n,unavailableParticipants:o,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:s+1}}buildSnapshot(e,r,n){let o=this.nowIso(),s=BM(r)?hx(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,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:GM(n.status),votes:o,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){let n=e?this.buildReportData(e,r):zx(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=XM(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=QM(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:Ox(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}
318
318
 
319
319
  **${n}:** ${e}`}formatRejectionFooter(e){let r=this.deps.i18n.t("moderator.narration.rejected");return e?`${r}
320
320
 
321
321
  Reason: ${e}`:r}formatLeaderTimeoutFooter(e){let r=this.deps.i18n.t("moderator.narration.leaderTimeoutFooter"),n=Date.parse(e.readyAt),o=Date.parse(e.deadline),s=Number.isFinite(n)&&Number.isFinite(o)&&o>n?Math.round((o-n)/(3600*1e3)):24,i=this.deps.i18n.t("approval.timeout",{hours:s});return`## ${r}
322
322
 
323
- ${i}`}emitTrace(e,r,n){if(this.deps.traceWriter)try{this.deps.traceWriter.write({traceId:e?.sessionId??"unknown",action:r,providerId:"moderator-engine",task:e?.config.topic??"",request:{promptSummary:JSON.stringify(n),fileCount:0},response:{success:!0,charLength:0},latencyMs:0})}catch{}}};function qM(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function Ix(t){for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function VM(t){return t==="ready-for-approval"||t==="escalated"}function BM(t,e){return e===0?t.agree===0&&!1:t.disagree>0||t.revise>0||t.missing>0||t.agree<1?!1:t.agree+t.abstain===e}function WM(t,e){if(e===0||t.agree>0||t.revise>0)return!1;let r=Math.ceil(e/2);return t.disagree>=r}function HM(t){return t.abstain>0&&t.agree===0&&t.disagree===0&&t.revise===0&&t.missing===0}function Fp(t,e,r){if(!e.includes(t.status))throw new Error(`Operation \`${r}\` is not allowed in state \`${t.status}\`. Allowed states: ${e.join(", ")}`)}function KM(t){switch(t){case"consensus":return"accepted";case"rejected":return"rejected";case"withdrawn-by-author":return"withdrawn-by-author";case"superseded":return"superseded";case"unresolved":return"inconclusive";default:return"open"}}function Dx(t){switch(t){case"running":return"running";case"ready-for-approval":return"ready-for-approval";case"escalated":return"escalated";case"approved":return"approved";case"rejected":return"rejected";case"leader-timeout":return"leader-timeout";default:return"error"}}function wc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function xc(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}function JM(t){let e=[];for(let r of t.aggregatedVotes){if(r.status==="accepted")continue;let n={agree:0,disagree:0,abstain:0,revise:0,total:0};for(let o of Object.values(r.votes))switch(n.total+=1,o.vote){case"agree":n.agree+=1;break;case"disagree":n.disagree+=1;break;case"abstain":n.abstain+=1;break;case"revise":n.revise+=1;break}e.push({title:r.title,severity:r.severity,status:r.status,proposerIds:r.proposers,...r.location!==void 0?{location:r.location}:{},votes:n})}return e}function GM(t){let e=0;for(let r of t){let n=r.id.match(/^P(\d+)$/);if(n){let o=Number.parseInt(n[1],10);Number.isFinite(o)&&o>e&&(e=o)}}return e+1}function Ax(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function YM(t,e){let r=0,n=0,o=[];for(let a of e){let c=t.votes.get(a);if(!c){o.push({participantId:a,vote:"missing"});continue}o.push({participantId:a,vote:c.vote,...c.reason!==void 0?{reason:c.reason}:{}}),c.vote==="agree"?r+=1:c.vote==="abstain"&&(n+=1)}let s=e.length-n,i=[];for(let a of o)a.vote==="agree"||a.vote==="abstain"||i.push(`${a.participantId} ${a.vote}`);return{agree:r,denominator:s,perParticipant:o,...i.length>0?{dissentSummary:i.join(", ")}:{}}}function XM(t){let e=new Map;for(let r of t.config.participants)e.set(r,{proposed:0,consensusReceived:0,revisesProposed:0,abstains:0});for(let r of t.ledger.proposals.values())if(r.status!=="merged"){for(let n of r.proposerIds){let o=e.get(n);o&&(o.proposed+=1,r.status==="consensus"&&(o.consensusReceived+=1))}for(let[n,o]of r.votes){let s=e.get(n);s&&(o.vote==="revise"&&(s.revisesProposed+=1),o.vote==="abstain"&&(s.abstains+=1))}}return Array.from(e.entries()).map(([r,n])=>({participantId:r,proposed:n.proposed,consensusReceived:n.consensusReceived,revisesProposed:n.revisesProposed,abstains:n.abstains}))}function Cx(t,e){let r=[],n=[],o=[],s=[],i=[];for(let a of t.aggregatedVotes){let c=t.config.participants.filter(m=>!a.proposers.includes(m)),u=c.map(m=>{let g=a.votes[m];return g?{participantId:m,vote:g.vote,...g.reason!==void 0?{reason:g.reason}:{}}:{participantId:m,vote:"missing"}}),l=0,d=0;for(let m of u)m.vote==="agree"?l+=1:m.vote==="abstain"&&(d+=1);let p=c.length-d;r.push({proposerIds:a.proposers,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,accepted:a.status==="accepted"}),a.status==="accepted"?n.push({id:a.proposalId,proposerIds:a.proposers,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,finalStatement:""}):a.status==="rejected"||a.status==="withdrawn-by-author"?o.push({id:a.proposalId,title:a.title,severity:a.severity,rejectionReason:a.status==="withdrawn-by-author"?"Withdrawn by author":"Rejected by tally",dissentVotes:u}):a.status==="open"&&s.push({id:a.proposalId,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,perParticipant:u}),u.some(m=>m.vote!=="agree"&&m.vote!=="abstain")&&a.status!=="accepted"&&i.push({proposalTitle:a.title,severity:a.severity,perParticipant:u})}return{topic:t.config.topic,rounds:t.rounds,maxRounds:t.config.maxRounds,status:Dx(t.status),participantIds:t.config.participants,individualPaths:Object.values(t.documentPaths.individual),debatePath:t.documentPaths.debate,...t.documentPaths.synthesis!==void 0?{synthesisPath:t.documentPaths.synthesis}:{},proposals:r,contributionSummary:[],dissentDetails:i,acceptedItems:n,rejectedItems:o,openItems:s}}var QM=/<proposals>([\s\S]*?)<\/proposals>/i,eN=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,tN=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function rN(t){let e=QM.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp(eN.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp(tN.source,"g"),l;for(;(l=u.exec(i))!==null;)c[l[1]]=l[2];let d=c.id,p=c.title,f=c.severity;if(!d||!p||!f)continue;let m={id:d,title:p,severity:f,...c.location?{location:c.location}:{},...a.length>0?{description:a}:{}};n.push(m)}return n}function nN(){return["You are a participant in the individual-review phase of a structured multi-AI debate.","Produce a concise review of the stated topic and propose concrete findings.","Findings must be emitted inside a `<proposals>` XML block using the exact shape:","<proposals>",' <item id="P1" title="Short title" severity="CRITICAL|HIGH|MEDIUM|LOW" location="file:line or component">'," Multi-line description / evidence."," </item>","</proposals>","Rules:","- Do NOT emit `<votes>` in this phase.","- Use stable, unique `id` attributes (e.g. P1, P2).","- Severity labels are free-form but stick to the four levels above.","- Description text is AI-native; the moderator preserves it verbatim."].join(`
324
- `)}function oN(t){let e=[];if(e.push(`Topic: ${t.config.topic}`),t.goal&&e.push(`Goal: ${t.goal}`),e.push(`Scope: ${t.config.scope}`),t.files.length>0){e.push("Files examined:");for(let r of t.files)e.push(` - ${r}`)}return t.individualReviewPrompt&&(e.push(""),e.push(t.individualReviewPrompt)),e.push(""),e.push("Return your review followed by the required `<proposals>` block."),e.join(`
325
- `)}function sN(t){let e=[];if(e.push(`Structured debate \u2014 round ${t.round} of ${t.maxRounds}.`),e.push(`Topic: ${t.topic}`),e.push(`Scope: ${t.scope}`),t.previousVoteIssues&&t.previousVoteIssues.length>0){e.push(""),e.push("Previous round vote issues in your response:");for(let r of t.previousVoteIssues)e.push(`- ${r}`);e.push("Correct these issues in this round. Every open proposal still needs an explicit vote.")}e.push(""),e.push("Open proposals:");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`),r.description&&e.push(` ${r.description}`);e.push(""),e.push("Respond with your analysis followed by a `<votes>` block:"),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`. Vote on every open proposal."),e.join(`
326
- `)}function iN(t){let e=[];e.push("Your previous response did not include a valid `<votes>` block."),e.push(`Problem: ${t.errorKind}.`),t.errorDetails&&e.push(`Details: ${t.errorDetails}`),e.push("Reply with ONLY the `<votes>` block. Do not include prose."),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`."),e.join(`
327
- `)}function aN(t){return t.map(e=>`${e.proposalId??"unparsed entry"}: ${e.reason}`)}function cN(t){let e=[];e.push(`## Round ${t.round} / ${t.maxRounds}`),e.push(""),e.push("### Proposal Ledger (open at round start)");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`);e.push(""),e.push("### Turns");for(let r of t.turns)e.push(""),e.push(`#### [${r.participantId}]${r.failed?" (failed)":""}`),e.push(r.text);e.push(""),e.push("### Aggregation");for(let r of t.aggregation){let o=t.ledger.proposals.get(r.proposalId)?.status??"open";e.push(`- ${r.proposalId} \u2192 ${o} (${r.verdict}; agree=${r.tally.agree}, disagree=${r.tally.disagree}, abstain=${r.tally.abstain}, revise=${r.tally.revise}, missing=${r.tally.missing})`)}return e.join(`
328
- `)}function uN(t,e){let n=[`## ${e.t("moderator.narration.aliasClarification")}`];if(t.mergesApplied.length>0){n.push(""),n.push("Applied merges:");for(let o of t.mergesApplied)n.push(`- ${o.alias} \u2192 ${o.primary} (same=${o.voteBreakdown.same}, different=${o.voteBreakdown.different}, unsure=${o.voteBreakdown.unsure}, missing=${o.voteBreakdown.missing})`)}if(t.undecided.length>0){n.push(""),n.push("Undecided pairs (kept separate):");for(let o of t.undecided)n.push(`- ${o.pair.proposalA} \u2194 ${o.pair.proposalB} (${o.reason})`)}return n.join(`
329
- `)}var zx=18e4;function Vs(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${zx/1e3}s)`)),zx))])}function Nx(t){return new On({tools:Ti(),baseDir:t})}var Zp,Ox;function jx(t){return(!Zp||Ox!==t)&&(Zp=new Do,Ox=t),Zp}var qs;function Sc(t,e){if(qs&&qs.registry===t&&qs.hostKind===e)return qs.bridge;let r=new On({tools:Ti(),baseDir:process.cwd()}),n=px({registry:t,readOnlyAdapter:r,hostKind:e});return qs={bridge:n,registry:t,hostKind:e},n}var Mx=new Map;function Lx(t){let e=Mx.get(t.workspaceBaseDir);if(e&&e.registry===t.structuredSessionRegistry&&e.documentManager===t.documentManager&&e.bridge===t.bridge)return e.engine;let r=new mo({bridge:t.bridge,documentManager:t.documentManager,registry:t.structuredSessionRegistry,i18n:t.i18n,...t.traceWriter!==void 0?{traceWriter:t.traceWriter}:{}});return Mx.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function Fx(t,e,r){let n=.7;if(r&&e){for(let o of r)e.updateQuality(t.id,o.provider,{score:o.score,evaluator:"claude",feedback:o.feedback});n=r.reduce((o,s)=>o+s.score,0)/r.length}else if(e){let o=new Map;for(let a of t.turns){if(a.speaker==="claude")continue;let c=t.turns.filter(d=>d.turnNumber<a.turnNumber).map(d=>({speaker:d.speaker,content:d.content})),u=jo(a.content,c,t.topic),l=o.get(a.speaker)??[];l.push(u.score),o.set(a.speaker,l)}let s=0,i=0;for(let[a,c]of o){let u=c.reduce((l,d)=>l+d,0)/c.length;e.updateQuality(t.id,a,{score:u,evaluator:"auto_rule_based",feedback:`Auto-aggregated from ${c.length} turns`}),s+=u,i++}i>0&&(n=s/i)}return{avgQuality:n}}function $c(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function Zx(t,e){let r=rc.parse(t),n=new Map(r.providers.map(l=>[l,e.registry.get(l)])),o=e.sessionManager.createSession("debate",{topic:r.topic,providers:r.providers,maxRounds:r.max_rounds});e.sessionManager.updateSessionStatus(o.id,"in_progress");let s=e.debateEngine,i=s.create({topic:r.topic,providerIds:r.providers,goal:r.goal}),a=!!(r.goal&&r.validator),c=a?e.registry.get(r.validator):void 0,u=a?r.min_rounds??2:r.max_rounds;return(async()=>{try{let l="";for(let p=0;p<r.max_rounds;p++){for(let[f,m]of n){let g=s.buildPromptForProvider(i.id,f);l&&(g+=`
323
+ ${i}`}emitTrace(e,r,n){if(this.deps.traceWriter)try{this.deps.traceWriter.write({traceId:e?.sessionId??"unknown",action:r,providerId:"moderator-engine",task:e?.config.topic??"",request:{promptSummary:JSON.stringify(n),fileCount:0},response:{success:!0,charLength:0},latencyMs:0})}catch{}}};function VM(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function Cx(t){for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function BM(t){return t==="ready-for-approval"||t==="escalated"}function WM(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 KM(t){return t.abstain>0&&t.agree===0&&t.disagree===0&&t.revise===0&&t.missing===0}function Zp(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 GM(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 Ox(t){switch(t){case"running":return"running";case"ready-for-approval":return"ready-for-approval";case"escalated":return"escalated";case"approved":return"approved";case"rejected":return"rejected";case"leader-timeout":return"leader-timeout";default:return"error"}}function wc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function xc(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}function JM(t){let e=[];for(let r of t.aggregatedVotes){if(r.status==="accepted")continue;let n={agree:0,disagree:0,abstain:0,revise:0,total:0};for(let o of Object.values(r.votes))switch(n.total+=1,o.vote){case"agree":n.agree+=1;break;case"disagree":n.disagree+=1;break;case"abstain":n.abstain+=1;break;case"revise":n.revise+=1;break}e.push({title:r.title,severity:r.severity,status:r.status,proposerIds:r.proposers,...r.location!==void 0?{location:r.location}:{},votes:n})}return e}function YM(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 Dx(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function XM(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 QM(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 zx(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:Ox(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 eN=/<proposals>([\s\S]*?)<\/proposals>/i,tN=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,rN=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function nN(t){let e=eN.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp(tN.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp(rN.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 oN(){return["You are a participant in the individual-review phase of a structured multi-AI debate.","Produce a concise review of the stated topic and propose concrete findings.","Findings must be emitted inside a `<proposals>` XML block using the exact shape:","<proposals>",' <item id="P1" title="Short title" severity="CRITICAL|HIGH|MEDIUM|LOW" location="file:line or component">'," Multi-line description / evidence."," </item>","</proposals>","Rules:","- Do NOT emit `<votes>` in this phase.","- Use stable, unique `id` attributes (e.g. P1, P2).","- Severity labels are free-form but stick to the four levels above.","- Description text is AI-native; the moderator preserves it verbatim."].join(`
324
+ `)}function sN(t){let e=[];if(e.push(`Topic: ${t.config.topic}`),t.goal&&e.push(`Goal: ${t.goal}`),e.push(`Scope: ${t.config.scope}`),t.files.length>0){e.push("Files examined:");for(let r of t.files)e.push(` - ${r}`)}return t.individualReviewPrompt&&(e.push(""),e.push(t.individualReviewPrompt)),e.push(""),e.push("Return your review followed by the required `<proposals>` block."),e.join(`
325
+ `)}function iN(t){let e=[];if(e.push(`Structured debate \u2014 round ${t.round} of ${t.maxRounds}.`),e.push(`Topic: ${t.topic}`),e.push(`Scope: ${t.scope}`),t.previousVoteIssues&&t.previousVoteIssues.length>0){e.push(""),e.push("Previous round vote issues in your response:");for(let r of t.previousVoteIssues)e.push(`- ${r}`);e.push("Correct these issues in this round. Every open proposal still needs an explicit vote.")}e.push(""),e.push("Open proposals:");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`),r.description&&e.push(` ${r.description}`);e.push(""),e.push("Respond with your analysis followed by a `<votes>` block:"),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`. Vote on every open proposal."),e.join(`
326
+ `)}function aN(t){let e=[];e.push("Your previous response did not include a valid `<votes>` block."),e.push(`Problem: ${t.errorKind}.`),t.errorDetails&&e.push(`Details: ${t.errorDetails}`),e.push("Reply with ONLY the `<votes>` block. Do not include prose."),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`."),e.join(`
327
+ `)}function cN(t){return t.map(e=>`${e.proposalId??"unparsed entry"}: ${e.reason}`)}function uN(t){let e=[];e.push(`## Round ${t.round} / ${t.maxRounds}`),e.push(""),e.push("### Proposal Ledger (open at round start)");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`);e.push(""),e.push("### Turns");for(let r of t.turns)e.push(""),e.push(`#### [${r.participantId}]${r.failed?" (failed)":""}`),e.push(r.text);e.push(""),e.push("### Aggregation");for(let r of t.aggregation){let o=t.ledger.proposals.get(r.proposalId)?.status??"open";e.push(`- ${r.proposalId} \u2192 ${o} (${r.verdict}; agree=${r.tally.agree}, disagree=${r.tally.disagree}, abstain=${r.tally.abstain}, revise=${r.tally.revise}, missing=${r.tally.missing})`)}return e.join(`
328
+ `)}function lN(t,e){let n=[`## ${e.t("moderator.narration.aliasClarification")}`];if(t.mergesApplied.length>0){n.push(""),n.push("Applied merges:");for(let o of t.mergesApplied)n.push(`- ${o.alias} \u2192 ${o.primary} (same=${o.voteBreakdown.same}, different=${o.voteBreakdown.different}, unsure=${o.voteBreakdown.unsure}, missing=${o.voteBreakdown.missing})`)}if(t.undecided.length>0){n.push(""),n.push("Undecided pairs (kept separate):");for(let o of t.undecided)n.push(`- ${o.pair.proposalA} \u2194 ${o.pair.proposalB} (${o.reason})`)}return n.join(`
329
+ `)}var Mx=18e4;function Vs(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${Mx/1e3}s)`)),Mx))])}function Lx(t){return new On({tools:Ti(),baseDir:t})}var Up,Nx;function Fx(t){return(!Up||Nx!==t)&&(Up=new zo,Nx=t),Up}var ho;function Sc(t,e,r){if(ho&&ho.registry===t&&ho.hostKind===e&&ho.baseDir===r)return ho.bridge;let n=new On({tools:Ti(),baseDir:r}),o=mx({registry:t,readOnlyAdapter:n,hostKind:e,agentsDir:dN(r,"agents")});return ho={bridge:o,registry:t,hostKind:e,baseDir:r},o}var jx=new Map;function Zx(t){let e=jx.get(t.workspaceBaseDir);if(e&&e.registry===t.structuredSessionRegistry&&e.documentManager===t.documentManager&&e.bridge===t.bridge)return e.engine;let r=new mo({bridge:t.bridge,documentManager:t.documentManager,registry:t.structuredSessionRegistry,i18n:t.i18n,...t.traceWriter!==void 0?{traceWriter:t.traceWriter}:{}});return jx.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function Ux(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=Lo(a.content,c,t.topic),l=o.get(a.speaker)??[];l.push(u.score),o.set(a.speaker,l)}let s=0,i=0;for(let[a,c]of o){let u=c.reduce((l,d)=>l+d,0)/c.length;e.updateQuality(t.id,a,{score:u,evaluator:"auto_rule_based",feedback:`Auto-aggregated from ${c.length} turns`}),s+=u,i++}i>0&&(n=s/i)}return{avgQuality:n}}function $c(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function qx(t,e){let r=rc.parse(t),n=new Map(r.providers.map(l=>[l,e.registry.get(l)])),o=e.sessionManager.createSession("debate",{topic:r.topic,providers:r.providers,maxRounds:r.max_rounds});e.sessionManager.updateSessionStatus(o.id,"in_progress");let s=e.debateEngine,i=s.create({topic:r.topic,providerIds:r.providers,goal:r.goal}),a=!!(r.goal&&r.validator),c=a?e.registry.get(r.validator):void 0,u=a?r.min_rounds??2:r.max_rounds;return(async()=>{try{let l="";for(let p=0;p<r.max_rounds;p++){for(let[f,m]of n){let g=s.buildPromptForProvider(i.id,f);l&&(g+=`
330
330
 
331
331
  Validator feedback from previous round:
332
- ${l}`);let v=await Vs(e.readOnlyAdapter.chat(m,{prompt:g}),f);s.addTurn(i.id,f,v.text)}if(a&&c&&p+1>=u){let f=s.buildTurnTranscript(i.id),m=`Evaluate this debate against the goal: "${r.goal}"
332
+ ${l}`);let y=await Vs(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}"
333
333
 
334
334
  Current discussion:
335
335
  ${f}
@@ -341,12 +341,12 @@ Respond in JSON:
341
341
  "accuracy": true/false,
342
342
  "consistency": true/false,
343
343
  "feedback": "..."
344
- }`,g=await Vs(e.readOnlyAdapter.chat(c,{prompt:m}),c.id);try{let v=JSON.parse(g.text);if(v.goalAchievement&&v.completeness&&v.accuracy&&v.consistency)break;l=String(v.feedback??"")}catch{l=g.text}}}let d=$c(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(o.id,d)}catch(l){let d=z(l);try{s.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(o.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
344
+ }`,g=await Vs(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=$c(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**
345
345
  **Session ID:** ${o.id}
346
346
  **Topic:** ${r.topic}
347
347
  **Participants:** ${r.providers.join(", ")}
348
348
 
349
- Use \`agent_debate_status\` to check progress.`}]}}async function Ux(t,e){let r=oc.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=`**Session ID:** ${n.id}
349
+ Use \`agent_debate_status\` to check progress.`}]}}async function Vx(t,e){let r=oc.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=`**Session ID:** ${n.id}
350
350
  **Type:** ${n.type}
351
351
  **Status:** ${n.status}
352
352
  **Created:** ${n.createdAt}
@@ -356,7 +356,7 @@ Use \`agent_debate_status\` to check progress.`}]}}async function Ux(t,e){let r=
356
356
 
357
357
  ---
358
358
 
359
- ${n.result}`),{content:[{type:"text",text:o}]}}async function qx(t,e){let r=nc.parse(t),n=new Oo(e.registry,e.readOnlyAdapter);try{let o=await n.validate({items:r.items.map(i=>({providerId:i.provider,content:i.content,task:i.task})),validators:r.validators?.map(i=>e.registry.get(i)),criteria:r.criteria}),s=`**Cross-Validation ${o.overallPass?"PASSED":"FAILED"}**
359
+ ${n.result}`),{content:[{type:"text",text:o}]}}async function Bx(t,e){let r=nc.parse(t),n=new Mo(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"}**
360
360
 
361
361
  `;for(let i of o.reviews)s+=`### ${i.targetProvider} reviewed by ${i.reviewerProvider}
362
362
  `,s+=`**Result:** ${i.passed?"PASS":"FAIL"}
@@ -366,13 +366,13 @@ ${n.result}`),{content:[{type:"text",text:o}]}}async function qx(t,e){let r=nc.p
366
366
  `;return o.conflicts.length>0&&(s+=`## Conflicts
367
367
  ${o.conflicts.map(i=>`- ${i}`).join(`
368
368
  `)}
369
- `),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${z(o)}`}],isError:!0}}}async function Vx(t,e){let r=sc.parse(t);for(let s of r.providers)s!=="claude"&&e.registry.get(s);let n;return r.save_document&&(n=(await e.documentManager.createDebateDocument({topic:r.topic,providers:r.providers,goal:r.goal})).id),{content:[{type:"text",text:`**Debate created**
369
+ `),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${M(o)}`}],isError:!0}}}async function Wx(t,e){let r=sc.parse(t);for(let s of r.providers)s!=="claude"&&e.registry.get(s);let n;return r.save_document&&(n=(await e.documentManager.createDebateDocument({topic:r.topic,providers:r.providers,goal:r.goal})).id),{content:[{type:"text",text:`**Debate created**
370
370
  **Debate ID:** ${e.debateEngine.create({topic:r.topic,providerIds:r.providers,goal:r.goal,documentId:n}).id}
371
371
  **Topic:** ${r.topic}
372
372
  **Participants:** ${r.providers.join(", ")}${n?`
373
- **Document ID:** ${n}`:""}`}]}}async function Bx(t,e){let r=ic.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};if(n.status==="concluded")return{content:[{type:"text",text:`Debate already concluded: ${r.debate_id}`}],isError:!0};if(r.provider==="claude")return r.claude_comment?(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}),{content:[{type:"text",text:`**[claude]:** ${r.claude_comment}`}]}):{content:[{type:"text",text:'provider: "claude" requires claude_comment to be set.'}],isError:!0};let o=e.registry.get(r.provider);r.claude_comment&&(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}));let s=e.debateEngine.buildPromptForProvider(r.debate_id,r.provider),i=e.traceWriter?{candidateProviders:n.providerIds,selectedProvider:r.provider,selectionReason:`Debate turn: ${r.provider}'s turn to respond`,memoryHit:!1}:void 0,a=performance.now(),c;try{c=await e.readOnlyAdapter.chat(o,{prompt:s})}catch(p){let f=Math.round(performance.now()-a),m=z(p);return e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!1,charLength:0,error:m},latencyMs:f,reasoning:i}),{content:[{type:"text",text:`**Debate turn failed (${r.provider}):** ${m}`}],isError:!0}}let u=Math.round(performance.now()-a);e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!0,charLength:c.text.length},latencyMs:u,reasoning:i});let l=n.turns.map(p=>({speaker:p.speaker,content:p.content})),d=jo(c.text,l,n.topic);return e.traceWriter&&e.traceWriter.updateQuality(n.id,r.provider,{score:d.score,evaluator:"auto_rule_based",feedback:JSON.stringify(d.breakdown)}),e.debateEngine.addTurn(r.debate_id,r.provider,c.text),n.documentId&&await e.documentManager.addComment(n.documentId,{author:r.provider,content:c.text}),{content:[{type:"text",text:`**[${r.provider}]:** ${c.text}
373
+ **Document ID:** ${n}`:""}`}]}}async function Hx(t,e){let r=ic.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};if(n.status==="concluded")return{content:[{type:"text",text:`Debate already concluded: ${r.debate_id}`}],isError:!0};if(r.provider==="claude")return r.claude_comment?(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}),{content:[{type:"text",text:`**[claude]:** ${r.claude_comment}`}]}):{content:[{type:"text",text:'provider: "claude" requires claude_comment to be set.'}],isError:!0};let o=e.registry.get(r.provider);r.claude_comment&&(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}));let s=e.debateEngine.buildPromptForProvider(r.debate_id,r.provider),i=e.traceWriter?{candidateProviders:n.providerIds,selectedProvider:r.provider,selectionReason:`Debate turn: ${r.provider}'s turn to respond`,memoryHit:!1}:void 0,a=performance.now(),c;try{c=await e.readOnlyAdapter.chat(o,{prompt:s})}catch(p){let f=Math.round(performance.now()-a),m=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=Lo(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}
374
374
 
375
- _Quality: ${d.score.toFixed(2)}_`}]}}async function Wx(t,e){let r=ac.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};r.summary&&(e.debateEngine.addTurn(r.debate_id,"claude",r.summary),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude (Summary)",content:r.summary})),e.debateEngine.conclude(r.debate_id);let{avgQuality:o}=Fx(n,e.traceWriter,r.quality_scores),s=$c(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
375
+ _Quality: ${d.score.toFixed(2)}_`}]}}async function Kx(t,e){let r=ac.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};r.summary&&(e.debateEngine.addTurn(r.debate_id,"claude",r.summary),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude (Summary)",content:r.summary})),e.debateEngine.conclude(r.debate_id);let{avgQuality:o}=Ux(n,e.traceWriter,r.quality_scores),s=$c(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
376
376
  **Debate ID:** ${r.debate_id}
377
377
  **Topic:** ${n.topic}
378
378
  **Turns:** ${n.turns.length}`;return n.documentId&&(i+=`
@@ -380,13 +380,13 @@ _Quality: ${d.score.toFixed(2)}_`}]}}async function Wx(t,e){let r=ac.parse(t),n=
380
380
 
381
381
  ---
382
382
 
383
- ${s}`,{content:[{type:"text",text:i}]}}async function Hx(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function kc(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function Pc(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
383
+ ${s}`,{content:[{type:"text",text:i}]}}async function Gx(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function kc(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function Pc(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
384
384
 
385
385
  **Suggestions:** ${t.suggestions}`:"";return`${t.feedback}${e}`}case"parseError":return`[Parse error: ${t.reason}]
386
386
 
387
387
  **Raw response:**
388
388
 
389
- ${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function Kx(t,e,r,n,o){if(!e)return;let s=await t.documentManager.createReview({files:[],rules:[`Independent review from ${o.provider}`,`Parent document: ${e}`,...r?[`Debate ID: ${r}`]:[]],provider:o.provider,topic:`review-${e.slice(0,12)}`});await t.documentManager.addComment(s.id,{author:"Moderator",content:`## Review Target
389
+ ${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function Jx(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
390
390
 
391
391
  Parent document: ${e}${r?`
392
392
  Debate ID: ${r}`:""}
@@ -399,25 +399,25 @@ ${n}`});let i=o.rawResponse?`
399
399
 
400
400
  ${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${kc(o.outcome)}**
401
401
 
402
- ${Pc(o.outcome)}${i}`}),s.id}function lN(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
403
- ${Tf}`}function dN(t){let e=zn(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=Xw.safeParse(e);if(!r.success)return{kind:"parseError",rawResponse:t,reason:`Response JSON did not match review contract: ${r.error.message}`};let{agrees:n,feedback:o,suggestions:s}=r.data;return n?{kind:"agree",feedback:o,suggestions:s}:{kind:"disagree",feedback:o,suggestions:s}}async function Jx(t,e){let r=cc.parse(t),n=[...r.providers],o=[],s=r.debate_id?e.debateEngine.getState(r.debate_id):void 0,i=s?.documentId;if(r.debate_id&&s){let _=new Set(e.debateEngine.getActiveProviders(r.debate_id)),S=[];for(let y of n)if(y==="claude"||_.has(y))S.push(y);else{let x=(s.unavailableProviders??[]).find($=>$.providerId===y);o.push({id:y,reason:x?`Marked unavailable for this debate: ${x.reason}`:"Not currently active in this debate."})}n=S}let a=o.length===0?"":`
404
- **Excluded Providers:** ${o.map(_=>`${_.id} (${_.reason})`).join(", ")}`;if(n.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${a}`}],isError:!0};let c=lN(r.review_prompt),u=[],l=n.map(async _=>{if(_==="claude")return null;let S=e.registry.get(_),y=`${c}
402
+ ${Pc(o.outcome)}${i}`}),s.id}function pN(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
403
+ ${Rf}`}function fN(t){let e=zn(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=ex.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 Yx(t,e){let r=cc.parse(t),n=[...r.providers],o=[],s=r.debate_id?e.debateEngine.getState(r.debate_id):void 0,i=s?.documentId;if(r.debate_id&&s){let v=new Set(e.debateEngine.getActiveProviders(r.debate_id)),S=[];for(let w of n)if(w==="claude"||v.has(w))S.push(w);else{let _=(s.unavailableProviders??[]).find(P=>P.providerId===w);o.push({id:w,reason:_?`Marked unavailable for this debate: ${_.reason}`:"Not currently active in this debate."})}n=S}let a=o.length===0?"":`
404
+ **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=pN(r.review_prompt),u=[],l=n.map(async v=>{if(v==="claude")return null;let S=e.registry.get(v),w=`${c}
405
405
 
406
406
  ---
407
407
 
408
- ${r.document}`,x,$;try{let O=await Vs(e.readOnlyAdapter.chat(S,{prompt:y}),_);x=O.text,$=dN(O.text)}catch(O){let Y=z(O);if($={kind:"unavailable",reason:Y},r.debate_id&&s){let Pe=O instanceof de?`Provider reported unavailable: ${Y}`:`Chat failed: ${Y}`;e.debateEngine.markProviderUnavailable(r.debate_id,_,Pe),s=e.debateEngine.getState(r.debate_id)}}let M={provider:_,outcome:$,rawResponse:x};if(M.linkedDocumentId=await Kx(e,i,r.debate_id,r.document,M),i){let O=Pc(M.outcome),Y=M.linkedDocumentId?`
408
+ ${r.document}`,_,P;try{let D=await Vs(e.readOnlyAdapter.chat(S,{prompt:w}),v);_=D.text,P=fN(D.text)}catch(D){let U=M(D);if(P={kind:"unavailable",reason:U},r.debate_id&&s){let $e=D instanceof de?`Provider reported unavailable: ${U}`:`Chat failed: ${U}`;e.debateEngine.markProviderUnavailable(r.debate_id,v,$e),s=e.debateEngine.getState(r.debate_id)}}let A={provider:v,outcome:P,rawResponse:_};if(A.linkedDocumentId=await Jx(e,i,r.debate_id,r.document,A),i){let D=Pc(A.outcome),U=A.linkedDocumentId?`
409
409
 
410
- **Independent review document:** ${M.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${_} (review)`,content:`**${kc(M.outcome)}**
410
+ **Independent review document:** ${A.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${v} (review)`,content:`**${kc(A.outcome)}**
411
411
 
412
- ${O}${Y}`})}return M}),d=await Promise.all(l);for(let _ of d)_&&u.push(_);let p=u.filter(_=>_.outcome.kind==="agree"||_.outcome.kind==="disagree"),f=u.length>0&&p.length===u.length&&p.every(_=>_.outcome.kind==="agree"),m=u.filter(_=>_.outcome.kind==="parseError"||_.outcome.kind==="unavailable"),v=`**Document Review** \u2014 ${f?"ALL AGREE \u2713":m.length>0&&p.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${a}
412
+ ${D}${U}`})}return A}),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}
413
413
 
414
- `;for(let _ of u)v+=`### ${_.provider}: ${kc(_.outcome)}
415
- `,v+=`${Pc(_.outcome)}
416
- `,_.linkedDocumentId&&(v+=`**Independent review document:** ${_.linkedDocumentId}
417
- `),v+=`
418
- `;if(!f){let _=m.length>0?`Revise the document addressing the feedback above. Note: ${m.length} provider(s) did not return a definite agree/disagree (parseError or unavailable) \u2014 they are NOT counted as agreement. Call \`agent_debate_review\` again with an updated document or a narrower providers list.`:"Revise the document addressing the feedback above, then call `agent_debate_review` again to check for consensus.";v+=`---
414
+ `;for(let v of u)y+=`### ${v.provider}: ${kc(v.outcome)}
415
+ `,y+=`${Pc(v.outcome)}
416
+ `,v.linkedDocumentId&&(y+=`**Independent review document:** ${v.linkedDocumentId}
417
+ `),y+=`
418
+ `;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+=`---
419
419
 
420
- **Next step:** ${_}`}return await Hx(e,i,"Moderator (Review Aggregation)",v),{content:[{type:"text",text:v}]}}async function Gx(t,e){let r=uc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};let n;try{n=e.cliWorkerManager.reviewChanges(r.task_id)}catch(s){return{content:[{type:"text",text:z(s)}],isError:!0}}let o=`**File Change Review**
420
+ **Next step:** ${v}`}return await Gx(e,i,"Moderator (Review Aggregation)",y),{content:[{type:"text",text:y}]}}async function Xx(t,e){let r=uc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};let n;try{n=e.cliWorkerManager.reviewChanges(r.task_id)}catch(s){return{content:[{type:"text",text:M(s)}],isError:!0}}let o=`**File Change Review**
421
421
  **Task ID:** ${r.task_id}
422
422
  **Worktree:** ${n.worktreePath}
423
423
  **Branch:** ${n.branch}
@@ -431,25 +431,25 @@ ${n.diffStat}
431
431
  ### Changes
432
432
  \`\`\`diff
433
433
  ${n.fullDiff}
434
- \`\`\``,{content:[{type:"text",text:o}]}}async function Yx(t,e){let r=lc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{let n=e.cliWorkerManager.acceptChanges(r.task_id,r.message);return{content:[{type:"text",text:`**Changes accepted**
434
+ \`\`\``,{content:[{type:"text",text:o}]}}async function Qx(t,e){let r=lc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{let n=e.cliWorkerManager.acceptChanges(r.task_id,r.message);return{content:[{type:"text",text:`**Changes accepted**
435
435
  **Task ID:** ${r.task_id}
436
436
  **Merged files:** ${n.merged.length}
437
437
 
438
438
  ${n.merged.map(o=>`- ${o}`).join(`
439
- `)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${z(n)}`}],isError:!0}}}async function Xx(t,e){let r=dc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{e.cliWorkerManager.rejectChanges(r.task_id)}catch(o){return{content:[{type:"text",text:z(o)}],isError:!0}}let n=`**Changes rejected**
439
+ `)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${M(n)}`}],isError:!0}}}async function eS(t,e){let r=dc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{e.cliWorkerManager.rejectChanges(r.task_id)}catch(o){return{content:[{type:"text",text:M(o)}],isError:!0}}let n=`**Changes rejected**
440
440
  **Task ID:** ${r.task_id}`;return r.reason&&(n+=`
441
- **Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as pN}from"path";var fN="unknown";async function Qx(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o=r.structuredSessionRegistry??new fo(pN(n,_o)),s=Sc(r.registry,r.sessionContext?.hostKind??fN),i=r.moderatorEngine??Lx({workspaceBaseDir:n,bridge:s,documentManager:r.documentManager,structuredSessionRegistry:o,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:jx(n),readOnlyAdapter:Nx(n),structuredSessionRegistry:o,moderatorEngine:i};switch(t){case"agent_debate_start":return Zx(e,a);case"agent_debate_status":return Ux(e,a);case"agent_cross_validate":return qx(e,a);case"agent_debate_create":return Vx(e,a);case"agent_debate_turn":return Bx(e,a);case"agent_debate_conclude":return Wx(e,a);case"agent_debate_review":return Jx(e,a);case"agent_changes_review":return Gx(e,a);case"agent_changes_accept":return Yx(e,a);case"agent_changes_reject":return Xx(e,a);case gc:return Qw(e,a);case co:return ex(e,a);case uo:return tx(e,a);case lo:return rx(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var qp={};Ve(qp,{getTools:()=>mN,handleTool:()=>xN});var eS=h.object({files:h.array(h.string()).min(1).describe("File paths to include in the review"),rules:h.array(h.string()).describe("Review rules/guidelines to apply")}),tS=h.object({doc_id:h.string().describe("Document ID to request review for"),provider:h.union([h.string(),h.array(h.string()).min(1)]).describe("Provider ID(s) to perform the review")}),rS=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),nS=h.object({doc_id:h.string().describe("Document ID to comment on"),author:h.string().describe("Comment author name"),content:h.string().describe("Comment content")}),oS=h.object({doc_id:h.string().describe("Document ID to read")}),sS=h.object({title:h.string().describe("Document title"),content:h.string().describe("Document content (markdown)"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata (e.g. Provider, Task, Mode)"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider independent work) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/. Always pass an explicit kind for idea/review workflows so the workspace tree stays sorted.")}),iS=h.object({});function mN(){return[{name:"workspace_create_review",title:"Create Code Review",description:"Create a code review document for the specified files with given review rules.",inputSchema:q(eS)},{name:"workspace_request_review",title:"Request Code Review",description:"Request AI provider(s) to perform a code review on an existing review document. Returns immediately with a session ID. Use workspace_review_status to check progress.",inputSchema:q(tS)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:q(rS)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:q(nS)},{name:"workspace_create_document",title:"Create Document",description:"Create a general-purpose workspace document with a title, content, and optional metadata. Use for independent analysis documents, aggregated reports, or any structured output.",inputSchema:q(sS)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:q(oS)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:q(iS)}]}async function hN(t,e){let r=eS.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
441
+ **Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as mN}from"path";var hN="unknown";async function tS(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o=r.structuredSessionRegistry??new fo(mN(n,bo)),s=Sc(r.registry,r.sessionContext?.hostKind??hN,n),i=r.moderatorEngine??Zx({workspaceBaseDir:n,bridge:s,documentManager:r.documentManager,structuredSessionRegistry:o,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:Fx(n),readOnlyAdapter:Lx(n),structuredSessionRegistry:o,moderatorEngine:i};switch(t){case"agent_debate_start":return qx(e,a);case"agent_debate_status":return Vx(e,a);case"agent_cross_validate":return Bx(e,a);case"agent_debate_create":return Wx(e,a);case"agent_debate_turn":return Hx(e,a);case"agent_debate_conclude":return Kx(e,a);case"agent_debate_review":return Yx(e,a);case"agent_changes_review":return Xx(e,a);case"agent_changes_accept":return Qx(e,a);case"agent_changes_reject":return eS(e,a);case gc:return tx(e,a);case co:return rx(e,a);case uo:return nx(e,a);case lo:return ox(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Vp={};Be(Vp,{getTools:()=>gN,handleTool:()=>$N});var rS=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")}),nS=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")}),oS=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),sS=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")}),iS=h.object({doc_id:h.string().describe("Document ID to read")}),aS=h.object({title:h.string().describe("Document title"),content:h.string().describe("Document content (markdown)"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata (e.g. Provider, Task, Mode)"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider independent work) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/. Always pass an explicit kind for idea/review workflows so the workspace tree stays sorted.")}),cS=h.object({});function gN(){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(rS)},{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(nS)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:V(oS)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:V(sS)},{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(aS)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:V(iS)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:V(cS)}]}async function yN(t,e){let r=rS.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
442
442
  **Document ID:** ${n.id}
443
443
  **Path:** ${n.path}
444
444
  **Files:** ${r.files.join(", ")}
445
- **Rules:** ${r.rules.length}`}]}}async function gN(t,e){let r=tS.parse(t),n=Array.isArray(r.provider)?r.provider:[r.provider],o=[];for(let c of n){let u=e.registry.get(c);o.push({id:c,provider:u})}let s=await e.documentManager.read(r.doc_id),i=e.sessionManager.createSession("review",{doc_id:r.doc_id,providers:n,completed:[],failed:[]});e.sessionManager.updateSessionStatus(i.id,"in_progress");let a=o.map(async({id:c,provider:u})=>{try{let l=await u.chat({prompt:`Please review the following document and provide feedback:
445
+ **Rules:** ${r.rules.length}`}]}}async function vN(t,e){let r=nS.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:
446
446
 
447
- ${s.content}`,system:"You are a code reviewer. Provide detailed, actionable feedback."});await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:l.text});let d=e.sessionManager.getSession(i.id);if(d){let p=d.config.completed||[];p.push(c),d.config.completed=p}}catch(l){let d=z(l);try{await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:`**Review failed:** ${d}`})}catch{}let p=e.sessionManager.getSession(i.id);if(p){let f=p.config.failed||[];f.push(c),p.config.failed=f}}});return Promise.all(a).then(()=>{try{let c=e.sessionManager.getSession(i.id),u=c?.config.completed||[],l=c?.config.failed||[],d=`Completed: ${u.join(", ")||"none"}. Failed: ${l.join(", ")||"none"}.`,p=yu({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
447
+ ${s.content}`,system:"You are a code reviewer. Provide detailed, actionable feedback."});await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:l.text});let d=e.sessionManager.getSession(i.id);if(d){let p=d.config.completed||[];p.push(c),d.config.completed=p}}catch(l){let d=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=vu({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
448
448
  **Session ID:** ${i.id}
449
449
  **Document ID:** ${r.doc_id}
450
450
  **Providers:** ${n.join(", ")}
451
451
 
452
- Use \`workspace_review_status\` with session_id to check progress.`}]}}async function yN(t,e){let r=rS.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=n.config.providers||[],s=n.config.completed||[],i=n.config.failed||[],a=o.filter(u=>!s.includes(u)&&!i.includes(u)),c=`**Review Session Status**
452
+ Use \`workspace_review_status\` with session_id to check progress.`}]}}async function _N(t,e){let r=oS.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**
453
453
  `;return c+=`**Session ID:** ${n.id}
454
454
  `,c+=`**Status:** ${n.status}
455
455
  `,c+=`**Document:** ${n.config.doc_id}
@@ -459,22 +459,22 @@ Use \`workspace_review_status\` with session_id to check progress.`}]}}async fun
459
459
  `,c+=`- Failed: ${i.join(", ")||"none"}
460
460
  `,c+=`- Pending: ${a.join(", ")||"none"}
461
461
  `,n.result&&(c+=`
462
- **Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function vN(t,e){let r=nS.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
462
+ **Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function bN(t,e){let r=sS.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
463
463
  **Document ID:** ${r.doc_id}
464
464
  **Author:** ${r.author}
465
465
 
466
- ${r.content}`}]}}async function _N(t,e){let r=sS.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata,kind:r.kind});return{content:[{type:"text",text:`**Document created**
466
+ ${r.content}`}]}}async function wN(t,e){let r=aS.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata,kind:r.kind});return{content:[{type:"text",text:`**Document created**
467
467
  **Document ID:** ${n.id}
468
468
  **Path:** ${n.path}
469
- **Title:** ${r.title}`}]}}async function bN(t,e){let r=oS.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
469
+ **Title:** ${r.title}`}]}}async function xN(t,e){let r=iS.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
470
470
  **Path:** ${n.path}
471
471
 
472
- ${n.content}`}]}}async function wN(t,e){iS.parse(t);let r=await e.documentManager.list();if(r.length===0)return{content:[{type:"text",text:"No workspace documents found."}]};let n=`# Workspace Documents
472
+ ${n.content}`}]}}async function SN(t,e){cS.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
473
473
 
474
474
  **Total:** ${r.length}
475
475
 
476
476
  `;for(let o of r){let s=o.content.slice(0,100).replace(/\n/g," ");n+=`- **${o.id}** \u2014 ${s}...
477
- `}return{content:[{type:"text",text:n}]}}async function xN(t,e,r){switch(t){case"workspace_create_review":return hN(e,r);case"workspace_request_review":return gN(e,r);case"workspace_review_status":return yN(e,r);case"workspace_add_comment":return vN(e,r);case"workspace_create_document":return _N(e,r);case"workspace_read":return bN(e,r);case"workspace_list":return wN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Vp={};Ve(Vp,{getTools:()=>$N,handleTool:()=>TN});function Tc(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var SN=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function $N(){return[{name:"provider_list",title:"List AI Providers",description:"List all registered AI providers with their availability status and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"provider_health",title:"Check Provider Health",description:"Run health checks on AI providers. Optionally specify a provider ID, or omit to check all.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider ID to check (omit to check all)"}},required:[]}}]}async function kN(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
477
+ `}return{content:[{type:"text",text:n}]}}async function $N(t,e,r){switch(t){case"workspace_create_review":return yN(e,r);case"workspace_request_review":return vN(e,r);case"workspace_review_status":return _N(e,r);case"workspace_add_comment":return bN(e,r);case"workspace_create_document":return wN(e,r);case"workspace_read":return xN(e,r);case"workspace_list":return SN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Bp={};Be(Bp,{getTools:()=>PN,handleTool:()=>RN});function Tc(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var kN=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function PN(){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 TN(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
478
478
 
479
479
  `;t.sessionContext&&(r+=`## Host Session
480
480
  `,r+=`- **Host:** ${t.sessionContext.hostId} (${t.sessionContext.hostKind})
@@ -497,33 +497,33 @@ ${n.content}`}]}}async function wN(t,e){iS.parse(t);let r=await e.documentManage
497
497
  `,s.strengths.length>0&&(r+=`- **Strengths:** ${s.strengths.join(", ")}
498
498
  `),s.models.length>0&&(r+=`- **Models:** ${s.models.map(c=>c.name).join(", ")}
499
499
  `),r+=`
500
- `}return{content:[{type:"text",text:r}]}}async function PN(t,e){let r=SN.parse(t),n=r.provider?[e.registry.get(r.provider)]:e.registry.getAll();if(n.length===0)return{content:[{type:"text",text:"No providers to check."}]};let o=await Promise.all(n.map(async i=>{try{let a=await i.healthCheck();return{id:i.id,type:i.type,status:a.status,message:a.message,details:a.details,error:null}}catch(a){return{id:i.id,type:i.type,status:"error",message:z(a),details:void 0,error:z(a)}}})),s=`# Health Check Results
500
+ `}return{content:[{type:"text",text:r}]}}async function EN(t,e){let r=kN.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
501
501
 
502
502
  `;for(let i of o){let a=i.status==="ok"?"OK":i.status==="degraded"?"DEGRADED":"ERROR";s+=`## ${i.id} (${i.type})
503
503
  `,s+=`- **Status:** ${a}
504
504
  `,i.message&&(s+=`- **Message:** ${i.message}
505
505
  `),i.error&&(s+=`- **Error:** ${i.error}
506
506
  `),s+=`
507
- `}return{content:[{type:"text",text:s}]}}async function TN(t,e,r){switch(t){case"provider_list":return kN(r);case"provider_health":return PN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Wp={};Ve(Wp,{getTools:()=>LN,handleTool:()=>UN});import{existsSync as DN,readFileSync as zN}from"fs";import{readFileSync as EN,existsSync as RN}from"fs";var IN={ollama:{executionPolicy:"workspace-write",config:{host:vo,defaultModel:"auto"}},"gemini-cli":{executionPolicy:Jt("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:Jt("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:Jt("claude-cli"),config:{timeout:12e4}}};async function ho(){let t=[{id:"ollama",type:"ollama",provider:new Gr({id:"ollama",host:vo})},{id:"gemini",type:"gemini-cli",provider:new Yr({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new Xr({id:"codex"})},{id:"claude-cli",type:"claude-cli",provider:new Qr({id:"claude-cli"})}],e=[],r=[];await Promise.all(t.map(async o=>{try{await o.provider.initialize()}catch{}let s=o.provider.isAvailable();e.push({id:o.id,type:o.type,available:s}),s&&r.push(o.provider)}));let n=["ollama","gemini","codex","claude-cli"];return e.sort((o,s)=>n.indexOf(o.id)-n.indexOf(s.id)),r.sort((o,s)=>n.indexOf(o.id)-n.indexOf(s.id)),{results:e,providers:r}}function AN(t){if(!RN(t))return null;try{return JSON.parse(EN(t,"utf-8"))}catch{return null}}function CN(t){return t==="auto"?"auto":"default-only"}function aS(t,e,r){let n=AN(t),o=new Set(r.enabledIds??[]),s=new Map((n?.providers??[]).map(d=>[d.id,d])),i=e.map(d=>{let p=IN[d.type]||{executionPolicy:Jt(d.type),config:{}},f=s.get(d.id);return s.delete(d.id),{id:d.id,type:d.type,enabled:d.available&&o.has(d.id),executionPolicy:f?.executionPolicy??p.executionPolicy,config:{...f?.config??p.config}}});for(let d of s.values())i.push({...d,enabled:o.has(d.id)?d.enabled:!1});if(i.length===0)throw new Error("No providers available to write into providers.config.json");let a={selectionPolicy:CN(r.selectionPolicy??n?.selectionPolicy),...r.locale!==void 0?{locale:r.locale}:n?.locale!==void 0?{locale:n.locale}:{},providers:i},c=n?JSON.stringify(n):null,u=JSON.stringify(a),l=c===null?"created":c===u?"unchanged":"updated";return!r.dryRun&&l!=="unchanged"&&(Vf(t),je(t,a)),{action:l,path:t,config:a}}function cS(t,e){Bp(t,e)}function Bp(t,e,r){let n=[];for(let o of t)e.has(o.id)||r?.excludeIds?.has(o.id)||r?.excludeTypes?.has(o.type)||(e.register(o),n.push(o));return n}var ON=h.object({}),MN=h.object({enabled_providers:h.array(h.string()).describe("Provider IDs to enable for Agestra workflows."),locale:h.enum(["ko","en","ja","zh"]).describe("UI language for moderator/setup-facing text."),selection_policy:h.enum(["default-only","auto"]).optional().default("default-only").describe("Provider selection policy stored in providers.config.json."),dry_run:h.boolean().optional().default(!1).describe("When true, compute the resulting config without writing it to disk.")});function NN(t){if(!DN(t))return null;try{return JSON.parse(zN(t,"utf-8"))}catch{return null}}function jN(t,e){if(!t)return["Current config: not found",`Expected location: ${e}`];let r=t.providers.filter(n=>n.enabled);return[`Current config: ${r.length>0?"present":"present (no providers enabled)"}`,`Config path: ${e}`,`Enabled providers: ${r.length>0?r.map(n=>n.id).join(", "):"(none)"}`,`Locale: ${t.locale??"(default)"}`,`Selection policy: ${t.selectionPolicy}`]}function LN(){return[{name:"setup_status",title:"Read Agestra Setup Status",description:"Detect available AI providers and show the current Agestra setup state from providers.config.json.",inputSchema:{type:"object",properties:{},required:[]}},{name:"setup_apply",title:"Apply Agestra Setup",description:"Write the selected AI providers and locale into providers.config.json for Agestra workflows.",inputSchema:{type:"object",properties:{enabled_providers:{type:"array",items:{type:"string"},description:"Provider IDs to enable"},locale:{type:"string",enum:["ko","en","ja","zh"],description:"UI locale"},selection_policy:{type:"string",enum:["default-only","auto"],description:"Stored provider selection policy"},dry_run:{type:"boolean",description:"Preview without writing providers.config.json"}},required:["enabled_providers","locale"]}}]}async function FN(t){let e=$o(),r=NN(e),{results:n}=await ho(),o=["# Agestra Setup"];if(o.push(""),o.push(...jN(r,e)),o.push(""),o.push("Detected providers:"),n.length===0)o.push("- (none detected)");else for(let s of n)o.push(`- ${s.id} (${s.type}) \u2014 ${s.available?"available":"unavailable"}`);return{content:[{type:"text",text:o.join(`
508
- `)}]}}async function ZN(t,e){let r=MN.parse(t),n=$o(),{results:o}=await ho();if(o.length===0)return{content:[{type:"text",text:"No AI providers were detected, so setup could not be applied."}],isError:!0};let s=new Set(o.filter(l=>l.available).map(l=>l.id)),i=r.enabled_providers.filter(l=>!s.has(l));if(i.length>0)return{content:[{type:"text",text:`These providers are not currently available and cannot be enabled: ${i.join(", ")}`}],isError:!0};let a=aS(n,o,{enabledIds:r.enabled_providers,locale:r.locale,selectionPolicy:r.selection_policy,dryRun:r.dry_run}),c=a.config.providers.filter(l=>l.enabled);return{content:[{type:"text",text:[r.dry_run?"# Agestra Setup Preview":"# Agestra Setup Applied","",`Config path: ${a.path}`,`Action: ${a.action}`,`Enabled providers: ${c.length>0?c.map(l=>l.id).join(", "):"(none)"}`,`Locale: ${a.config.locale??"(default)"}`,`Selection policy: ${a.config.selectionPolicy}`].join(`
509
- `)}]}}async function UN(t,e,r){switch(t){case"setup_status":return ON.parse(e),FN(r);case"setup_apply":return ZN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Hp={};Ve(Hp,{getTools:()=>VN,handleTool:()=>HN});var qN=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function VN(){return[{name:"ollama_models",title:"List Ollama Models",description:"List installed Ollama models with their sizes and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"ollama_pull",title:"Pull Ollama Model",description:"Download (pull) a model from the Ollama registry.",inputSchema:{type:"object",properties:{model:{type:"string",description:"Model name to download (e.g. 'llama3', 'codellama')"}},required:["model"]}}]}function uS(t){let e=t.ollamaProviderId||"ollama",r=t.registry.get(e);if(r.type!=="ollama")throw new Error(`Provider '${e}' is not an Ollama provider (type: ${r.type})`);return r}async function BN(t){let r=uS(t).getModels();if(r.length===0)return{content:[{type:"text",text:"No models installed. Use `ollama_pull` to download a model."}]};let n=`# Installed Ollama Models (${r.length})
507
+ `}return{content:[{type:"text",text:s}]}}async function RN(t,e,r){switch(t){case"provider_list":return TN(r);case"provider_health":return EN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Hp={};Be(Hp,{getTools:()=>ZN,handleTool:()=>VN});import{existsSync as ON,readFileSync as MN}from"fs";import{readFileSync as IN,existsSync as AN}from"fs";var CN={ollama:{executionPolicy:"workspace-write",config:{host:_o,defaultModel:"auto"}},"gemini-cli":{executionPolicy:Jt("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:Jt("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:Jt("claude-cli"),config:{timeout:12e4}}};async function go(t){let e=t?.workspaceBaseDir,r=[{id:"ollama",type:"ollama",provider:new Gr({id:"ollama",host:_o})},{id:"gemini",type:"gemini-cli",provider:new Jr({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new Yr({id:"codex",workspaceBaseDir:e})},{id:"claude-cli",type:"claude-cli",provider:new Xr({id:"claude-cli"})}],n=[],o=[];await Promise.all(r.map(async i=>{try{await i.provider.initialize()}catch{}let a=i.provider.isAvailable();n.push({id:i.id,type:i.type,available:a}),a&&o.push(i.provider)}));let s=["ollama","gemini","codex","claude-cli"];return n.sort((i,a)=>s.indexOf(i.id)-s.indexOf(a.id)),o.sort((i,a)=>s.indexOf(i.id)-s.indexOf(a.id)),{results:n,providers:o}}function DN(t){if(!AN(t))return null;try{return JSON.parse(IN(t,"utf-8"))}catch{return null}}function zN(t){return t==="auto"?"auto":"default-only"}function uS(t,e,r){let n=DN(t),o=new Set(r.enabledIds??[]),s=new Map((n?.providers??[]).map(d=>[d.id,d])),i=e.map(d=>{let p=CN[d.type]||{executionPolicy:Jt(d.type),config:{}},f=s.get(d.id);return s.delete(d.id),{id:d.id,type:d.type,enabled:d.available&&o.has(d.id),executionPolicy:f?.executionPolicy??p.executionPolicy,config:{...f?.config??p.config}}});for(let d of s.values())i.push({...d,enabled:o.has(d.id)?d.enabled:!1});if(i.length===0)throw new Error("No providers available to write into providers.config.json");let a={selectionPolicy:zN(r.selectionPolicy??n?.selectionPolicy),...r.locale!==void 0?{locale:r.locale}:n?.locale!==void 0?{locale:n.locale}:{},providers:i},c=n?JSON.stringify(n):null,u=JSON.stringify(a),l=c===null?"created":c===u?"unchanged":"updated";return!r.dryRun&&l!=="unchanged"&&(Wf(t),je(t,a)),{action:l,path:t,config:a}}function lS(t,e){Wp(t,e)}function Wp(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 NN=h.object({}),jN=h.object({enabled_providers:h.array(h.string()).describe("Provider IDs to enable for Agestra workflows."),locale:h.enum(["ko","en","ja","zh"]).describe("UI language for moderator/setup-facing text."),selection_policy:h.enum(["default-only","auto"]).optional().default("default-only").describe("Provider selection policy stored in providers.config.json."),dry_run:h.boolean().optional().default(!1).describe("When true, compute the resulting config without writing it to disk.")});function LN(t){if(!ON(t))return null;try{return JSON.parse(MN(t,"utf-8"))}catch{return null}}function FN(t,e){if(!t)return["Current config: not found",`Expected location: ${e}`];let r=t.providers.filter(n=>n.enabled);return[`Current config: ${r.length>0?"present":"present (no providers enabled)"}`,`Config path: ${e}`,`Enabled providers: ${r.length>0?r.map(n=>n.id).join(", "):"(none)"}`,`Locale: ${t.locale??"(default)"}`,`Selection policy: ${t.selectionPolicy}`]}function ZN(){return[{name:"setup_status",title:"Read Agestra Setup Status",description:"Detect available AI providers and show the current Agestra setup state from providers.config.json.",inputSchema:{type:"object",properties:{},required:[]}},{name:"setup_apply",title:"Apply Agestra Setup",description:"Write the selected AI providers and locale into providers.config.json for Agestra workflows.",inputSchema:{type:"object",properties:{enabled_providers:{type:"array",items:{type:"string"},description:"Provider IDs to enable"},locale:{type:"string",enum:["ko","en","ja","zh"],description:"UI locale"},selection_policy:{type:"string",enum:["default-only","auto"],description:"Stored provider selection policy"},dry_run:{type:"boolean",description:"Preview without writing providers.config.json"}},required:["enabled_providers","locale"]}}]}async function UN(t){let e=ko(),r=LN(e),{results:n}=await go(),o=["# Agestra Setup"];if(o.push(""),o.push(...FN(r,e)),o.push(""),o.push("Detected providers:"),n.length===0)o.push("- (none detected)");else for(let s of n)o.push(`- ${s.id} (${s.type}) \u2014 ${s.available?"available":"unavailable"}`);return{content:[{type:"text",text:o.join(`
508
+ `)}]}}async function qN(t,e){let r=jN.parse(t),n=ko(),{results:o}=await go();if(o.length===0)return{content:[{type:"text",text:"No AI providers were detected, so setup could not be applied."}],isError:!0};let s=new Set(o.filter(l=>l.available).map(l=>l.id)),i=r.enabled_providers.filter(l=>!s.has(l));if(i.length>0)return{content:[{type:"text",text:`These providers are not currently available and cannot be enabled: ${i.join(", ")}`}],isError:!0};let a=uS(n,o,{enabledIds:r.enabled_providers,locale:r.locale,selectionPolicy:r.selection_policy,dryRun:r.dry_run}),c=a.config.providers.filter(l=>l.enabled);return{content:[{type:"text",text:[r.dry_run?"# Agestra Setup Preview":"# Agestra Setup Applied","",`Config path: ${a.path}`,`Action: ${a.action}`,`Enabled providers: ${c.length>0?c.map(l=>l.id).join(", "):"(none)"}`,`Locale: ${a.config.locale??"(default)"}`,`Selection policy: ${a.config.selectionPolicy}`].join(`
509
+ `)}]}}async function VN(t,e,r){switch(t){case"setup_status":return NN.parse(e),UN(r);case"setup_apply":return qN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Kp={};Be(Kp,{getTools:()=>WN,handleTool:()=>GN});var BN=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function WN(){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 dS(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 HN(t){let r=dS(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})
510
510
 
511
511
  `;for(let o of r){let s=(o.size/1e9).toFixed(1);n+=`## ${o.name}
512
512
  `,n+=`- **Size:** ${s} GB
513
513
  `,o.strengths.length>0&&(n+=`- **Strengths:** ${o.strengths.join(", ")}
514
514
  `),n+=`
515
- `}return{content:[{type:"text",text:n}]}}async function WN(t,e){let r=qN.parse(t),n=uS(e);try{let o=n.getConnectionInfo().host,s=await fetch(`${o}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.model,stream:!1})});if(!s.ok){let a=await s.text();return{content:[{type:"text",text:`**Pull failed**
515
+ `}return{content:[{type:"text",text:n}]}}async function KN(t,e){let r=BN.parse(t),n=dS(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**
516
516
  **Model:** ${r.model}
517
517
  **Error:** HTTP ${s.status}: ${a}`}],isError:!0}}let i=await s.json();return{content:[{type:"text",text:`**Model pulled successfully**
518
518
  **Model:** ${r.model}
519
- **Status:** ${i.status||"success"}`}]}}catch(o){let s=z(o);return{content:[{type:"text",text:`**Pull failed**
519
+ **Status:** ${i.status||"success"}`}]}}catch(o){let s=M(o);return{content:[{type:"text",text:`**Pull failed**
520
520
  **Model:** ${r.model}
521
- **Error:** ${s}`}],isError:!0}}}async function HN(t,e,r){switch(t){case"ollama_models":return BN(r);case"ollama_pull":return WN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Kp={};Ve(Kp,{getTools:()=>JN,handleTool:()=>XN});var KN=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' / 'debate' / 'synthesis' / 'general' (default).")}).optional(),lS=h.object({provider:h.string().describe("Provider ID (e.g. 'gemini', 'codex')"),prompt:h.string().describe("Prompt to send to the provider CLI"),timeout:h.number().int().positive().optional().describe("Timeout in ms (default: 300000)"),save_as_document:KN.describe("If set, the job output will be saved as a workspace document on completion. Returned via cli_job_status once finalized.")}).strict(),dS=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function JN(){return[{name:"cli_job_submit",title:"Submit CLI Job",description:"Submit a long-running CLI job to a provider. Returns a job ID immediately. Use cli_job_status to check progress.",inputSchema:q(lS)},{name:"cli_job_status",title:"Check CLI Job Status",description:"Check the status of a CLI job. Returns state, output (on completion), and stderr.",inputSchema:q(dS)}]}async function GN(t,e){let r=lS.parse(t),n=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:r.timeout,saveAsDocument:r.save_as_document}),o=r.save_as_document?`
521
+ **Error:** ${s}`}],isError:!0}}}async function GN(t,e,r){switch(t){case"ollama_models":return HN(r);case"ollama_pull":return KN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Gp={};Be(Gp,{getTools:()=>YN,handleTool:()=>ej});var JN=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' / 'debate' / 'synthesis' / 'general' (default).")}).optional(),pS=h.object({provider:h.string().describe("Provider ID (e.g. 'gemini', 'codex')"),prompt:h.string().describe("Prompt to send to the provider CLI"),timeout:h.number().int().positive().optional().describe("Timeout in ms (default: 300000)"),save_as_document:JN.describe("If set, the job output will be saved as a workspace document on completion. Returned via cli_job_status once finalized.")}).strict(),fS=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function YN(){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(pS)},{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(fS)}]}async function XN(t,e){let r=pS.parse(t),n=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:r.timeout,saveAsDocument:r.save_as_document}),o=r.save_as_document?`
522
522
  **Save on complete:** ${r.save_as_document.title}`:"";return{content:[{type:"text",text:`**Job submitted**
523
523
  **Job ID:** ${n}
524
524
  **Provider:** ${r.provider}${o}
525
525
 
526
- Use \`cli_job_status\` with this job_id to check progress.`}]}}async function YN(t,e){let r=dS.parse(t),n=typeof e.jobManager.getResultAwaited=="function"?await e.jobManager.getResultAwaited(r.job_id):e.jobManager.getResult(r.job_id);if(!n)return{content:[{type:"text",text:`Job not found: ${r.job_id}`}],isError:!0};let o=`**Job ID:** ${n.id}
526
+ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function QN(t,e){let r=fS.parse(t),n=typeof e.jobManager.getResultAwaited=="function"?await e.jobManager.getResultAwaited(r.job_id):e.jobManager.getResult(r.job_id);if(!n)return{content:[{type:"text",text:`Job not found: ${r.job_id}`}],isError:!0};let o=`**Job ID:** ${n.id}
527
527
  **State:** ${n.state}`;return n.exitCode!==void 0&&(o+=`
528
528
  **Exit Code:** ${n.exitCode}`),n.savedDocumentId?o+=`
529
529
  **Document ID:** ${n.savedDocumentId}`:n.saveError&&(o+=`
@@ -535,10 +535,10 @@ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function YN
535
535
  ${n.output}`),n.error&&(o+=`
536
536
 
537
537
  **Stderr:**
538
- ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function XN(t,e,r){switch(t){case"cli_job_submit":return GN(e,r);case"cli_job_status":return YN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Jp={};Ve(Jp,{getTools:()=>QN,handleTool:()=>ej});var pS=h.object({provider_id:h.string().optional(),task:h.string().optional(),trace_id:h.string().optional(),days_back:h.number().optional().default(7),limit:h.number().optional().default(50)}),fS=h.object({days_back:h.number().optional().default(30)}),mS=h.object({trace_id:h.string()});function QN(){return[{name:"trace_query",title:"Query Trace Records",description:"Query trace records with filtering. Returns recent provider interactions with latency, quality scores, and reasoning.",inputSchema:q(pS)},{name:"trace_summary",title:"Summarize Trace Stats",description:"Get quality and performance stats per provider and task type. Shows average quality scores, latency, and success rates.",inputSchema:q(fS)},{name:"trace_visualize",title:"Visualize Trace Flow",description:"Generate a Mermaid diagram showing the flow of a traced operation. Shows provider selection, execution, and quality assessment.",inputSchema:q(mS)}]}async function ej(t,e,r){if(!r.traceWriter)return{content:[{type:"text",text:"Trace tools require traceWriter to be configured."}],isError:!0};let n={traceWriter:r.traceWriter};switch(t){case"trace_query":return tj(e,n);case"trace_summary":return rj(e,n);case"trace_visualize":return nj(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function tj(t,e){let r=pS.parse(t),n=e.traceWriter.query({providerId:r.provider_id,task:r.task,traceId:r.trace_id,daysBack:r.days_back,limit:r.limit});if(n.length===0)return{content:[{type:"text",text:"No trace records found."}]};let o=`**Trace Records** (${n.length} results)
538
+ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function ej(t,e,r){switch(t){case"cli_job_submit":return XN(e,r);case"cli_job_status":return QN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Jp={};Be(Jp,{getTools:()=>tj,handleTool:()=>rj});var mS=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)}),hS=h.object({days_back:h.number().optional().default(30)}),gS=h.object({trace_id:h.string()});function tj(){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(mS)},{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(hS)},{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(gS)}]}async function rj(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 nj(e,n);case"trace_summary":return oj(e,n);case"trace_visualize":return sj(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function nj(t,e){let r=mS.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)
539
539
 
540
540
  `;for(let s of n)o+=`| ${s.timestamp?.slice(0,19)} | ${s.providerId} | ${s.task} | ${s.latencyMs}ms | ${s.response.success?"OK":"FAIL"} |`,s.quality&&(o+=` quality: ${s.quality.score}`),o+=`
541
- `;return{content:[{type:"text",text:o}]}}function rj(t,e){let r=fS.parse(t),n=e.traceWriter.getQualityStats(r.days_back);if(n.size===0)return{content:[{type:"text",text:"No quality data available yet."}]};let o=`**Provider Quality Summary** (last ${r.days_back} days)
541
+ `;return{content:[{type:"text",text:o}]}}function oj(t,e){let r=hS.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)
542
542
 
543
543
  `;o+=`| Provider:Task | Avg Quality | Count | Avg Latency |
544
544
  `,o+=`|---|---|---|---|
@@ -549,13 +549,13 @@ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state=
549
549
  `,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${Ys.medium}) | High (>=${Ys.high}) |
550
550
  `,o+=`|---|---|---|---|---|---|
551
551
  `;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>Xs(u,d)?"YES":"no");o+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
552
- `}return{content:[{type:"text",text:o}]}}function nj(t,e){let r=mS.parse(t),n=e.traceWriter.query({traceId:r.trace_id});if(n.length===0)return{content:[{type:"text",text:`No records found for trace: ${r.trace_id}`}],isError:!0};let o="```mermaid\ngraph LR\n";o+=` A[User Request] --> B{Provider Selection}
552
+ `}return{content:[{type:"text",text:o}]}}function sj(t,e){let r=gS.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}
553
553
  `;for(let i=0;i<n.length;i++){let a=n[i],c=String.fromCharCode(67+i),u=a.reasoning?.selectionReason?a.reasoning.selectionReason.slice(0,40):`${a.latencyMs}ms`;o+=` B -->|${u}| ${c}[${a.providerId}]
554
554
  `;let l=a.response.success?`${a.response.charLength} chars, ${a.latencyMs}ms`:`FAIL: ${a.response.error?.slice(0,30)??"error"}`;o+=` ${c} --> ${c}R[${l}]
555
555
  `,a.quality&&(o+=` ${c}R --> ${c}Q[Quality: ${a.quality.score}]
556
556
  `)}return o+="```",{content:[{type:"text",text:`**Trace Visualization: ${r.trace_id}**
557
557
 
558
- ${o}`}]}}var Yp={};Ve(Yp,{getTools:()=>aj,handleTool:()=>lj,resetCache:()=>cj});import{execFile as oj}from"child_process";import{promisify as sj}from"util";var gS=sj(oj),yS=5e3;async function Bs(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await gS(e,[t],{timeout:yS,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function ij(){try{return await gS("git",["worktree","list"],{timeout:yS,encoding:"utf-8"}),!0}catch{return!1}}function aj(){return[{name:"environment_check",title:"Check Environment",description:"Check installed AI CLI tools (codex, gemini), infrastructure (tmux, git worktree), and Ollama models. Returns a capability map showing available v3 orchestration modes. Results are cached per session \u2014 call with force_refresh to re-check.",inputSchema:{type:"object",properties:{force_refresh:{type:"boolean",description:"Force re-check even if cached (default: false)"}},required:[]}}]}var Ec=null,Gp=null;function cj(){Ec=null,Gp=null}async function uj(t,e){let r=JSON.stringify(e.sessionContext??null);if(Ec&&Gp===r&&!t.force_refresh)return{content:[{type:"text",text:hS(Ec)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(K=>K.isAvailable()),o=n.find(K=>K.type==="claude-cli"),s=n.find(K=>K.type==="claude-host"),i=n.find(K=>K.type==="codex-cli"),a=n.find(K=>K.type==="codex-host"),c=n.find(K=>K.type==="gemini-cli"),u=n.find(K=>K.type==="gemini-host"),[l,d,p,f,m,g]=await Promise.all([Bs("claude"),Bs("codex"),Bs("gemini"),Bs("tmux"),Bs("git"),ij()]),v=[],_=e.registry.getAll(),S=_.find(K=>K.id==="ollama");if(S?.isAvailable()){let K=S.getCapabilities();for(let ot of K.models){let Re=ot.sizeGb??0;v.push({name:ot.name,size_gb:Re,tier:Zc(Re)})}}let y=i!==void 0||c!==void 0,x=f!==null,$=m!==null&&g,M=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",O=_.some(K=>K.isAvailable()&&!K.type.endsWith("-host")&&K.id!=="ollama"),Y=[M?"leader_only":"claude_only"];(O||v.length>0)&&Y.push("independent","debate"),y&&$&&Y.push("team");let Pe={host:e.sessionContext?{id:e.sessionContext.hostId,kind:e.sessionContext.hostKind,leader_provider:e.sessionContext.leaderProviderId,execution_mode:e.sessionContext.executionMode,participant_providers:e.sessionContext.participantProviderIds}:void 0,providers:{ollama:{available:S?.isAvailable()??!1,models:v},claude:{available:o!==void 0||s!==void 0,cli_path:l,host_backed:s!==void 0},gemini:{available:c!==void 0||u!==void 0,cli_path:p,autonomous_capable:c!==void 0,host_backed:u!==void 0},codex:{available:i!==void 0||a!==void 0,cli_path:d,autonomous_capable:i!==void 0,host_backed:a!==void 0}},infrastructure:{tmux:{available:x,path:f},git:{available:m!==null,worktree_support:$}},capabilities:{can_autonomous_work:y&&$,can_tmux_visible:x,can_parallel_workers:y&&$,max_parallel_workers:y?3:0,available_modes:Y}};return Ec=Pe,Gp=r,{content:[{type:"text",text:hS(Pe)}]}}function hS(t){let e=`# Environment Check
558
+ ${o}`}]}}var Xp={};Be(Xp,{getTools:()=>uj,handleTool:()=>pj,resetCache:()=>lj});import{execFile as ij}from"child_process";import{promisify as aj}from"util";var vS=aj(ij),_S=5e3;async function Bs(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await vS(e,[t],{timeout:_S,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function cj(){try{return await vS("git",["worktree","list"],{timeout:_S,encoding:"utf-8"}),!0}catch{return!1}}function uj(){return[{name:"environment_check",title:"Check Environment",description:"Check installed AI CLI tools (codex, gemini), infrastructure (tmux, git worktree), and Ollama models. Returns a capability map showing available v3 orchestration modes. Results are cached per session \u2014 call with force_refresh to re-check.",inputSchema:{type:"object",properties:{force_refresh:{type:"boolean",description:"Force re-check even if cached (default: false)"}},required:[]}}]}var Ec=null,Yp=null;function lj(){Ec=null,Yp=null}async function dj(t,e){let r=JSON.stringify(e.sessionContext??null);if(Ec&&Yp===r&&!t.force_refresh)return{content:[{type:"text",text:yS(Ec)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(G=>G.isAvailable()),o=n.find(G=>G.type==="claude-cli"),s=n.find(G=>G.type==="claude-host"),i=n.find(G=>G.type==="codex-cli"),a=n.find(G=>G.type==="codex-host"),c=n.find(G=>G.type==="gemini-cli"),u=n.find(G=>G.type==="gemini-host"),[l,d,p,f,m,g]=await Promise.all([Bs("claude"),Bs("codex"),Bs("gemini"),Bs("tmux"),Bs("git"),cj()]),y=[],v=e.registry.getAll(),S=v.find(G=>G.id==="ollama");if(S?.isAvailable()){let G=S.getCapabilities();for(let _t of G.models){let Te=_t.sizeGb??0;y.push({name:_t.name,size_gb:Te,tier:Uc(Te)})}}let w=i!==void 0||c!==void 0,_=f!==null,P=m!==null&&g,A=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",D=v.some(G=>G.isAvailable()&&!G.type.endsWith("-host")&&G.id!=="ollama"),U=[A?"leader_only":"claude_only"];(D||y.length>0)&&U.push("independent","debate"),w&&P&&U.push("team");let $e={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:_,path:f},git:{available:m!==null,worktree_support:P}},capabilities:{can_autonomous_work:w&&P,can_tmux_visible:_,can_parallel_workers:w&&P,max_parallel_workers:w?3:0,available_modes:U}};return Ec=$e,Yp=r,{content:[{type:"text",text:yS($e)}]}}function yS(t){let e=`# Environment Check
559
559
 
560
560
  `;t.host&&(e+=`## Host Session
561
561
 
@@ -586,14 +586,14 @@ ${o}`}]}}var Yp={};Ve(Yp,{getTools:()=>aj,handleTool:()=>lj,resetCache:()=>cj});
586
586
  `,e+=`- **tmux visible:** ${t.capabilities.can_tmux_visible?"Yes":"No"}
587
587
  `,e+=`- **Parallel workers:** ${t.capabilities.can_parallel_workers?`Yes (max ${t.capabilities.max_parallel_workers})`:"No"}
588
588
  `,e+=`- **Available modes:** ${t.capabilities.available_modes.join(", ")}
589
- `,e}async function lj(t,e,r){return t==="environment_check"?uj(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Xp={};Ve(Xp,{getTools:()=>dj,handleTool:()=>bj});var vS=h.object({provider:h.string().trim().min(1),task_description:h.string().trim().min(1),working_dir:h.string().trim().min(1),files_to_read:h.array(h.string().trim().min(1)).optional(),files_to_modify:h.array(h.string().trim().min(1)).optional(),constraints:h.string().optional(),success_criteria:h.array(h.string().trim().min(1)).optional(),timeout_minutes:h.number().positive().optional(),use_worktree:h.boolean().optional(),use_tmux:h.boolean().optional()}).strict(),_S=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),bS=h.object({worker_id:h.string().trim().min(1)}).strict(),wS=h.object({worker_id:h.string().trim().min(1)}).strict();function dj(){return[{name:"cli_worker_spawn",title:"Spawn CLI Worker",description:"Spawn a CLI AI worker (any registered provider; use `provider_list` to discover available) in autonomous mode. The worker runs in the background and can be monitored with cli_worker_status.",inputSchema:q(vS)},{name:"cli_worker_status",title:"Check CLI Worker Status",description:"Get the status of a CLI worker by ID, or list all tracked workers if no ID is given.",inputSchema:q(_S)},{name:"cli_worker_collect",title:"Collect CLI Worker Results",description:"Collect results from a successful COLLECTING worker, a completed worker, or a failed CLI worker. Returns full output, git diff, and changed files.",inputSchema:q(bS)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:q(wS)}]}function Rc(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function Rt(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function pj(t){let e=`# Worker Spawned
589
+ `,e}async function pj(t,e,r){return t==="environment_check"?dj(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Qp={};Be(Qp,{getTools:()=>fj,handleTool:()=>xj});var bS=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(),wS=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),xS=h.object({worker_id:h.string().trim().min(1)}).strict(),SS=h.object({worker_id:h.string().trim().min(1)}).strict();function fj(){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(bS)},{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(wS)},{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(xS)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:V(SS)}]}function Rc(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function Rt(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function mj(t){let e=`# Worker Spawned
590
590
 
591
591
  `;return e+=`- **Worker ID:** ${t.workerId}
592
592
  `,e+=`- **Provider:** ${t.provider}
593
593
  `,e+=`- **State:** ${t.state}
594
594
  `,e+=`- **PID:** ${t.pid??"N/A"}
595
595
  `,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
596
- `),e}function fj(t){let e=`# Worker Status
596
+ `),e}function hj(t){let e=`# Worker Status
597
597
 
598
598
  `;return e+=`- **Worker ID:** ${t.workerId}
599
599
  `,e+=`- **Provider:** ${t.provider}
@@ -602,18 +602,18 @@ ${o}`}]}}var Yp={};Ve(Yp,{getTools:()=>aj,handleTool:()=>lj,resetCache:()=>cj});
602
602
  `,e+=`- **PID:** ${t.pid??"N/A"}
603
603
  `,e+=`- **Retry Count:** ${t.retryCount}
604
604
  `,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
605
- `),t.state===$e.COLLECTING&&(e+="- **Next Step:** Worker exited successfully and is ready for `cli_worker_collect`\n"),t.outputTail&&(e+=`
605
+ `),t.state===ke.COLLECTING&&(e+="- **Next Step:** Worker exited successfully and is ready for `cli_worker_collect`\n"),t.outputTail&&(e+=`
606
606
  ## Recent Output
607
607
 
608
608
  \`\`\`
609
609
  ${t.outputTail}
610
610
  \`\`\`
611
- `),e}function mj(t){if(t.length===0)return`# Workers
611
+ `),e}function gj(t){if(t.length===0)return`# Workers
612
612
 
613
613
  No tracked workers.`;let e=`# Workers (${t.length})
614
614
 
615
615
  `;for(let r of t)e+=`- **${r.workerId}** \u2014 ${r.provider} \u2014 ${r.state}`,r.pid&&(e+=` (PID ${r.pid})`),e+=`
616
- `;return e}function hj(t){let e=`# Worker Results
616
+ `;return e}function yj(t){let e=`# Worker Results
617
617
 
618
618
  `;if(e+=`- **Worker ID:** ${t.workerId}
619
619
  `,e+=`- **State:** ${t.state}
@@ -635,7 +635,7 @@ ${t.gitDiff}
635
635
  \`\`\`
636
636
  ${t.outputFull}
637
637
  \`\`\`
638
- `),e}async function gj(t,e){let r=Rc(e),n=vS.parse(t),o=r.knownProviders();if(!o.includes(n.provider))return Rt(`Unknown provider: "${n.provider}". Known: [${o.join(", ")}]`,!0);let s={provider:n.provider,taskDescription:n.task_description,workingDir:n.working_dir,filesToRead:n.files_to_read,filesToModify:n.files_to_modify,constraints:n.constraints,successCriteria:n.success_criteria,timeoutMinutes:n.timeout_minutes,useWorktree:n.use_worktree,useTmux:n.use_tmux};try{let i=r.spawn(s);return Rt(pj(i))}catch(i){let a=z(i);return Rt(`Error spawning worker: ${a}`,!0)}}async function yj(t,e){let r=Rc(e),n=_S.parse(t);if(!n.worker_id){let s=r.listAll();return Rt(mj(s))}let o=r.getStatus(n.worker_id);return o?Rt(fj(o)):Rt(`Worker not found: ${n.worker_id}`,!0)}async function vj(t,e){let r=Rc(e),n=bS.parse(t),o=r.collect(n.worker_id);return o?Rt(hj(o)):Rt(`Worker not found: ${n.worker_id}`,!0)}async function _j(t,e){let r=Rc(e),n=wS.parse(t);return r.stop(n.worker_id),Rt(`Stop signal sent to worker: ${n.worker_id}`)}async function bj(t,e,r){try{switch(t){case"cli_worker_spawn":return await gj(e??{},r);case"cli_worker_status":return await yj(e??{},r);case"cli_worker_collect":return await vj(e??{},r);case"cli_worker_stop":return await _j(e??{},r);default:return Rt(`Unknown tool: ${t}`,!0)}}catch(n){let o=z(n);return Rt(`Error: ${o}`,!0)}}var Qp={};Ve(Qp,{getTools:()=>wj,handleTool:()=>Sj});var xS=h.object({design_doc:h.string().optional().describe("Optional design document path to verify against"),build_profile:h.enum(["auto","tsc","vitest","npm-build","npm-test"]).optional().describe("QA build profile to execute. Defaults to 'auto' which detects from project structure."),timeout_ms:h.number().int().positive().optional().describe("Timeout per command in milliseconds")}).strict();function wj(){return[{name:"qa_run",title:"Run Auto QA",description:"Run automatic QA for the current project. Detects build/test commands, optionally includes a design document reference, and returns a PASS/FAIL summary with captured output.",inputSchema:q(xS)}]}function xj(t){let e=`# Auto QA
638
+ `),e}async function vj(t,e){let r=Rc(e),n=bS.parse(t),o=r.knownProviders();if(!o.includes(n.provider))return Rt(`Unknown provider: "${n.provider}". Known: [${o.join(", ")}]`,!0);let s={provider:n.provider,taskDescription:n.task_description,workingDir:n.working_dir,filesToRead:n.files_to_read,filesToModify:n.files_to_modify,constraints:n.constraints,successCriteria:n.success_criteria,timeoutMinutes:n.timeout_minutes,useWorktree:n.use_worktree,useTmux:n.use_tmux};try{let i=r.spawn(s);return Rt(mj(i))}catch(i){let a=M(i);return Rt(`Error spawning worker: ${a}`,!0)}}async function _j(t,e){let r=Rc(e),n=wS.parse(t);if(!n.worker_id){let s=r.listAll();return Rt(gj(s))}let o=r.getStatus(n.worker_id);return o?Rt(hj(o)):Rt(`Worker not found: ${n.worker_id}`,!0)}async function bj(t,e){let r=Rc(e),n=xS.parse(t),o=r.collect(n.worker_id);return o?Rt(yj(o)):Rt(`Worker not found: ${n.worker_id}`,!0)}async function wj(t,e){let r=Rc(e),n=SS.parse(t);return r.stop(n.worker_id),Rt(`Stop signal sent to worker: ${n.worker_id}`)}async function xj(t,e,r){try{switch(t){case"cli_worker_spawn":return await vj(e??{},r);case"cli_worker_status":return await _j(e??{},r);case"cli_worker_collect":return await bj(e??{},r);case"cli_worker_stop":return await wj(e??{},r);default:return Rt(`Unknown tool: ${t}`,!0)}}catch(n){let o=M(n);return Rt(`Error: ${o}`,!0)}}var ef={};Be(ef,{getTools:()=>Sj,handleTool:()=>kj});var $S=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 Sj(){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($S)}]}function $j(t){let e=`# Auto QA
639
639
 
640
640
  ${t.summary}
641
641
  `;return t.designDoc&&(e+=`
@@ -652,12 +652,12 @@ ${t.buildOutput||"(no output)"}
652
652
  \`\`\`
653
653
  ${t.testOutput||"(no output)"}
654
654
  \`\`\`
655
- `,e}async function Sj(t,e,r){if(t==="qa_run"){let n=xS.parse(e??{}),s=await new No(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:xj(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var kS=[Tp,Up,qp,Vp,Wp,Hp,Kp,Jp,Yp,Xp,Qp];function PS(){let t=[];for(let e of kS)t.push(...e.getTools());return t}var $S=new Map;function kj(t){return t.sessionId??"__default__"}function Pj(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return $j(e.uri)}catch{}}async function Tj(t,e,r){let n=kj(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=Pj(o.roots);if(s)return $S.set(n,s),s}catch{}return $S.get(n)??e.workspaceBaseDir??process.cwd()}function Ej(t,e){return t.filter(r=>TS(r.name,e))}function Rj(t,e){let r=ir(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return si(n)}function TS(t,e){let r=e.registry.getAvailable(),n=r.length>0,o=r.some(i=>i.type==="ollama"),s=r.some(i=>Rj(i,e.providerPolicies));return t.startsWith("ollama_")?o:t.startsWith("cli_worker_")||t.startsWith("agent_changes_")?s&&e.cliWorkerManager!==void 0:t.startsWith("ai_")||t.startsWith("agent_debate_")||t==="agent_cross_validate"?n:!0}function Ij(t,e){let r=[],n=0;for(let o of t){let s=Buffer.byteLength(o,"utf-8");if(n+s>e)break;r.push(o),n+=s}return r.join("")}var ef=null;function Aj(){if(ef)return ef;let t=new Map;for(let e of kS)for(let r of e.getTools())t.set(r.name,e);return ef=t,t}function ES(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:Ij(r.text,51200)+`
655
+ `,e}async function kj(t,e,r){if(t==="qa_run"){let n=$S.parse(e??{}),s=await new jo(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:$j(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var TS=[Ep,qp,Vp,Bp,Hp,Kp,Gp,Jp,Xp,Qp,ef];function ES(){let t=[];for(let e of TS)t.push(...e.getTools());return t}var PS=new Map;function Tj(t){return t.sessionId??"__default__"}function Ej(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return Pj(e.uri)}catch{}}async function Rj(t,e,r){let n=Tj(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=Ej(o.roots);if(s)return PS.set(n,s),s}catch{}return PS.get(n)??e.workspaceBaseDir??process.cwd()}function Ij(t,e){return t.filter(r=>RS(r.name,e))}function Aj(t,e){let r=ir(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return si(n)}function RS(t,e){let r=e.registry.getAvailable(),n=r.length>0,o=r.some(i=>i.type==="ollama"),s=r.some(i=>Aj(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 Cj(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 tf=null;function Dj(){if(tf)return tf;let t=new Map;for(let e of TS)for(let r of e.getTools())t.set(r.name,e);return tf=t,t}function IS(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:Cj(r.text,51200)+`
656
656
 
657
- ... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function RS(t,e,r){let o=Aj().get(t);if(!o)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(!TS(t,r))return{content:[{type:"text",text:`Tool unavailable in current environment: ${t}`}],isError:!0};let s={registry:r.registry,sessionManager:r.sessionManager,documentManager:r.documentManager,jobManager:r.jobManager,traceWriter:r.traceWriter,qualityStatsProvider:r.qualityStatsProvider,cliWorkerManager:r.cliWorkerManager,sessionContext:r.resolveSessionContext?.()??r.sessionContext,workspaceBaseDir:r.workspaceBaseDir,i18n:r.i18n,structuredSessionRegistry:r.structuredSessionRegistry,moderatorEngine:r.moderatorEngine},i=await o.handleTool(t,e,s);return ES(i)}function tf(t){let e=new Qa({name:"agestra",version:lf},{capabilities:{tools:{}}});return e.setRequestHandler($l,async()=>({tools:Ej(PS(),t)})),e.setRequestHandler(us,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await Tj(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await RS(o,s??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${z(i)}`}],isError:!0}}}),e}async function rf(t){let e=new tc;await t.connect(e)}function IS(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function Cj(t){return Array.isArray(t)?t.filter(IS).map(e=>e.text).join(`
657
+ ... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function AS(t,e,r){let o=Dj().get(t);if(!o)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(!RS(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 IS(i)}function rf(t){let e=new Qa({name:"agestra",version:pf},{capabilities:{tools:{}}});return e.setRequestHandler(kl,async()=>({tools:Ij(ES(),t)})),e.setRequestHandler(ls,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await Rj(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await AS(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 nf(t){let e=new tc;await t.connect(e)}function CS(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function zj(t){return Array.isArray(t)?t.filter(CS).map(e=>e.text).join(`
658
658
 
659
- `).trim():IS(t)?t.text:""}function AS(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function CS(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function go(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function nf(t,e,r){let n=()=>go(t.getClientVersion()?.name);return{providerId:e,isAvailable(){return!!t.getClientCapabilities()?.sampling&&n()===r.expectedHostKind},async healthCheck(){if(!t.getClientCapabilities()?.sampling)return{status:"error",message:"Client does not support MCP sampling"};let o=n();return o!==r.expectedHostKind?{status:"error",message:`${r.displayName} host bridge requires a ${r.displayName} host, got ${o}`}:{status:"ok",message:`${r.displayName} host bridge available via ${t.getClientVersion()?.name??"unknown client"}`}},async runTurn(o){if(!this.isAvailable())throw new Error(r.unavailableMessage);let s=await t.createMessage({messages:[{role:"user",content:{type:"text",text:o.prompt}}],systemPrompt:o.system,includeContext:"none",maxTokens:AS(o.metadata,"maxTokens")??4096,temperature:AS(o.metadata,"temperature"),modelPreferences:CS(o.metadata,"model")?{hints:[{name:CS(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=Cj(s.content);if(!i)throw new Error("Claude host bridge returned no text content");return{text:i,metadata:{model:s.model,stopReason:s.stopReason,hostKind:n()}}}}}function Ic(t,e="claude"){return nf(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Ac(t,e="codex-host"){return nf(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Cc(t,e="gemini-host"){return nf(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var Dj=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new _i({id:e,bridge:Ic(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new bi({id:e,bridge:Ac(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new wi({id:e,bridge:Cc(t,e)})}];function yo(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function zj(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function Oj(t,e){switch(t){case"claude-code":return yo(e,"claude-host","claude");case"codex-cli":return yo(e,"codex-host","codex-host");case"gemini-cli":return yo(e,"gemini-host","gemini-host");default:return}}function Mj(t,e){return t.some(o=>o.roles.includes("worker")&&o.supportsAutonomousExecution)?"team":t.some(o=>o.id!==e&&o.supportsReadOnlyChat)&&t.length>1?"debate":"claude-only"}function of(t,e){let r=()=>go(t.getClientVersion()?.name),n=()=>zj(r()),o=()=>Oj(r(),e);return{get id(){return r()},get kind(){return r()},get leaderProviderId(){return o()},get leaderProviderType(){return n()},get supportsHooks(){return r()==="claude-code"},get supportsInteractiveChoices(){return r()!=="unknown"},get supportsSampling(){return!!t.getClientCapabilities()?.sampling},createLeaderBridge(){switch(r()){case"claude-code":{let s=yo(e,"claude-host","claude");return Ic(t,s)}case"codex-cli":{let s=yo(e,"codex-host","codex-host");return Ac(t,s)}case"gemini-cli":{let s=yo(e,"gemini-host","gemini-host");return Cc(t,s)}default:return null}},createHostProviders(){let s=r();return Dj.flatMap(i=>{if(s==="unknown"||!i.supportedHosts.includes(s))return[];let a=e?.providers.find(u=>u.type===i.type||u.id===i.defaultId);if(a?.enabled===!1)return[];let c=a?.id??i.defaultId;return[{id:c,type:i.type,executionPolicy:a?.executionPolicy??Jt(i.type),provider:i.createProvider(t,c)}]})},createSessionContext(s){let i=s.filter(u=>u.supportsReadOnlyChat);if(i.length===0)return;let a=o(),c=(a?i.find(u=>u.id===a):void 0)??(n()?i.find(u=>u.type===n()):void 0)??i.find(u=>u.roles.includes("leader"))??i[0];return{hostId:r(),hostKind:r(),leaderProviderId:c.id,participantProviderIds:i.map(u=>u.id),executionMode:Mj(i,c.id)}}}}async function sf(t,e,r,n){let o=t.createHostProviders();for(let s of o)e.has(s.id)||(await s.provider.initialize(),e.register(s.provider),r.set(s.id,s.executionPolicy),n(`Registered provider: ${s.id} (${s.type})`))}function af(t,e){let r=typeof e.getAvailableDescriptors=="function"?e.getAvailableDescriptors():e.getAvailable().map(n=>typeof e.getDescriptor=="function"?e.getDescriptor(n.id):{id:n.id,type:n.type,invocation:"unknown",roles:["participant"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0,supportsToolUse:n.getCapabilities().supportsToolUse});return t.createSessionContext?.(r)}import{existsSync as DS}from"fs";import{dirname as MS,join as zS,resolve as NS}from"path";import{fileURLToPath as Nj}from"url";function jj(t){return DS(zS(t,"package.json"))&&DS(zS(t,"AGENTS.md"))}function OS(t){let e=NS(t);for(;;){if(jj(e))return e;let r=MS(e);if(r===e)return null;e=r}}function Lj(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return NS(t);let e=MS(Nj(import.meta.url));return OS(process.cwd())??OS(e)??process.cwd()}function jS(){let t=Lj();return process.cwd()!==t&&process.chdir(t),t}var Uj={ollama:t=>new Gr({id:t.id,host:t.config?.host||vo}),"gemini-cli":t=>new Yr({id:t.id,timeout:t.config?.timeout}),"codex-cli":t=>new Xr({id:t.id,timeout:t.config?.timeout}),"claude-cli":t=>new Qr({id:t.id,timeout:t.config?.timeout})};async function qj(t,e,r){if(t.getAll().length>0)return r("Providers already registered, skipping auto-detect."),{detected:0};r("No providers found \u2014 running auto-detect...");try{let{results:n,providers:o}=await ho(),s=n.filter(i=>i.available);return s.length===0?(r("Auto-detect found no available providers."),{detected:0}):(cS(o,t),r(`Auto-detected ${s.length} provider(s): ${s.map(i=>i.id).join(", ")}`),{detected:s.length})}catch(n){return r(`Auto-detect failed (non-fatal): ${z(n)}`),{detected:0}}}async function Vj(){let t=y=>process.stderr.write(`[mcp-server] ${y}
660
- `),e=jS(),r=$o(),n;try{let y=Fj(r,"utf-8");n=JSON.parse(y)}catch(y){t(`Warning: Could not load ${r}: ${z(y)}`),t("Starting with empty provider registry."),n=null}let o=new Qs,s=null;if(n)try{s=Zf(n)}catch(y){t(`Warning: Invalid provider config in ${r}: ${z(y)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}if(s){let y=s.enabledProviders.map($=>{let M=Uj[$.type];if(!M)return t(`Unknown provider type: ${$.type} (id: ${$.id}), skipping`),null;let O=M($);return{pc:$,provider:O}}).filter($=>$!==null),x=await Promise.allSettled(y.map(async({pc:$,provider:M})=>(await M.initialize(),{pc:$,provider:M})));for(let $ of x)if($.status==="fulfilled"){let{pc:M,provider:O}=$.value;o.register(O),t(`Registered provider: ${M.id} (${M.type})`)}else t(`Failed to initialize provider: ${z($.reason)}`)}if(await qj(o,e,t),s){let y=new Set(s.providers.filter($=>!$.enabled).map($=>$.id)),x=new Set(s.providers.filter($=>!$.enabled).map($=>$.type));try{let{providers:$}=await ho(),M=Bp($,o,{excludeIds:y,excludeTypes:x});for(let O of M)t(`Registered newly detected provider: ${O.id} (${O.type})`)}catch($){t(`Supplemental provider detection failed (non-fatal): ${z($)}`)}}let i=new Map(s?.providers.map(y=>[y.id,y.executionPolicy])??[]),a=new Map(o.getAll().map(y=>[y.id,i.get(y.id)??Jt(y.type)])),c;try{c=lu(s?.locale)}catch(y){let x=y instanceof Error?y.message:String(y);t(`[i18n] failed to load requested locale (${s?.locale??"default"}): ${x}. Retrying with default bundle.`),c=lu(void 0)}t(`Localization active: ${c.locale}`);let u=new Map,l=()=>"unknown",d=async y=>{let x=u.get(y);if(x)return x;let $=new zo(cf(y,hf)),M=new Zo(cf(y,_o)),O=new li(y,{completionHandler:async({descriptor:It,result:Dc,saveAsDocument:zc})=>!Dc.output||Dc.output.trim().length===0?null:{documentId:(await M.createDocument({title:zc.title,content:Dc.output,metadata:{...zc.metadata,Provider:It.provider,Model:It.provider,JobId:It.id},kind:zc.kind})).id}});try{let It=O.reconcileOrphans();It>0&&t(`Reconciled ${It} orphaned job(s) in ${y}`)}catch(It){t(`Job orphan reconcile failed for ${y}: ${z(It)}`)}let Y=new di(y);Y.cleanup(30);let Pe=new gi(Y,{ttlMs:6e4}),K=new Ao(y,{providerPolicies:a}),ot=new fo(cf(y,_o));try{await ot.hydrateFromDisk()}catch(It){t(`Structured session registry hydrate failed for ${y}: ${z(It)}`)}let Re=Sc(o,l()),Pr=new mo({bridge:Re,documentManager:M,registry:ot,i18n:c,traceWriter:Y}),Tr={sessionManager:$,documentManager:M,jobManager:O,traceWriter:Y,qualityStatsProvider:Pe,cliWorkerManager:K,structuredSessionRegistry:ot,moderatorEngine:Pr};return u.set(y,Tr),Tr},p=await d(e),f={registry:o,...p,providerPolicies:a,workspaceBaseDir:e,resolveWorkspaceServices:async y=>d(y),i18n:c},m=tf(f),g=of(m,s);l=()=>go(m.getClientVersion()?.name),await sf(g,o,a,t),f.resolveSessionContext=()=>af(g,o);let v=setInterval(()=>{(async()=>{for(let y of u.values())try{let x=await y.structuredSessionRegistry.sweepTimeouts();x.length>0&&await y.moderatorEngine.handleTimedOutSnapshots(x)}catch(x){t(`Session sweep failed: ${z(x)}`)}})()},kf);v.unref?.();let _=!1,S=async()=>{if(!_){_=!0,t("Shutting down..."),clearInterval(v);for(let y of u.values())y.traceWriter.shutdown();for(let y of o.getAll())if(y.shutdown)try{await y.shutdown()}catch{}}};process.on("SIGTERM",()=>{S().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{S().finally(()=>process.exit(0))}),process.on("uncaughtException",y=>{for(let x of u.values())x.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${y}
661
- `),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await rf(m),t("MCP server connected via stdio.")}var Bj=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=Zj(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();Bj&&Vj().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
662
- `),process.exit(1)});export{qj as autoDetectIfNeeded,PS as collectTools,rf as connectStdio,Ic as createClaudeLeaderBridge,Ac as createCodexLeaderBridge,Cc as createGeminiLeaderBridge,of as createRuntimeHostAdapter,tf as createServer,RS as dispatch,go as inferHostKindFromClientName,sf as registerHostBackedProviders,af as resolveSessionContext,ES as truncateResponse};
659
+ `).trim():CS(t)?t.text:""}function DS(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function zS(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function yo(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function of(t,e,r){let n=()=>yo(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:DS(o.metadata,"maxTokens")??4096,temperature:DS(o.metadata,"temperature"),modelPreferences:zS(o.metadata,"model")?{hints:[{name:zS(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=zj(s.content);if(!i)throw new Error("Claude host bridge returned no text content");return{text:i,metadata:{model:s.model,stopReason:s.stopReason,hostKind:n()}}}}}function Ic(t,e="claude"){return of(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Ac(t,e="codex-host"){return of(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Cc(t,e="gemini-host"){return of(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var Oj=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new _i({id:e,bridge:Ic(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new bi({id:e,bridge:Ac(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new wi({id:e,bridge:Cc(t,e)})}];function vo(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function Mj(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function Nj(t,e){switch(t){case"claude-code":return vo(e,"claude-host","claude");case"codex-cli":return vo(e,"codex-host","codex-host");case"gemini-cli":return vo(e,"gemini-host","gemini-host");default:return}}function jj(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 sf(t,e){let r=()=>yo(t.getClientVersion()?.name),n=()=>Mj(r()),o=()=>Nj(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=vo(e,"claude-host","claude");return Ic(t,s)}case"codex-cli":{let s=vo(e,"codex-host","codex-host");return Ac(t,s)}case"gemini-cli":{let s=vo(e,"gemini-host","gemini-host");return Cc(t,s)}default:return null}},createHostProviders(){let s=r();return Oj.flatMap(i=>{if(s==="unknown"||!i.supportedHosts.includes(s))return[];let a=e?.providers.find(u=>u.type===i.type||u.id===i.defaultId);if(a?.enabled===!1)return[];let c=a?.id??i.defaultId;return[{id:c,type:i.type,executionPolicy:a?.executionPolicy??Jt(i.type),provider:i.createProvider(t,c)}]})},createSessionContext(s){let i=s.filter(u=>u.supportsReadOnlyChat);if(i.length===0)return;let a=o(),c=(a?i.find(u=>u.id===a):void 0)??(n()?i.find(u=>u.type===n()):void 0)??i.find(u=>u.roles.includes("leader"))??i[0];return{hostId:r(),hostKind:r(),leaderProviderId:c.id,participantProviderIds:i.map(u=>u.id),executionMode:jj(i,c.id)}}}}async function af(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 cf(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 OS}from"fs";import{dirname as NS,join as Dc,resolve as jS,sep as Lj}from"path";import{fileURLToPath as Fj}from"url";var Zj=[Dc(".claude","plugins","cache"),Dc(".claude","plugins","local")];function Uj(t){let e=t.split(/[\\/]/).join(Lj);return Zj.some(r=>e.includes(r))}function qj(t){return!(!OS(Dc(t,"package.json"))||!OS(Dc(t,"AGENTS.md"))||Uj(t))}function MS(t){let e=jS(t);for(;;){if(qj(e))return e;let r=NS(e);if(r===e)return null;e=r}}function LS(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return jS(t);let e=NS(Fj(import.meta.url));return MS(process.cwd())??MS(e)??process.cwd()}function Wj(t){return{ollama:e=>new Gr({id:e.id,host:e.config?.host||_o}),"gemini-cli":e=>new Jr({id:e.id,timeout:e.config?.timeout}),"codex-cli":e=>new Yr({id:e.id,timeout:e.config?.timeout,workspaceBaseDir:t}),"claude-cli":e=>new Xr({id:e.id,timeout:e.config?.timeout})}}async function Hj(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 go({workspaceBaseDir:e}),s=n.filter(i=>i.available);return s.length===0?(r("Auto-detect found no available providers."),{detected:0}):(lS(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 Kj(){let t=_=>process.stderr.write(`[mcp-server] ${_}
660
+ `),e=LS(),r=ko(),n;try{let _=Vj(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 Qs,s=null;if(n)try{s=qf(n)}catch(_){t(`Warning: Invalid provider config in ${r}: ${M(_)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}let i=Wj(e);if(s){let _=s.enabledProviders.map(A=>{let D=i[A.type];if(!D)return t(`Unknown provider type: ${A.type} (id: ${A.id}), skipping`),null;let U=D(A);return{pc:A,provider:U}}).filter(A=>A!==null),P=await Promise.allSettled(_.map(async({pc:A,provider:D})=>(await D.initialize(),{pc:A,provider:D})));for(let A of P)if(A.status==="fulfilled"){let{pc:D,provider:U}=A.value;o.register(U),t(`Registered provider: ${D.id} (${D.type})`)}else t(`Failed to initialize provider: ${M(A.reason)}`)}if(await Hj(o,e,t),s){let _=new Set(s.providers.filter(A=>!A.enabled).map(A=>A.id)),P=new Set(s.providers.filter(A=>!A.enabled).map(A=>A.type));try{let{providers:A}=await go({workspaceBaseDir:e}),D=Wp(A,o,{excludeIds:_,excludeTypes:P});for(let U of D)t(`Registered newly detected provider: ${U.id} (${U.type})`)}catch(A){t(`Supplemental provider detection failed (non-fatal): ${M(A)}`)}}let a=new Map(s?.providers.map(_=>[_.id,_.executionPolicy])??[]),c=new Map(o.getAll().map(_=>[_.id,a.get(_.id)??Jt(_.type)])),u;try{u=du(s?.locale)}catch(_){let P=_ instanceof Error?_.message:String(_);t(`[i18n] failed to load requested locale (${s?.locale??"default"}): ${P}. Retrying with default bundle.`),u=du(void 0)}t(`Localization active: ${u.locale}`);let l=new Map,d=()=>"unknown",p=async _=>{let P=l.get(_);if(P)return P;let A=new Oo(uf(_,yf)),D=new Uo(uf(_,bo)),U=new li(_,{completionHandler:async({descriptor:It,result:zc,saveAsDocument:Oc})=>!zc.output||zc.output.trim().length===0?null:{documentId:(await D.createDocument({title:Oc.title,content:zc.output,metadata:{...Oc.metadata,Provider:It.provider,Model:It.provider,JobId:It.id},kind:Oc.kind})).id}});try{let It=U.reconcileOrphans();It>0&&t(`Reconciled ${It} orphaned job(s) in ${_}`)}catch(It){t(`Job orphan reconcile failed for ${_}: ${M(It)}`)}let $e=new di(_);$e.cleanup(30);let G=new gi($e,{ttlMs:6e4}),_t=new Co(_,{providerPolicies:c}),Te=new fo(uf(_,bo));try{await Te.hydrateFromDisk()}catch(It){t(`Structured session registry hydrate failed for ${_}: ${M(It)}`)}let Pr=Sc(o,d(),_),fn=new mo({bridge:Pr,documentManager:D,registry:Te,i18n:u,traceWriter:$e}),lf={sessionManager:A,documentManager:D,jobManager:U,traceWriter:$e,qualityStatsProvider:G,cliWorkerManager:_t,structuredSessionRegistry:Te,moderatorEngine:fn};return l.set(_,lf),lf},f=await p(e),m={registry:o,...f,providerPolicies:c,workspaceBaseDir:e,resolveWorkspaceServices:async _=>p(_),i18n:u},g=rf(m),y=sf(g,s);d=()=>yo(g.getClientVersion()?.name),await af(y,o,c,t),m.resolveSessionContext=()=>cf(y,o);let v=setInterval(()=>{(async()=>{for(let _ of l.values())try{let P=await _.structuredSessionRegistry.sweepTimeouts();P.length>0&&await _.moderatorEngine.handleTimedOutSnapshots(P)}catch(P){t(`Session sweep failed: ${M(P)}`)}})()},Tf);v.unref?.();let S=!1,w=async()=>{if(!S){S=!0,t("Shutting down..."),clearInterval(v);for(let _ of l.values())_.traceWriter.shutdown();for(let _ of o.getAll())if(_.shutdown)try{await _.shutdown()}catch{}}};process.on("SIGTERM",()=>{w().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{w().finally(()=>process.exit(0))}),process.on("uncaughtException",_=>{for(let P of l.values())P.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${_}
661
+ `),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await nf(g),t("MCP server connected via stdio.")}var Gj=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=Bj(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();Gj&&Kj().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
662
+ `),process.exit(1)});export{Hj as autoDetectIfNeeded,ES as collectTools,nf as connectStdio,Ic as createClaudeLeaderBridge,Ac as createCodexLeaderBridge,Cc as createGeminiLeaderBridge,sf as createRuntimeHostAdapter,rf as createServer,AS as dispatch,yo as inferHostKindFromClientName,af as registerHostBackedProviders,cf as resolveSessionContext,IS as truncateResponse};
663
663
  //# sourceMappingURL=bundle.js.map