diff --git a/launcher/banner.py b/launcher/banner.py index 37dd15fa..c43e6e90 100644 Binary files a/launcher/banner.py and b/launcher/banner.py differ diff --git a/pilot/commands/spec-bugfix-plan.md b/pilot/commands/spec-bugfix-plan.md index 53d03ef6..f747a779 100644 --- a/pilot/commands/spec-bugfix-plan.md +++ b/pilot/commands/spec-bugfix-plan.md @@ -321,20 +321,27 @@ Type: Bugfix CODEX_COMPANION=$(ls ~/.claude/plugins/cache/openai-codex/codex/*/scripts/codex-companion.mjs 2>/dev/null | head -1) ``` -2. Launch adversarial review: +2. Launch adversarial review with specific focus text: ```bash -node "$CODEX_COMPANION" adversarial-review --background --base main "Adversarial review of bugfix plan: " +node "$CODEX_COMPANION" adversarial-review --background --base main "Challenge this bugfix plan: . Plan: . Focus on: wrong root cause, incomplete fix, missing edge cases, regression risk, and whether the fix addresses symptoms vs cause." ``` -3. Collect results: +3. Wait for completion: ```bash node "$CODEX_COMPANION" status --wait --timeout-ms 120000 --json ``` -4. **Handle Codex result:** +4. **Handle status:** - `waitTimedOut: true` → Log "Codex review timed out — skipping" and continue. - `job.status` is `"cancelled"` or exit code non-zero → Log "Codex review failed: " and continue. - - `job.status` is `"completed"` → Parse output. Map severities: critical/high → must_fix, medium/low → should_fix. Fix all must_fix/should_fix in the plan. + - `job.status` is `"completed"` → fetch full result: + +5. Get review findings: +```bash +node "$CODEX_COMPANION" result --json +``` + +6. Parse the result JSON — look for `verdict`, `findings`, `details`. Map severities: critical/high → must_fix, medium/low → should_fix. Fix all must_fix/should_fix in the plan. --- diff --git a/pilot/commands/spec-plan.md b/pilot/commands/spec-plan.md index 74cf0ae4..111aacfc 100644 --- a/pilot/commands/spec-plan.md +++ b/pilot/commands/spec-plan.md @@ -426,9 +426,9 @@ Launch Codex review NOW — it runs in parallel with the Claude reviewer above. CODEX_COMPANION=$(ls ~/.claude/plugins/cache/openai-codex/codex/*/scripts/codex-companion.mjs 2>/dev/null | head -1) ``` -2. Launch adversarial review in background: +2. Launch adversarial review in background. Include the plan's goal/summary as focus text so Codex knows what to challenge: ```bash -node "$CODEX_COMPANION" adversarial-review --background --base main "Adversarial review of plan: " +node "$CODEX_COMPANION" adversarial-review --background --base main "Challenge this plan: . Plan file: . Focus on: wrong assumptions, missing edge cases, scope gaps, and design choices that could fail under real-world conditions." ``` Capture the job ID from stdout. **Do NOT wait** — proceed to collect whichever reviewer finishes first. @@ -451,14 +451,22 @@ Then Read the file once. If not READY after 5 min, re-launch synchronously. **If Codex was launched above**, collect its results now: +1. Wait for completion: ```bash node "$CODEX_COMPANION" status --wait --timeout-ms 120000 --json ``` -**Handle Codex result:** -- `waitTimedOut: true` → Codex timed out. Log "Codex review timed out — skipping" and continue without Codex findings. -- `job.status` is `"cancelled"` or exit code non-zero → Codex crashed/failed. Log "Codex review failed: " and continue without Codex findings. -- `job.status` is `"completed"` → Parse output. Map severities: critical/high → must_fix, medium/low → should_fix. Fix all must_fix/should_fix. +2. **Handle status:** + - `waitTimedOut: true` → Log "Codex review timed out — skipping" and continue. + - `job.status` is `"cancelled"` or exit code non-zero → Log "Codex review failed: " and continue. + - `job.status` is `"completed"` → fetch the full result: + +3. Get review findings: +```bash +node "$CODEX_COMPANION" result --json +``` + +4. Parse the result JSON — look for `verdict`, `findings`, `details`. Map severities: critical/high → must_fix, medium/low → should_fix. Fix all must_fix/should_fix. **If Codex was NOT launched**, proceed after all Claude reviewer must_fix/should_fix resolved. diff --git a/pilot/commands/spec-verify.md b/pilot/commands/spec-verify.md index dd12c195..8911b24b 100644 --- a/pilot/commands/spec-verify.md +++ b/pilot/commands/spec-verify.md @@ -119,12 +119,13 @@ Task( run_in_background=true, prompt=""" **Plan file:** + **User request:** **Changed files:** [file list] **Output path:** **Runtime environment:** [how to start, port, deploy path] **Test framework constraints:** [what it can/cannot test] - Review implementation: compliance (plan match), quality (security, bugs, tests, performance), goal (achievement, artifacts, wiring). + Review implementation: compliance (plan match + user request match), quality (security, bugs, tests, performance), goal (achievement, artifacts, wiring). Performance: check for expensive uncached work on hot paths, heavy dependency imports with lighter alternatives, and repeated invocations that redo work when input hasn't changed. Write findings JSON to output_path using Write tool. IMPORTANT: Include the plan file path in your output JSON as the "plan_file" field. @@ -145,9 +146,9 @@ Launch Codex review NOW — it runs in parallel with the Claude reviewer above. CODEX_COMPANION=$(ls ~/.claude/plugins/cache/openai-codex/codex/*/scripts/codex-companion.mjs 2>/dev/null | head -1) ``` -2. Launch adversarial review in background using `--scope working-tree` (reviews all uncommitted changes regardless of staging state — works in both worktree and non-worktree mode): +2. Launch adversarial review in background using `--scope working-tree` (reviews all uncommitted changes regardless of staging state — works in both worktree and non-worktree mode). Include the plan's goal as focus text: ```bash -node "$CODEX_COMPANION" adversarial-review --background --scope working-tree "Review changes against spec: " +node "$CODEX_COMPANION" adversarial-review --background --scope working-tree "Challenge this implementation: . Plan: . Focus on: wrong approach, missing edge cases, security gaps, untested paths, and design choices that could fail under load." ``` Capture the job ID from stdout. **Do NOT wait** — proceed to Step 3.2 immediately. @@ -207,14 +208,22 @@ For each fix: implement → run relevant tests → log "Fixed: [title]" **If Codex was launched in Step 3.1**, collect its results now: +1. Wait for completion: ```bash node "$CODEX_COMPANION" status --wait --timeout-ms 120000 --json ``` -**Handle Codex result:** -- `waitTimedOut: true` → Codex timed out. Log "Codex review timed out — skipping" and continue without Codex findings. -- `job.status` is `"cancelled"` or exit code non-zero → Codex crashed/failed. Log "Codex review failed: " and continue without Codex findings. -- `job.status` is `"completed"` → Parse output. Map severities: critical/high → must_fix, medium/low → should_fix. Fix all must_fix/should_fix. +2. **Handle status:** + - `waitTimedOut: true` → Log "Codex review timed out — skipping" and continue. + - `job.status` is `"cancelled"` or exit code non-zero → Log "Codex review failed: " and continue. + - `job.status` is `"completed"` → fetch the full result: + +3. Get review findings: +```bash +node "$CODEX_COMPANION" result --json +``` + +4. Parse the result JSON — look for `verdict`, `findings`, `details`. Map severities: critical/high → must_fix, medium/low → should_fix. Fix all must_fix/should_fix. **Report:** ``` diff --git a/pilot/scripts/mcp-server.cjs b/pilot/scripts/mcp-server.cjs index 37853044..a5dccd4e 100755 --- a/pilot/scripts/mcp-server.cjs +++ b/pilot/scripts/mcp-server.cjs @@ -41,7 +41,7 @@ ${s.stack}`:` ${s.message}`:this.getLevel()===0&&typeof s=="object"?l=` path: iss.path ? [${mt(b)}, ...iss.path] : [${mt(b)}] })));`),p.write(`newResult[${mt(b)}] = ${$}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let v=p.compile();return(b,$)=>v(d,b,$)},n,s=Pt,i=!to.jitless,c=i&&jn.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let g=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)n||(n=o(e.shape)),d=n(d,p);else{d.value={};let $=l.shape;for(let k of l.keys){let T=$[k],he=T._zod.run({value:f[k],issues:[]},p),ze=T._zod.optin==="optional"&&T._zod.optout==="optional";he instanceof Promise?g.push(he.then(Tt=>ze?qc(Tt,d,k,f):co(Tt,d,k))):ze?qc(he,d,k,f):co(he,d,k)}}if(!u)return g.length?Promise.all(g).then(()=>d):d;let _=[],y=l.keySet,v=u._zod,b=v.def.type;for(let $ of Object.keys(f)){if(y.has($))continue;if(b==="never"){_.push($);continue}let k=v.run({value:f[$],issues:[]},p);k instanceof Promise?g.push(k.then(T=>co(T,d,$))):co(k,d,$)}return _.length&&d.issues.push({code:"unrecognized_keys",keys:_,input:f,inst:t}),g.length?Promise.all(g).then(()=>d):d}});function Mc(t,e,r,o){for(let n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(s=>Ne(s,o,ke())))}),e}var Xn=h("$ZodUnion",(t,e)=>{K.init(t,e),H(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),H(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),H(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),H(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>or(o.source)).join("|")})$`)}}),t._zod.parse=(r,o)=>{let n=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},o);if(a instanceof Promise)s.push(a),n=!0;else{if(a.issues.length===0)return a;s.push(a)}}return n?Promise.all(s).then(i=>Mc(i,r,t,o)):Mc(s,r,t,o)}}),zu=h("$ZodDiscriminatedUnion",(t,e)=>{Xn.init(t,e);let r=t._zod.parse;H(t._zod,"propValues",()=>{let n={};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)){n[a]||(n[a]=new Set);for(let u of c)n[a].add(u)}}return n});let o=tr(()=>{let n=e.options,s=new Map;for(let i of n){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=(n,s)=>{let i=n.value;if(!Pt(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),n;let a=o.value.get(i?.[e.discriminator]);return a?a._zod.run(n,s):e.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),n)}}),ku=h("$ZodIntersection",(t,e)=>{K.init(t,e),t._zod.parse=(r,o)=>{let n=r.value,s=e.left._zod.run({value:n,issues:[]},o),i=e.right._zod.run({value:n,issues:[]},o);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Uc(r,c,u)):Uc(r,s,i)}});function Jn(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(Ot(t)&&Ot(e)){let r=Object.keys(e),o=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(let s of o){let i=Jn(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};n[s]=i.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o{K.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;if(!Ot(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,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:n[c],issues:[]},o);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Me(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Me(c,u.issues)),r.value[c]=u.value)}let a;for(let c in n)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(n)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},o);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=>Ne(u,o,ke())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:n[i],issues:[]},o);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Me(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Me(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Tu=h("$ZodEnum",(t,e)=>{K.init(t,e);let r=Nn(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(o=>Ln.has(typeof o)).map(o=>typeof o=="string"?rt(o):o.toString()).join("|")})$`),t._zod.parse=(o,n)=>{let s=o.value;return t._zod.values.has(s)||o.issues.push({code:"invalid_value",values:r,input:s,inst:t}),o}}),Pu=h("$ZodLiteral",(t,e)=>{K.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?rt(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,o)=>{let n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:e.values,input:n,inst:t}),r}});var Ou=h("$ZodTransform",(t,e)=>{K.init(t,e),t._zod.parse=(r,o)=>{let n=e.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(i=>(r.value=i,r));if(n instanceof Promise)throw new Be;return r.value=n,r}}),Iu=h("$ZodOptional",(t,e)=>{K.init(t,e),t._zod.optin="optional",t._zod.optout="optional",H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),H(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${or(r.source)})?$`):void 0}),t._zod.parse=(r,o)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,o):r.value===void 0?r:e.innerType._zod.run(r,o)}),Ru=h("$ZodNullable",(t,e)=>{K.init(t,e),H(t._zod,"optin",()=>e.innerType._zod.optin),H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${or(r.source)}|null)$`):void 0}),H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,o)=>r.value===null?r:e.innerType._zod.run(r,o)}),Nu=h("$ZodDefault",(t,e)=>{K.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>Fc(s,e)):Fc(n,e)}});function Fc(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Au=h("$ZodPrefault",(t,e)=>{K.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,o))}),Cu=h("$ZodNonOptional",(t,e)=>{K.init(t,e),H(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),t._zod.parse=(r,o)=>{let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>Vc(s,t)):Vc(n,t)}});function Vc(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 Du=h("$ZodCatch",(t,e)=>{K.init(t,e),t._zod.optin="optional",H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,o)=>{let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Ne(i,o,ke()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>Ne(s,o,ke()))},input:r.value}),r.issues=[]),r)}});var ju=h("$ZodPipe",(t,e)=>{K.init(t,e),H(t._zod,"values",()=>e.in._zod.values),H(t._zod,"optin",()=>e.in._zod.optin),H(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,o)=>{let n=e.in._zod.run(r,o);return n instanceof Promise?n.then(s=>Hc(s,e,o)):Hc(n,e,o)}});function Hc(t,e,r){return ht(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Lu=h("$ZodReadonly",(t,e)=>{K.init(t,e),H(t._zod,"propValues",()=>e.innerType._zod.propValues),H(t._zod,"values",()=>e.innerType._zod.values),H(t._zod,"optin",()=>e.innerType._zod.optin),H(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,o)=>{let n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(Kc):Kc(n)}});function Kc(t){return t.value=Object.freeze(t.value),t}var Zu=h("$ZodCustom",(t,e)=>{de.init(t,e),K.init(t,e),t._zod.parse=(r,o)=>r,t._zod.check=r=>{let o=r.value,n=e.fn(o);if(n instanceof Promise)return n.then(s=>Wc(s,r,o,t));Wc(n,r,o,t)}});function Wc(t,e,r,o){if(!t){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),e.issues.push(Mn(n))}}var Lm=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},Zm=()=>{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(o){return t[o]??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 o=>{switch(o.code){case"invalid_type":return`Invalid input: expected ${o.expected}, received ${Lm(o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${no(o.values[0])}`:`Invalid option: expected one of ${ro(o.values,"|")}`;case"too_big":{let n=o.inclusive?"<=":"<",s=e(o.origin);return s?`Too big: expected ${o.origin??"value"} to have ${n}${o.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${n}${o.maximum.toString()}`}case"too_small":{let n=o.inclusive?">=":">",s=e(o.origin);return s?`Too small: expected ${o.origin} to have ${n}${o.minimum.toString()} ${s.unit}`:`Too small: expected ${o.origin} to be ${n}${o.minimum.toString()}`}case"invalid_format":{let n=o;return n.format==="starts_with"?`Invalid string: must start with "${n.prefix}"`:n.format==="ends_with"?`Invalid string: must end with "${n.suffix}"`:n.format==="includes"?`Invalid string: must include "${n.includes}"`:n.format==="regex"?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${r[n.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${ro(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function qu(){return{localeError:Zm()}}var Qn=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let o=r[0];if(this._map.set(e,o),o&&typeof o=="object"&&"id"in o){if(this._idmap.has(o.id))throw new Error(`ID ${o.id} already exists in the registry`);this._idmap.set(o.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 o={...this.get(r)??{}};return delete o.id,{...o,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function qm(){return new Qn}var ar=qm();function Mu(t,e){return new t({type:"string",...E(e)})}function Uu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...E(e)})}function es(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...E(e)})}function Fu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...E(e)})}function Vu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(e)})}function Hu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(e)})}function Ku(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(e)})}function Wu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...E(e)})}function Gu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...E(e)})}function Bu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(e)})}function Ju(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...E(e)})}function Yu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(e)})}function Xu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...E(e)})}function Qu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...E(e)})}function el(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(e)})}function tl(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(e)})}function rl(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(e)})}function ol(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(e)})}function nl(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(e)})}function sl(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...E(e)})}function il(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...E(e)})}function al(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...E(e)})}function cl(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...E(e)})}function ul(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(e)})}function ll(t,e){return new t({type:"string",format:"date",check:"string_format",...E(e)})}function dl(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...E(e)})}function pl(t,e){return new t({type:"string",format:"duration",check:"string_format",...E(e)})}function fl(t,e){return new t({type:"number",checks:[],...E(e)})}function ml(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...E(e)})}function hl(t,e){return new t({type:"boolean",...E(e)})}function gl(t,e){return new t({type:"null",...E(e)})}function _l(t){return new t({type:"unknown"})}function yl(t,e){return new t({type:"never",...E(e)})}function lo(t,e){return new Gn({check:"less_than",...E(e),value:t,inclusive:!1})}function cr(t,e){return new Gn({check:"less_than",...E(e),value:t,inclusive:!0})}function po(t,e){return new Bn({check:"greater_than",...E(e),value:t,inclusive:!1})}function ur(t,e){return new Bn({check:"greater_than",...E(e),value:t,inclusive:!0})}function fo(t,e){return new zc({check:"multiple_of",...E(e),value:t})}function mo(t,e){return new Ec({check:"max_length",...E(e),maximum:t})}function It(t,e){return new Tc({check:"min_length",...E(e),minimum:t})}function ho(t,e){return new Pc({check:"length_equals",...E(e),length:t})}function ts(t,e){return new Oc({check:"string_format",format:"regex",...E(e),pattern:t})}function rs(t){return new Ic({check:"string_format",format:"lowercase",...E(t)})}function os(t){return new Rc({check:"string_format",format:"uppercase",...E(t)})}function ns(t,e){return new Nc({check:"string_format",format:"includes",...E(e),includes:t})}function ss(t,e){return new Ac({check:"string_format",format:"starts_with",...E(e),prefix:t})}function is(t,e){return new Cc({check:"string_format",format:"ends_with",...E(e),suffix:t})}function gt(t){return new Dc({check:"overwrite",tx:t})}function as(t){return gt(e=>e.normalize(t))}function cs(){return gt(t=>t.trim())}function us(){return gt(t=>t.toLowerCase())}function ls(){return gt(t=>t.toUpperCase())}function vl(t,e,r){return new t({type:"array",element:e,...E(r)})}function $l(t,e,r){let o=E(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function bl(t,e,r){return new t({type:"custom",check:"custom",fn:e,...E(r)})}function Rt(t){return!!t._zod}function ot(t,e){return Rt(t)?sr(t,e):t.safeParse(e)}function go(t){if(!t)return;let e;if(Rt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Sl(t){if(Rt(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 o=t.value;if(o!==void 0)return o}var dr={};La(dr,{ZodISODate:()=>xl,ZodISODateTime:()=>wl,ZodISODuration:()=>kl,ZodISOTime:()=>zl,date:()=>ps,datetime:()=>ds,duration:()=>ms,time:()=>fs});var wl=h("ZodISODateTime",(t,e)=>{su.init(t,e),Y.init(t,e)});function ds(t){return ul(wl,t)}var xl=h("ZodISODate",(t,e)=>{iu.init(t,e),Y.init(t,e)});function ps(t){return ll(xl,t)}var zl=h("ZodISOTime",(t,e)=>{au.init(t,e),Y.init(t,e)});function fs(t){return dl(zl,t)}var kl=h("ZodISODuration",(t,e)=>{cu.init(t,e),Y.init(t,e)});function ms(t){return pl(kl,t)}var El=(t,e)=>{so.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ka(t,r)},flatten:{value:r=>Ha(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},mw=h("ZodError",El),pr=h("ZodError",El,{Parent:Error});var Tl=Wa(pr),Pl=Ga(pr),Ol=Fn(pr),Il=Vn(pr);var te=h("ZodType",(t,e)=>(K.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),t.clone=(r,o)=>qe(t,r,o),t.brand=()=>t,t.register=((r,o)=>(r.add(t,o),t)),t.parse=(r,o)=>Tl(t,r,o,{callee:t.parse}),t.safeParse=(r,o)=>Ol(t,r,o),t.parseAsync=async(r,o)=>Pl(t,r,o,{callee:t.parseAsync}),t.safeParseAsync=async(r,o)=>Il(t,r,o),t.spa=t.safeParseAsync,t.refine=(r,o)=>t.check(jh(r,o)),t.superRefine=r=>t.check(Lh(r)),t.overwrite=r=>t.check(gt(r)),t.optional=()=>ee(t),t.nullable=()=>Al(t),t.nullish=()=>ee(Al(t)),t.nonoptional=r=>Oh(t,r),t.array=()=>D(t),t.or=r=>W([t,r]),t.and=r=>yo(t,r),t.transform=r=>gs(t,Zl(r)),t.default=r=>Eh(t,r),t.prefault=r=>Ph(t,r),t.catch=r=>Rh(t,r),t.pipe=r=>gs(t,r),t.readonly=()=>Ch(t),t.describe=r=>{let o=t.clone();return ar.add(o,{description:r}),o},Object.defineProperty(t,"description",{get(){return ar.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return ar.get(t);let o=t.clone();return ar.add(o,r[0]),o},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Cl=h("_ZodString",(t,e)=>{uo.init(t,e),te.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=(...o)=>t.check(ts(...o)),t.includes=(...o)=>t.check(ns(...o)),t.startsWith=(...o)=>t.check(ss(...o)),t.endsWith=(...o)=>t.check(is(...o)),t.min=(...o)=>t.check(It(...o)),t.max=(...o)=>t.check(mo(...o)),t.length=(...o)=>t.check(ho(...o)),t.nonempty=(...o)=>t.check(It(1,...o)),t.lowercase=o=>t.check(rs(o)),t.uppercase=o=>t.check(os(o)),t.trim=()=>t.check(cs()),t.normalize=(...o)=>t.check(as(...o)),t.toLowerCase=()=>t.check(us()),t.toUpperCase=()=>t.check(ls())}),Bm=h("ZodString",(t,e)=>{uo.init(t,e),Cl.init(t,e),t.email=r=>t.check(Uu(Jm,r)),t.url=r=>t.check(Wu(Ym,r)),t.jwt=r=>t.check(cl(ph,r)),t.emoji=r=>t.check(Gu(Xm,r)),t.guid=r=>t.check(es(Rl,r)),t.uuid=r=>t.check(Fu(_o,r)),t.uuidv4=r=>t.check(Vu(_o,r)),t.uuidv6=r=>t.check(Hu(_o,r)),t.uuidv7=r=>t.check(Ku(_o,r)),t.nanoid=r=>t.check(Bu(Qm,r)),t.guid=r=>t.check(es(Rl,r)),t.cuid=r=>t.check(Ju(eh,r)),t.cuid2=r=>t.check(Yu(th,r)),t.ulid=r=>t.check(Xu(rh,r)),t.base64=r=>t.check(sl(uh,r)),t.base64url=r=>t.check(il(lh,r)),t.xid=r=>t.check(Qu(oh,r)),t.ksuid=r=>t.check(el(nh,r)),t.ipv4=r=>t.check(tl(sh,r)),t.ipv6=r=>t.check(rl(ih,r)),t.cidrv4=r=>t.check(ol(ah,r)),t.cidrv6=r=>t.check(nl(ch,r)),t.e164=r=>t.check(al(dh,r)),t.datetime=r=>t.check(ds(r)),t.date=r=>t.check(ps(r)),t.time=r=>t.check(fs(r)),t.duration=r=>t.check(ms(r))});function m(t){return Mu(Bm,t)}var Y=h("ZodStringFormat",(t,e)=>{G.init(t,e),Cl.init(t,e)}),Jm=h("ZodEmail",(t,e)=>{Jc.init(t,e),Y.init(t,e)});var Rl=h("ZodGUID",(t,e)=>{Gc.init(t,e),Y.init(t,e)});var _o=h("ZodUUID",(t,e)=>{Bc.init(t,e),Y.init(t,e)});var Ym=h("ZodURL",(t,e)=>{Yc.init(t,e),Y.init(t,e)});var Xm=h("ZodEmoji",(t,e)=>{Xc.init(t,e),Y.init(t,e)});var Qm=h("ZodNanoID",(t,e)=>{Qc.init(t,e),Y.init(t,e)});var eh=h("ZodCUID",(t,e)=>{eu.init(t,e),Y.init(t,e)});var th=h("ZodCUID2",(t,e)=>{tu.init(t,e),Y.init(t,e)});var rh=h("ZodULID",(t,e)=>{ru.init(t,e),Y.init(t,e)});var oh=h("ZodXID",(t,e)=>{ou.init(t,e),Y.init(t,e)});var nh=h("ZodKSUID",(t,e)=>{nu.init(t,e),Y.init(t,e)});var sh=h("ZodIPv4",(t,e)=>{uu.init(t,e),Y.init(t,e)});var ih=h("ZodIPv6",(t,e)=>{lu.init(t,e),Y.init(t,e)});var ah=h("ZodCIDRv4",(t,e)=>{du.init(t,e),Y.init(t,e)});var ch=h("ZodCIDRv6",(t,e)=>{pu.init(t,e),Y.init(t,e)});var uh=h("ZodBase64",(t,e)=>{mu.init(t,e),Y.init(t,e)});var lh=h("ZodBase64URL",(t,e)=>{hu.init(t,e),Y.init(t,e)});var dh=h("ZodE164",(t,e)=>{gu.init(t,e),Y.init(t,e)});var ph=h("ZodJWT",(t,e)=>{_u.init(t,e),Y.init(t,e)});var Dl=h("ZodNumber",(t,e)=>{Yn.init(t,e),te.init(t,e),t.gt=(o,n)=>t.check(po(o,n)),t.gte=(o,n)=>t.check(ur(o,n)),t.min=(o,n)=>t.check(ur(o,n)),t.lt=(o,n)=>t.check(lo(o,n)),t.lte=(o,n)=>t.check(cr(o,n)),t.max=(o,n)=>t.check(cr(o,n)),t.int=o=>t.check(Nl(o)),t.safe=o=>t.check(Nl(o)),t.positive=o=>t.check(po(0,o)),t.nonnegative=o=>t.check(ur(0,o)),t.negative=o=>t.check(lo(0,o)),t.nonpositive=o=>t.check(cr(0,o)),t.multipleOf=(o,n)=>t.check(fo(o,n)),t.step=(o,n)=>t.check(fo(o,n)),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 U(t){return fl(Dl,t)}var fh=h("ZodNumberFormat",(t,e)=>{yu.init(t,e),Dl.init(t,e)});function Nl(t){return ml(fh,t)}var mh=h("ZodBoolean",(t,e)=>{vu.init(t,e),te.init(t,e)});function oe(t){return hl(mh,t)}var hh=h("ZodNull",(t,e)=>{$u.init(t,e),te.init(t,e)});function _s(t){return gl(hh,t)}var gh=h("ZodUnknown",(t,e)=>{bu.init(t,e),te.init(t,e)});function X(){return _l(gh)}var _h=h("ZodNever",(t,e)=>{Su.init(t,e),te.init(t,e)});function yh(t){return yl(_h,t)}var vh=h("ZodArray",(t,e)=>{wu.init(t,e),te.init(t,e),t.element=e.element,t.min=(r,o)=>t.check(It(r,o)),t.nonempty=r=>t.check(It(1,r)),t.max=(r,o)=>t.check(mo(r,o)),t.length=(r,o)=>t.check(ho(r,o)),t.unwrap=()=>t.element});function D(t,e){return vl(vh,t,e)}var jl=h("ZodObject",(t,e)=>{xu.init(t,e),te.init(t,e),M.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>ve(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:X()}),t.loose=()=>t.clone({...t._zod.def,catchall:X()}),t.strict=()=>t.clone({...t._zod.def,catchall:yh()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>M.extend(t,r),t.merge=r=>M.merge(t,r),t.pick=r=>M.pick(t,r),t.omit=r=>M.omit(t,r),t.partial=(...r)=>M.partial(ql,t,r[0]),t.required=(...r)=>M.required(Ml,t,r[0])});function w(t,e){let r={type:"object",get shape(){return M.assignProp(this,"shape",{...t}),this.shape},...M.normalizeParams(e)};return new jl(r)}function ge(t,e){return new jl({type:"object",get shape(){return M.assignProp(this,"shape",{...t}),this.shape},catchall:X(),...M.normalizeParams(e)})}var Ll=h("ZodUnion",(t,e)=>{Xn.init(t,e),te.init(t,e),t.options=e.options});function W(t,e){return new Ll({type:"union",options:t,...M.normalizeParams(e)})}var $h=h("ZodDiscriminatedUnion",(t,e)=>{Ll.init(t,e),zu.init(t,e)});function ys(t,e,r){return new $h({type:"union",options:e,discriminator:t,...M.normalizeParams(r)})}var bh=h("ZodIntersection",(t,e)=>{ku.init(t,e),te.init(t,e)});function yo(t,e){return new bh({type:"intersection",left:t,right:e})}var Sh=h("ZodRecord",(t,e)=>{Eu.init(t,e),te.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Q(t,e,r){return new Sh({type:"record",keyType:t,valueType:e,...M.normalizeParams(r)})}var hs=h("ZodEnum",(t,e)=>{Tu.init(t,e),te.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new hs({...e,checks:[],...M.normalizeParams(n),entries:s})},t.exclude=(o,n)=>{let s={...e.entries};for(let i of o)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new hs({...e,checks:[],...M.normalizeParams(n),entries:s})}});function ve(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new hs({type:"enum",entries:r,...M.normalizeParams(e)})}var wh=h("ZodLiteral",(t,e)=>{Pu.init(t,e),te.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 x(t,e){return new wh({type:"literal",values:Array.isArray(t)?t:[t],...M.normalizeParams(e)})}var xh=h("ZodTransform",(t,e)=>{Ou.init(t,e),te.init(t,e),t._zod.parse=(r,o)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(M.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(M.issue(i))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r)):(r.value=n,r)}});function Zl(t){return new xh({type:"transform",transform:t})}var ql=h("ZodOptional",(t,e)=>{Iu.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ee(t){return new ql({type:"optional",innerType:t})}var zh=h("ZodNullable",(t,e)=>{Ru.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Al(t){return new zh({type:"nullable",innerType:t})}var kh=h("ZodDefault",(t,e)=>{Nu.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Eh(t,e){return new kh({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Th=h("ZodPrefault",(t,e)=>{Au.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ph(t,e){return new Th({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Ml=h("ZodNonOptional",(t,e)=>{Cu.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Oh(t,e){return new Ml({type:"nonoptional",innerType:t,...M.normalizeParams(e)})}var Ih=h("ZodCatch",(t,e)=>{Du.init(t,e),te.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Rh(t,e){return new Ih({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Nh=h("ZodPipe",(t,e)=>{ju.init(t,e),te.init(t,e),t.in=e.in,t.out=e.out});function gs(t,e){return new Nh({type:"pipe",in:t,out:e})}var Ah=h("ZodReadonly",(t,e)=>{Lu.init(t,e),te.init(t,e)});function Ch(t){return new Ah({type:"readonly",innerType:t})}var Ul=h("ZodCustom",(t,e)=>{Zu.init(t,e),te.init(t,e)});function Dh(t){let e=new de({check:"custom"});return e._zod.check=t,e}function Fl(t,e){return $l(Ul,t??(()=>!0),e)}function jh(t,e={}){return bl(Ul,t,e)}function Lh(t){let e=Dh(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(M.issue(o,r.value,e._zod.def));else{let n=o;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),n.continue??(n.continue=!e._zod.def.abort),r.issues.push(M.issue(n))}},t(r.value,r)));return e}function vs(t,e){return gs(Zl(t),e)}ke(qu());var bs="2025-11-25";var Vl=[bs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],nt="io.modelcontextprotocol/related-task",$o="2.0",se=Fl(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Hl=W([m(),U().int()]),Kl=m(),ax=ge({ttl:W([U(),_s()]).optional(),pollInterval:U().optional()}),Zh=w({ttl:U().optional()}),qh=w({taskId:m()}),Ss=ge({progressToken:Hl.optional(),[nt]:qh.optional()}),xe=w({_meta:Ss.optional()}),fr=xe.extend({task:Zh.optional()}),Wl=t=>fr.safeParse(t).success,ie=w({method:m(),params:xe.loose().optional()}),Ee=w({_meta:Ss.optional()}),Te=w({method:m(),params:Ee.loose().optional()}),ae=ge({_meta:Ss.optional()}),bo=W([m(),U().int()]),Gl=w({jsonrpc:x($o),id:bo,...ie.shape}).strict(),ws=t=>Gl.safeParse(t).success,Bl=w({jsonrpc:x($o),...Te.shape}).strict(),Jl=t=>Bl.safeParse(t).success,xs=w({jsonrpc:x($o),id:bo,result:ae}).strict(),mr=t=>xs.safeParse(t).success;var C;(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"})(C||(C={}));var zs=w({jsonrpc:x($o),id:bo.optional(),error:w({code:U().int(),message:m(),data:X().optional()})}).strict();var Yl=t=>zs.safeParse(t).success;var Xl=W([Gl,Bl,xs,zs]),cx=W([xs,zs]),So=ae.strict(),Mh=Ee.extend({requestId:bo.optional(),reason:m().optional()}),wo=Te.extend({method:x("notifications/cancelled"),params:Mh}),Uh=w({src:m(),mimeType:m().optional(),sizes:D(m()).optional(),theme:ve(["light","dark"]).optional()}),hr=w({icons:D(Uh).optional()}),Nt=w({name:m(),title:m().optional()}),Ql=Nt.extend({...Nt.shape,...hr.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),Fh=yo(w({applyDefaults:oe().optional()}),Q(m(),X())),Vh=vs(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,yo(w({form:Fh.optional(),url:se.optional()}),Q(m(),X()).optional())),Hh=ge({list:se.optional(),cancel:se.optional(),requests:ge({sampling:ge({createMessage:se.optional()}).optional(),elicitation:ge({create:se.optional()}).optional()}).optional()}),Kh=ge({list:se.optional(),cancel:se.optional(),requests:ge({tools:ge({call:se.optional()}).optional()}).optional()}),Wh=w({experimental:Q(m(),se).optional(),sampling:w({context:se.optional(),tools:se.optional()}).optional(),elicitation:Vh.optional(),roots:w({listChanged:oe().optional()}).optional(),tasks:Hh.optional()}),Gh=xe.extend({protocolVersion:m(),capabilities:Wh,clientInfo:Ql}),ks=ie.extend({method:x("initialize"),params:Gh});var Bh=w({experimental:Q(m(),se).optional(),logging:se.optional(),completions:se.optional(),prompts:w({listChanged:oe().optional()}).optional(),resources:w({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:w({listChanged:oe().optional()}).optional(),tasks:Kh.optional()}),Jh=ae.extend({protocolVersion:m(),capabilities:Bh,serverInfo:Ql,instructions:m().optional()}),Es=Te.extend({method:x("notifications/initialized"),params:Ee.optional()});var xo=ie.extend({method:x("ping"),params:xe.optional()}),Yh=w({progress:U(),total:ee(U()),message:ee(m())}),Xh=w({...Ee.shape,...Yh.shape,progressToken:Hl}),zo=Te.extend({method:x("notifications/progress"),params:Xh}),Qh=xe.extend({cursor:Kl.optional()}),gr=ie.extend({params:Qh.optional()}),_r=ae.extend({nextCursor:Kl.optional()}),eg=ve(["working","input_required","completed","failed","cancelled"]),yr=w({taskId:m(),status:eg,ttl:W([U(),_s()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:ee(U()),statusMessage:ee(m())}),At=ae.extend({task:yr}),tg=Ee.merge(yr),vr=Te.extend({method:x("notifications/tasks/status"),params:tg}),ko=ie.extend({method:x("tasks/get"),params:xe.extend({taskId:m()})}),Eo=ae.merge(yr),To=ie.extend({method:x("tasks/result"),params:xe.extend({taskId:m()})}),ux=ae.loose(),Po=gr.extend({method:x("tasks/list")}),Oo=_r.extend({tasks:D(yr)}),Io=ie.extend({method:x("tasks/cancel"),params:xe.extend({taskId:m()})}),ed=ae.merge(yr),td=w({uri:m(),mimeType:ee(m()),_meta:Q(m(),X()).optional()}),rd=td.extend({text:m()}),Ts=m().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),od=td.extend({blob:Ts}),$r=ve(["user","assistant"]),Ct=w({audience:D($r).optional(),priority:U().min(0).max(1).optional(),lastModified:dr.datetime({offset:!0}).optional()}),nd=w({...Nt.shape,...hr.shape,uri:m(),description:ee(m()),mimeType:ee(m()),annotations:Ct.optional(),_meta:ee(ge({}))}),rg=w({...Nt.shape,...hr.shape,uriTemplate:m(),description:ee(m()),mimeType:ee(m()),annotations:Ct.optional(),_meta:ee(ge({}))}),og=gr.extend({method:x("resources/list")}),ng=_r.extend({resources:D(nd)}),sg=gr.extend({method:x("resources/templates/list")}),ig=_r.extend({resourceTemplates:D(rg)}),Ps=xe.extend({uri:m()}),ag=Ps,cg=ie.extend({method:x("resources/read"),params:ag}),ug=ae.extend({contents:D(W([rd,od]))}),lg=Te.extend({method:x("notifications/resources/list_changed"),params:Ee.optional()}),dg=Ps,pg=ie.extend({method:x("resources/subscribe"),params:dg}),fg=Ps,mg=ie.extend({method:x("resources/unsubscribe"),params:fg}),hg=Ee.extend({uri:m()}),gg=Te.extend({method:x("notifications/resources/updated"),params:hg}),_g=w({name:m(),description:ee(m()),required:ee(oe())}),yg=w({...Nt.shape,...hr.shape,description:ee(m()),arguments:ee(D(_g)),_meta:ee(ge({}))}),vg=gr.extend({method:x("prompts/list")}),$g=_r.extend({prompts:D(yg)}),bg=xe.extend({name:m(),arguments:Q(m(),m()).optional()}),Sg=ie.extend({method:x("prompts/get"),params:bg}),Os=w({type:x("text"),text:m(),annotations:Ct.optional(),_meta:Q(m(),X()).optional()}),Is=w({type:x("image"),data:Ts,mimeType:m(),annotations:Ct.optional(),_meta:Q(m(),X()).optional()}),Rs=w({type:x("audio"),data:Ts,mimeType:m(),annotations:Ct.optional(),_meta:Q(m(),X()).optional()}),wg=w({type:x("tool_use"),name:m(),id:m(),input:Q(m(),X()),_meta:Q(m(),X()).optional()}),xg=w({type:x("resource"),resource:W([rd,od]),annotations:Ct.optional(),_meta:Q(m(),X()).optional()}),zg=nd.extend({type:x("resource_link")}),Ns=W([Os,Is,Rs,zg,xg]),kg=w({role:$r,content:Ns}),Eg=ae.extend({description:m().optional(),messages:D(kg)}),Tg=Te.extend({method:x("notifications/prompts/list_changed"),params:Ee.optional()}),Pg=w({title:m().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),Og=w({taskSupport:ve(["required","optional","forbidden"]).optional()}),sd=w({...Nt.shape,...hr.shape,description:m().optional(),inputSchema:w({type:x("object"),properties:Q(m(),se).optional(),required:D(m()).optional()}).catchall(X()),outputSchema:w({type:x("object"),properties:Q(m(),se).optional(),required:D(m()).optional()}).catchall(X()).optional(),annotations:Pg.optional(),execution:Og.optional(),_meta:Q(m(),X()).optional()}),As=gr.extend({method:x("tools/list")}),Ig=_r.extend({tools:D(sd)}),Ro=ae.extend({content:D(Ns).default([]),structuredContent:Q(m(),X()).optional(),isError:oe().optional()}),lx=Ro.or(ae.extend({toolResult:X()})),Rg=fr.extend({name:m(),arguments:Q(m(),X()).optional()}),br=ie.extend({method:x("tools/call"),params:Rg}),Ng=Te.extend({method:x("notifications/tools/list_changed"),params:Ee.optional()}),dx=w({autoRefresh:oe().default(!0),debounceMs:U().int().nonnegative().default(300)}),Sr=ve(["debug","info","notice","warning","error","critical","alert","emergency"]),Ag=xe.extend({level:Sr}),Cs=ie.extend({method:x("logging/setLevel"),params:Ag}),Cg=Ee.extend({level:Sr,logger:m().optional(),data:X()}),Dg=Te.extend({method:x("notifications/message"),params:Cg}),jg=w({name:m().optional()}),Lg=w({hints:D(jg).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),Zg=w({mode:ve(["auto","required","none"]).optional()}),qg=w({type:x("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:D(Ns).default([]),structuredContent:w({}).loose().optional(),isError:oe().optional(),_meta:Q(m(),X()).optional()}),Mg=ys("type",[Os,Is,Rs]),vo=ys("type",[Os,Is,Rs,wg,qg]),Ug=w({role:$r,content:W([vo,D(vo)]),_meta:Q(m(),X()).optional()}),Fg=fr.extend({messages:D(Ug),modelPreferences:Lg.optional(),systemPrompt:m().optional(),includeContext:ve(["none","thisServer","allServers"]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:D(m()).optional(),metadata:se.optional(),tools:D(sd).optional(),toolChoice:Zg.optional()}),Vg=ie.extend({method:x("sampling/createMessage"),params:Fg}),Ds=ae.extend({model:m(),stopReason:ee(ve(["endTurn","stopSequence","maxTokens"]).or(m())),role:$r,content:Mg}),js=ae.extend({model:m(),stopReason:ee(ve(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:$r,content:W([vo,D(vo)])}),Hg=w({type:x("boolean"),title:m().optional(),description:m().optional(),default:oe().optional()}),Kg=w({type:x("string"),title:m().optional(),description:m().optional(),minLength:U().optional(),maxLength:U().optional(),format:ve(["email","uri","date","date-time"]).optional(),default:m().optional()}),Wg=w({type:ve(["number","integer"]),title:m().optional(),description:m().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),Gg=w({type:x("string"),title:m().optional(),description:m().optional(),enum:D(m()),default:m().optional()}),Bg=w({type:x("string"),title:m().optional(),description:m().optional(),oneOf:D(w({const:m(),title:m()})),default:m().optional()}),Jg=w({type:x("string"),title:m().optional(),description:m().optional(),enum:D(m()),enumNames:D(m()).optional(),default:m().optional()}),Yg=W([Gg,Bg]),Xg=w({type:x("array"),title:m().optional(),description:m().optional(),minItems:U().optional(),maxItems:U().optional(),items:w({type:x("string"),enum:D(m())}),default:D(m()).optional()}),Qg=w({type:x("array"),title:m().optional(),description:m().optional(),minItems:U().optional(),maxItems:U().optional(),items:w({anyOf:D(w({const:m(),title:m()}))}),default:D(m()).optional()}),e_=W([Xg,Qg]),t_=W([Jg,Yg,e_]),r_=W([t_,Hg,Kg,Wg]),o_=fr.extend({mode:x("form").optional(),message:m(),requestedSchema:w({type:x("object"),properties:Q(m(),r_),required:D(m()).optional()})}),n_=fr.extend({mode:x("url"),message:m(),elicitationId:m(),url:m().url()}),s_=W([o_,n_]),i_=ie.extend({method:x("elicitation/create"),params:s_}),a_=Ee.extend({elicitationId:m()}),c_=Te.extend({method:x("notifications/elicitation/complete"),params:a_}),No=ae.extend({action:ve(["accept","decline","cancel"]),content:vs(t=>t===null?void 0:t,Q(m(),W([m(),U(),oe(),D(m())])).optional())}),u_=w({type:x("ref/resource"),uri:m()});var l_=w({type:x("ref/prompt"),name:m()}),d_=xe.extend({ref:W([l_,u_]),argument:w({name:m(),value:m()}),context:w({arguments:Q(m(),m()).optional()}).optional()}),p_=ie.extend({method:x("completion/complete"),params:d_});var f_=ae.extend({completion:ge({values:D(m()).max(100),total:ee(U().int()),hasMore:ee(oe())})}),m_=w({uri:m().startsWith("file://"),name:m().optional(),_meta:Q(m(),X()).optional()}),h_=ie.extend({method:x("roots/list"),params:xe.optional()}),Ls=ae.extend({roots:D(m_)}),g_=Te.extend({method:x("notifications/roots/list_changed"),params:Ee.optional()}),px=W([xo,ks,p_,Cs,Sg,vg,og,sg,cg,pg,mg,br,As,ko,To,Po,Io]),fx=W([wo,zo,Es,g_,vr]),mx=W([So,Ds,js,No,Ls,Eo,Oo,At]),hx=W([xo,Vg,i_,h_,ko,To,Po,Io]),gx=W([wo,zo,Dg,gg,lg,Ng,Tg,vr,c_]),_x=W([So,Jh,f_,Eg,$g,ng,ig,ug,Ro,Ig,Eo,Oo,At]),O=class t extends Error{constructor(e,r,o){super(`MCP error ${e}: ${r}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,r,o){if(e===C.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new $s(n.elicitations,r)}return new t(e,r,o)}},$s=class extends O{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(C.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function st(t){return t==="completed"||t==="failed"||t==="cancelled"}var Jx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Zs(t){let r=go(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Sl(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function qs(t,e){let r=ot(t,e);if(!r.success)throw r.error;return r.data}var S_=6e4,Ao=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(wo,r=>{this._oncancel(r)}),this.setNotificationHandler(zo,r=>{this._onprogress(r)}),this.setRequestHandler(xo,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ko,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new O(C.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(To,async(r,o)=>{let n=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,o.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 O(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:o.requestId})}}let i=await this._taskStore.getTask(s,o.sessionId);if(!i)throw new O(C.InvalidParams,`Task not found: ${s}`);if(!st(i.status))return await this._waitForTaskUpdate(s,o.signal),await n();if(st(i.status)){let a=await this._taskStore.getTaskResult(s,o.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[nt]:{taskId:s}}}}return await n()};return await n()}),this.setRequestHandler(Po,async(r,o)=>{try{let{tasks:n,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(n){throw new O(C.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Io,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new O(C.InvalidParams,`Task not found: ${r.params.taskId}`);if(st(n.status))throw new O(C.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!s)throw new O(C.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(n){throw n instanceof O?n:new O(C.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,o,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),O.fromError(C.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});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){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=s=>{o?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),mr(s)||Yl(s)?this._onresponse(s):ws(s)?this._onrequest(s,i):Jl(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();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=O.fromError(C.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(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(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,s=e.params?._meta?.[nt]?.taskId;if(o===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:C.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.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=Wl(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,u={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new O(C.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let g=f.relatedTask?.taskId??s;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(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()},n?.sessionId):await n?.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:C.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()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...o}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(o)}_onresponse(e){let r=Number(e.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),mr(e))o(e);else{let i=new O(e.error.code,e.error.message,e.error.data);o(i)}return}let n=this._responseHandlers.get(r);if(n===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(mr(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),mr(e))n(e);else{let i=O.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(e,r,o)}}catch(i){yield{type:"error",error:i instanceof O?i:new O(C.InternalError,String(i))}}return}let s;try{let i=await this.request(e,At,o);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new O(C.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},o);if(yield{type:"taskStatus",task:a},st(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)}:a.status==="failed"?yield{type:"error",error:new O(C.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new O(C.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof O?i:new O(C.InternalError,String(i))}}}request(e,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=b=>{l(b)};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(b){d(b);return}o?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.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||{},[nt]:c}});let g=b=>{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(b)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let $=b instanceof O?b:new O(C.RequestTimeout,String(b));l($)};this._responseHandlers.set(p,b=>{if(!o?.signal?.aborted){if(b instanceof Error)return l(b);try{let $=ot(r,b.result);$.success?u($.data):l($.error)}catch($){l($)}}}),o?.signal?.addEventListener("abort",()=>{g(o?.signal?.reason)});let _=o?.timeout??S_,y=()=>g(O.fromError(C.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,o?.maxTotalTimeout,y,o?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=$=>{let k=this._responseHandlers.get(p);k?k($):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(p),l($)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(p),l(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Eo,r)}async getTaskResult(e,r,o){return this.request({method:"tasks/result",params:e},r,o)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Oo,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ed,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=r?.relatedTask?.taskId;if(o){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[nt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{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||{},[nt]: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||{},[nt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let o=Zs(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,s)=>{let i=qs(e,n);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 o=Zs(e);this._notificationHandlers.set(o,n=>{let s=qs(e,n);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,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,o,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,r);for(let n of o)if(n.type==="request"&&ws(n.message)){let s=n.message.id,i=this._requestResolvers.get(s);i?(i(new O(C.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 o=this._options?.defaultTaskPollInterval??1e3;try{let n=await this._taskStore?.getTask(e);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,s)=>{if(r.aborted){s(new O(C.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(i),s(new O(C.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await o.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let s=await o.getTask(n,r);if(!s)throw new O(C.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(n,s,i)=>{await o.storeTaskResult(n,s,i,r);let a=await o.getTask(n,r);if(a){let c=vr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),st(a.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,s,i)=>{let a=await o.getTask(n,r);if(!a)throw new O(C.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(st(a.status))throw new O(C.InvalidParams,`Cannot update task "${n}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,s,i,r);let c=await o.getTask(n,r);if(c){let u=vr.parse({method:"notifications/tasks/status",params:c});await this.notification(u),st(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function id(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ad(t,e){let r={...t};for(let o in e){let n=o,s=e[n];if(s===void 0)continue;let i=r[n];id(i)&&id(s)?r[n]={...i,...s}:r[n]=s}return r}var Gf=eo(za(),1),Bf=eo(Wf(),1);function pS(){let t=new Gf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Bf.default)(t),t}var yn=class{constructor(e){this._ajv=e??pS()}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 o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var vn=class{constructor(e){this._server=e}requestStream(e,r,o){return this._server.requestStream(e,r,o)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._server.getTaskResult({taskId:e},r,o)}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 Jf(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 Yf(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 $n=class extends Ao{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Sr.options.map((o,n)=>[o,n])),this.isMessageIgnored=(o,n)=>{let s=this._loggingLevels.get(n);return s?this.LOG_LEVEL_SEVERITY.get(o)this._oninitialize(o)),this.setNotificationHandler(Es,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Cs,async(o,n)=>{let s=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=o.params,a=Sr.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new vn(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ad(this._capabilities,e)}setRequestHandler(e,r){let n=go(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let s;if(Rt(n)){let a=n;s=a._zod?.def?.value??a.value}else{let a=n;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=ot(br,c);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new O(C.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let g=ot(At,p);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new O(C.InvalidParams,`Invalid task creation result: ${_}`)}return g.data}let f=ot(Ro,p);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new O(C.InvalidParams,`Invalid tools/call result: ${g}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Yf(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Jf(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:Vl.includes(r)?r:bs,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"},So)}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 o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],s=n.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(n.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(n.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},js,r):this.request({method:"sampling/createMessage",params:e},Ds,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 n=e;return this.request({method:"elicitation/create",params:n},No,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:n},No,r);if(s.action==="accept"&&s.content&&n.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(n.requestedSchema)(s.content);if(!a.valid)throw new O(C.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof O?i:new O(C.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},Ls,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"})}};var Na=eo(require("node:process"),1);var bn=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),fS(r)}clear(){this._buffer=void 0}};function fS(t){return Xl.parse(JSON.parse(t))}function Xf(t){return JSON.stringify(t)+` -`}var Sn=class{constructor(e=Na.default.stdin,r=Na.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new bn,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}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 o=Xf(e);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var Aa=eo(require("path"),1);var Ze=require("fs"),wn=require("path"),tm=require("os");var Qf="bugfix,feature,refactor,discovery,decision,change",em="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var Et=class{static DEFAULTS={CLAUDE_PILOT_MODEL:"haiku",CLAUDE_PILOT_CONTEXT_OBSERVATIONS:"50",CLAUDE_PILOT_WORKER_PORT:"41777",CLAUDE_PILOT_WORKER_HOST:"127.0.0.1",CLAUDE_PILOT_WORKER_BIND:"127.0.0.1",CLAUDE_PILOT_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_PILOT_DATA_DIR:(0,wn.join)((0,tm.homedir)(),".pilot/memory"),CLAUDE_PILOT_LOG_LEVEL:"INFO",CLAUDE_PILOT_PYTHON_VERSION:"3.12",CLAUDE_CODE_PATH:"",CLAUDE_PILOT_CONTEXT_SHOW_READ_TOKENS:!1,CLAUDE_PILOT_CONTEXT_SHOW_WORK_TOKENS:!1,CLAUDE_PILOT_CONTEXT_SHOW_SAVINGS_AMOUNT:!1,CLAUDE_PILOT_CONTEXT_SHOW_SAVINGS_PERCENT:!1,CLAUDE_PILOT_CONTEXT_OBSERVATION_TYPES:Qf,CLAUDE_PILOT_CONTEXT_OBSERVATION_CONCEPTS:em,CLAUDE_PILOT_CONTEXT_FULL_COUNT:"10",CLAUDE_PILOT_CONTEXT_FULL_FIELD:"facts",CLAUDE_PILOT_CONTEXT_SESSION_COUNT:"10",CLAUDE_PILOT_CONTEXT_SHOW_LAST_SUMMARY:!0,CLAUDE_PILOT_CONTEXT_SHOW_LAST_MESSAGE:!0,CLAUDE_PILOT_FOLDER_CLAUDEMD_ENABLED:!1,CLAUDE_PILOT_FOLDER_MD_EXCLUDE:"[]",CLAUDE_PILOT_CHROMA_ENABLED:!0,CLAUDE_PILOT_VECTOR_DB:"chroma",CLAUDE_PILOT_EMBEDDING_MODEL:"Xenova/all-MiniLM-L6-v2",CLAUDE_PILOT_EXCLUDE_PROJECTS:"[]",CLAUDE_PILOT_REMOTE_TOKEN:"",CLAUDE_PILOT_RETENTION_ENABLED:!0,CLAUDE_PILOT_RETENTION_MAX_AGE_DAYS:"31",CLAUDE_PILOT_RETENTION_MAX_COUNT:"5000",CLAUDE_PILOT_RETENTION_EXCLUDE_TYPES:'["summary"]',CLAUDE_PILOT_RETENTION_SOFT_DELETE:!1,CLAUDE_PILOT_BATCH_SIZE:"5"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){return this.get(e)==="true"}static loadFromFile(e){try{if(!(0,Ze.existsSync)(e)){let c=this.getAllDefaults();try{let u=(0,wn.dirname)(e);(0,Ze.existsSync)(u)||(0,Ze.mkdirSync)(u,{recursive:!0}),(0,Ze.writeFileSync)(e,JSON.stringify(c,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u)}return c}let r=(0,Ze.readFileSync)(e,"utf-8"),o=JSON.parse(r),n=o;if(o.env&&typeof o.env=="object"){n=o.env;try{(0,Ze.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c)}}let s=["CLAUDE_PILOT_CONTEXT_SHOW_READ_TOKENS","CLAUDE_PILOT_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_PILOT_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_PILOT_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_PILOT_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_PILOT_CONTEXT_SHOW_LAST_MESSAGE","CLAUDE_PILOT_FOLDER_CLAUDEMD_ENABLED","CLAUDE_PILOT_CHROMA_ENABLED","CLAUDE_PILOT_RETENTION_ENABLED","CLAUDE_PILOT_RETENTION_SOFT_DELETE"],i={...this.DEFAULTS},a=!1;for(let c of Object.keys(this.DEFAULTS))if(n[c]!==void 0)if(s.includes(c)){let u=n[c];typeof u=="string"?(i[c]=u==="true",a=!0):i[c]=u}else i[c]=n[c];if(a)try{(0,Ze.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Migrated boolean settings from strings to actual booleans:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate boolean settings:",e,c)}return i}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.getAllDefaults()}}};var xn=null,zn=null;function rm(){if(xn!==null)return xn;let t=Aa.default.join(Et.get("CLAUDE_PILOT_DATA_DIR"),"settings.json"),e=Et.loadFromFile(t);return xn=parseInt(e.CLAUDE_PILOT_WORKER_PORT,10),xn}function om(){if(zn!==null)return zn;let t=Aa.default.join(Et.get("CLAUDE_PILOT_DATA_DIR"),"settings.json");return zn=Et.loadFromFile(t).CLAUDE_PILOT_WORKER_HOST,zn}var mS="7.8.5";console.log=(...t)=>{ne.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var hS=rm(),gS=om(),Qr=`http://${gS}:${hS}`,nm={search:"/api/search",timeline:"/api/timeline"};async function sm(t,e){ne.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});try{let r=new URLSearchParams;for(let[i,a]of Object.entries(e))a!=null&&r.append(i,String(a));let o=`${Qr}${t}?${r}`,n=await fetch(o);if(!n.ok){let i=await n.text();throw new Error(`Worker API error (${n.status}): ${i}`)}let s=await n.json();return ne.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(r){return ne.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function im(t,e){ne.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=`${Qr}${t}`,o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok){let s=await o.text();throw new Error(`Worker API error (${o.status}): ${s}`)}let n=await o.json();return ne.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(r){return ne.error("HTTP","Worker API error (POST)",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function _S(){try{return(await fetch(`${Qr}/api/health`)).ok}catch(t){return ne.debug("SYSTEM","Worker health check failed",{},t),!1}}var am=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): +`}var Sn=class{constructor(e=Na.default.stdin,r=Na.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new bn,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}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 o=Xf(e);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var Aa=eo(require("path"),1);var Ze=require("fs"),wn=require("path"),tm=require("os");var Qf="bugfix,feature,refactor,discovery,decision,change",em="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var Et=class{static DEFAULTS={CLAUDE_PILOT_MODEL:"haiku",CLAUDE_PILOT_CONTEXT_OBSERVATIONS:"50",CLAUDE_PILOT_WORKER_PORT:"41777",CLAUDE_PILOT_WORKER_HOST:"127.0.0.1",CLAUDE_PILOT_WORKER_BIND:"127.0.0.1",CLAUDE_PILOT_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_PILOT_DATA_DIR:(0,wn.join)((0,tm.homedir)(),".pilot/memory"),CLAUDE_PILOT_LOG_LEVEL:"INFO",CLAUDE_PILOT_PYTHON_VERSION:"3.12",CLAUDE_CODE_PATH:"",CLAUDE_PILOT_CONTEXT_SHOW_READ_TOKENS:!1,CLAUDE_PILOT_CONTEXT_SHOW_WORK_TOKENS:!1,CLAUDE_PILOT_CONTEXT_SHOW_SAVINGS_AMOUNT:!1,CLAUDE_PILOT_CONTEXT_SHOW_SAVINGS_PERCENT:!1,CLAUDE_PILOT_CONTEXT_OBSERVATION_TYPES:Qf,CLAUDE_PILOT_CONTEXT_OBSERVATION_CONCEPTS:em,CLAUDE_PILOT_CONTEXT_FULL_COUNT:"10",CLAUDE_PILOT_CONTEXT_FULL_FIELD:"facts",CLAUDE_PILOT_CONTEXT_SESSION_COUNT:"10",CLAUDE_PILOT_CONTEXT_SHOW_LAST_SUMMARY:!0,CLAUDE_PILOT_CONTEXT_SHOW_LAST_MESSAGE:!0,CLAUDE_PILOT_FOLDER_CLAUDEMD_ENABLED:!1,CLAUDE_PILOT_FOLDER_MD_EXCLUDE:"[]",CLAUDE_PILOT_CHROMA_ENABLED:!0,CLAUDE_PILOT_VECTOR_DB:"chroma",CLAUDE_PILOT_EMBEDDING_MODEL:"Xenova/all-MiniLM-L6-v2",CLAUDE_PILOT_EXCLUDE_PROJECTS:"[]",CLAUDE_PILOT_REMOTE_TOKEN:"",CLAUDE_PILOT_RETENTION_ENABLED:!0,CLAUDE_PILOT_RETENTION_MAX_AGE_DAYS:"31",CLAUDE_PILOT_RETENTION_MAX_COUNT:"5000",CLAUDE_PILOT_RETENTION_EXCLUDE_TYPES:'["summary"]',CLAUDE_PILOT_RETENTION_SOFT_DELETE:!1,CLAUDE_PILOT_BATCH_SIZE:"5"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){return this.get(e)==="true"}static loadFromFile(e){try{if(!(0,Ze.existsSync)(e)){let c=this.getAllDefaults();try{let u=(0,wn.dirname)(e);(0,Ze.existsSync)(u)||(0,Ze.mkdirSync)(u,{recursive:!0}),(0,Ze.writeFileSync)(e,JSON.stringify(c,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u)}return c}let r=(0,Ze.readFileSync)(e,"utf-8"),o=JSON.parse(r),n=o;if(o.env&&typeof o.env=="object"){n=o.env;try{(0,Ze.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c)}}let s=["CLAUDE_PILOT_CONTEXT_SHOW_READ_TOKENS","CLAUDE_PILOT_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_PILOT_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_PILOT_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_PILOT_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_PILOT_CONTEXT_SHOW_LAST_MESSAGE","CLAUDE_PILOT_FOLDER_CLAUDEMD_ENABLED","CLAUDE_PILOT_CHROMA_ENABLED","CLAUDE_PILOT_RETENTION_ENABLED","CLAUDE_PILOT_RETENTION_SOFT_DELETE"],i={...this.DEFAULTS},a=!1;for(let c of Object.keys(this.DEFAULTS))if(n[c]!==void 0)if(s.includes(c)){let u=n[c];typeof u=="string"?(i[c]=u==="true",a=!0):i[c]=u}else i[c]=n[c];if(a)try{(0,Ze.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Migrated boolean settings from strings to actual booleans:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate boolean settings:",e,c)}return i}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.getAllDefaults()}}};var xn=null,zn=null;function rm(){if(xn!==null)return xn;let t=Aa.default.join(Et.get("CLAUDE_PILOT_DATA_DIR"),"settings.json"),e=Et.loadFromFile(t);return xn=parseInt(e.CLAUDE_PILOT_WORKER_PORT,10),xn}function om(){if(zn!==null)return zn;let t=Aa.default.join(Et.get("CLAUDE_PILOT_DATA_DIR"),"settings.json");return zn=Et.loadFromFile(t).CLAUDE_PILOT_WORKER_HOST,zn}var mS="7.9.0";console.log=(...t)=>{ne.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var hS=rm(),gS=om(),Qr=`http://${gS}:${hS}`,nm={search:"/api/search",timeline:"/api/timeline"};async function sm(t,e){ne.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});try{let r=new URLSearchParams;for(let[i,a]of Object.entries(e))a!=null&&r.append(i,String(a));let o=`${Qr}${t}?${r}`,n=await fetch(o);if(!n.ok){let i=await n.text();throw new Error(`Worker API error (${n.status}): ${i}`)}let s=await n.json();return ne.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(r){return ne.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function im(t,e){ne.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=`${Qr}${t}`,o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok){let s=await o.text();throw new Error(`Worker API error (${o.status}): ${s}`)}let n=await o.json();return ne.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(r){return ne.error("HTTP","Worker API error (POST)",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function _S(){try{return(await fetch(`${Qr}/api/health`)).ok}catch(t){return ne.debug("SYSTEM","Worker health check failed",{},t),!1}}var am=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): 1. search(query) \u2192 Get index with IDs (~50-100 tokens/result) 2. timeline(anchor=ID) \u2192 Get context around interesting results 3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs diff --git a/pilot/scripts/worker-service.cjs b/pilot/scripts/worker-service.cjs index 77af40ed..949384b3 100755 --- a/pilot/scripts/worker-service.cjs +++ b/pilot/scripts/worker-service.cjs @@ -953,7 +953,7 @@ ${J.dim}No previous sessions found for this project yet.${J.reset} path: iss.path ? [${vi(v)}, ...iss.path] : [${vi(v)}] })));`),d.write(`newResult[${vi(v)}] = ${b}.value`)}d.write("payload.value = newResult;"),d.write("return payload;");let h=d.compile();return(v,b)=>h(p,v,b)},s,i=uo,o=!mp.jitless,c=o&&hg.value,l=e.catchall,u;t._zod.parse=(p,d)=>{u??(u=r.value);let m=p.value;if(!i(m))return p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p;let f=[];if(o&&c&&d?.async===!1&&d.jitless!==!0)s||(s=n(e.shape)),p=s(p,d);else{p.value={};let b=u.shape;for(let x of u.keys){let w=b[x],S=w._zod.run({value:m[x],issues:[]},d),E=w._zod.optin==="optional"&&w._zod.optout==="optional";S instanceof Promise?f.push(S.then(k=>E?oE(k,p,x,m):xp(k,p,x))):E?oE(S,p,x,m):xp(S,p,x)}}if(!l)return f.length?Promise.all(f).then(()=>p):p;let y=[],g=u.keySet,h=l._zod,v=h.def.type;for(let b of Object.keys(m)){if(g.has(b))continue;if(v==="never"){y.push(b);continue}let x=h.run({value:m[b],issues:[]},d);x instanceof Promise?f.push(x.then(w=>xp(w,p,b))):xp(x,p,b)}return y.length&&p.issues.push({code:"unrecognized_keys",keys:y,input:m,inst:t}),f.length?Promise.all(f).then(()=>p):p}});function aE(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>xn(i,n,rn())))}),e}var Og=z("$ZodUnion",(t,e)=>{pt.init(t,e),ut(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ut(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ut(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ut(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=>mc(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,i=[];for(let o of e.options){let a=o._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),s=!0;else{if(a.issues.length===0)return a;i.push(a)}}return s?Promise.all(i).then(o=>aE(o,r,t,n)):aE(i,r,t,n)}}),WE=z("$ZodDiscriminatedUnion",(t,e)=>{Og.init(t,e);let r=t._zod.parse;ut(t._zod,"propValues",()=>{let s={};for(let i of e.options){let o=i._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,c]of Object.entries(o)){s[a]||(s[a]=new Set);for(let l of c)s[a].add(l)}}return s});let n=pc(()=>{let s=e.options,i=new Map;for(let o of s){let a=o._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,o)}}return i});t._zod.parse=(s,i)=>{let o=s.value;if(!uo(o))return s.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),s;let a=n.value.get(o?.[e.discriminator]);return a?a._zod.run(s,i):e.unionFallback?r(s,i):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),s)}}),ZE=z("$ZodIntersection",(t,e)=>{pt.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,i=e.left._zod.run({value:s,issues:[]},n),o=e.right._zod.run({value:s,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([c,l])=>cE(r,c,l)):cE(r,i,o)}});function $g(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(po(t)&&po(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),s={...t,...e};for(let i of n){let o=$g(t[i],e[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};s[i]=o.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n{pt.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!po(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let i=[];if(e.keyType._zod.values){let o=e.keyType._zod.values;r.value={};for(let c of o)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:s[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...Bn(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Bn(c,l.issues)),r.value[c]=l.value)}let a;for(let c in s)o.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let o of Reflect.ownKeys(s)){if(o==="__proto__")continue;let a=e.keyType._zod.run({value:o,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(l=>xn(l,n,rn())),input:o,path:[o],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[o],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...Bn(o,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Bn(o,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var GE=z("$ZodEnum",(t,e)=>{pt.init(t,e);let r=pg(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>gg.has(typeof n)).map(n=>typeof n=="string"?zs(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:t}),n}}),YE=z("$ZodLiteral",(t,e)=>{pt.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?zs(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var KE=z("$ZodTransform",(t,e)=>{pt.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(o=>(r.value=o,r));if(s instanceof Promise)throw new fs;return r.value=s,r}}),JE=z("$ZodOptional",(t,e)=>{pt.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ut(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${mc(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)}),QE=z("$ZodNullable",(t,e)=>{pt.init(t,e),ut(t._zod,"optin",()=>e.innerType._zod.optin),ut(t._zod,"optout",()=>e.innerType._zod.optout),ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${mc(r.source)}|null)$`):void 0}),ut(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)}),XE=z("$ZodDefault",(t,e)=>{pt.init(t,e),t._zod.optin="optional",ut(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>lE(i,e)):lE(s,e)}});function lE(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var ek=z("$ZodPrefault",(t,e)=>{pt.init(t,e),t._zod.optin="optional",ut(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))}),tk=z("$ZodNonOptional",(t,e)=>{pt.init(t,e),ut(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 s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>uE(i,t)):uE(s,t)}});function uE(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 rk=z("$ZodCatch",(t,e)=>{pt.init(t,e),t._zod.optin="optional",ut(t._zod,"optout",()=>e.innerType._zod.optout),ut(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(o=>xn(o,n,rn()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>xn(i,n,rn()))},input:r.value}),r.issues=[]),r)}});var nk=z("$ZodPipe",(t,e)=>{pt.init(t,e),ut(t._zod,"values",()=>e.in._zod.values),ut(t._zod,"optin",()=>e.in._zod.optin),ut(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(i=>pE(i,e,n)):pE(s,e,n)}});function pE(t,e,r){return yi(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var sk=z("$ZodReadonly",(t,e)=>{pt.init(t,e),ut(t._zod,"propValues",()=>e.innerType._zod.propValues),ut(t._zod,"values",()=>e.innerType._zod.values),ut(t._zod,"optin",()=>e.innerType._zod.optin),ut(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(dE):dE(s)}});function dE(t){return t.value=Object.freeze(t.value),t}var ik=z("$ZodCustom",(t,e)=>{cr.init(t,e),pt.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(i=>mE(i,r,n,t));mE(s,r,n,t)}});function mE(t,e,r,n){if(!t){let s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(bg(s))}}var pF=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},dF=()=>{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 ${pF(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${gp(n.values[0])}`:`Invalid option: expected one of ${fp(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",i=e(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",i=e(n.origin);return i?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.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":""}: ${fp(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 ok(){return{localeError:dF()}}var Cg=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 mF(){return new Cg}var vc=mF();function ak(t,e){return new t({type:"string",...fe(e)})}function ck(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...fe(e)})}function Ig(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...fe(e)})}function lk(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(e)})}function uk(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(e)})}function pk(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(e)})}function dk(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(e)})}function mk(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...fe(e)})}function fk(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(e)})}function hk(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(e)})}function gk(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(e)})}function vk(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(e)})}function yk(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(e)})}function bk(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...fe(e)})}function xk(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(e)})}function _k(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(e)})}function wk(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(e)})}function Sk(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fe(e)})}function Ek(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(e)})}function kk(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...fe(e)})}function Tk(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(e)})}function Rk(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...fe(e)})}function $k(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(e)})}function Pk(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(e)})}function Ok(t,e){return new t({type:"string",format:"date",check:"string_format",...fe(e)})}function Ck(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...fe(e)})}function Ik(t,e){return new t({type:"string",format:"duration",check:"string_format",...fe(e)})}function Ak(t,e){return new t({type:"number",checks:[],...fe(e)})}function jk(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(e)})}function Nk(t,e){return new t({type:"boolean",...fe(e)})}function Dk(t,e){return new t({type:"null",...fe(e)})}function Mk(t){return new t({type:"unknown"})}function zk(t,e){return new t({type:"never",...fe(e)})}function wp(t,e){return new Tg({check:"less_than",...fe(e),value:t,inclusive:!1})}function yc(t,e){return new Tg({check:"less_than",...fe(e),value:t,inclusive:!0})}function Sp(t,e){return new Rg({check:"greater_than",...fe(e),value:t,inclusive:!1})}function bc(t,e){return new Rg({check:"greater_than",...fe(e),value:t,inclusive:!0})}function Ep(t,e){return new WS({check:"multiple_of",...fe(e),value:t})}function kp(t,e){return new VS({check:"max_length",...fe(e),maximum:t})}function mo(t,e){return new GS({check:"min_length",...fe(e),minimum:t})}function Tp(t,e){return new YS({check:"length_equals",...fe(e),length:t})}function Ag(t,e){return new KS({check:"string_format",format:"regex",...fe(e),pattern:t})}function jg(t){return new JS({check:"string_format",format:"lowercase",...fe(t)})}function Ng(t){return new QS({check:"string_format",format:"uppercase",...fe(t)})}function Dg(t,e){return new XS({check:"string_format",format:"includes",...fe(e),includes:t})}function Mg(t,e){return new eE({check:"string_format",format:"starts_with",...fe(e),prefix:t})}function zg(t,e){return new tE({check:"string_format",format:"ends_with",...fe(e),suffix:t})}function bi(t){return new rE({check:"overwrite",tx:t})}function Lg(t){return bi(e=>e.normalize(t))}function qg(){return bi(t=>t.trim())}function Fg(){return bi(t=>t.toLowerCase())}function Ug(){return bi(t=>t.toUpperCase())}function Lk(t,e,r){return new t({type:"array",element:e,...fe(r)})}function qk(t,e,r){let n=fe(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Fk(t,e,r){return new t({type:"custom",check:"custom",fn:e,...fe(r)})}function fo(t){return!!t._zod}function _n(t,e){return fo(t)?hc(t,e):t.safeParse(e)}function Rp(t){if(!t)return;let e;if(fo(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Uk(t){if(fo(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.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 _c={};Un(_c,{ZodISODate:()=>Bk,ZodISODateTime:()=>Hk,ZodISODuration:()=>Zk,ZodISOTime:()=>Wk,date:()=>Bg,datetime:()=>Hg,duration:()=>Zg,time:()=>Wg});var Hk=z("ZodISODateTime",(t,e)=>{kE.init(t,e),St.init(t,e)});function Hg(t){return Pk(Hk,t)}var Bk=z("ZodISODate",(t,e)=>{TE.init(t,e),St.init(t,e)});function Bg(t){return Ok(Bk,t)}var Wk=z("ZodISOTime",(t,e)=>{RE.init(t,e),St.init(t,e)});function Wg(t){return Ck(Wk,t)}var Zk=z("ZodISODuration",(t,e)=>{$E.init(t,e),St.init(t,e)});function Zg(t){return Ik(Zk,t)}var Vk=(t,e)=>{vp.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>dS(t,r)},flatten:{value:r=>pS(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},qfe=z("ZodError",Vk),wc=z("ZodError",Vk,{Parent:Error});var Gk=mS(wc),Yk=fS(wc),Kk=_g(wc),Jk=wg(wc);var Pt=z("ZodType",(t,e)=>(pt.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)=>Hn(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Gk(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Kk(t,r,n),t.parseAsync=async(r,n)=>Yk(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Jk(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(u9(r,n)),t.superRefine=r=>t.check(p9(r)),t.overwrite=r=>t.check(bi(r)),t.optional=()=>$t(t),t.nullable=()=>eT(t),t.nullish=()=>$t(eT(t)),t.nonoptional=r=>n9(t,r),t.array=()=>Me(t),t.or=r=>dt([t,r]),t.and=r=>Pp(t,r),t.transform=r=>Gg(t,iT(r)),t.default=r=>e9(t,r),t.prefault=r=>r9(t,r),t.catch=r=>i9(t,r),t.pipe=r=>Gg(t,r),t.readonly=()=>c9(t),t.describe=r=>{let n=t.clone();return vc.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return vc.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return vc.get(t);let n=t.clone();return vc.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),tT=z("_ZodString",(t,e)=>{_p.init(t,e),Pt.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(Ag(...n)),t.includes=(...n)=>t.check(Dg(...n)),t.startsWith=(...n)=>t.check(Mg(...n)),t.endsWith=(...n)=>t.check(zg(...n)),t.min=(...n)=>t.check(mo(...n)),t.max=(...n)=>t.check(kp(...n)),t.length=(...n)=>t.check(Tp(...n)),t.nonempty=(...n)=>t.check(mo(1,...n)),t.lowercase=n=>t.check(jg(n)),t.uppercase=n=>t.check(Ng(n)),t.trim=()=>t.check(qg()),t.normalize=(...n)=>t.check(Lg(...n)),t.toLowerCase=()=>t.check(Fg()),t.toUpperCase=()=>t.check(Ug())}),wF=z("ZodString",(t,e)=>{_p.init(t,e),tT.init(t,e),t.email=r=>t.check(ck(SF,r)),t.url=r=>t.check(mk(EF,r)),t.jwt=r=>t.check($k(LF,r)),t.emoji=r=>t.check(fk(kF,r)),t.guid=r=>t.check(Ig(Qk,r)),t.uuid=r=>t.check(lk($p,r)),t.uuidv4=r=>t.check(uk($p,r)),t.uuidv6=r=>t.check(pk($p,r)),t.uuidv7=r=>t.check(dk($p,r)),t.nanoid=r=>t.check(hk(TF,r)),t.guid=r=>t.check(Ig(Qk,r)),t.cuid=r=>t.check(gk(RF,r)),t.cuid2=r=>t.check(vk($F,r)),t.ulid=r=>t.check(yk(PF,r)),t.base64=r=>t.check(kk(DF,r)),t.base64url=r=>t.check(Tk(MF,r)),t.xid=r=>t.check(bk(OF,r)),t.ksuid=r=>t.check(xk(CF,r)),t.ipv4=r=>t.check(_k(IF,r)),t.ipv6=r=>t.check(wk(AF,r)),t.cidrv4=r=>t.check(Sk(jF,r)),t.cidrv6=r=>t.check(Ek(NF,r)),t.e164=r=>t.check(Rk(zF,r)),t.datetime=r=>t.check(Hg(r)),t.date=r=>t.check(Bg(r)),t.time=r=>t.check(Wg(r)),t.duration=r=>t.check(Zg(r))});function D(t){return ak(wF,t)}var St=z("ZodStringFormat",(t,e)=>{bt.init(t,e),tT.init(t,e)}),SF=z("ZodEmail",(t,e)=>{gE.init(t,e),St.init(t,e)});var Qk=z("ZodGUID",(t,e)=>{fE.init(t,e),St.init(t,e)});var $p=z("ZodUUID",(t,e)=>{hE.init(t,e),St.init(t,e)});var EF=z("ZodURL",(t,e)=>{vE.init(t,e),St.init(t,e)});var kF=z("ZodEmoji",(t,e)=>{yE.init(t,e),St.init(t,e)});var TF=z("ZodNanoID",(t,e)=>{bE.init(t,e),St.init(t,e)});var RF=z("ZodCUID",(t,e)=>{xE.init(t,e),St.init(t,e)});var $F=z("ZodCUID2",(t,e)=>{_E.init(t,e),St.init(t,e)});var PF=z("ZodULID",(t,e)=>{wE.init(t,e),St.init(t,e)});var OF=z("ZodXID",(t,e)=>{SE.init(t,e),St.init(t,e)});var CF=z("ZodKSUID",(t,e)=>{EE.init(t,e),St.init(t,e)});var IF=z("ZodIPv4",(t,e)=>{PE.init(t,e),St.init(t,e)});var AF=z("ZodIPv6",(t,e)=>{OE.init(t,e),St.init(t,e)});var jF=z("ZodCIDRv4",(t,e)=>{CE.init(t,e),St.init(t,e)});var NF=z("ZodCIDRv6",(t,e)=>{IE.init(t,e),St.init(t,e)});var DF=z("ZodBase64",(t,e)=>{jE.init(t,e),St.init(t,e)});var MF=z("ZodBase64URL",(t,e)=>{NE.init(t,e),St.init(t,e)});var zF=z("ZodE164",(t,e)=>{DE.init(t,e),St.init(t,e)});var LF=z("ZodJWT",(t,e)=>{ME.init(t,e),St.init(t,e)});var rT=z("ZodNumber",(t,e)=>{Pg.init(t,e),Pt.init(t,e),t.gt=(n,s)=>t.check(Sp(n,s)),t.gte=(n,s)=>t.check(bc(n,s)),t.min=(n,s)=>t.check(bc(n,s)),t.lt=(n,s)=>t.check(wp(n,s)),t.lte=(n,s)=>t.check(yc(n,s)),t.max=(n,s)=>t.check(yc(n,s)),t.int=n=>t.check(Xk(n)),t.safe=n=>t.check(Xk(n)),t.positive=n=>t.check(Sp(0,n)),t.nonnegative=n=>t.check(bc(0,n)),t.negative=n=>t.check(wp(0,n)),t.nonpositive=n=>t.check(yc(0,n)),t.multipleOf=(n,s)=>t.check(Ep(n,s)),t.step=(n,s)=>t.check(Ep(n,s)),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 st(t){return Ak(rT,t)}var qF=z("ZodNumberFormat",(t,e)=>{zE.init(t,e),rT.init(t,e)});function Xk(t){return jk(qF,t)}var FF=z("ZodBoolean",(t,e)=>{LE.init(t,e),Pt.init(t,e)});function Wt(t){return Nk(FF,t)}var UF=z("ZodNull",(t,e)=>{qE.init(t,e),Pt.init(t,e)});function Yg(t){return Dk(UF,t)}var HF=z("ZodUnknown",(t,e)=>{FE.init(t,e),Pt.init(t,e)});function Et(){return Mk(HF)}var BF=z("ZodNever",(t,e)=>{UE.init(t,e),Pt.init(t,e)});function WF(t){return zk(BF,t)}var ZF=z("ZodArray",(t,e)=>{HE.init(t,e),Pt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(mo(r,n)),t.nonempty=r=>t.check(mo(1,r)),t.max=(r,n)=>t.check(kp(r,n)),t.length=(r,n)=>t.check(Tp(r,n)),t.unwrap=()=>t.element});function Me(t,e){return Lk(ZF,t,e)}var nT=z("ZodObject",(t,e)=>{BE.init(t,e),Pt.init(t,e),Ge.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Ar(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Et()}),t.loose=()=>t.clone({...t._zod.def,catchall:Et()}),t.strict=()=>t.clone({...t._zod.def,catchall:WF()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Ge.extend(t,r),t.merge=r=>Ge.merge(t,r),t.pick=r=>Ge.pick(t,r),t.omit=r=>Ge.omit(t,r),t.partial=(...r)=>Ge.partial(oT,t,r[0]),t.required=(...r)=>Ge.required(aT,t,r[0])});function te(t,e){let r={type:"object",get shape(){return Ge.assignProp(this,"shape",{...t}),this.shape},...Ge.normalizeParams(e)};return new nT(r)}function vr(t,e){return new nT({type:"object",get shape(){return Ge.assignProp(this,"shape",{...t}),this.shape},catchall:Et(),...Ge.normalizeParams(e)})}var sT=z("ZodUnion",(t,e)=>{Og.init(t,e),Pt.init(t,e),t.options=e.options});function dt(t,e){return new sT({type:"union",options:t,...Ge.normalizeParams(e)})}var VF=z("ZodDiscriminatedUnion",(t,e)=>{sT.init(t,e),WE.init(t,e)});function Kg(t,e,r){return new VF({type:"union",options:e,discriminator:t,...Ge.normalizeParams(r)})}var GF=z("ZodIntersection",(t,e)=>{ZE.init(t,e),Pt.init(t,e)});function Pp(t,e){return new GF({type:"intersection",left:t,right:e})}var YF=z("ZodRecord",(t,e)=>{VE.init(t,e),Pt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function kt(t,e,r){return new YF({type:"record",keyType:t,valueType:e,...Ge.normalizeParams(r)})}var Vg=z("ZodEnum",(t,e)=>{GE.init(t,e),Pt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let i={};for(let o of n)if(r.has(o))i[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Vg({...e,checks:[],...Ge.normalizeParams(s),entries:i})},t.exclude=(n,s)=>{let i={...e.entries};for(let o of n)if(r.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Vg({...e,checks:[],...Ge.normalizeParams(s),entries:i})}});function Ar(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Vg({type:"enum",entries:r,...Ge.normalizeParams(e)})}var KF=z("ZodLiteral",(t,e)=>{YE.init(t,e),Pt.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 ae(t,e){return new KF({type:"literal",values:Array.isArray(t)?t:[t],...Ge.normalizeParams(e)})}var JF=z("ZodTransform",(t,e)=>{KE.init(t,e),Pt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(Ge.issue(i,r.value,e));else{let o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(Ge.issue(o))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(i=>(r.value=i,r)):(r.value=s,r)}});function iT(t){return new JF({type:"transform",transform:t})}var oT=z("ZodOptional",(t,e)=>{JE.init(t,e),Pt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function $t(t){return new oT({type:"optional",innerType:t})}var QF=z("ZodNullable",(t,e)=>{QE.init(t,e),Pt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function eT(t){return new QF({type:"nullable",innerType:t})}var XF=z("ZodDefault",(t,e)=>{XE.init(t,e),Pt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function e9(t,e){return new XF({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var t9=z("ZodPrefault",(t,e)=>{ek.init(t,e),Pt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function r9(t,e){return new t9({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var aT=z("ZodNonOptional",(t,e)=>{tk.init(t,e),Pt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function n9(t,e){return new aT({type:"nonoptional",innerType:t,...Ge.normalizeParams(e)})}var s9=z("ZodCatch",(t,e)=>{rk.init(t,e),Pt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function i9(t,e){return new s9({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var o9=z("ZodPipe",(t,e)=>{nk.init(t,e),Pt.init(t,e),t.in=e.in,t.out=e.out});function Gg(t,e){return new o9({type:"pipe",in:t,out:e})}var a9=z("ZodReadonly",(t,e)=>{sk.init(t,e),Pt.init(t,e)});function c9(t){return new a9({type:"readonly",innerType:t})}var cT=z("ZodCustom",(t,e)=>{ik.init(t,e),Pt.init(t,e)});function l9(t){let e=new cr({check:"custom"});return e._zod.check=t,e}function lT(t,e){return qk(cT,t??(()=>!0),e)}function u9(t,e={}){return Fk(cT,t,e)}function p9(t){let e=l9(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ge.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(Ge.issue(s))}},t(r.value,r)));return e}function Jg(t,e){return Gg(iT(t),e)}rn(ok());var Xg="2025-11-25";var uT=[Xg,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ls="io.modelcontextprotocol/related-task",Cp="2.0",tr=lT(t=>t!==null&&(typeof t=="object"||typeof t=="function")),pT=dt([D(),st().int()]),dT=D(),Ahe=vr({ttl:dt([st(),Yg()]).optional(),pollInterval:st().optional()}),d9=te({ttl:st().optional()}),m9=te({taskId:D()}),ev=vr({progressToken:pT.optional(),[Ls]:m9.optional()}),Jr=te({_meta:ev.optional()}),Sc=Jr.extend({task:d9.optional()}),mT=t=>Sc.safeParse(t).success,rr=te({method:D(),params:Jr.loose().optional()}),nn=te({_meta:ev.optional()}),sn=te({method:D(),params:nn.loose().optional()}),nr=vr({_meta:ev.optional()}),Ip=dt([D(),st().int()]),fT=te({jsonrpc:ae(Cp),id:Ip,...rr.shape}).strict(),tv=t=>fT.safeParse(t).success,hT=te({jsonrpc:ae(Cp),...sn.shape}).strict(),gT=t=>hT.safeParse(t).success,rv=te({jsonrpc:ae(Cp),id:Ip,result:nr}).strict(),Ec=t=>rv.safeParse(t).success;var be;(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"})(be||(be={}));var nv=te({jsonrpc:ae(Cp),id:Ip.optional(),error:te({code:st().int(),message:D(),data:Et().optional()})}).strict();var vT=t=>nv.safeParse(t).success;var yT=dt([fT,hT,rv,nv]),jhe=dt([rv,nv]),xi=nr.strict(),f9=nn.extend({requestId:Ip.optional(),reason:D().optional()}),Ap=sn.extend({method:ae("notifications/cancelled"),params:f9}),h9=te({src:D(),mimeType:D().optional(),sizes:Me(D()).optional(),theme:Ar(["light","dark"]).optional()}),kc=te({icons:Me(h9).optional()}),ho=te({name:D(),title:D().optional()}),bT=ho.extend({...ho.shape,...kc.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),g9=Pp(te({applyDefaults:Wt().optional()}),kt(D(),Et())),v9=Jg(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Pp(te({form:g9.optional(),url:tr.optional()}),kt(D(),Et()).optional())),y9=vr({list:tr.optional(),cancel:tr.optional(),requests:vr({sampling:vr({createMessage:tr.optional()}).optional(),elicitation:vr({create:tr.optional()}).optional()}).optional()}),b9=vr({list:tr.optional(),cancel:tr.optional(),requests:vr({tools:vr({call:tr.optional()}).optional()}).optional()}),x9=te({experimental:kt(D(),tr).optional(),sampling:te({context:tr.optional(),tools:tr.optional()}).optional(),elicitation:v9.optional(),roots:te({listChanged:Wt().optional()}).optional(),tasks:y9.optional()}),_9=Jr.extend({protocolVersion:D(),capabilities:x9,clientInfo:bT}),w9=rr.extend({method:ae("initialize"),params:_9});var S9=te({experimental:kt(D(),tr).optional(),logging:tr.optional(),completions:tr.optional(),prompts:te({listChanged:Wt().optional()}).optional(),resources:te({subscribe:Wt().optional(),listChanged:Wt().optional()}).optional(),tools:te({listChanged:Wt().optional()}).optional(),tasks:b9.optional()}),sv=nr.extend({protocolVersion:D(),capabilities:S9,serverInfo:bT,instructions:D().optional()}),E9=sn.extend({method:ae("notifications/initialized"),params:nn.optional()});var jp=rr.extend({method:ae("ping"),params:Jr.optional()}),k9=te({progress:st(),total:$t(st()),message:$t(D())}),T9=te({...nn.shape,...k9.shape,progressToken:pT}),Np=sn.extend({method:ae("notifications/progress"),params:T9}),R9=Jr.extend({cursor:dT.optional()}),Tc=rr.extend({params:R9.optional()}),Rc=nr.extend({nextCursor:dT.optional()}),$9=Ar(["working","input_required","completed","failed","cancelled"]),$c=te({taskId:D(),status:$9,ttl:dt([st(),Yg()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:$t(st()),statusMessage:$t(D())}),_i=nr.extend({task:$c}),P9=nn.merge($c),Pc=sn.extend({method:ae("notifications/tasks/status"),params:P9}),Dp=rr.extend({method:ae("tasks/get"),params:Jr.extend({taskId:D()})}),Mp=nr.merge($c),zp=rr.extend({method:ae("tasks/result"),params:Jr.extend({taskId:D()})}),Nhe=nr.loose(),Lp=Tc.extend({method:ae("tasks/list")}),qp=Rc.extend({tasks:Me($c)}),Fp=rr.extend({method:ae("tasks/cancel"),params:Jr.extend({taskId:D()})}),xT=nr.merge($c),_T=te({uri:D(),mimeType:$t(D()),_meta:kt(D(),Et()).optional()}),wT=_T.extend({text:D()}),iv=D().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ST=_T.extend({blob:iv}),Oc=Ar(["user","assistant"]),go=te({audience:Me(Oc).optional(),priority:st().min(0).max(1).optional(),lastModified:_c.datetime({offset:!0}).optional()}),ET=te({...ho.shape,...kc.shape,uri:D(),description:$t(D()),mimeType:$t(D()),annotations:go.optional(),_meta:$t(vr({}))}),O9=te({...ho.shape,...kc.shape,uriTemplate:D(),description:$t(D()),mimeType:$t(D()),annotations:go.optional(),_meta:$t(vr({}))}),C9=Tc.extend({method:ae("resources/list")}),ov=Rc.extend({resources:Me(ET)}),I9=Tc.extend({method:ae("resources/templates/list")}),av=Rc.extend({resourceTemplates:Me(O9)}),cv=Jr.extend({uri:D()}),A9=cv,j9=rr.extend({method:ae("resources/read"),params:A9}),lv=nr.extend({contents:Me(dt([wT,ST]))}),uv=sn.extend({method:ae("notifications/resources/list_changed"),params:nn.optional()}),N9=cv,D9=rr.extend({method:ae("resources/subscribe"),params:N9}),M9=cv,z9=rr.extend({method:ae("resources/unsubscribe"),params:M9}),L9=nn.extend({uri:D()}),q9=sn.extend({method:ae("notifications/resources/updated"),params:L9}),F9=te({name:D(),description:$t(D()),required:$t(Wt())}),U9=te({...ho.shape,...kc.shape,description:$t(D()),arguments:$t(Me(F9)),_meta:$t(vr({}))}),H9=Tc.extend({method:ae("prompts/list")}),pv=Rc.extend({prompts:Me(U9)}),B9=Jr.extend({name:D(),arguments:kt(D(),D()).optional()}),W9=rr.extend({method:ae("prompts/get"),params:B9}),dv=te({type:ae("text"),text:D(),annotations:go.optional(),_meta:kt(D(),Et()).optional()}),mv=te({type:ae("image"),data:iv,mimeType:D(),annotations:go.optional(),_meta:kt(D(),Et()).optional()}),fv=te({type:ae("audio"),data:iv,mimeType:D(),annotations:go.optional(),_meta:kt(D(),Et()).optional()}),Z9=te({type:ae("tool_use"),name:D(),id:D(),input:kt(D(),Et()),_meta:kt(D(),Et()).optional()}),V9=te({type:ae("resource"),resource:dt([wT,ST]),annotations:go.optional(),_meta:kt(D(),Et()).optional()}),G9=ET.extend({type:ae("resource_link")}),hv=dt([dv,mv,fv,G9,V9]),Y9=te({role:Oc,content:hv}),gv=nr.extend({description:D().optional(),messages:Me(Y9)}),vv=sn.extend({method:ae("notifications/prompts/list_changed"),params:nn.optional()}),K9=te({title:D().optional(),readOnlyHint:Wt().optional(),destructiveHint:Wt().optional(),idempotentHint:Wt().optional(),openWorldHint:Wt().optional()}),J9=te({taskSupport:Ar(["required","optional","forbidden"]).optional()}),kT=te({...ho.shape,...kc.shape,description:D().optional(),inputSchema:te({type:ae("object"),properties:kt(D(),tr).optional(),required:Me(D()).optional()}).catchall(Et()),outputSchema:te({type:ae("object"),properties:kt(D(),tr).optional(),required:Me(D()).optional()}).catchall(Et()).optional(),annotations:K9.optional(),execution:J9.optional(),_meta:kt(D(),Et()).optional()}),Q9=Tc.extend({method:ae("tools/list")}),yv=Rc.extend({tools:Me(kT)}),vo=nr.extend({content:Me(hv).default([]),structuredContent:kt(D(),Et()).optional(),isError:Wt().optional()}),Dhe=vo.or(nr.extend({toolResult:Et()})),X9=Sc.extend({name:D(),arguments:kt(D(),Et()).optional()}),eU=rr.extend({method:ae("tools/call"),params:X9}),bv=sn.extend({method:ae("notifications/tools/list_changed"),params:nn.optional()}),TT=te({autoRefresh:Wt().default(!0),debounceMs:st().int().nonnegative().default(300)}),RT=Ar(["debug","info","notice","warning","error","critical","alert","emergency"]),tU=Jr.extend({level:RT}),rU=rr.extend({method:ae("logging/setLevel"),params:tU}),nU=nn.extend({level:RT,logger:D().optional(),data:Et()}),sU=sn.extend({method:ae("notifications/message"),params:nU}),iU=te({name:D().optional()}),oU=te({hints:Me(iU).optional(),costPriority:st().min(0).max(1).optional(),speedPriority:st().min(0).max(1).optional(),intelligencePriority:st().min(0).max(1).optional()}),aU=te({mode:Ar(["auto","required","none"]).optional()}),cU=te({type:ae("tool_result"),toolUseId:D().describe("The unique identifier for the corresponding tool call."),content:Me(hv).default([]),structuredContent:te({}).loose().optional(),isError:Wt().optional(),_meta:kt(D(),Et()).optional()}),lU=Kg("type",[dv,mv,fv]),Op=Kg("type",[dv,mv,fv,Z9,cU]),uU=te({role:Oc,content:dt([Op,Me(Op)]),_meta:kt(D(),Et()).optional()}),pU=Sc.extend({messages:Me(uU),modelPreferences:oU.optional(),systemPrompt:D().optional(),includeContext:Ar(["none","thisServer","allServers"]).optional(),temperature:st().optional(),maxTokens:st().int(),stopSequences:Me(D()).optional(),metadata:tr.optional(),tools:Me(kT).optional(),toolChoice:aU.optional()}),xv=rr.extend({method:ae("sampling/createMessage"),params:pU}),_v=nr.extend({model:D(),stopReason:$t(Ar(["endTurn","stopSequence","maxTokens"]).or(D())),role:Oc,content:lU}),wv=nr.extend({model:D(),stopReason:$t(Ar(["endTurn","stopSequence","maxTokens","toolUse"]).or(D())),role:Oc,content:dt([Op,Me(Op)])}),dU=te({type:ae("boolean"),title:D().optional(),description:D().optional(),default:Wt().optional()}),mU=te({type:ae("string"),title:D().optional(),description:D().optional(),minLength:st().optional(),maxLength:st().optional(),format:Ar(["email","uri","date","date-time"]).optional(),default:D().optional()}),fU=te({type:Ar(["number","integer"]),title:D().optional(),description:D().optional(),minimum:st().optional(),maximum:st().optional(),default:st().optional()}),hU=te({type:ae("string"),title:D().optional(),description:D().optional(),enum:Me(D()),default:D().optional()}),gU=te({type:ae("string"),title:D().optional(),description:D().optional(),oneOf:Me(te({const:D(),title:D()})),default:D().optional()}),vU=te({type:ae("string"),title:D().optional(),description:D().optional(),enum:Me(D()),enumNames:Me(D()).optional(),default:D().optional()}),yU=dt([hU,gU]),bU=te({type:ae("array"),title:D().optional(),description:D().optional(),minItems:st().optional(),maxItems:st().optional(),items:te({type:ae("string"),enum:Me(D())}),default:Me(D()).optional()}),xU=te({type:ae("array"),title:D().optional(),description:D().optional(),minItems:st().optional(),maxItems:st().optional(),items:te({anyOf:Me(te({const:D(),title:D()}))}),default:Me(D()).optional()}),_U=dt([bU,xU]),wU=dt([vU,yU,_U]),SU=dt([wU,dU,mU,fU]),EU=Sc.extend({mode:ae("form").optional(),message:D(),requestedSchema:te({type:ae("object"),properties:kt(D(),SU),required:Me(D()).optional()})}),kU=Sc.extend({mode:ae("url"),message:D(),elicitationId:D(),url:D().url()}),TU=dt([EU,kU]),Sv=rr.extend({method:ae("elicitation/create"),params:TU}),RU=nn.extend({elicitationId:D()}),$U=sn.extend({method:ae("notifications/elicitation/complete"),params:RU}),Ev=nr.extend({action:Ar(["accept","decline","cancel"]),content:Jg(t=>t===null?void 0:t,kt(D(),dt([D(),st(),Wt(),Me(D())])).optional())}),PU=te({type:ae("ref/resource"),uri:D()});var OU=te({type:ae("ref/prompt"),name:D()}),CU=Jr.extend({ref:dt([OU,PU]),argument:te({name:D(),value:D()}),context:te({arguments:kt(D(),D()).optional()}).optional()}),IU=rr.extend({method:ae("completion/complete"),params:CU});var kv=nr.extend({completion:vr({values:Me(D()).max(100),total:$t(st().int()),hasMore:$t(Wt())})}),AU=te({uri:D().startsWith("file://"),name:D().optional(),_meta:kt(D(),Et()).optional()}),jU=rr.extend({method:ae("roots/list"),params:Jr.optional()}),NU=nr.extend({roots:Me(AU)}),DU=sn.extend({method:ae("notifications/roots/list_changed"),params:nn.optional()}),Mhe=dt([jp,w9,IU,rU,W9,H9,C9,I9,j9,D9,z9,eU,Q9,Dp,zp,Lp,Fp]),zhe=dt([Ap,Np,E9,DU,Pc]),Lhe=dt([xi,_v,wv,Ev,NU,Mp,qp,_i]),qhe=dt([jp,xv,Sv,jU,Dp,zp,Lp,Fp]),Fhe=dt([Ap,Np,sU,q9,uv,bv,vv,Pc,$U]),Uhe=dt([xi,sv,kv,gv,pv,ov,av,lv,vo,yv,Mp,qp,_i]),me=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===be.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Qg(s.elicitations,r)}return new t(e,r,n)}},Qg=class extends me{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(be.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function qs(t){return t==="completed"||t==="failed"||t==="cancelled"}var _ge=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Tv(t){let r=Rp(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Uk(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Rv(t,e){let r=_n(t,e);if(!r.success)throw r.error;return r.data}var UU=6e4,Up=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(Ap,r=>{this._oncancel(r)}),this.setNotificationHandler(Np,r=>{this._onprogress(r)}),this.setRequestHandler(jp,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Dp,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new me(be.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(zp,async(r,n)=>{let s=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,d=new me(p.error.code,p.error.message,p.error.data);u(d)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(i,n.sessionId);if(!o)throw new me(be.InvalidParams,`Task not found: ${i}`);if(!qs(o.status))return await this._waitForTaskUpdate(i,n.signal),await s();if(qs(o.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Ls]:{taskId:i}}}}return await s()};return await s()}),this.setRequestHandler(Lp,async(r,n)=>{try{let{tasks:s,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:i,_meta:{}}}catch(s){throw new me(be.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Fp,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new me(be.InvalidParams,`Task not found: ${r.params.taskId}`);if(qs(s.status))throw new me(be.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new me(be.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(s){throw s instanceof me?s:new me(be.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:s})}_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),me.fromError(be.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){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let s=this._transport?.onmessage;this._transport.onmessage=(i,o)=>{s?.(i,o),Ec(i)||vT(i)?this._onresponse(i):tv(i)?this._onrequest(i,o):gT(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=me.fromError(be.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,s=this._transport,i=e.params?._meta?.[Ls]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:be.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},s?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):s?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let a=mT(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,l={signal:o.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(o.signal.aborted)return;let p={relatedRequestId:e.id};i&&(p.relatedTask={taskId:i}),await this.notification(u,p)},sendRequest:async(u,p,d)=>{if(o.signal.aborted)throw new me(be.ConnectionClosed,"Request was cancelled");let m={...d,relatedRequestId:e.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});let f=m.relatedTask?.taskId??i;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(u,p,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(o.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:p,timestamp:Date.now()},s?.sessionId):await s?.send(p)},async u=>{if(o.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:be.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},s?.sessionId):await s?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),i=this._progressHandlers.get(s);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),o(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ec(e))n(e);else{let o=new me(e.error.code,e.error.message,e.error.data);n(o)}return}let s=this._responseHandlers.get(r);if(s===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 i=!1;if(Ec(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let a=o.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Ec(e))s(e);else{let o=me.fromError(e.error.code,e.error.message,e.error.data);s(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(o){yield{type:"error",error:o instanceof me?o:new me(be.InternalError,String(o))}}return}let i;try{let o=await this.request(e,_i,n);if(o.task)i=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new me(be.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},qs(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new me(be.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new me(be.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof me?o:new me(be.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=v=>{u(v)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){p(v);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Ls]:c}});let f=v=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(v)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let b=v instanceof me?v:new me(be.RequestTimeout,String(v));u(b)};this._responseHandlers.set(d,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{let b=_n(r,v.result);b.success?l(b.data):u(b.error)}catch(b){u(b)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let y=n?.timeout??UU,g=()=>f(me.fromError(be.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(d,y,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let h=c?.taskId;if(h){let v=b=>{let x=this._responseHandlers.get(d);x?x(b):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,v),this._enqueueTaskMessage(h,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(d),u(b)})}else this._transport.send(m,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(v=>{this._cleanupTimeout(d),u(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Mp,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},qp,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},xT,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||{},[Ls]: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||{},[Ls]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[Ls]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=Tv(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,i)=>{let o=Rv(e,s);return Promise.resolve(r(o,i))})}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=Tv(e);this._notificationHandlers.set(n,s=>{let i=Rv(e,s);return Promise.resolve(r(i))})}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 s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&tv(s.message)){let i=s.message.id,o=this._requestResolvers.get(i);o?(o(new me(be.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new me(be.InvalidRequest,"Request cancelled"));return}let o=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(o),i(new me(be.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let i=await n.getTask(s,r);if(!i)throw new me(be.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(s,i,o)=>{await n.storeTaskResult(s,i,o,r);let a=await n.getTask(s,r);if(a){let c=Pc.parse({method:"notifications/tasks/status",params:a});await this.notification(c),qs(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,i,o)=>{let a=await n.getTask(s,r);if(!a)throw new me(be.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(qs(a.status))throw new me(be.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,i,o,r);let c=await n.getTask(s,r);if(c){let l=Pc.parse({method:"notifications/tasks/status",params:c});await this.notification(l),qs(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function $T(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function PT(t,e){let r={...t};for(let n in e){let s=n,i=e[s];if(i===void 0)continue;let o=r[s];$T(o)&&$T(i)?r[s]={...o,...i}:r[s]=i}return r}var h$=X(db(),1),g$=X(f$(),1);function IW(){let t=new h$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,g$.default)(t),t}var kd=class{constructor(e){this._ajv=e??IW()}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 Td=class{constructor(e){this._client=e}async*callToolStream(e,r=vo,n){let s=this._client,i={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},o=s.requestStream({method:"tools/call",params:e},r,i),a=s.getToolOutputValidator(e.name);for await(let c of o){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new me(be.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new me(be.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof me){yield{type:"error",error:u};return}yield{type:"error",error:new me(be.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function v$(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 y$(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}}function Rd(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let s of Object.keys(n)){let i=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[s]=i.default),r[s]!==void 0&&Rd(i,r[s])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Rd(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Rd(r,e)}}function AW(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var jo=class extends Up{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new kd,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",bv,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",vv,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",uv,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Td(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=PT(this._capabilities,e)}setRequestHandler(e,r){let s=Rp(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let i;if(fo(s)){let a=s;i=a._zod?.def?.value??a.value}else{let a=s;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let o=i;if(o==="elicitation/create"){let a=async(c,l)=>{let u=_n(Sv,c);if(!u.success){let v=u.error instanceof Error?u.error.message:String(u.error);throw new me(be.InvalidParams,`Invalid elicitation request: ${v}`)}let{params:p}=u.data;p.mode=p.mode??"form";let{supportsFormMode:d,supportsUrlMode:m}=AW(this._capabilities.elicitation);if(p.mode==="form"&&!d)throw new me(be.InvalidParams,"Client does not support form-mode elicitation requests");if(p.mode==="url"&&!m)throw new me(be.InvalidParams,"Client does not support URL-mode elicitation requests");let f=await Promise.resolve(r(c,l));if(p.task){let v=_n(_i,f);if(!v.success){let b=v.error instanceof Error?v.error.message:String(v.error);throw new me(be.InvalidParams,`Invalid task creation result: ${b}`)}return v.data}let y=_n(Ev,f);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new me(be.InvalidParams,`Invalid elicitation result: ${v}`)}let g=y.data,h=p.mode==="form"?p.requestedSchema:void 0;if(p.mode==="form"&&g.action==="accept"&&g.content&&h&&this._capabilities.elicitation?.form?.applyDefaults)try{Rd(h,g.content)}catch{}return g};return super.setRequestHandler(e,a)}if(o==="sampling/createMessage"){let a=async(c,l)=>{let u=_n(xv,c);if(!u.success){let g=u.error instanceof Error?u.error.message:String(u.error);throw new me(be.InvalidParams,`Invalid sampling request: ${g}`)}let{params:p}=u.data,d=await Promise.resolve(r(c,l));if(p.task){let g=_n(_i,d);if(!g.success){let h=g.error instanceof Error?g.error.message:String(g.error);throw new me(be.InvalidParams,`Invalid task creation result: ${h}`)}return g.data}let f=p.tools||p.toolChoice?wv:_v,y=_n(f,d);if(!y.success){let g=y.error instanceof Error?y.error.message:String(y.error);throw new me(be.InvalidParams,`Invalid sampling result: ${g}`)}return y.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Xg,capabilities:this._capabilities,clientInfo:this._clientInfo}},sv,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!uT.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){v$(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&y$(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},xi,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},kv,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},xi,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},gv,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},pv,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},ov,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},av,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},lv,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},xi,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},xi,r)}async callTool(e,r=vo,n){if(this.isToolTaskRequired(e.name))throw new me(be.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let s=await this.request({method:"tools/call",params:e},r,n),i=this.getToolOutputValidator(e.name);if(i){if(!s.structuredContent&&!s.isError)throw new me(be.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{let o=i(s.structuredContent);if(!o.valid)throw new me(be.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof me?o:new me(be.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return s}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let s=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,s)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},yv,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,s){let i=TT.safeParse(n);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:o,debounceMs:a}=i.data,{onChanged:c}=n,l=async()=>{if(!o){c(null,null);return}try{let p=await s();c(null,p)}catch(p){let d=p instanceof Error?p:new Error(String(p));c(d,null)}},u=()=>{if(a){let p=this._listChangedDebounceTimers.get(e);p&&clearTimeout(p);let d=setTimeout(l,a);this._listChangedDebounceTimers.set(e,d)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var cP=X(oP(),1),al=X(require("node:process"),1),lP=require("node:stream");var Pd=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),oZ(r)}clear(){this._buffer=void 0}};function oZ(t){return yT.parse(JSON.parse(t))}function aP(t){return JSON.stringify(t)+` -`}var aZ=al.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function cZ(){let t={};for(let e of aZ){let r=al.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Mo=class{constructor(e){this._readBuffer=new Pd,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new lP.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,cP.default)(this._serverParams.command,this._serverParams.args??[],{env:{...cZ(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:al.default.platform==="win32"&&lZ(),cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=aP(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function lZ(){return"type"in al.default}Pn();Id();ne();fl();ne();Pn();var fZ=5e3;async function Zd(t,e={},r=fZ){let n=new Promise((s,i)=>setTimeout(()=>i(new Error(`Fetch timeout after ${r}ms`)),r));return Promise.race([fetch(t,e),n])}var hZ="7.8.5";function Vd(t){let e=$n();return`http://${e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}:${t}`}async function qb(t){try{return(await Zd(`${Vd(t)}/api/health`)).ok}catch{return!1}}async function hl(t,e=3e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function gl(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function vl(t){try{let e=await Zd(`${Vd(t)}/api/admin/shutdown`,{method:"POST"});return e.ok?!0:(_.warn("SYSTEM","Shutdown request returned error",{port:t,status:e.status}),!1)}catch(e){return e instanceof Error&&(e.message?.includes("ECONNREFUSED")||e.message?.includes("Fetch timeout"))?(_.debug("SYSTEM","Worker already stopped or not responding",{port:t}),!1):(_.error("SYSTEM","Shutdown request failed unexpectedly",{port:t},e),!1)}}function gZ(){return hZ}async function vZ(t){try{let e=await Zd(`${Vd(t)}/api/version`);return e.ok?(await e.json()).version:null}catch{return _.debug("SYSTEM","Could not fetch worker version",{port:t}),null}}async function UP(t){let e=gZ(),r=await vZ(t);return r?{matches:e===r,pluginVersion:e,workerVersion:r}:{matches:!0,pluginVersion:e,workerVersion:r}}ne();fl();var yl=5e3;async function bl(t,e,r){let n=new Promise(i=>setTimeout(()=>{_.warn("SYSTEM",`${r} timed out after ${e}ms`),i({completed:!1})},e)),s=t.then(i=>({completed:!0,result:i}));return Promise.race([s,n])}async function HP(t){_.info("SYSTEM","Shutdown initiated"),Cn();let e=await bl(Db(process.pid),yl,"Enumerate child processes"),r=e.completed?e.result??[]:[];if(_.info("SYSTEM","Found child processes",{count:r.length,pids:r}),t.server&&(await bl(yZ(t.server),yl,"Close HTTP server"),_.info("SYSTEM","HTTP server closed")),await bl(t.sessionManager.shutdownAll(),yl,"Shutdown sessions"),t.mcpClient&&(await bl(t.mcpClient.close(),yl,"Close MCP client"),_.info("SYSTEM","MCP client closed")),t.dbManager&&await bl(t.dbManager.close(),yl,"Close database"),r.length>0){_.info("SYSTEM","Force killing remaining children");for(let n of r)await Mb(n);await zb(r,5e3)}_.info("SYSTEM","Worker shutdown complete")}async function yZ(t){t.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),_.info("SYSTEM","Waited for Windows port cleanup"))}fl();ne();Jn();var bZ={waitForHealth:hl,checkVersionMatch:UP,httpShutdown:vl,waitForPortFree:gl,isPortInUse:qb,spawnDaemon:ml,writePidFile:dl,removePidFile:Cn,cleanStalePidFile:Nb,getPlatformTimeout:Ni};async function Fb(t,e,r=bZ){if(r.cleanStalePidFile(),await r.waitForHealth(t,1e3)){let i=await r.checkVersionMatch(t);if(i.matches)return{ready:!0};if(_.info("SYSTEM","Worker version mismatch detected - auto-restarting",{pluginVersion:i.pluginVersion,workerVersion:i.workerVersion}),await r.httpShutdown(t),!await r.waitForPortFree(t,r.getPlatformTimeout(Ot.PORT_IN_USE_WAIT)))return{ready:!1,error:"Port did not free after version mismatch restart"};r.removePidFile()}if(await r.isPortInUse(t))return _.info("SYSTEM","Port in use, waiting for worker to become healthy"),await r.waitForHealth(t,r.getPlatformTimeout(Ot.PORT_IN_USE_WAIT))?{ready:!0}:{ready:!1,error:"Port in use but worker not responding"};_.info("SYSTEM","Starting worker daemon");let n=r.spawnDaemon(e,t);return n===void 0?{ready:!1,error:"Failed to spawn worker daemon"}:(r.writePidFile({pid:n,port:t,startedAt:new Date().toISOString()}),await r.waitForHealth(t,r.getPlatformTimeout(Ot.POST_SPAWN_WAIT))?{ready:!0}:(r.removePidFile(),{ready:!1,error:"Worker failed to start (health check timeout)"}))}var tz=X(vu(),1),p0=X(require("fs"),1),d0=X(require("path"),1);ne();var o0=X(vu(),1),BM=X(OM(),1),WM=X(jM(),1),ZM=X(require("path"),1);kr();ne();Id();var Yre=[/^https?:\/\/localhost(:\d+)?$/,/^https?:\/\/127\.0\.0\.1(:\d+)?$/,/^https?:\/\/\[::1\](:\d+)?$/];function Kre(t){if(t===void 0||Yre.some(e=>e.test(t)))return!0;if(Ai()){let e=hP();if(e&&t&&new RegExp(`^https?://${e.replace(/\./g,"\\.")}(:\\d+)?$`).test(t))return!0}return!1}function a0(t){let e=[];e.push(o0.default.json({limit:"50mb"})),e.push((0,BM.default)({origin:(s,i)=>{Kre(s)?i(null,!0):(_.warn("SECURITY","CORS request blocked",{origin:s}),i(null,!1))}})),e.push((0,WM.default)()),e.push((s,i,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>s.path.endsWith(f)),l=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||c||l)return o();let u=Date.now(),p=`${s.method}-${Date.now()}`,d=t(s.method,s.path,s.body);_.info("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},d);let m=i.send.bind(i);i.send=function(f){let y=Date.now()-u;return _.info("HTTP",`\u2190 ${i.statusCode} ${s.path}`,{requestId:p,duration:`${y}ms`}),m(f)},o()});let r=Es(),n=ZM.default.join(r,"plugin","ui");return e.push(o0.default.static(n)),e}function af(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function c0(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",s=r.tool_input;return`tool=${_.formatTool(n,s)}`}return e.includes("/summarize")?"requesting summary":""}ne();var xu=class extends Error{constructor(r,n=500,s,i){super(r);this.statusCode=n;this.code=s;this.details=i;this.name="AppError"}};function VM(t,e,r,n){let s={error:t,message:e};return r&&(s.code=r),n&&(s.details=n),s}var GM=(t,e,r,n)=>{let s=t instanceof xu?t.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:s,error:t.message,code:t instanceof xu?t.code:void 0},t);let i=t instanceof xu,o=VM(i&&t.name||"Error",i?t.message:"Internal server error",i?t.code:void 0,i?t.details:void 0);r.status(s).json(o)};function YM(t,e){e.status(404).json(VM("NotFound",`Cannot ${t.method} ${t.path}`))}var cf=X(require("crypto"),1);ne();Qr();kr();function Jre(t,e){let r=Buffer.from(t),n=Buffer.from(e);return r.length!==n.length?(cf.default.timingSafeEqual(r,r),!1):cf.default.timingSafeEqual(r,n)}var KM="claude_pilot_session",JM=1440*60*1e3,ba=new Map;function Qre(t){let e=t.ip||t.socket.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"||e==="localhost"}function lf(){return qe.loadFromFile(dr).CLAUDE_PILOT_REMOTE_TOKEN}function Xre(){return cf.default.randomBytes(32).toString("hex")}function ene(t,e){let r=ba.get(t);return r?Date.now()-r.createdAt>JM?(ba.delete(t),!1):r.ip!==e?(_.warn("SECURITY","Session IP mismatch - possible session replay",{sessionIp:r.ip,requestIp:e}),!1):!0:!1}function QM(t){let e=Xre();return ba.set(e,{createdAt:Date.now(),ip:t}),e}function XM(t){ba.delete(t)}function tne(){let t=Date.now();for(let[e,r]of ba.entries())t-r.createdAt>JM&&ba.delete(e)}setInterval(tne,3600*1e3);function l0(t,e,r){if(Qre(t))return t.auth={isLocal:!0,scopes:["*"]},r();if(t.path==="/login"||t.path.startsWith("/api/auth/"))return r();let n=t.ip||t.socket.remoteAddress||"unknown",s=t.cookies?.[KM];if(s&&ene(s,n))return t.auth={isLocal:!1,clientId:"web-session",scopes:["*"]},r();let i=t.headers.authorization;if(i&&i.startsWith("Bearer ")){let c=i.slice(7),l=lf();if(l&&Jre(c,l))return t.auth={isLocal:!1,clientId:"api-client",scopes:["*"]},r()}if((t.headers.accept||"").includes("text/html")&&(t.path==="/"||t.path==="/viewer.html")){e.redirect("/login");return}_.warn("SECURITY","Unauthorized request",{path:t.path,ip:n}),e.status(401).json({code:"UNAUTHORIZED",message:"Authentication required"})}function u0(){return KM}function xa(){return!!lf()}ne();var ez=new Map;function rne(t){let e=t.ip||t.socket.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}function nne(t){let e=t.headers.authorization?.slice(7,23);return e?`token:${e}`:`ip:${t.ip||t.socket.remoteAddress||"unknown"}`}function uf(t=1e3,e=6e4){return(r,n,s)=>{if(rne(r))return s();let i=nne(r),o=Date.now(),a=o-e,c=ez.get(i);if(c||(c={timestamps:[]},ez.set(i,c)),c.timestamps=c.timestamps.filter(u=>u>a),c.timestamps.length>=t){let u=Math.ceil(e/1e3);_.warn("SECURITY","Rate limit exceeded",{key:i,requests:c.timestamps.length,limit:t}),n.setHeader("Retry-After",u.toString()),n.setHeader("X-RateLimit-Limit",t.toString()),n.setHeader("X-RateLimit-Remaining","0"),n.setHeader("X-RateLimit-Reset",Math.ceil((o+e)/1e3).toString()),n.status(429).json({code:"RATE_LIMITED",message:"Too many requests",retryAfter:u});return}c.timestamps.push(o);let l=t-c.timestamps.length;n.setHeader("X-RateLimit-Limit",t.toString()),n.setHeader("X-RateLimit-Remaining",l.toString()),n.setHeader("X-RateLimit-Reset",Math.ceil((o+e)/1e3).toString()),s()}}Pn();var sne="7.8.5",pf=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,tz.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,s)=>{this.server=this.app.listen(e,r,()=>{_.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",s)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(YM),this.app.use(GM)}setupMiddleware(){a0(c0).forEach(s=>this.app.use(s)),this.app.use("/api/auth/login",uf(10,6e4)),this.app.use(uf(1e3,6e4));let r=Md();if(r!=="127.0.0.1"&&r!=="localhost"){let s=xa();_.info("SYSTEM","Enabling authentication middleware for network access",{bind:r,tokenConfigured:s}),s||_.warn("SYSTEM","No CLAUDE_PILOT_REMOTE_TOKEN set - all remote requests will be rejected until a token is configured",{bind:r}),this.app.use(l0)}}setupCoreRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,n)=>{n.status(200).json({status:"ok",build:e,managed:process.env.CLAUDE_PILOT_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),coreReady:this.options.getCoreReady(),mcpReady:this.options.getMcpReady()})}),this.app.get("/api/core-ready",(r,n)=>{this.options.getCoreReady()?n.status(200).json({status:"ready",message:"Core services ready (Database + SearchManager)"}):n.status(503).json({status:"initializing",message:"Core services still initializing, please retry"})}),this.app.get("/api/readiness",(r,n)=>{this.options.getInitializationComplete()?n.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):n.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,n)=>{n.status(200).json({version:sne})}),this.app.get("/api/process-stats",async(r,n)=>{try{let{getProcessStats:s}=await Promise.resolve().then(()=>(fl(),FP)),i=await s();n.status(200).json({...i,uptime:Math.round((Date.now()-this.startTime)/1e3),platform:process.platform,pid:process.pid})}catch(s){_.error("SYSTEM","Failed to get process stats",{},s),n.status(500).json({error:"Failed to get process stats"})}}),this.app.get("/api/instructions",async(r,n)=>{let s=r.query.topic||"all",i=r.query.operation;try{let o;if(i){let a=d0.default.join(__dirname,"../skills/mem-search/operations",`${i}.md`);o=await p0.promises.readFile(a,"utf-8")}else{let a=d0.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await p0.promises.readFile(a,"utf-8");o=this.extractInstructionSection(c,s)}n.json({content:[{type:"text",text:o}]})}catch{n.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",af,async(r,n)=>{n.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_PILOT_MANAGED==="true"&&process.send?(_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.options.onRestart()},100)}),this.app.post("/api/admin/shutdown",af,async(r,n)=>{n.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_PILOT_MANAGED==="true"&&process.send?(_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.options.onShutdown()},100)})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let s=e.indexOf(r),i=e.indexOf(n);return s===-1?e:i===-1?e.substring(s):e.substring(s,i).trim()}};df();var nz=require("bun:sqlite");kr();ne();var mf=class{db;constructor(e){e||(Nn(Br),e=bu),this.db=new nz.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(n=>n.name==="observations_fts"||n.name==="session_summaries_fts")||(_.info("DB","Creating FTS5 tables"),this.db.run(` +`}var aZ=al.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function cZ(){let t={};for(let e of aZ){let r=al.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Mo=class{constructor(e){this._readBuffer=new Pd,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new lP.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,cP.default)(this._serverParams.command,this._serverParams.args??[],{env:{...cZ(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:al.default.platform==="win32"&&lZ(),cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=aP(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function lZ(){return"type"in al.default}Pn();Id();ne();fl();ne();Pn();var fZ=5e3;async function Zd(t,e={},r=fZ){let n=new Promise((s,i)=>setTimeout(()=>i(new Error(`Fetch timeout after ${r}ms`)),r));return Promise.race([fetch(t,e),n])}var hZ="7.9.0";function Vd(t){let e=$n();return`http://${e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}:${t}`}async function qb(t){try{return(await Zd(`${Vd(t)}/api/health`)).ok}catch{return!1}}async function hl(t,e=3e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function gl(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function vl(t){try{let e=await Zd(`${Vd(t)}/api/admin/shutdown`,{method:"POST"});return e.ok?!0:(_.warn("SYSTEM","Shutdown request returned error",{port:t,status:e.status}),!1)}catch(e){return e instanceof Error&&(e.message?.includes("ECONNREFUSED")||e.message?.includes("Fetch timeout"))?(_.debug("SYSTEM","Worker already stopped or not responding",{port:t}),!1):(_.error("SYSTEM","Shutdown request failed unexpectedly",{port:t},e),!1)}}function gZ(){return hZ}async function vZ(t){try{let e=await Zd(`${Vd(t)}/api/version`);return e.ok?(await e.json()).version:null}catch{return _.debug("SYSTEM","Could not fetch worker version",{port:t}),null}}async function UP(t){let e=gZ(),r=await vZ(t);return r?{matches:e===r,pluginVersion:e,workerVersion:r}:{matches:!0,pluginVersion:e,workerVersion:r}}ne();fl();var yl=5e3;async function bl(t,e,r){let n=new Promise(i=>setTimeout(()=>{_.warn("SYSTEM",`${r} timed out after ${e}ms`),i({completed:!1})},e)),s=t.then(i=>({completed:!0,result:i}));return Promise.race([s,n])}async function HP(t){_.info("SYSTEM","Shutdown initiated"),Cn();let e=await bl(Db(process.pid),yl,"Enumerate child processes"),r=e.completed?e.result??[]:[];if(_.info("SYSTEM","Found child processes",{count:r.length,pids:r}),t.server&&(await bl(yZ(t.server),yl,"Close HTTP server"),_.info("SYSTEM","HTTP server closed")),await bl(t.sessionManager.shutdownAll(),yl,"Shutdown sessions"),t.mcpClient&&(await bl(t.mcpClient.close(),yl,"Close MCP client"),_.info("SYSTEM","MCP client closed")),t.dbManager&&await bl(t.dbManager.close(),yl,"Close database"),r.length>0){_.info("SYSTEM","Force killing remaining children");for(let n of r)await Mb(n);await zb(r,5e3)}_.info("SYSTEM","Worker shutdown complete")}async function yZ(t){t.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),_.info("SYSTEM","Waited for Windows port cleanup"))}fl();ne();Jn();var bZ={waitForHealth:hl,checkVersionMatch:UP,httpShutdown:vl,waitForPortFree:gl,isPortInUse:qb,spawnDaemon:ml,writePidFile:dl,removePidFile:Cn,cleanStalePidFile:Nb,getPlatformTimeout:Ni};async function Fb(t,e,r=bZ){if(r.cleanStalePidFile(),await r.waitForHealth(t,1e3)){let i=await r.checkVersionMatch(t);if(i.matches)return{ready:!0};if(_.info("SYSTEM","Worker version mismatch detected - auto-restarting",{pluginVersion:i.pluginVersion,workerVersion:i.workerVersion}),await r.httpShutdown(t),!await r.waitForPortFree(t,r.getPlatformTimeout(Ot.PORT_IN_USE_WAIT)))return{ready:!1,error:"Port did not free after version mismatch restart"};r.removePidFile()}if(await r.isPortInUse(t))return _.info("SYSTEM","Port in use, waiting for worker to become healthy"),await r.waitForHealth(t,r.getPlatformTimeout(Ot.PORT_IN_USE_WAIT))?{ready:!0}:{ready:!1,error:"Port in use but worker not responding"};_.info("SYSTEM","Starting worker daemon");let n=r.spawnDaemon(e,t);return n===void 0?{ready:!1,error:"Failed to spawn worker daemon"}:(r.writePidFile({pid:n,port:t,startedAt:new Date().toISOString()}),await r.waitForHealth(t,r.getPlatformTimeout(Ot.POST_SPAWN_WAIT))?{ready:!0}:(r.removePidFile(),{ready:!1,error:"Worker failed to start (health check timeout)"}))}var tz=X(vu(),1),p0=X(require("fs"),1),d0=X(require("path"),1);ne();var o0=X(vu(),1),BM=X(OM(),1),WM=X(jM(),1),ZM=X(require("path"),1);kr();ne();Id();var Yre=[/^https?:\/\/localhost(:\d+)?$/,/^https?:\/\/127\.0\.0\.1(:\d+)?$/,/^https?:\/\/\[::1\](:\d+)?$/];function Kre(t){if(t===void 0||Yre.some(e=>e.test(t)))return!0;if(Ai()){let e=hP();if(e&&t&&new RegExp(`^https?://${e.replace(/\./g,"\\.")}(:\\d+)?$`).test(t))return!0}return!1}function a0(t){let e=[];e.push(o0.default.json({limit:"50mb"})),e.push((0,BM.default)({origin:(s,i)=>{Kre(s)?i(null,!0):(_.warn("SECURITY","CORS request blocked",{origin:s}),i(null,!1))}})),e.push((0,WM.default)()),e.push((s,i,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>s.path.endsWith(f)),l=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||c||l)return o();let u=Date.now(),p=`${s.method}-${Date.now()}`,d=t(s.method,s.path,s.body);_.info("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},d);let m=i.send.bind(i);i.send=function(f){let y=Date.now()-u;return _.info("HTTP",`\u2190 ${i.statusCode} ${s.path}`,{requestId:p,duration:`${y}ms`}),m(f)},o()});let r=Es(),n=ZM.default.join(r,"plugin","ui");return e.push(o0.default.static(n)),e}function af(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function c0(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",s=r.tool_input;return`tool=${_.formatTool(n,s)}`}return e.includes("/summarize")?"requesting summary":""}ne();var xu=class extends Error{constructor(r,n=500,s,i){super(r);this.statusCode=n;this.code=s;this.details=i;this.name="AppError"}};function VM(t,e,r,n){let s={error:t,message:e};return r&&(s.code=r),n&&(s.details=n),s}var GM=(t,e,r,n)=>{let s=t instanceof xu?t.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:s,error:t.message,code:t instanceof xu?t.code:void 0},t);let i=t instanceof xu,o=VM(i&&t.name||"Error",i?t.message:"Internal server error",i?t.code:void 0,i?t.details:void 0);r.status(s).json(o)};function YM(t,e){e.status(404).json(VM("NotFound",`Cannot ${t.method} ${t.path}`))}var cf=X(require("crypto"),1);ne();Qr();kr();function Jre(t,e){let r=Buffer.from(t),n=Buffer.from(e);return r.length!==n.length?(cf.default.timingSafeEqual(r,r),!1):cf.default.timingSafeEqual(r,n)}var KM="claude_pilot_session",JM=1440*60*1e3,ba=new Map;function Qre(t){let e=t.ip||t.socket.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"||e==="localhost"}function lf(){return qe.loadFromFile(dr).CLAUDE_PILOT_REMOTE_TOKEN}function Xre(){return cf.default.randomBytes(32).toString("hex")}function ene(t,e){let r=ba.get(t);return r?Date.now()-r.createdAt>JM?(ba.delete(t),!1):r.ip!==e?(_.warn("SECURITY","Session IP mismatch - possible session replay",{sessionIp:r.ip,requestIp:e}),!1):!0:!1}function QM(t){let e=Xre();return ba.set(e,{createdAt:Date.now(),ip:t}),e}function XM(t){ba.delete(t)}function tne(){let t=Date.now();for(let[e,r]of ba.entries())t-r.createdAt>JM&&ba.delete(e)}setInterval(tne,3600*1e3);function l0(t,e,r){if(Qre(t))return t.auth={isLocal:!0,scopes:["*"]},r();if(t.path==="/login"||t.path.startsWith("/api/auth/"))return r();let n=t.ip||t.socket.remoteAddress||"unknown",s=t.cookies?.[KM];if(s&&ene(s,n))return t.auth={isLocal:!1,clientId:"web-session",scopes:["*"]},r();let i=t.headers.authorization;if(i&&i.startsWith("Bearer ")){let c=i.slice(7),l=lf();if(l&&Jre(c,l))return t.auth={isLocal:!1,clientId:"api-client",scopes:["*"]},r()}if((t.headers.accept||"").includes("text/html")&&(t.path==="/"||t.path==="/viewer.html")){e.redirect("/login");return}_.warn("SECURITY","Unauthorized request",{path:t.path,ip:n}),e.status(401).json({code:"UNAUTHORIZED",message:"Authentication required"})}function u0(){return KM}function xa(){return!!lf()}ne();var ez=new Map;function rne(t){let e=t.ip||t.socket.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}function nne(t){let e=t.headers.authorization?.slice(7,23);return e?`token:${e}`:`ip:${t.ip||t.socket.remoteAddress||"unknown"}`}function uf(t=1e3,e=6e4){return(r,n,s)=>{if(rne(r))return s();let i=nne(r),o=Date.now(),a=o-e,c=ez.get(i);if(c||(c={timestamps:[]},ez.set(i,c)),c.timestamps=c.timestamps.filter(u=>u>a),c.timestamps.length>=t){let u=Math.ceil(e/1e3);_.warn("SECURITY","Rate limit exceeded",{key:i,requests:c.timestamps.length,limit:t}),n.setHeader("Retry-After",u.toString()),n.setHeader("X-RateLimit-Limit",t.toString()),n.setHeader("X-RateLimit-Remaining","0"),n.setHeader("X-RateLimit-Reset",Math.ceil((o+e)/1e3).toString()),n.status(429).json({code:"RATE_LIMITED",message:"Too many requests",retryAfter:u});return}c.timestamps.push(o);let l=t-c.timestamps.length;n.setHeader("X-RateLimit-Limit",t.toString()),n.setHeader("X-RateLimit-Remaining",l.toString()),n.setHeader("X-RateLimit-Reset",Math.ceil((o+e)/1e3).toString()),s()}}Pn();var sne="7.9.0",pf=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,tz.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,s)=>{this.server=this.app.listen(e,r,()=>{_.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",s)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(YM),this.app.use(GM)}setupMiddleware(){a0(c0).forEach(s=>this.app.use(s)),this.app.use("/api/auth/login",uf(10,6e4)),this.app.use(uf(1e3,6e4));let r=Md();if(r!=="127.0.0.1"&&r!=="localhost"){let s=xa();_.info("SYSTEM","Enabling authentication middleware for network access",{bind:r,tokenConfigured:s}),s||_.warn("SYSTEM","No CLAUDE_PILOT_REMOTE_TOKEN set - all remote requests will be rejected until a token is configured",{bind:r}),this.app.use(l0)}}setupCoreRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,n)=>{n.status(200).json({status:"ok",build:e,managed:process.env.CLAUDE_PILOT_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),coreReady:this.options.getCoreReady(),mcpReady:this.options.getMcpReady()})}),this.app.get("/api/core-ready",(r,n)=>{this.options.getCoreReady()?n.status(200).json({status:"ready",message:"Core services ready (Database + SearchManager)"}):n.status(503).json({status:"initializing",message:"Core services still initializing, please retry"})}),this.app.get("/api/readiness",(r,n)=>{this.options.getInitializationComplete()?n.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):n.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,n)=>{n.status(200).json({version:sne})}),this.app.get("/api/process-stats",async(r,n)=>{try{let{getProcessStats:s}=await Promise.resolve().then(()=>(fl(),FP)),i=await s();n.status(200).json({...i,uptime:Math.round((Date.now()-this.startTime)/1e3),platform:process.platform,pid:process.pid})}catch(s){_.error("SYSTEM","Failed to get process stats",{},s),n.status(500).json({error:"Failed to get process stats"})}}),this.app.get("/api/instructions",async(r,n)=>{let s=r.query.topic||"all",i=r.query.operation;try{let o;if(i){let a=d0.default.join(__dirname,"../skills/mem-search/operations",`${i}.md`);o=await p0.promises.readFile(a,"utf-8")}else{let a=d0.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await p0.promises.readFile(a,"utf-8");o=this.extractInstructionSection(c,s)}n.json({content:[{type:"text",text:o}]})}catch{n.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",af,async(r,n)=>{n.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_PILOT_MANAGED==="true"&&process.send?(_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.options.onRestart()},100)}),this.app.post("/api/admin/shutdown",af,async(r,n)=>{n.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_PILOT_MANAGED==="true"&&process.send?(_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.options.onShutdown()},100)})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let s=e.indexOf(r),i=e.indexOf(n);return s===-1?e:i===-1?e.substring(s):e.substring(s,i).trim()}};df();var nz=require("bun:sqlite");kr();ne();var mf=class{db;constructor(e){e||(Nn(Br),e=bu),this.db=new nz.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(n=>n.name==="observations_fts"||n.name==="session_summaries_fts")||(_.info("DB","Creating FTS5 tables"),this.db.run(` CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5( title, subtitle, @@ -1894,7 +1894,7 @@ ${s}`;try{let o=(0,je.execSync)(`echo ${JSON.stringify(i)} | claude -p --model c `).map(n=>n.trim()).filter(Boolean).map(n=>({path:n,status:"?",staged:!1,additions:0,deletions:0}))}catch{return[]}}getChangedFilesInRange(e,r){try{let n=(0,je.execFileSync)("git",["diff","--name-status",r],{cwd:e,encoding:"utf-8",timeout:1e4,env:Ue}),s=(0,je.execFileSync)("git",["diff","--numstat",r],{cwd:e,encoding:"utf-8",timeout:1e4,env:Ue});return this.parseChangedFiles(n,s,!0)}catch{return[]}}parseChangedFiles(e,r,n){let s=new Map;for(let o of r.split(` `)){if(!o.trim())continue;let a=o.split(" ");if(a.length>=3){let c=a[0],l=a[1],u=a[a.length-1];s.set(u,{additions:c==="-"?0:parseInt(c,10)||0,deletions:l==="-"?0:parseInt(l,10)||0})}}let i=[];for(let o of e.split(` `)){if(!o.trim())continue;let a=o.split(" ");if(a.length>=2){let c=a[0].charAt(0),l=a[a.length-1],u=s.get(l)||{additions:0,deletions:0};i.push({path:l,status:c,staged:n,...u})}}return i}isValidFilePath(e){return!(!e||e.trim()===""||fi.default.isAbsolute(e)||fi.default.normalize(e).startsWith(".."))}isValidBranchName(e){return!(!e||e.trim()===""||/\.\.|\x00-\x1f|[\x7f~^:?*\[\\]|@\{/.test(e)||e.startsWith("-")||e.startsWith(".")||e.endsWith(".lock"))}gitShowFile(e,r,n){try{return(0,je.execFileSync)("git",["show",`${r}:${n}`],{cwd:e,encoding:"utf-8",timeout:5e3,env:Ue,maxBuffer:10*1024*1024})}catch{return""}}hasBinaryContent(e){return e.includes("\0")}getMainRepoRoot(e){try{let r=fi.default.join(e,".git");if((0,hi.existsSync)(r))try{let n=(0,hi.readFileSync)(r,"utf-8").trim();if(n.startsWith("gitdir:")){let s=n.replace("gitdir:","").trim(),i=fi.default.resolve(e,s,"..","..");return fi.default.dirname(i)}}catch{return e}return e}catch{return null}}};var Zq=X(require("path"),1);var ds=require("node:fs"),Zh=X(require("node:path"),1);function qq(t){return Zh.default.join(t,"docs","plans",".annotations")}function Fw(t,e){let r=Zh.default.basename(e).replace(/\.md$/,".json");return Zh.default.join(qq(t),r)}function Sme(t){(0,ds.mkdirSync)(qq(t),{recursive:!0})}function qw(t){return{planPath:t,planAnnotations:[],codeReviewAnnotations:[],updatedAt:Date.now()}}function nc(t,e){let r=Fw(t,e);if(!(0,ds.existsSync)(r))return qw(e);try{let n=(0,ds.readFileSync)(r,"utf-8"),s=JSON.parse(n);if(Array.isArray(s.planAnnotations))return{planPath:s.planPath??e,planAnnotations:s.planAnnotations,codeReviewAnnotations:Array.isArray(s.codeReviewAnnotations)?s.codeReviewAnnotations:[],updatedAt:s.updatedAt??Date.now()};if(Array.isArray(s.annotations)){let i=s.annotations.map(o=>({id:o.id,blockId:o.blockId,originalText:o.originalText??"",text:o.text??"",createdAt:o.createdAt??Date.now()}));return{planPath:s.planPath??e,planAnnotations:i,codeReviewAnnotations:[],updatedAt:s.updatedAt??Date.now()}}return qw(e)}catch{return qw(e)}}function Vh(t,e){Sme(t);let r=Fw(t,e.planPath);(0,ds.writeFileSync)(r,JSON.stringify({...e,updatedAt:Date.now()},null,2),"utf-8")}function Fq(t,e,r){let n=nc(t,e);Vh(t,{...n,planPath:e,planAnnotations:r})}function Uq(t,e){let r=nc(t,e);Vh(t,{...r,planAnnotations:[]})}function Hq(t,e,r){let n=nc(t,e);Vh(t,{...n,planPath:e,codeReviewAnnotations:r})}function Bq(t,e){let r=nc(t,e);Vh(t,{...r,codeReviewAnnotations:[]})}function Wq(t,e){let r=Fw(t,e);try{(0,ds.unlinkSync)(r)}catch(n){if(n.code!=="ENOENT")throw n}}var Gh=class extends Se{dbManager;constructor(e){super(),this.dbManager=e??null}setupRoutes(e){e.get("/api/annotations",this.handleGet.bind(this)),e.post("/api/annotations/plan",this.handleSavePlan.bind(this)),e.post("/api/annotations/code-review",this.handleSaveCodeReview.bind(this)),e.delete("/api/annotations",this.handleDeleteAll.bind(this)),e.delete("/api/annotations/plan",this.handleClearPlan.bind(this)),e.delete("/api/annotations/code-review",this.handleClearCodeReview.bind(this))}resolvePlanPath(e,r,n){let s=Zq.default.resolve(r,n);return ap(r,s)?s:(this.badRequest(e,"Invalid plan path"),null)}requirePath(e,r){let n=e.query.project,s=e.query.path;if(!s)return this.badRequest(r,"Missing path query parameter"),null;let i=gr(this.dbManager,n),o=this.resolvePlanPath(r,i,s);return o?{projectRoot:i,resolvedPlanPath:o}:null}handleGet=this.wrapHandler((e,r)=>{let n=this.requirePath(e,r);if(!n)return;let s=nc(n.projectRoot,n.resolvedPlanPath);r.json({planAnnotations:s.planAnnotations,codeReviewAnnotations:s.codeReviewAnnotations})});handleSavePlan=this.wrapHandler((e,r)=>{let n=this.requirePath(e,r);if(!n)return;let s=e.body.annotations;if(!Array.isArray(s)){this.badRequest(r,"annotations must be an array");return}Fq(n.projectRoot,n.resolvedPlanPath,s),r.json({ok:!0})});handleSaveCodeReview=this.wrapHandler((e,r)=>{let n=this.requirePath(e,r);if(!n)return;let s=e.body.annotations;if(!Array.isArray(s)){this.badRequest(r,"annotations must be an array");return}Hq(n.projectRoot,n.resolvedPlanPath,s),r.json({ok:!0})});handleDeleteAll=this.wrapHandler((e,r)=>{let n=this.requirePath(e,r);n&&(Wq(n.projectRoot,n.resolvedPlanPath),r.json({ok:!0}))});handleClearPlan=this.wrapHandler((e,r)=>{let n=this.requirePath(e,r);n&&(Uq(n.projectRoot,n.resolvedPlanPath),r.json({ok:!0}))});handleClearCodeReview=this.wrapHandler((e,r)=>{let n=this.requirePath(e,r);n&&(Bq(n.projectRoot,n.resolvedPlanPath),r.json({ok:!0}))})};var Kq=require("os"),Jq=require("path");var Kr=require("fs"),sc=require("path"),Vq=512*1024,Gq=8,Uw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Eme=256-256%Uw.length;function kme(){let t=[];for(;t.lengthVq)throw new Error(`Payload too large (max ${Vq/1024} KB)`);let n=kme(),s={data:e,expiresAt:Date.now()+r*1e3};return(0,Kr.writeFileSync)(this.safePath(n),JSON.stringify(s),"utf-8"),n}async get(e){let r=this.safePath(e);if(!(0,Kr.existsSync)(r))return null;try{let n=JSON.parse((0,Kr.readFileSync)(r,"utf-8"));return Date.now()>n.expiresAt?((0,Kr.unlinkSync)(r),null):n.data}catch{return null}}sweep(){try{let e=(0,Kr.readdirSync)(this.dataDir).filter(n=>n.endsWith(".json")),r=Date.now();for(let n of e){let s=(0,sc.join)(this.dataDir,n);try{let i=(0,Kr.readFileSync)(s,"utf-8"),o=JSON.parse(i);r>o.expiresAt&&(0,Kr.unlinkSync)(s)}catch{}}}catch{}}},Yq=4320*60;var Tme=(0,Jq.join)((0,Kq.homedir)(),".pilot","share"),Kh=class extends Se{store;constructor(e=Tme){super(),this.store=new Yh(e)}setupRoutes(e){e.post("/api/share",this.handlePost.bind(this)),e.get("/api/share/:id",this.handleGet.bind(this))}handlePost=this.wrapHandler(async(e,r)=>{let{data:n}=e.body;if(typeof n!="string"||!n){this.badRequest(r,"Missing or invalid data field");return}try{let s=await this.store.put(n,Yq);r.status(201).json({id:s})}catch(s){let i=s instanceof Error?s.message:"Failed to store";if(i.includes("too large"))r.status(413).json({error:i});else throw s}});handleGet=this.wrapHandler(async(e,r)=>{let{id:n}=e.params;try{let s=await this.store.get(n);if(s===null){this.notFound(r,"Share not found or expired");return}r.setHeader("Cache-Control","private, no-store"),r.json({data:s})}catch(s){let i=s instanceof Error?s.message:"";if(i.includes("Invalid share ID")||i.includes("traversal"))this.badRequest(r,"Invalid share ID");else throw s}})};var Jh=class{dbManager;sessionManager;startTime;requestMetrics=[];providerRequests=0;providerTokens=0;providerErrors=0;providerName="unknown";METRICS_WINDOW_MS=300*1e3;constructor(e,r,n){this.dbManager=e,this.sessionManager=r,this.startTime=n,setInterval(()=>this.cleanupOldMetrics(),6e4)}recordRequest(e,r,n=!1){this.requestMetrics.push({endpoint:e,responseTimeMs:r,timestamp:Date.now(),error:n})}recordProviderUsage(e,r,n=!1){this.providerName=e,this.providerRequests++,this.providerTokens+=r,n&&this.providerErrors++}cleanupOldMetrics(){let e=Date.now()-this.METRICS_WINDOW_MS;this.requestMetrics=this.requestMetrics.filter(r=>r.timestamp>e)}async getMetrics(){let r=this.dbManager.getSessionStore().db,n=$=>{try{return r.prepare(`SELECT COUNT(*) as count FROM ${$}`).get().count}catch{return 0}},s=n("observations"),i=n("sdk_sessions"),o=n("session_summaries"),a=n("prompts"),{DATA_DIR:c}=await Promise.resolve().then(()=>(kr(),HM)),l=await import("fs"),p=(await import("path")).join(c,"pilot-memory.db"),d=0;try{d=l.statSync(p).size}catch{}let m=process.memoryUsage(),f=this.requestMetrics.filter($=>$.timestamp>Date.now()-this.METRICS_WINDOW_MS),y=f.length,g=f.filter($=>$.error).length,h=y>0?f.reduce(($,I)=>$+I.responseTimeMs,0)/y:0,v={};for(let $ of f)v[$.endpoint]=(v[$.endpoint]||0)+1;let b=Date.now()-6e4,x=0;try{x=r.prepare("SELECT COUNT(*) as count FROM observations WHERE created_at_epoch > ?").get(b).count}catch{}let w=f.filter($=>$.timestamp>b).length,S=this.sessionManager.isAnySessionProcessing(),E=this.sessionManager.getTotalActiveWork(),k=this.sessionManager.getActiveSessionCount();return{uptime:Math.floor((Date.now()-this.startTime)/1e3),memoryUsage:{heapUsed:m.heapUsed,heapTotal:m.heapTotal,rss:m.rss,external:m.external},database:{observations:s,sessions:i,summaries:o,prompts:a,sizeBytes:d},processing:{activeSessions:k,queueDepth:E,isProcessing:S},requests:{total:y,byEndpoint:v,errors:g,avgResponseTimeMs:Math.round(h)},provider:{name:this.providerName,requestsTotal:this.providerRequests,tokensTotal:this.providerTokens,errorsTotal:this.providerErrors},rates:{observationsPerMinute:x,requestsPerMinute:w}}}async toPrometheus(){let e=await this.getMetrics(),r=[],n=(s,i,o,a="gauge",c={})=>{r.push(`# HELP claude_pilot_${s} ${o}`),r.push(`# TYPE claude_pilot_${s} ${a}`);let l=Object.entries(c).map(([p,d])=>`${p}="${d}"`).join(","),u=l?`{${l}}`:"";r.push(`claude_pilot_${s}${u} ${i}`)};return n("uptime_seconds",e.uptime,"Worker uptime in seconds"),n("memory_heap_used_bytes",e.memoryUsage.heapUsed,"Heap memory used"),n("memory_heap_total_bytes",e.memoryUsage.heapTotal,"Total heap memory"),n("memory_rss_bytes",e.memoryUsage.rss,"Resident set size"),n("database_observations_total",e.database.observations,"Total observations"),n("database_sessions_total",e.database.sessions,"Total sessions"),n("database_summaries_total",e.database.summaries,"Total summaries"),n("database_prompts_total",e.database.prompts,"Total prompts"),n("database_size_bytes",e.database.sizeBytes,"Database file size"),n("processing_active_sessions",e.processing.activeSessions,"Active processing sessions"),n("processing_queue_depth",e.processing.queueDepth,"Queue depth"),n("processing_is_active",e.processing.isProcessing?1:0,"Is processing active"),n("requests_total",e.requests.total,"Total requests in window","counter"),n("requests_errors_total",e.requests.errors,"Total request errors","counter"),n("requests_response_time_avg_ms",e.requests.avgResponseTimeMs,"Average response time"),n("provider_requests_total",e.provider.requestsTotal,"Provider requests","counter",{provider:e.provider.name}),n("provider_tokens_total",e.provider.tokensTotal,"Provider tokens used","counter",{provider:e.provider.name}),n("provider_errors_total",e.provider.errorsTotal,"Provider errors","counter",{provider:e.provider.name}),n("observations_per_minute",e.rates.observationsPerMinute,"Observations created per minute"),n("requests_per_minute",e.rates.requestsPerMinute,"Requests per minute"),r.join(` -`)}};ne();var Rme=1440*60*1e3,$me=3e4,Qh=null,Xh=null;async function Qq(t){let e=t.getVectorSyncOrNull(),r=new tc(t,e),n=r.getPolicy();if(!n.enabled){_.debug("RETENTION","Auto-cleanup skipped: retention policy is disabled");return}_.info("RETENTION","Running scheduled auto-cleanup",{maxAgeDays:n.maxAgeDays,maxCount:n.maxCount});let s=await r.run();_.info("RETENTION","Auto-cleanup complete",{deleted:s.deleted,archived:s.archived,errors:s.errors.length,duration:s.duration})}function Xq(t){Hw(),Xh=setTimeout(async()=>{try{await Qq(t)}catch(e){_.error("RETENTION","Scheduled retention failed",{},e)}Qh=setInterval(async()=>{try{await Qq(t)}catch(e){_.error("RETENTION","Scheduled retention failed",{},e)}},Rme),_.info("RETENTION","Scheduled daily auto-cleanup")},$me),_.info("RETENTION","Retention scheduler initialized (first run in 30s)")}function Hw(){Xh&&(clearTimeout(Xh),Xh=null),Qh&&(clearInterval(Qh),Qh=null),_.debug("RETENTION","Retention scheduler stopped")}var Wme={},Fme="7.8.5";function N8(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}function D8(){let t=`${(0,j8.homedir)()}/.pilot/bin/pilot`;if(!(0,nS.existsSync)(t))return _.warn("SYSTEM","Pilot binary not found, skipping license check"),!0;try{return(0,A8.execSync)(`"${t}" verify`,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}var og=class{server;startTime=Date.now();mcpClient;coreReady=!1;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;paginationHelper;sessionEventBroadcaster;searchRoutes=null;metricsService=null;initializationComplete;resolveInitialization;cleanupInterval=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new vf,this.sessionManager=new yf(this.dbManager),this.sseBroadcaster=new bf,this.sdkAgent=new th(this.dbManager,this.sessionManager),this.paginationHelper=new rh(this.dbManager),this.sessionEventBroadcaster=new oh(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new jo({name:"worker-search-proxy",version:Fme},{capabilities:{}}),this.server=new pf({getInitializationComplete:()=>this.initializationCompleteFlag,getCoreReady:()=>this.coreReady,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown()}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){let e={value:this.isShuttingDown},r=Lb(()=>this.shutdown(),e);process.on("SIGTERM",()=>{this.isShuttingDown=e.value,r("SIGTERM")}),process.on("SIGINT",()=>{this.isShuttingDown=e.value,r("SIGINT")}),process.platform!=="win32"&&process.on("SIGHUP",()=>{process.argv.includes("--daemon")?_.info("SYSTEM","Received SIGHUP in daemon mode, ignoring",{}):(this.isShuttingDown=e.value,r("SIGHUP"))})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{try{let i=new Promise((o,a)=>setTimeout(()=>a(new Error("Initialization timeout")),3e5));if(await Promise.race([this.initializationComplete,i]),!this.searchRoutes){r.status(503).json({error:"Search routes not initialized"});return}n()}catch{r.status(503).json({error:"Service initialization timed out"})}}),this.server.registerRoutes(new kh),this.server.registerRoutes(new ch(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new uh(this.sessionManager,this.dbManager,this.sdkAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new dh(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new bh),this.server.registerRoutes(new xh(this.dbManager,"pilot-memory")),this.server.registerRoutes(new _h(this.dbManager)),this.server.registerRoutes(new Sh(this.dbManager)),this.server.registerRoutes(new Ah(this.dbManager,this.sseBroadcaster)),this.server.registerRoutes(new Gh(this.dbManager)),this.server.registerRoutes(new Kh),this.server.registerRoutes(new jh(this.dbManager,this.sseBroadcaster)),this.server.registerRoutes(new Dh),this.metricsService=new Jh(this.dbManager,this.sessionManager,this.startTime),this.server.registerRoutes(new Eh(this.metricsService)),this.server.registerRoutes(new zh),this.server.registerRoutes(new qh),this.server.registerRoutes(new Fh(this.dbManager)),this.server.registerRoutes(new Hh),this.server.registerRoutes(new Bh),this.server.registerRoutes(new Wh(this.dbManager)),Xq(this.dbManager)}async start(){let e=zr(),r=Md(),n=$n();await this.server.listen(e,r),_.info("SYSTEM","Worker started",{bind:r,host:n,port:e,pid:process.pid}),Ai()&&_.info("SYSTEM","WSL2 detected \u2014 Console bound to 0.0.0.0 for Windows host access",{url:`http://localhost:${e}`}),this.initializeBackground().catch(s=>{_.error("SYSTEM","Background initialization failed",{},s)})}async initializeBackground(){try{await Hd(),await pl(),await ul();let{ModeManager:e}=await Promise.resolve().then(()=>(mn(),mz));e.getInstance().loadMode(),_.info("SYSTEM","Mode loaded: Code Development"),await this.dbManager.initialize();let r=process.env.CLAUDE_PROJECT_ROOT||process.cwd(),n=pp.default.basename(r);this.dbManager.getSessionStore().upsertProjectRoot(n,r);let{PendingMessageStore:s}=await Promise.resolve().then(()=>(oi(),Ji)),i=new s(this.dbManager.getSessionStore().db,3),o=300*1e3,a=i.resetStuckMessages(o);a>0&&_.info("SYSTEM",`Recovered ${a} stuck messages from previous session`,{thresholdMinutes:5});let c=new sh,l=new ih,u=new nh(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getVectorSync(),c,l);this.searchRoutes=new vh(u),this.server.registerRoutes(this.searchRoutes),_.info("WORKER","SearchManager initialized and search routes registered"),this.coreReady=!0,_.info("SYSTEM","Core services ready (hooks can proceed)");let p=[pp.default.join(__dirname,"mcp-server.cjs"),pp.default.join(__dirname,"..","servers","mcp-server.ts"),pp.default.join(__dirname,"..","..","servers","mcp-server.ts")],d=p.find(x=>(0,nS.existsSync)(x))||p[0],m=d.endsWith(".ts"),f=new Mo({command:m?"bun":"node",args:[d],env:process.env}),y=3e5,g=this.mcpClient.connect(f),h=new Promise((x,w)=>setTimeout(()=>w(new Error("MCP connection timeout after 5 minutes")),y));await Promise.race([g,h]),this.mcpReady=!0,_.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),_.info("SYSTEM","Background initialization complete"),this.processPendingQueues(50).then(x=>{x.sessionsStarted>0&&_.info("SYSTEM",`Auto-recovered ${x.sessionsStarted} sessions with pending work`,{totalPending:x.totalPendingSessions,started:x.sessionsStarted,sessionIds:x.startedSessionIds})}).catch(x=>{_.error("SYSTEM","Auto-recovery of pending queues failed",{},x)});let v=300*1e3,b=3600*1e3;this.cleanupInterval=setInterval(async()=>{try{let x=await this.sessionManager.cleanupStaleSessions(b);x>0&&_.info("SYSTEM",`Periodic cleanup: removed ${x} stale sessions`),await pl(),await ul(),_.debug("SYSTEM","Periodic cleanup completed")}catch(x){_.error("SYSTEM","Periodic cleanup failed",{},x)}},v),_.info("SYSTEM","Started periodic cleanup (every 5 minutes)")}catch(e){throw _.error("SYSTEM","Background initialization failed",{},e),e}}getActiveAgent(){return this.sdkAgent}startSessionProcessor(e,r){if(!e)return;e.abortController.signal.aborted&&(e.abortController=new AbortController,_.debug("SYSTEM","Reset AbortController for session restart",{sessionId:e.sessionDbId}));let n=e.sessionDbId,s=this.getActiveAgent(),i=s.constructor.name;_.info("SYSTEM",`Starting generator (${r}) using ${i}`,{sessionId:n}),e.generatorPromise=s.startSession(e,this).catch(o=>{_.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:i},o)}).finally(()=>{e.generatorPromise=null,this.broadcastProcessingStatus()})}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(oi(),Ji)),n=new r(this.dbManager.getSessionStore().db,3),s=this.dbManager.getSessionStore(),i=1800*1e3,o=Date.now()-i;try{let l=s.db.prepare(` +`)}};ne();var Rme=1440*60*1e3,$me=3e4,Qh=null,Xh=null;async function Qq(t){let e=t.getVectorSyncOrNull(),r=new tc(t,e),n=r.getPolicy();if(!n.enabled){_.debug("RETENTION","Auto-cleanup skipped: retention policy is disabled");return}_.info("RETENTION","Running scheduled auto-cleanup",{maxAgeDays:n.maxAgeDays,maxCount:n.maxCount});let s=await r.run();_.info("RETENTION","Auto-cleanup complete",{deleted:s.deleted,archived:s.archived,errors:s.errors.length,duration:s.duration})}function Xq(t){Hw(),Xh=setTimeout(async()=>{try{await Qq(t)}catch(e){_.error("RETENTION","Scheduled retention failed",{},e)}Qh=setInterval(async()=>{try{await Qq(t)}catch(e){_.error("RETENTION","Scheduled retention failed",{},e)}},Rme),_.info("RETENTION","Scheduled daily auto-cleanup")},$me),_.info("RETENTION","Retention scheduler initialized (first run in 30s)")}function Hw(){Xh&&(clearTimeout(Xh),Xh=null),Qh&&(clearInterval(Qh),Qh=null),_.debug("RETENTION","Retention scheduler stopped")}var Wme={},Fme="7.9.0";function N8(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}function D8(){let t=`${(0,j8.homedir)()}/.pilot/bin/pilot`;if(!(0,nS.existsSync)(t))return _.warn("SYSTEM","Pilot binary not found, skipping license check"),!0;try{return(0,A8.execSync)(`"${t}" verify`,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}var og=class{server;startTime=Date.now();mcpClient;coreReady=!1;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;paginationHelper;sessionEventBroadcaster;searchRoutes=null;metricsService=null;initializationComplete;resolveInitialization;cleanupInterval=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new vf,this.sessionManager=new yf(this.dbManager),this.sseBroadcaster=new bf,this.sdkAgent=new th(this.dbManager,this.sessionManager),this.paginationHelper=new rh(this.dbManager),this.sessionEventBroadcaster=new oh(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new jo({name:"worker-search-proxy",version:Fme},{capabilities:{}}),this.server=new pf({getInitializationComplete:()=>this.initializationCompleteFlag,getCoreReady:()=>this.coreReady,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown()}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){let e={value:this.isShuttingDown},r=Lb(()=>this.shutdown(),e);process.on("SIGTERM",()=>{this.isShuttingDown=e.value,r("SIGTERM")}),process.on("SIGINT",()=>{this.isShuttingDown=e.value,r("SIGINT")}),process.platform!=="win32"&&process.on("SIGHUP",()=>{process.argv.includes("--daemon")?_.info("SYSTEM","Received SIGHUP in daemon mode, ignoring",{}):(this.isShuttingDown=e.value,r("SIGHUP"))})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{try{let i=new Promise((o,a)=>setTimeout(()=>a(new Error("Initialization timeout")),3e5));if(await Promise.race([this.initializationComplete,i]),!this.searchRoutes){r.status(503).json({error:"Search routes not initialized"});return}n()}catch{r.status(503).json({error:"Service initialization timed out"})}}),this.server.registerRoutes(new kh),this.server.registerRoutes(new ch(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new uh(this.sessionManager,this.dbManager,this.sdkAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new dh(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new bh),this.server.registerRoutes(new xh(this.dbManager,"pilot-memory")),this.server.registerRoutes(new _h(this.dbManager)),this.server.registerRoutes(new Sh(this.dbManager)),this.server.registerRoutes(new Ah(this.dbManager,this.sseBroadcaster)),this.server.registerRoutes(new Gh(this.dbManager)),this.server.registerRoutes(new Kh),this.server.registerRoutes(new jh(this.dbManager,this.sseBroadcaster)),this.server.registerRoutes(new Dh),this.metricsService=new Jh(this.dbManager,this.sessionManager,this.startTime),this.server.registerRoutes(new Eh(this.metricsService)),this.server.registerRoutes(new zh),this.server.registerRoutes(new qh),this.server.registerRoutes(new Fh(this.dbManager)),this.server.registerRoutes(new Hh),this.server.registerRoutes(new Bh),this.server.registerRoutes(new Wh(this.dbManager)),Xq(this.dbManager)}async start(){let e=zr(),r=Md(),n=$n();await this.server.listen(e,r),_.info("SYSTEM","Worker started",{bind:r,host:n,port:e,pid:process.pid}),Ai()&&_.info("SYSTEM","WSL2 detected \u2014 Console bound to 0.0.0.0 for Windows host access",{url:`http://localhost:${e}`}),this.initializeBackground().catch(s=>{_.error("SYSTEM","Background initialization failed",{},s)})}async initializeBackground(){try{await Hd(),await pl(),await ul();let{ModeManager:e}=await Promise.resolve().then(()=>(mn(),mz));e.getInstance().loadMode(),_.info("SYSTEM","Mode loaded: Code Development"),await this.dbManager.initialize();let r=process.env.CLAUDE_PROJECT_ROOT||process.cwd(),n=pp.default.basename(r);this.dbManager.getSessionStore().upsertProjectRoot(n,r);let{PendingMessageStore:s}=await Promise.resolve().then(()=>(oi(),Ji)),i=new s(this.dbManager.getSessionStore().db,3),o=300*1e3,a=i.resetStuckMessages(o);a>0&&_.info("SYSTEM",`Recovered ${a} stuck messages from previous session`,{thresholdMinutes:5});let c=new sh,l=new ih,u=new nh(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getVectorSync(),c,l);this.searchRoutes=new vh(u),this.server.registerRoutes(this.searchRoutes),_.info("WORKER","SearchManager initialized and search routes registered"),this.coreReady=!0,_.info("SYSTEM","Core services ready (hooks can proceed)");let p=[pp.default.join(__dirname,"mcp-server.cjs"),pp.default.join(__dirname,"..","servers","mcp-server.ts"),pp.default.join(__dirname,"..","..","servers","mcp-server.ts")],d=p.find(x=>(0,nS.existsSync)(x))||p[0],m=d.endsWith(".ts"),f=new Mo({command:m?"bun":"node",args:[d],env:process.env}),y=3e5,g=this.mcpClient.connect(f),h=new Promise((x,w)=>setTimeout(()=>w(new Error("MCP connection timeout after 5 minutes")),y));await Promise.race([g,h]),this.mcpReady=!0,_.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),_.info("SYSTEM","Background initialization complete"),this.processPendingQueues(50).then(x=>{x.sessionsStarted>0&&_.info("SYSTEM",`Auto-recovered ${x.sessionsStarted} sessions with pending work`,{totalPending:x.totalPendingSessions,started:x.sessionsStarted,sessionIds:x.startedSessionIds})}).catch(x=>{_.error("SYSTEM","Auto-recovery of pending queues failed",{},x)});let v=300*1e3,b=3600*1e3;this.cleanupInterval=setInterval(async()=>{try{let x=await this.sessionManager.cleanupStaleSessions(b);x>0&&_.info("SYSTEM",`Periodic cleanup: removed ${x} stale sessions`),await pl(),await ul(),_.debug("SYSTEM","Periodic cleanup completed")}catch(x){_.error("SYSTEM","Periodic cleanup failed",{},x)}},v),_.info("SYSTEM","Started periodic cleanup (every 5 minutes)")}catch(e){throw _.error("SYSTEM","Background initialization failed",{},e),e}}getActiveAgent(){return this.sdkAgent}startSessionProcessor(e,r){if(!e)return;e.abortController.signal.aborted&&(e.abortController=new AbortController,_.debug("SYSTEM","Reset AbortController for session restart",{sessionId:e.sessionDbId}));let n=e.sessionDbId,s=this.getActiveAgent(),i=s.constructor.name;_.info("SYSTEM",`Starting generator (${r}) using ${i}`,{sessionId:n}),e.generatorPromise=s.startSession(e,this).catch(o=>{_.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:i},o)}).finally(()=>{e.generatorPromise=null,this.broadcastProcessingStatus()})}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(oi(),Ji)),n=new r(this.dbManager.getSessionStore().db,3),s=this.dbManager.getSessionStore(),i=1800*1e3,o=Date.now()-i;try{let l=s.db.prepare(` SELECT s.id FROM sdk_sessions s WHERE s.status = 'active' AND s.started_at_epoch < ?