lexic-mcp 0.1.18 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bundle.cjs +2 -2
  2. package/package.json +1 -1
package/dist/bundle.cjs CHANGED
@@ -96,7 +96,7 @@ return fn.apply(this, arguments)
96
96
 
97
97
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of t.seen.entries()){let s=a[1];if(e===a[0]){o(a);continue}if(t.external){let u=t.external.registry.get(a[0])?.id;if(e!==a[0]&&u){o(a);continue}}if(t.metadataRegistry.get(a[0])?.id){o(a);continue}if(s.cycle){o(a);continue}if(s.count>1&&t.reused==="ref"){o(a);continue}}}function Kc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let s=t.seen.get(a);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.ref=null,l){n(l);let d=t.seen.get(l),f=d.schema;if(f.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(f)):Object.assign(c,f),Object.assign(c,u),a._zod.parent===l)for(let h in c)h==="$ref"||h==="allOf"||h in u||delete c[h];if(f.$ref)for(let h in c)h==="$ref"||h==="allOf"||h in d.def&&JSON.stringify(c[h])===JSON.stringify(d.def[h])&&delete c[h]}let p=a._zod.parent;if(p&&p!==l){n(p);let d=t.seen.get(p);if(d?.schema.$ref&&(c.$ref=d.schema.$ref,d.def))for(let f in c)f==="$ref"||f==="allOf"||f in d.def&&JSON.stringify(c[f])===JSON.stringify(d.def[f])&&delete c[f]}t.override({zodSchema:a,jsonSchema:c,path:s.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(a)}Object.assign(i,r.def??r.schema);let o=t.external?.defs??{};for(let a of t.seen.entries()){let s=a[1];s.def&&s.defId&&(o[s.defId]=s.def)}t.external||Object.keys(o).length>0&&(t.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{let a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Sa(e,"input",t.processors),output:Sa(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function st(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return st(n.element,r);if(n.type==="set")return st(n.valueType,r);if(n.type==="lazy")return st(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return st(n.innerType,r);if(n.type==="intersection")return st(n.left,r)||st(n.right,r);if(n.type==="record"||n.type==="map")return st(n.keyType,r)||st(n.valueType,r);if(n.type==="pipe")return st(n.in,r)||st(n.out,r);if(n.type==="object"){for(let i in n.shape)if(st(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(st(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(st(i,r))return!0;return!!(n.rest&&st(n.rest,r))}return!1}var Y0=(t,e={})=>r=>{let n=Jc({...r,processors:e});return xe(t,n),Gc(n,t),Kc(n,t)},Sa=(t,e,r={})=>n=>{let{libraryOptions:i,target:o}=n??{},a=Jc({...i??{},target:o,io:e,processors:r});return xe(t,a),Gc(a,t),Kc(a,t)};var E2={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Q0=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:o,maximum:a,format:s,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof a=="number"&&(i.maxLength=a),s&&(i.format=E2[s]??s,i.format===""&&delete i.format,s==="time"&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},e_=(t,e,r,n)=>{let i=r,{minimum:o,maximum:a,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof s=="string"&&s.includes("int")?i.type="integer":i.type="number",typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l),typeof o=="number"&&(i.minimum=o,typeof l=="number"&&e.target!=="draft-04"&&(l>=o?delete i.minimum:delete i.exclusiveMinimum)),typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u),typeof a=="number"&&(i.maximum=a,typeof u=="number"&&e.target!=="draft-04"&&(u<=a?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},t_=(t,e,r,n)=>{r.type="boolean"},r_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},n_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},i_=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},o_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},a_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},s_=(t,e,r,n)=>{r.not={}},c_=(t,e,r,n)=>{},u_=(t,e,r,n)=>{},l_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},p_=(t,e,r,n)=>{let i=t._zod.def,o=Jo(i.entries);o.every(a=>typeof a=="number")&&(r.type="number"),o.every(a=>typeof a=="string")&&(r.type="string"),r.enum=o},d_=(t,e,r,n)=>{let i=t._zod.def,o=[];for(let a of i.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(a))}else o.push(a);if(o.length!==0)if(o.length===1){let a=o[0];r.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[a]:r.const=a}else o.every(a=>typeof a=="number")&&(r.type="number"),o.every(a=>typeof a=="string")&&(r.type="string"),o.every(a=>typeof a=="boolean")&&(r.type="boolean"),o.every(a=>a===null)&&(r.type="null"),r.enum=o},f_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},m_=(t,e,r,n)=>{let i=r,o=t._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=o.source},h_=(t,e,r,n)=>{let i=r,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=t._zod.bag;a!==void 0&&(o.minLength=a),s!==void 0&&(o.maxLength=s),c?c.length===1?(o.contentMediaType=c[0],Object.assign(i,o)):(Object.assign(i,o),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,o)},g_=(t,e,r,n)=>{r.type="boolean"},v_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},y_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},x_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},b_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},__=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},w_=(t,e,r,n)=>{let i=r,o=t._zod.def,{minimum:a,maximum:s}=t._zod.bag;typeof a=="number"&&(i.minItems=a),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=xe(o.element,e,{...n,path:[...n.path,"items"]})},$_=(t,e,r,n)=>{let i=r,o=t._zod.def;i.type="object",i.properties={};let a=o.shape;for(let u in a)i.properties[u]=xe(a[u],e,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(a)),c=new Set([...s].filter(u=>{let l=o.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=xe(o.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},Um=(t,e,r,n)=>{let i=t._zod.def,o=i.inclusive===!1,a=i.options.map((s,c)=>xe(s,e,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=a:r.anyOf=a},k_=(t,e,r,n)=>{let i=t._zod.def,o=xe(i.left,e,{...n,path:[...n.path,"allOf",0]}),a=xe(i.right,e,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]];r.allOf=c},S_=(t,e,r,n)=>{let i=r,o=t._zod.def;i.type="array";let a=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((d,f)=>xe(d,e,{...n,path:[...n.path,a,f]})),u=o.rest?xe(o.rest,e,{...n,path:[...n.path,s,...e.target==="openapi-3.0"?[o.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=c,u&&(i.items=u)):e.target==="openapi-3.0"?(i.items={anyOf:c},u&&i.items.anyOf.push(u),i.minItems=c.length,u||(i.maxItems=c.length)):(i.items=c,u&&(i.additionalItems=u));let{minimum:l,maximum:p}=t._zod.bag;typeof l=="number"&&(i.minItems=l),typeof p=="number"&&(i.maxItems=p)},E_=(t,e,r,n)=>{let i=r,o=t._zod.def;i.type="object";let a=o.keyType,c=a._zod.bag?.patterns;if(o.mode==="loose"&&c&&c.size>0){let l=xe(o.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let p of c)i.patternProperties[p.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=xe(o.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=xe(o.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=a._zod.values;if(u){let l=[...u].filter(p=>typeof p=="string"||typeof p=="number");l.length>0&&(i.required=l)}},z_=(t,e,r,n)=>{let i=t._zod.def,o=xe(i.innerType,e,n),a=e.seen.get(t);e.target==="openapi-3.0"?(a.ref=i.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},I_=(t,e,r,n)=>{let i=t._zod.def;xe(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType},T_=(t,e,r,n)=>{let i=t._zod.def;xe(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},P_=(t,e,r,n)=>{let i=t._zod.def;xe(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},O_=(t,e,r,n)=>{let i=t._zod.def;xe(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType;let a;try{a=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},j_=(t,e,r,n)=>{let i=t._zod.def,o=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;xe(o,e,n);let a=e.seen.get(t);a.ref=o},A_=(t,e,r,n)=>{let i=t._zod.def;xe(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType,r.readOnly=!0},C_=(t,e,r,n)=>{let i=t._zod.def;xe(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType},qm=(t,e,r,n)=>{let i=t._zod.def;xe(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType},R_=(t,e,r,n)=>{let i=t._zod.innerType;xe(i,e,n);let o=e.seen.get(t);o.ref=i};function Ni(t){return!!t._zod}function an(t,e){return Ni(t)?Oi(t,e):t.safeParse(e)}function Wc(t){if(!t)return;let e;if(Ni(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function U_(t){if(Ni(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.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 Ea={};fi(Ea,{ZodAny:()=>rw,ZodArray:()=>aw,ZodBase64:()=>lh,ZodBase64URL:()=>ph,ZodBigInt:()=>ja,ZodBigIntFormat:()=>mh,ZodBoolean:()=>Oa,ZodCIDRv4:()=>ch,ZodCIDRv6:()=>uh,ZodCUID:()=>th,ZodCUID2:()=>rh,ZodCatch:()=>Ew,ZodCodec:()=>_h,ZodCustom:()=>su,ZodCustomStringFormat:()=>Ta,ZodDate:()=>ru,ZodDefault:()=>bw,ZodDiscriminatedUnion:()=>cw,ZodE164:()=>dh,ZodEmail:()=>Xm,ZodEmoji:()=>Qm,ZodEnum:()=>za,ZodExactOptional:()=>vw,ZodFile:()=>hw,ZodFunction:()=>Rw,ZodGUID:()=>Yc,ZodIPv4:()=>ah,ZodIPv6:()=>sh,ZodIntersection:()=>uw,ZodJWT:()=>fh,ZodKSUID:()=>oh,ZodLazy:()=>jw,ZodLiteral:()=>mw,ZodMAC:()=>Y_,ZodMap:()=>dw,ZodNaN:()=>Iw,ZodNanoID:()=>eh,ZodNever:()=>iw,ZodNonOptional:()=>xh,ZodNull:()=>tw,ZodNullable:()=>xw,ZodNumber:()=>Pa,ZodNumberFormat:()=>Di,ZodObject:()=>nu,ZodOptional:()=>yh,ZodPipe:()=>bh,ZodPrefault:()=>ww,ZodPromise:()=>Cw,ZodReadonly:()=>Tw,ZodRecord:()=>au,ZodSet:()=>fw,ZodString:()=>Ia,ZodStringFormat:()=>ge,ZodSuccess:()=>Sw,ZodSymbol:()=>Q_,ZodTemplateLiteral:()=>Ow,ZodTransform:()=>gw,ZodTuple:()=>lw,ZodType:()=>J,ZodULID:()=>nh,ZodURL:()=>tu,ZodUUID:()=>Rr,ZodUndefined:()=>ew,ZodUnion:()=>iu,ZodUnknown:()=>nw,ZodVoid:()=>ow,ZodXID:()=>ih,ZodXor:()=>sw,_ZodString:()=>Wm,_default:()=>_w,_function:()=>Rj,any:()=>hh,array:()=>I,base64:()=>tj,base64url:()=>rj,bigint:()=>fj,boolean:()=>le,catch:()=>zw,check:()=>Nj,cidrv4:()=>Q2,cidrv6:()=>ej,codec:()=>jj,cuid:()=>B2,cuid2:()=>H2,custom:()=>wh,date:()=>xj,describe:()=>Dj,discriminatedUnion:()=>ou,e164:()=>nj,email:()=>N2,emoji:()=>F2,enum:()=>Qe,exactOptional:()=>yw,file:()=>Ij,float32:()=>uj,float64:()=>lj,function:()=>Rj,guid:()=>D2,hash:()=>cj,hex:()=>sj,hostname:()=>aj,httpUrl:()=>Z2,instanceof:()=>qj,int:()=>Km,int32:()=>pj,int64:()=>mj,intersection:()=>Ca,ipv4:()=>W2,ipv6:()=>Y2,json:()=>Lj,jwt:()=>ij,keyof:()=>bj,ksuid:()=>K2,lazy:()=>Aw,literal:()=>A,looseObject:()=>Oe,looseRecord:()=>kj,mac:()=>X2,map:()=>Sj,meta:()=>Uj,nan:()=>Oj,nanoid:()=>V2,nativeEnum:()=>zj,never:()=>gh,nonoptional:()=>kw,null:()=>Aa,nullable:()=>Qc,nullish:()=>Tj,number:()=>ie,object:()=>z,optional:()=>$e,partialRecord:()=>$j,pipe:()=>eu,prefault:()=>$w,preprocess:()=>cu,promise:()=>Cj,readonly:()=>Pw,record:()=>be,refine:()=>Nw,set:()=>Ej,strictObject:()=>_j,string:()=>v,stringFormat:()=>oj,stringbool:()=>Mj,success:()=>Pj,superRefine:()=>Dw,symbol:()=>gj,templateLiteral:()=>Aj,transform:()=>vh,tuple:()=>pw,uint32:()=>dj,uint64:()=>hj,ulid:()=>J2,undefined:()=>vj,union:()=>de,unknown:()=>ve,url:()=>Ym,uuid:()=>U2,uuidv4:()=>q2,uuidv6:()=>M2,uuidv7:()=>L2,void:()=>yj,xid:()=>G2,xor:()=>wj});var Xc={};fi(Xc,{endsWith:()=>xa,gt:()=>Ar,gte:()=>at,includes:()=>va,length:()=>Ci,lowercase:()=>ha,lt:()=>jr,lte:()=>wt,maxLength:()=>Ai,maxSize:()=>Nn,mime:()=>ba,minLength:()=>on,minSize:()=>Cr,multipleOf:()=>Rn,negative:()=>zm,nonnegative:()=>Tm,nonpositive:()=>Im,normalize:()=>_a,overwrite:()=>dr,positive:()=>Em,property:()=>Pm,regex:()=>ma,size:()=>ji,slugify:()=>Hc,startsWith:()=>ya,toLowerCase:()=>$a,toUpperCase:()=>ka,trim:()=>wa,uppercase:()=>ga});var Dn={};fi(Dn,{ZodISODate:()=>Fm,ZodISODateTime:()=>Lm,ZodISODuration:()=>Jm,ZodISOTime:()=>Bm,date:()=>Vm,datetime:()=>Zm,duration:()=>Gm,time:()=>Hm});var Lm=b("ZodISODateTime",(t,e)=>{Kd.init(t,e),ge.init(t,e)});function Zm(t){return Qf(Lm,t)}var Fm=b("ZodISODate",(t,e)=>{Wd.init(t,e),ge.init(t,e)});function Vm(t){return em(Fm,t)}var Bm=b("ZodISOTime",(t,e)=>{Xd.init(t,e),ge.init(t,e)});function Hm(t){return tm(Bm,t)}var Jm=b("ZodISODuration",(t,e)=>{Yd.init(t,e),ge.init(t,e)});function Gm(t){return rm(Jm,t)}var q_=(t,e)=>{pc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>fc(t,r)},flatten:{value:r=>dc(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Ii,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Ii,2)}},isEmpty:{get(){return t.issues.length===0}}})},CX=b("ZodError",q_),$t=b("ZodError",q_,{Parent:Error});var M_=Qo($t),L_=ta($t),Z_=na($t),F_=ia($t),V_=Qb($t),B_=e0($t),H_=t0($t),J_=r0($t),G_=n0($t),K_=i0($t),W_=o0($t),X_=a0($t);var J=b("ZodType",(t,e)=>(Z.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Sa(t,"input"),output:Sa(t,"output")}}),t.toJSONSchema=Y0(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(E.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),t.with=t.check,t.clone=(r,n)=>it(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>M_(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Z_(t,r,n),t.parseAsync=async(r,n)=>L_(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>F_(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>V_(t,r,n),t.decode=(r,n)=>B_(t,r,n),t.encodeAsync=async(r,n)=>H_(t,r,n),t.decodeAsync=async(r,n)=>J_(t,r,n),t.safeEncode=(r,n)=>G_(t,r,n),t.safeDecode=(r,n)=>K_(t,r,n),t.safeEncodeAsync=async(r,n)=>W_(t,r,n),t.safeDecodeAsync=async(r,n)=>X_(t,r,n),t.refine=(r,n)=>t.check(Nw(r,n)),t.superRefine=r=>t.check(Dw(r)),t.overwrite=r=>t.check(dr(r)),t.optional=()=>$e(t),t.exactOptional=()=>yw(t),t.nullable=()=>Qc(t),t.nullish=()=>$e(Qc(t)),t.nonoptional=r=>kw(t,r),t.array=()=>I(t),t.or=r=>de([t,r]),t.and=r=>Ca(t,r),t.transform=r=>eu(t,vh(r)),t.default=r=>_w(t,r),t.prefault=r=>$w(t,r),t.catch=r=>zw(t,r),t.pipe=r=>eu(t,r),t.readonly=()=>Pw(t),t.describe=r=>{let n=t.clone();return ot.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return ot.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return ot.get(t);let n=t.clone();return ot.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),Wm=b("_ZodString",(t,e)=>{Cn.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,i,o)=>Q0(t,n,i,o);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(ma(...n)),t.includes=(...n)=>t.check(va(...n)),t.startsWith=(...n)=>t.check(ya(...n)),t.endsWith=(...n)=>t.check(xa(...n)),t.min=(...n)=>t.check(on(...n)),t.max=(...n)=>t.check(Ai(...n)),t.length=(...n)=>t.check(Ci(...n)),t.nonempty=(...n)=>t.check(on(1,...n)),t.lowercase=n=>t.check(ha(n)),t.uppercase=n=>t.check(ga(n)),t.trim=()=>t.check(wa()),t.normalize=(...n)=>t.check(_a(...n)),t.toLowerCase=()=>t.check($a()),t.toUpperCase=()=>t.check(ka()),t.slugify=()=>t.check(Hc())}),Ia=b("ZodString",(t,e)=>{Cn.init(t,e),Wm.init(t,e),t.email=r=>t.check(Ec(Xm,r)),t.url=r=>t.check(fa(tu,r)),t.jwt=r=>t.check(Bc(fh,r)),t.emoji=r=>t.check(Oc(Qm,r)),t.guid=r=>t.check(da(Yc,r)),t.uuid=r=>t.check(zc(Rr,r)),t.uuidv4=r=>t.check(Ic(Rr,r)),t.uuidv6=r=>t.check(Tc(Rr,r)),t.uuidv7=r=>t.check(Pc(Rr,r)),t.nanoid=r=>t.check(jc(eh,r)),t.guid=r=>t.check(da(Yc,r)),t.cuid=r=>t.check(Ac(th,r)),t.cuid2=r=>t.check(Cc(rh,r)),t.ulid=r=>t.check(Rc(nh,r)),t.base64=r=>t.check(Zc(lh,r)),t.base64url=r=>t.check(Fc(ph,r)),t.xid=r=>t.check(Nc(ih,r)),t.ksuid=r=>t.check(Dc(oh,r)),t.ipv4=r=>t.check(Uc(ah,r)),t.ipv6=r=>t.check(qc(sh,r)),t.cidrv4=r=>t.check(Mc(ch,r)),t.cidrv6=r=>t.check(Lc(uh,r)),t.e164=r=>t.check(Vc(dh,r)),t.datetime=r=>t.check(Zm(r)),t.date=r=>t.check(Vm(r)),t.time=r=>t.check(Hm(r)),t.duration=r=>t.check(Gm(r))});function v(t){return Wf(Ia,t)}var ge=b("ZodStringFormat",(t,e)=>{pe.init(t,e),Wm.init(t,e)}),Xm=b("ZodEmail",(t,e)=>{Md.init(t,e),ge.init(t,e)});function N2(t){return Ec(Xm,t)}var Yc=b("ZodGUID",(t,e)=>{Ud.init(t,e),ge.init(t,e)});function D2(t){return da(Yc,t)}var Rr=b("ZodUUID",(t,e)=>{qd.init(t,e),ge.init(t,e)});function U2(t){return zc(Rr,t)}function q2(t){return Ic(Rr,t)}function M2(t){return Tc(Rr,t)}function L2(t){return Pc(Rr,t)}var tu=b("ZodURL",(t,e)=>{Ld.init(t,e),ge.init(t,e)});function Ym(t){return fa(tu,t)}function Z2(t){return fa(tu,{protocol:/^https?$/,hostname:Ct.domain,...E.normalizeParams(t)})}var Qm=b("ZodEmoji",(t,e)=>{Zd.init(t,e),ge.init(t,e)});function F2(t){return Oc(Qm,t)}var eh=b("ZodNanoID",(t,e)=>{Fd.init(t,e),ge.init(t,e)});function V2(t){return jc(eh,t)}var th=b("ZodCUID",(t,e)=>{Vd.init(t,e),ge.init(t,e)});function B2(t){return Ac(th,t)}var rh=b("ZodCUID2",(t,e)=>{Bd.init(t,e),ge.init(t,e)});function H2(t){return Cc(rh,t)}var nh=b("ZodULID",(t,e)=>{Hd.init(t,e),ge.init(t,e)});function J2(t){return Rc(nh,t)}var ih=b("ZodXID",(t,e)=>{Jd.init(t,e),ge.init(t,e)});function G2(t){return Nc(ih,t)}var oh=b("ZodKSUID",(t,e)=>{Gd.init(t,e),ge.init(t,e)});function K2(t){return Dc(oh,t)}var ah=b("ZodIPv4",(t,e)=>{Qd.init(t,e),ge.init(t,e)});function W2(t){return Uc(ah,t)}var Y_=b("ZodMAC",(t,e)=>{tf.init(t,e),ge.init(t,e)});function X2(t){return Yf(Y_,t)}var sh=b("ZodIPv6",(t,e)=>{ef.init(t,e),ge.init(t,e)});function Y2(t){return qc(sh,t)}var ch=b("ZodCIDRv4",(t,e)=>{rf.init(t,e),ge.init(t,e)});function Q2(t){return Mc(ch,t)}var uh=b("ZodCIDRv6",(t,e)=>{nf.init(t,e),ge.init(t,e)});function ej(t){return Lc(uh,t)}var lh=b("ZodBase64",(t,e)=>{of.init(t,e),ge.init(t,e)});function tj(t){return Zc(lh,t)}var ph=b("ZodBase64URL",(t,e)=>{af.init(t,e),ge.init(t,e)});function rj(t){return Fc(ph,t)}var dh=b("ZodE164",(t,e)=>{sf.init(t,e),ge.init(t,e)});function nj(t){return Vc(dh,t)}var fh=b("ZodJWT",(t,e)=>{cf.init(t,e),ge.init(t,e)});function ij(t){return Bc(fh,t)}var Ta=b("ZodCustomStringFormat",(t,e)=>{uf.init(t,e),ge.init(t,e)});function oj(t,e,r={}){return Ri(Ta,t,e,r)}function aj(t){return Ri(Ta,"hostname",Ct.hostname,t)}function sj(t){return Ri(Ta,"hex",Ct.hex,t)}function cj(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=Ct[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return Ri(Ta,n,i,e)}var Pa=b("ZodNumber",(t,e)=>{wc.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,i,o)=>e_(t,n,i,o),t.gt=(n,i)=>t.check(Ar(n,i)),t.gte=(n,i)=>t.check(at(n,i)),t.min=(n,i)=>t.check(at(n,i)),t.lt=(n,i)=>t.check(jr(n,i)),t.lte=(n,i)=>t.check(wt(n,i)),t.max=(n,i)=>t.check(wt(n,i)),t.int=n=>t.check(Km(n)),t.safe=n=>t.check(Km(n)),t.positive=n=>t.check(Ar(0,n)),t.nonnegative=n=>t.check(at(0,n)),t.negative=n=>t.check(jr(0,n)),t.nonpositive=n=>t.check(wt(0,n)),t.multipleOf=(n,i)=>t.check(Rn(n,i)),t.step=(n,i)=>t.check(Rn(n,i)),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 ie(t){return nm(Pa,t)}var Di=b("ZodNumberFormat",(t,e)=>{lf.init(t,e),Pa.init(t,e)});function Km(t){return om(Di,t)}function uj(t){return am(Di,t)}function lj(t){return sm(Di,t)}function pj(t){return cm(Di,t)}function dj(t){return um(Di,t)}var Oa=b("ZodBoolean",(t,e)=>{ua.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>t_(t,r,n,i)});function le(t){return lm(Oa,t)}var ja=b("ZodBigInt",(t,e)=>{$c.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,i,o)=>r_(t,n,i,o),t.gte=(n,i)=>t.check(at(n,i)),t.min=(n,i)=>t.check(at(n,i)),t.gt=(n,i)=>t.check(Ar(n,i)),t.gte=(n,i)=>t.check(at(n,i)),t.min=(n,i)=>t.check(at(n,i)),t.lt=(n,i)=>t.check(jr(n,i)),t.lte=(n,i)=>t.check(wt(n,i)),t.max=(n,i)=>t.check(wt(n,i)),t.positive=n=>t.check(Ar(BigInt(0),n)),t.negative=n=>t.check(jr(BigInt(0),n)),t.nonpositive=n=>t.check(wt(BigInt(0),n)),t.nonnegative=n=>t.check(at(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(Rn(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function fj(t){return dm(ja,t)}var mh=b("ZodBigIntFormat",(t,e)=>{pf.init(t,e),ja.init(t,e)});function mj(t){return mm(mh,t)}function hj(t){return hm(mh,t)}var Q_=b("ZodSymbol",(t,e)=>{df.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>n_(t,r,n,i)});function gj(t){return gm(Q_,t)}var ew=b("ZodUndefined",(t,e)=>{ff.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>o_(t,r,n,i)});function vj(t){return vm(ew,t)}var tw=b("ZodNull",(t,e)=>{mf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>i_(t,r,n,i)});function Aa(t){return ym(tw,t)}var rw=b("ZodAny",(t,e)=>{hf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>c_(t,r,n,i)});function hh(){return xm(rw)}var nw=b("ZodUnknown",(t,e)=>{gf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>u_(t,r,n,i)});function ve(){return bm(nw)}var iw=b("ZodNever",(t,e)=>{vf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>s_(t,r,n,i)});function gh(t){return _m(iw,t)}var ow=b("ZodVoid",(t,e)=>{yf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>a_(t,r,n,i)});function yj(t){return wm(ow,t)}var ru=b("ZodDate",(t,e)=>{xf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,i,o)=>l_(t,n,i,o),t.min=(n,i)=>t.check(at(n,i)),t.max=(n,i)=>t.check(wt(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function xj(t){return $m(ru,t)}var aw=b("ZodArray",(t,e)=>{bf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>w_(t,r,n,i),t.element=e.element,t.min=(r,n)=>t.check(on(r,n)),t.nonempty=r=>t.check(on(1,r)),t.max=(r,n)=>t.check(Ai(r,n)),t.length=(r,n)=>t.check(Ci(r,n)),t.unwrap=()=>t.element});function I(t,e){return X0(aw,t,e)}function bj(t){let e=t._zod.def.shape;return Qe(Object.keys(e))}var nu=b("ZodObject",(t,e)=>{J0.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>$_(t,r,n,i),E.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Qe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ve()}),t.loose=()=>t.clone({...t._zod.def,catchall:ve()}),t.strict=()=>t.clone({...t._zod.def,catchall:gh()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>E.extend(t,r),t.safeExtend=r=>E.safeExtend(t,r),t.merge=r=>E.merge(t,r),t.pick=r=>E.pick(t,r),t.omit=r=>E.omit(t,r),t.partial=(...r)=>E.partial(yh,t,r[0]),t.required=(...r)=>E.required(xh,t,r[0])});function z(t,e){let r={type:"object",shape:t??{},...E.normalizeParams(e)};return new nu(r)}function _j(t,e){return new nu({type:"object",shape:t,catchall:gh(),...E.normalizeParams(e)})}function Oe(t,e){return new nu({type:"object",shape:t,catchall:ve(),...E.normalizeParams(e)})}var iu=b("ZodUnion",(t,e)=>{la.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Um(t,r,n,i),t.options=e.options});function de(t,e){return new iu({type:"union",options:t,...E.normalizeParams(e)})}var sw=b("ZodXor",(t,e)=>{iu.init(t,e),_f.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Um(t,r,n,i),t.options=e.options});function wj(t,e){return new sw({type:"union",options:t,inclusive:!1,...E.normalizeParams(e)})}var cw=b("ZodDiscriminatedUnion",(t,e)=>{iu.init(t,e),wf.init(t,e)});function ou(t,e,r){return new cw({type:"union",options:e,discriminator:t,...E.normalizeParams(r)})}var uw=b("ZodIntersection",(t,e)=>{$f.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>k_(t,r,n,i)});function Ca(t,e){return new uw({type:"intersection",left:t,right:e})}var lw=b("ZodTuple",(t,e)=>{kc.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>S_(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function pw(t,e,r){let n=e instanceof Z,i=n?r:e,o=n?e:null;return new lw({type:"tuple",items:t,rest:o,...E.normalizeParams(i)})}var au=b("ZodRecord",(t,e)=>{kf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>E_(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new au({type:"record",keyType:t,valueType:e,...E.normalizeParams(r)})}function $j(t,e,r){let n=it(t);return n._zod.values=void 0,new au({type:"record",keyType:n,valueType:e,...E.normalizeParams(r)})}function kj(t,e,r){return new au({type:"record",keyType:t,valueType:e,mode:"loose",...E.normalizeParams(r)})}var dw=b("ZodMap",(t,e)=>{Sf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>b_(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Cr(...r)),t.nonempty=r=>t.check(Cr(1,r)),t.max=(...r)=>t.check(Nn(...r)),t.size=(...r)=>t.check(ji(...r))});function Sj(t,e,r){return new dw({type:"map",keyType:t,valueType:e,...E.normalizeParams(r)})}var fw=b("ZodSet",(t,e)=>{Ef.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>__(t,r,n,i),t.min=(...r)=>t.check(Cr(...r)),t.nonempty=r=>t.check(Cr(1,r)),t.max=(...r)=>t.check(Nn(...r)),t.size=(...r)=>t.check(ji(...r))});function Ej(t,e){return new fw({type:"set",valueType:t,...E.normalizeParams(e)})}var za=b("ZodEnum",(t,e)=>{zf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(n,i,o)=>p_(t,n,i,o),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let o={};for(let a of n)if(r.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new za({...e,checks:[],...E.normalizeParams(i),entries:o})},t.exclude=(n,i)=>{let o={...e.entries};for(let a of n)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new za({...e,checks:[],...E.normalizeParams(i),entries:o})}});function Qe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new za({type:"enum",entries:r,...E.normalizeParams(e)})}function zj(t,e){return new za({type:"enum",entries:t,...E.normalizeParams(e)})}var mw=b("ZodLiteral",(t,e)=>{If.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>d_(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function A(t,e){return new mw({type:"literal",values:Array.isArray(t)?t:[t],...E.normalizeParams(e)})}var hw=b("ZodFile",(t,e)=>{Tf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>h_(t,r,n,i),t.min=(r,n)=>t.check(Cr(r,n)),t.max=(r,n)=>t.check(Nn(r,n)),t.mime=(r,n)=>t.check(ba(Array.isArray(r)?r:[r],n))});function Ij(t){return Om(hw,t)}var gw=b("ZodTransform",(t,e)=>{Pf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>x_(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new On(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(E.issue(o,r.value,e));else{let a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),r.issues.push(E.issue(a))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r)):(r.value=i,r)}});function vh(t){return new gw({type:"transform",transform:t})}var yh=b("ZodOptional",(t,e)=>{Sc.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>qm(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function $e(t){return new yh({type:"optional",innerType:t})}var vw=b("ZodExactOptional",(t,e)=>{Of.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>qm(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function yw(t){return new vw({type:"optional",innerType:t})}var xw=b("ZodNullable",(t,e)=>{jf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>z_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Qc(t){return new xw({type:"nullable",innerType:t})}function Tj(t){return $e(Qc(t))}var bw=b("ZodDefault",(t,e)=>{Af.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>T_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function _w(t,e){return new bw({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():E.shallowClone(e)}})}var ww=b("ZodPrefault",(t,e)=>{Cf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>P_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function $w(t,e){return new ww({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():E.shallowClone(e)}})}var xh=b("ZodNonOptional",(t,e)=>{Rf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>I_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function kw(t,e){return new xh({type:"nonoptional",innerType:t,...E.normalizeParams(e)})}var Sw=b("ZodSuccess",(t,e)=>{Nf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>g_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Pj(t){return new Sw({type:"success",innerType:t})}var Ew=b("ZodCatch",(t,e)=>{Df.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>O_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function zw(t,e){return new Ew({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Iw=b("ZodNaN",(t,e)=>{Uf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>f_(t,r,n,i)});function Oj(t){return Sm(Iw,t)}var bh=b("ZodPipe",(t,e)=>{qf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>j_(t,r,n,i),t.in=e.in,t.out=e.out});function eu(t,e){return new bh({type:"pipe",in:t,out:e})}var _h=b("ZodCodec",(t,e)=>{bh.init(t,e),pa.init(t,e)});function jj(t,e,r){return new _h({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var Tw=b("ZodReadonly",(t,e)=>{Mf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>A_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Pw(t){return new Tw({type:"readonly",innerType:t})}var Ow=b("ZodTemplateLiteral",(t,e)=>{Lf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>m_(t,r,n,i)});function Aj(t,e){return new Ow({type:"template_literal",parts:t,...E.normalizeParams(e)})}var jw=b("ZodLazy",(t,e)=>{Vf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>R_(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function Aw(t){return new jw({type:"lazy",getter:t})}var Cw=b("ZodPromise",(t,e)=>{Ff.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>C_(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Cj(t){return new Cw({type:"promise",innerType:t})}var Rw=b("ZodFunction",(t,e)=>{Zf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>y_(t,r,n,i)});function Rj(t){return new Rw({type:"function",input:Array.isArray(t?.input)?pw(t?.input):t?.input??I(ve()),output:t?.output??ve()})}var su=b("ZodCustom",(t,e)=>{Bf.init(t,e),J.init(t,e),t._zod.processJSONSchema=(r,n,i)=>v_(t,r,n,i)});function Nj(t){let e=new he({check:"custom"});return e._zod.check=t,e}function wh(t,e){return jm(su,t??(()=>!0),e)}function Nw(t,e={}){return Am(su,t,e)}function Dw(t){return Cm(t)}var Dj=Rm,Uj=Nm;function qj(t,e={}){let r=new su({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...E.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var Mj=(...t)=>Dm({Codec:_h,Boolean:Oa,String:Ia},...t);function Lj(t){let e=Aw(()=>de([v(t),ie(),le(),Aa(),I(e),be(v(),e)]));return e}function cu(t,e){return eu(vh(t),e)}var qw={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Uw;Uw||(Uw={});var ZX={...Ea,...Xc,iso:Dn};var uu={};fi(uu,{bigint:()=>Bj,boolean:()=>Vj,date:()=>Hj,number:()=>Fj,string:()=>Zj});function Zj(t){return Xf(Ia,t)}function Fj(t){return im(Pa,t)}function Vj(t){return pm(Oa,t)}function Bj(t){return fm(ja,t)}function Hj(t){return km(ru,t)}je(Hf());var kh="2025-11-25",Mw="2025-03-26",Na=[kh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],sn="io.modelcontextprotocol/related-task",pu="2.0",Ze=wh(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Lw=de([v(),ie().int()]),Zw=v(),sY=Oe({ttl:de([ie(),Aa()]).optional(),pollInterval:ie().optional()}),Gj=z({ttl:ie().optional()}),Kj=z({taskId:v()}),Sh=Oe({progressToken:Lw.optional(),[sn]:Kj.optional()}),kt=z({_meta:Sh.optional()}),Da=kt.extend({task:Gj.optional()}),Fw=t=>Da.safeParse(t).success,Fe=z({method:v(),params:kt.loose().optional()}),Rt=z({_meta:Sh.optional()}),Nt=z({method:v(),params:Rt.loose().optional()}),Ve=Oe({_meta:Sh.optional()}),du=de([v(),ie().int()]),Vw=z({jsonrpc:A(pu),id:du,...Fe.shape}).strict(),cn=t=>Vw.safeParse(t).success,Bw=z({jsonrpc:A(pu),...Nt.shape}).strict(),Hw=t=>Bw.safeParse(t).success,Eh=z({jsonrpc:A(pu),id:du,result:Ve}).strict(),Nr=t=>Eh.safeParse(t).success;var re;(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"})(re||(re={}));var zh=z({jsonrpc:A(pu),id:du.optional(),error:z({code:ie().int(),message:v(),data:ve().optional()})}).strict();var qi=t=>zh.safeParse(t).success;var Ua=de([Vw,Bw,Eh,zh]),cY=de([Eh,zh]),fu=Ve.strict(),Wj=Rt.extend({requestId:du.optional(),reason:v().optional()}),mu=Nt.extend({method:A("notifications/cancelled"),params:Wj}),Xj=z({src:v(),mimeType:v().optional(),sizes:I(v()).optional(),theme:Qe(["light","dark"]).optional()}),qa=z({icons:I(Xj).optional()}),Ui=z({name:v(),title:v().optional()}),Jw=Ui.extend({...Ui.shape,...qa.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),Yj=Ca(z({applyDefaults:le().optional()}),be(v(),ve())),Qj=cu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ca(z({form:Yj.optional(),url:Ze.optional()}),be(v(),ve()).optional())),e8=Oe({list:Ze.optional(),cancel:Ze.optional(),requests:Oe({sampling:Oe({createMessage:Ze.optional()}).optional(),elicitation:Oe({create:Ze.optional()}).optional()}).optional()}),t8=Oe({list:Ze.optional(),cancel:Ze.optional(),requests:Oe({tools:Oe({call:Ze.optional()}).optional()}).optional()}),r8=z({experimental:be(v(),Ze).optional(),sampling:z({context:Ze.optional(),tools:Ze.optional()}).optional(),elicitation:Qj.optional(),roots:z({listChanged:le().optional()}).optional(),tasks:e8.optional()}),n8=kt.extend({protocolVersion:v(),capabilities:r8,clientInfo:Jw}),hu=Fe.extend({method:A("initialize"),params:n8}),Ih=t=>hu.safeParse(t).success,i8=z({experimental:be(v(),Ze).optional(),logging:Ze.optional(),completions:Ze.optional(),prompts:z({listChanged:le().optional()}).optional(),resources:z({subscribe:le().optional(),listChanged:le().optional()}).optional(),tools:z({listChanged:le().optional()}).optional(),tasks:t8.optional()}),o8=Ve.extend({protocolVersion:v(),capabilities:i8,serverInfo:Jw,instructions:v().optional()}),Th=Nt.extend({method:A("notifications/initialized"),params:Rt.optional()});var gu=Fe.extend({method:A("ping"),params:kt.optional()}),a8=z({progress:ie(),total:$e(ie()),message:$e(v())}),s8=z({...Rt.shape,...a8.shape,progressToken:Lw}),vu=Nt.extend({method:A("notifications/progress"),params:s8}),c8=kt.extend({cursor:Zw.optional()}),Ma=Fe.extend({params:c8.optional()}),La=Ve.extend({nextCursor:Zw.optional()}),u8=Qe(["working","input_required","completed","failed","cancelled"]),Za=z({taskId:v(),status:u8,ttl:de([ie(),Aa()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:$e(ie()),statusMessage:$e(v())}),Mi=Ve.extend({task:Za}),l8=Rt.merge(Za),Fa=Nt.extend({method:A("notifications/tasks/status"),params:l8}),yu=Fe.extend({method:A("tasks/get"),params:kt.extend({taskId:v()})}),xu=Ve.merge(Za),bu=Fe.extend({method:A("tasks/result"),params:kt.extend({taskId:v()})}),uY=Ve.loose(),_u=Ma.extend({method:A("tasks/list")}),wu=La.extend({tasks:I(Za)}),$u=Fe.extend({method:A("tasks/cancel"),params:kt.extend({taskId:v()})}),Gw=Ve.merge(Za),Kw=z({uri:v(),mimeType:$e(v()),_meta:be(v(),ve()).optional()}),Ww=Kw.extend({text:v()}),Ph=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Xw=Kw.extend({blob:Ph}),Va=Qe(["user","assistant"]),Li=z({audience:I(Va).optional(),priority:ie().min(0).max(1).optional(),lastModified:Dn.datetime({offset:!0}).optional()}),Yw=z({...Ui.shape,...qa.shape,uri:v(),description:$e(v()),mimeType:$e(v()),annotations:Li.optional(),_meta:$e(Oe({}))}),p8=z({...Ui.shape,...qa.shape,uriTemplate:v(),description:$e(v()),mimeType:$e(v()),annotations:Li.optional(),_meta:$e(Oe({}))}),d8=Ma.extend({method:A("resources/list")}),f8=La.extend({resources:I(Yw)}),m8=Ma.extend({method:A("resources/templates/list")}),h8=La.extend({resourceTemplates:I(p8)}),Oh=kt.extend({uri:v()}),g8=Oh,v8=Fe.extend({method:A("resources/read"),params:g8}),y8=Ve.extend({contents:I(de([Ww,Xw]))}),x8=Nt.extend({method:A("notifications/resources/list_changed"),params:Rt.optional()}),b8=Oh,_8=Fe.extend({method:A("resources/subscribe"),params:b8}),w8=Oh,$8=Fe.extend({method:A("resources/unsubscribe"),params:w8}),k8=Rt.extend({uri:v()}),S8=Nt.extend({method:A("notifications/resources/updated"),params:k8}),E8=z({name:v(),description:$e(v()),required:$e(le())}),z8=z({...Ui.shape,...qa.shape,description:$e(v()),arguments:$e(I(E8)),_meta:$e(Oe({}))}),I8=Ma.extend({method:A("prompts/list")}),T8=La.extend({prompts:I(z8)}),P8=kt.extend({name:v(),arguments:be(v(),v()).optional()}),O8=Fe.extend({method:A("prompts/get"),params:P8}),jh=z({type:A("text"),text:v(),annotations:Li.optional(),_meta:be(v(),ve()).optional()}),Ah=z({type:A("image"),data:Ph,mimeType:v(),annotations:Li.optional(),_meta:be(v(),ve()).optional()}),Ch=z({type:A("audio"),data:Ph,mimeType:v(),annotations:Li.optional(),_meta:be(v(),ve()).optional()}),j8=z({type:A("tool_use"),name:v(),id:v(),input:be(v(),ve()),_meta:be(v(),ve()).optional()}),A8=z({type:A("resource"),resource:de([Ww,Xw]),annotations:Li.optional(),_meta:be(v(),ve()).optional()}),C8=Yw.extend({type:A("resource_link")}),Rh=de([jh,Ah,Ch,C8,A8]),R8=z({role:Va,content:Rh}),N8=Ve.extend({description:v().optional(),messages:I(R8)}),D8=Nt.extend({method:A("notifications/prompts/list_changed"),params:Rt.optional()}),U8=z({title:v().optional(),readOnlyHint:le().optional(),destructiveHint:le().optional(),idempotentHint:le().optional(),openWorldHint:le().optional()}),q8=z({taskSupport:Qe(["required","optional","forbidden"]).optional()}),Qw=z({...Ui.shape,...qa.shape,description:v().optional(),inputSchema:z({type:A("object"),properties:be(v(),Ze).optional(),required:I(v()).optional()}).catchall(ve()),outputSchema:z({type:A("object"),properties:be(v(),Ze).optional(),required:I(v()).optional()}).catchall(ve()).optional(),annotations:U8.optional(),execution:q8.optional(),_meta:be(v(),ve()).optional()}),Ba=Ma.extend({method:A("tools/list")}),M8=La.extend({tools:I(Qw)}),ku=Ve.extend({content:I(Rh).default([]),structuredContent:be(v(),ve()).optional(),isError:le().optional()}),lY=ku.or(Ve.extend({toolResult:ve()})),L8=Da.extend({name:v(),arguments:be(v(),ve()).optional()}),Un=Fe.extend({method:A("tools/call"),params:L8}),Z8=Nt.extend({method:A("notifications/tools/list_changed"),params:Rt.optional()}),pY=z({autoRefresh:le().default(!0),debounceMs:ie().int().nonnegative().default(300)}),Ha=Qe(["debug","info","notice","warning","error","critical","alert","emergency"]),F8=kt.extend({level:Ha}),Nh=Fe.extend({method:A("logging/setLevel"),params:F8}),V8=Rt.extend({level:Ha,logger:v().optional(),data:ve()}),B8=Nt.extend({method:A("notifications/message"),params:V8}),H8=z({name:v().optional()}),J8=z({hints:I(H8).optional(),costPriority:ie().min(0).max(1).optional(),speedPriority:ie().min(0).max(1).optional(),intelligencePriority:ie().min(0).max(1).optional()}),G8=z({mode:Qe(["auto","required","none"]).optional()}),K8=z({type:A("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:I(Rh).default([]),structuredContent:z({}).loose().optional(),isError:le().optional(),_meta:be(v(),ve()).optional()}),W8=ou("type",[jh,Ah,Ch]),lu=ou("type",[jh,Ah,Ch,j8,K8]),X8=z({role:Va,content:de([lu,I(lu)]),_meta:be(v(),ve()).optional()}),Y8=Da.extend({messages:I(X8),modelPreferences:J8.optional(),systemPrompt:v().optional(),includeContext:Qe(["none","thisServer","allServers"]).optional(),temperature:ie().optional(),maxTokens:ie().int(),stopSequences:I(v()).optional(),metadata:Ze.optional(),tools:I(Qw).optional(),toolChoice:G8.optional()}),Q8=Fe.extend({method:A("sampling/createMessage"),params:Y8}),Dh=Ve.extend({model:v(),stopReason:$e(Qe(["endTurn","stopSequence","maxTokens"]).or(v())),role:Va,content:W8}),Uh=Ve.extend({model:v(),stopReason:$e(Qe(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:Va,content:de([lu,I(lu)])}),eA=z({type:A("boolean"),title:v().optional(),description:v().optional(),default:le().optional()}),tA=z({type:A("string"),title:v().optional(),description:v().optional(),minLength:ie().optional(),maxLength:ie().optional(),format:Qe(["email","uri","date","date-time"]).optional(),default:v().optional()}),rA=z({type:Qe(["number","integer"]),title:v().optional(),description:v().optional(),minimum:ie().optional(),maximum:ie().optional(),default:ie().optional()}),nA=z({type:A("string"),title:v().optional(),description:v().optional(),enum:I(v()),default:v().optional()}),iA=z({type:A("string"),title:v().optional(),description:v().optional(),oneOf:I(z({const:v(),title:v()})),default:v().optional()}),oA=z({type:A("string"),title:v().optional(),description:v().optional(),enum:I(v()),enumNames:I(v()).optional(),default:v().optional()}),aA=de([nA,iA]),sA=z({type:A("array"),title:v().optional(),description:v().optional(),minItems:ie().optional(),maxItems:ie().optional(),items:z({type:A("string"),enum:I(v())}),default:I(v()).optional()}),cA=z({type:A("array"),title:v().optional(),description:v().optional(),minItems:ie().optional(),maxItems:ie().optional(),items:z({anyOf:I(z({const:v(),title:v()}))}),default:I(v()).optional()}),uA=de([sA,cA]),lA=de([oA,aA,uA]),pA=de([lA,eA,tA,rA]),dA=Da.extend({mode:A("form").optional(),message:v(),requestedSchema:z({type:A("object"),properties:be(v(),pA),required:I(v()).optional()})}),fA=Da.extend({mode:A("url"),message:v(),elicitationId:v(),url:v().url()}),mA=de([dA,fA]),hA=Fe.extend({method:A("elicitation/create"),params:mA}),gA=Rt.extend({elicitationId:v()}),vA=Nt.extend({method:A("notifications/elicitation/complete"),params:gA}),Su=Ve.extend({action:Qe(["accept","decline","cancel"]),content:cu(t=>t===null?void 0:t,be(v(),de([v(),ie(),le(),I(v())])).optional())}),yA=z({type:A("ref/resource"),uri:v()});var xA=z({type:A("ref/prompt"),name:v()}),bA=kt.extend({ref:de([xA,yA]),argument:z({name:v(),value:v()}),context:z({arguments:be(v(),v()).optional()}).optional()}),_A=Fe.extend({method:A("completion/complete"),params:bA});var wA=Ve.extend({completion:Oe({values:I(v()).max(100),total:$e(ie().int()),hasMore:$e(le())})}),$A=z({uri:v().startsWith("file://"),name:v().optional(),_meta:be(v(),ve()).optional()}),kA=Fe.extend({method:A("roots/list"),params:kt.optional()}),qh=Ve.extend({roots:I($A)}),SA=Nt.extend({method:A("notifications/roots/list_changed"),params:Rt.optional()}),dY=de([gu,hu,_A,Nh,O8,I8,d8,m8,v8,_8,$8,Un,Ba,yu,bu,_u,$u]),fY=de([mu,vu,Th,SA,Fa]),mY=de([fu,Dh,Uh,Su,qh,xu,wu,Mi]),hY=de([gu,Q8,hA,kA,yu,bu,_u,$u]),gY=de([mu,vu,B8,S8,x8,Z8,D8,Fa,vA]),vY=de([fu,o8,wA,N8,T8,f8,h8,y8,ku,M8,xu,wu,Mi]),K=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===re.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new $h(i.elicitations,r)}return new t(e,r,n)}},$h=class extends K{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(re.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function un(t){return t==="completed"||t==="failed"||t==="cancelled"}var EA=Symbol("Let zodToJsonSchema decide on which parser to use");var XY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Mh(t){let r=Wc(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=U_(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Lh(t,e){let r=an(t,e);if(!r.success)throw r.error;return r.data}var jA=6e4,Eu=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(mu,r=>{this._oncancel(r)}),this.setNotificationHandler(vu,r=>{this._onprogress(r)}),this.setRequestHandler(gu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(yu,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new K(re.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(bu,async(r,n)=>{let i=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let p=c,d=new K(p.error.code,p.error.message,p.error.data);l(d)}else{let p=s.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new K(re.InvalidParams,`Task not found: ${o}`);if(!un(a.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(un(a.status)){let s=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[sn]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(_u,async(r,n)=>{try{let{tasks:i,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new K(re.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler($u,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new K(re.InvalidParams,`Task not found: ${r.params.taskId}`);if(un(i.status))throw new K(re.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new K(re.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof K?i:new K(re.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_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),K.fromError(re.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let i=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{i?.(o,a),Nr(o)||qi(o)?this._onresponse(o):cn(o)?this._onrequest(o,a):Hw(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=K.fromError(re.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,i=this._transport,o=e.params?._meta?.[sn]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:re.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},i?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):i?.send(l).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=Fw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,u={signal:a.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let p={relatedRequestId:e.id};o&&(p.relatedTask={taskId:o}),await this.notification(l,p)},sendRequest:async(l,p,d)=>{let f={...d,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let m=f.relatedTask?.taskId??o;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,p,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(a.signal.aborted)return;let p={result:l,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async l=>{if(a.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:re.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),a(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Nr(e))n(e);else{let a=new K(e.error.code,e.error.message,e.error.data);n(a)}return}let i=this._responseHandlers.get(r);if(i===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 o=!1;if(Nr(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),Nr(e))i(e);else{let a=K.fromError(e.error.code,e.error.message,e.error.data);i(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof K?a:new K(re.InternalError,String(a))}}return}let o;try{let a=await this.request(e,Mi,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new K(re.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:s},un(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:s.status==="failed"?yield{type:"error",error:new K(re.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new K(re.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof K?a:new K(re.InternalError,String(a))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{let p=_=>{l(_)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(_){p(_);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[sn]:c}});let m=_=>{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(_)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let $=_ instanceof K?_:new K(re.RequestTimeout,String(_));l($)};this._responseHandlers.set(d,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let $=an(r,_.result);$.success?u($.data):l($.error)}catch($){l($)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??jA,g=()=>m(K.fromError(re.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let _=$=>{let k=this._responseHandlers.get(d);k?k($):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,_),this._enqueueTaskMessage(x,{type:"request",message:f,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(d),l($)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a}).catch(_=>{this._cleanupTimeout(d),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},xu,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},wu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Gw,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 s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[sn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,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 s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[sn]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[sn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let n=Mh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let a=Lh(e,i);return Promise.resolve(r(a,o))})}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=Mh(e);this._notificationHandlers.set(n,i=>{let o=Lh(e,i);return Promise.resolve(r(o))})}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 i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,i)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&cn(i.message)){let o=i.message.id,a=this._requestResolvers.get(o);a?(a(new K(re.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,o)=>{if(r.aborted){o(new K(re.InvalidRequest,"Request cancelled"));return}let a=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(a),o(new K(re.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new K(re.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,a)=>{await n.storeTaskResult(i,o,a,r);let s=await n.getTask(i,r);if(s){let c=Fa.parse({method:"notifications/tasks/status",params:s});await this.notification(c),un(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,a)=>{let s=await n.getTask(i,r);if(!s)throw new K(re.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(un(s.status))throw new K(re.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,a,r);let c=await n.getTask(i,r);if(c){let u=Fa.parse({method:"notifications/tasks/status",params:c});await this.notification(u),un(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function e1(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function t1(t,e){let r={...t};for(let n in e){let i=n,o=e[i];if(o===void 0)continue;let a=r[i];e1(a)&&e1(o)?r[i]={...a,...o}:r[i]=o}return r}var Lk=Ce(Ev(),1),Zk=Ce(Mk(),1);function wU(){let t=new Lk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Zk.default)(t),t}var ul=class{constructor(e){this._ajv=e??wU()}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 ll=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Fk(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 Vk(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 io=class extends Eu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ha.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let o=this._loggingLevels.get(i);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new ul,this.setRequestHandler(hu,n=>this._oninitialize(n)),this.setNotificationHandler(Th,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Nh,async(n,i)=>{let o=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=Ha.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ll(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=t1(this._capabilities,e)}setRequestHandler(e,r){let i=Wc(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let o;if(Ni(i)){let s=i;o=s._zod?.def?.value??s.value}else{let s=i;o=s._def?.value??s.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(c,u)=>{let l=an(Un,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new K(re.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=l.data,d=await Promise.resolve(r(c,u));if(p.task){let m=an(Mi,d);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new K(re.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=an(ku,d);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new K(re.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,s)}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){Vk(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Fk(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:Na.includes(r)?r:kh,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"},fu)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],o=i.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(o){if(i.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(s.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(u.size!==l.size||![...u].every(p=>l.has(p)))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},Uh,r):this.request({method:"sampling/createMessage",params:e},Dh,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 i=e;return this.request({method:"elicitation/create",params:i},Su,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:i},Su,r);if(o.action==="accept"&&o.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(o.content);if(!s.valid)throw new K(re.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof K?a:new K(re.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}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},qh,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 Cv=Ce(require("node:process"),1);var pl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
98
98
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),$U(r)}clear(){this._buffer=void 0}};function $U(t){return Ua.parse(JSON.parse(t))}function Bk(t){return JSON.stringify(t)+`
99
- `}var dl=class{constructor(e=Cv.default.stdin,r=Cv.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new pl,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Bk(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var kU="https://app.lexic.io/api";function Hk(){let t=process.env.LEXIC_API_URL||kU,e=process.env.LEXIC_PAT;if(!e)throw new Error("LEXIC_PAT is required");if(!e.startsWith("pat_"))throw new Error("LEXIC_PAT must start with pat_");return{apiUrl:t,pat:e,logLevel:process.env.LOG_LEVEL||"info"}}var SU="https://app.lexic.io/api";var EU="localhost",zU=["lexic:read","lexic:write","lexic:admin"];function IU(){let t=process.env.LEXIC_PAT;if(!t)throw new Error("LEXIC_PAT is required for stdio transport");if(!t.startsWith("pat_"))throw new Error("LEXIC_PAT must start with pat_");return{pat:t}}function TU(){let t=process.env.LEXIC_SUPABASE_URL,e=process.env.LEXIC_SUPABASE_ANON_KEY,r=process.env.LEXIC_SUPABASE_JWT_SECRET;if(!t)throw new Error("LEXIC_SUPABASE_URL is required for HTTP transport");if(!e)throw new Error("LEXIC_SUPABASE_ANON_KEY is required for HTTP transport");if(!r)throw new Error("LEXIC_SUPABASE_JWT_SECRET is required for HTTP transport");try{new URL(t)}catch{throw new Error("LEXIC_SUPABASE_URL must be a valid URL")}let n=parseInt(process.env.LEXIC_HTTP_PORT||String(3e3),10);if(isNaN(n)||n<1||n>65535)throw new Error("LEXIC_HTTP_PORT must be a valid port number (1-65535)");let i=process.env.LEXIC_HTTP_HOST||EU,o=process.env.LEXIC_BASE_URL;if(o)try{new URL(o)}catch{throw new Error("LEXIC_BASE_URL must be a valid URL")}let a=process.env.LEXIC_OAUTH_SCOPES,s=zU;if(a){let c=a.split(",").map(l=>l.trim()),u=new Set(["lexic:read","lexic:write","lexic:admin"]);for(let l of c)if(!u.has(l))throw new Error(`Invalid scope: ${l}. Valid scopes are: ${Array.from(u).join(", ")}`);s=c}return{supabaseUrl:t,supabaseAnonKey:e,supabaseJwtSecret:r,httpPort:n,httpHost:i,baseUrl:o,scopesSupported:s}}function Rv(){let e=process.env.LEXIC_TRANSPORT?.toLowerCase()==="http"?"http":"stdio",r=process.env.LEXIC_API_URL||SU,n=process.env.LOG_LEVEL||"info",i={transport:e,apiUrl:r,logLevel:n};return e==="stdio"?i.patConfig=IU():i.oauthConfig=TU(),i}function Nv(t){return t.transport==="http"&&t.oauthConfig!==void 0}function Dv(t){return t.baseUrl?t.baseUrl:`${t.httpHost==="localhost"||t.httpHost==="127.0.0.1"?"http":"https"}://${t.httpHost}:${t.httpPort}`}function Uv(t){let e=t.replace(/\/$/,"");return{authorizationUrl:`${e}/auth/v1/authorize`,tokenUrl:`${e}/auth/v1/token`,userInfoUrl:`${e}/auth/v1/user`,jwksUrl:`${e}/auth/v1/.well-known/jwks.json`}}function fl(t){let r=(t||process.env.LEXIC_API_URL||"https://app.lexic.io/api").replace(/\/api\/?$/,"");return{authorizationUrl:`${r}/cli/auth`,tokenUrl:`${r}/api/auth/token`}}var qv={debug:0,info:1,warn:2,error:3},Mv=class{level="info";setLevel(e){qv[e]!==void 0&&(this.level=e)}getLevel(){return this.level}shouldLog(e){return qv[e]>=qv[this.level]}format(e,r,n){let o=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${r}`;if(n){let a={...n};return"pat"in a&&(a.pat="[REDACTED]"),"token"in a&&(a.token="[REDACTED]"),"authorization"in a&&(a.authorization="[REDACTED]"),`${o} ${JSON.stringify(a)}`}return o}debug(e,r){this.shouldLog("debug")&&console.error(this.format("debug",e,r))}info(e,r){this.shouldLog("info")&&console.error(this.format("info",e,r))}warn(e,r){this.shouldLog("warn")&&console.error(this.format("warn",e,r))}error(e,r){this.shouldLog("error")&&console.error(this.format("error",e,r))}},w=new Mv;var oo=class extends Error{statusCode;correlationId;constructor(e,r,n){super(e),this.statusCode=r,this.correlationId=n,this.name="LexicApiError"}};var PU="0.1.18";function Fr(t){return typeof t=="object"&&t!==null&&"_meta"in t&&typeof t._meta=="object"&&t._meta!==null&&t._meta.dataType==="user_content"}var OU=3e4,Jk=1,jU=1e3;function Gk(t){return ml({apiUrl:t.apiUrl,auth:{type:"pat",token:t.pat}})}function ml(t){let{apiUrl:e,lexiconId:r}=t,n=t.auth.token,i=t.auth.type,o=null;function a(){let c={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Client-Version":`lexic-mcp/${PU}`};return r&&i==="oauth"&&(c["X-Lexicon-Id"]=r),c}async function s(c,u,l=Jk){let p=new AbortController,d=setTimeout(()=>p.abort(),OU);try{let f=await fetch(c,{...u,signal:p.signal,headers:{...a(),...u.headers}});if(clearTimeout(d),f.status>=500&&l>0){let m=jU*Math.pow(2,Jk-l);return w.debug("Retrying request after server error",{url:c,status:f.status,delay:m,retriesLeft:l-1}),await AU(m),s(c,u,l-1)}return f}catch(f){throw clearTimeout(d),f instanceof Error&&f.name==="AbortError"?new oo("Request timeout",408):f}}return{async executeTool(c,u){try{w.debug("Executing tool via API",{toolName:c,args:u});let l=await s(`${e}/mcp/execute`,{method:"POST",body:JSON.stringify({tool:c,arguments:u})}),p=await l.json();return l.ok?{success:p.success??!0,data:p.data,error:p.error}:{success:!1,error:p.error||`Tool execution failed with status ${l.status}`}}catch(l){return w.error("Tool execution failed",{toolName:c,error:l instanceof Error?l.message:String(l)}),{success:!1,error:l instanceof Error?l.message:"Unknown error"}}},async validateConnection(){try{let c=await fetch(`${e}/mcp/validate`,{method:"GET",headers:a()}),u=await c.json();return c.ok?(o={valid:u.valid??!0,lexiconId:u.lexiconId,userId:u.userId,isUserScoped:u.isUserScoped??!u.lexiconId,expiresAt:u.expiresAt?new Date(u.expiresAt):null},o):(o={valid:!1,isUserScoped:!1,error:u.error||"Authentication failed"},o)}catch(c){return o={valid:!1,isUserScoped:!1,error:`Network error: ${c instanceof Error?c.message:String(c)}`},o}},async fetchTriggers(c){let u=new URL(`${e}/mcp/triggers`);c!==void 0&&u.searchParams.set("since",c.toString());try{let l=await s(u.toString(),{method:"GET",headers:{Accept:"application/json","Accept-Encoding":"gzip"}});if(!l.ok)throw w.warn("Failed to fetch triggers",{status:l.status,statusText:l.statusText}),new oo(`HTTP ${l.status}`,l.status);return await l.json()}catch(l){throw w.error("Trigger fetch error",{error:l instanceof Error?l.message:String(l)}),l}},async fetchDomains(c){let u=new URL(`${e}/mcp/domains`);c!==void 0&&u.searchParams.set("since",c.toString());try{let l=await s(u.toString(),{method:"GET",headers:{Accept:"application/json","Accept-Encoding":"gzip"}});if(!l.ok)throw w.warn("Failed to fetch domains",{status:l.status,statusText:l.statusText}),new oo(`HTTP ${l.status}`,l.status);return await l.json()}catch(l){throw w.error("Domain fetch error",{error:l instanceof Error?l.message:String(l)}),l}},isUserScoped(){return o?.isUserScoped??!1},getCurrentLexiconId(){return o?.lexiconId},getExpiresAt(){return o?.expiresAt},updateToken(c){n=c,w.debug("Token updated")},getAuthType(){return i}}}function AU(t){return new Promise(e=>setTimeout(e,t))}var vt=require("fs"),Kk=require("os"),Lv=require("path");var CU=".lexic",RU="credentials.json",hl=1;function Zv(){return(0,Lv.join)((0,Kk.homedir)(),CU)}function gl(){return(0,Lv.join)(Zv(),RU)}function NU(){let t=Zv();(0,vt.existsSync)(t)||((0,vt.mkdirSync)(t,{recursive:!0,mode:448}),w.debug("Created Lexic config directory",{path:t}))}function ao(){let t=gl();if(!(0,vt.existsSync)(t))return{version:hl,credentials:{}};try{let e=(0,vt.readFileSync)(t,"utf8"),r=JSON.parse(e);return r.version!==hl&&w.warn("Credentials file version mismatch, may need migration",{fileVersion:r.version,currentVersion:hl}),r}catch(e){return w.warn("Failed to load credentials file, starting fresh",{error:e instanceof Error?e.message:String(e)}),{version:hl,credentials:{}}}}function Fv(t){NU();let e=gl(),r=JSON.stringify(t,null,2);(0,vt.writeFileSync)(e,r,{encoding:"utf8",mode:384});try{(0,vt.chmodSync)(e,384)}catch{}w.debug("Saved credentials file",{path:e})}function Vv(t,e,r){let n=ao(),i=t.replace(/\/$/,""),o={access_token:e.access_token,refresh_token:e.refresh_token,token_type:e.token_type,supabase_url:i,stored_at:Math.floor(Date.now()/1e3),user_id:r?.user_id,email:r?.email};e.expires_in&&(o.expires_at=o.stored_at+e.expires_in),n.credentials[i]=o,n.default_project=i,Fv(n),w.info("Stored OAuth credentials",{supabaseUrl:i,expiresAt:o.expires_at?new Date(o.expires_at*1e3).toISOString():"unknown"})}function nr(t){let e=ao(),r=t?.replace(/\/$/,"")||e.default_project;if(!r){w.debug("No Supabase URL provided and no default project set");return}let n=e.credentials[r];if(!n){w.debug("No credentials found for project",{supabaseUrl:r});return}return n}function yn(t){let e=nr(t);if(!e)return!1;if(e.expires_at){let r=Math.floor(Date.now()/1e3),n=5*60,i=e.expires_at-n;if(w.debug("Checking credential validity",{expiresAt:e.expires_at,expiresAtDate:new Date(e.expires_at*1e3).toISOString(),now:r,nowDate:new Date(r*1e3).toISOString(),expiresWithBuffer:i,isExpired:i<r}),i<r)return w.debug("Credentials expired or expiring soon",{expiresAt:new Date(e.expires_at*1e3).toISOString()}),!1}return!0}function Kn(t){let e=nr(t);if(!e||!e.expires_at||!e.refresh_token)return!1;let r=Math.floor(Date.now()/1e3),n=5*60;return e.expires_at-n<r}function $s(t,e){let r=ao(),n=t.replace(/\/$/,""),i=r.credentials[n];if(!i){w.warn("Cannot update tokens - no existing credentials",{supabaseUrl:n});return}i.access_token=e.access_token,i.token_type=e.token_type,i.stored_at=Math.floor(Date.now()/1e3),e.refresh_token&&(i.refresh_token=e.refresh_token),e.expires_in&&(i.expires_at=i.stored_at+e.expires_in),r.credentials[n]=i,Fv(r),w.info("Updated OAuth tokens",{supabaseUrl:n,expiresAt:i.expires_at?new Date(i.expires_at*1e3).toISOString():"unknown"})}function Bv(t){let e=ao(),r=t.replace(/\/$/,"");if(e.credentials[r]){if(delete e.credentials[r],e.default_project===r){let n=Object.keys(e.credentials);e.default_project=n.length>0?n[0]:void 0}Fv(e),w.info("Removed credentials",{supabaseUrl:r})}}function Hv(){let t=gl();(0,vt.existsSync)(t)&&((0,vt.unlinkSync)(t),w.info("Cleared all stored credentials"))}function vl(){let t=ao();return Object.keys(t.credentials)}function yl(){return ao().default_project}var ey=require("http"),Qv=require("url"),tS=require("child_process"),rS=require("os");var ks=require("crypto");function Wk(){return(0,ks.randomBytes)(32).toString("base64url")}function Xk(t){return(0,ks.createHash)("sha256").update(t,"ascii").digest().toString("base64url")}function Jv(){let t=Wk(),e=Xk(t);return{codeVerifier:t,codeChallenge:e}}function Gv(){return(0,ks.randomBytes)(16).toString("base64url")}function Kv(){return`<!DOCTYPE html>
99
+ `}var dl=class{constructor(e=Cv.default.stdin,r=Cv.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new pl,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Bk(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var kU="https://app.lexic.io/api";function Hk(){let t=process.env.LEXIC_API_URL||kU,e=process.env.LEXIC_PAT;if(!e)throw new Error("LEXIC_PAT is required");if(!e.startsWith("pat_"))throw new Error("LEXIC_PAT must start with pat_");return{apiUrl:t,pat:e,logLevel:process.env.LOG_LEVEL||"info"}}var SU="https://app.lexic.io/api";var EU="localhost",zU=["lexic:read","lexic:write","lexic:admin"];function IU(){let t=process.env.LEXIC_PAT;if(!t)throw new Error("LEXIC_PAT is required for stdio transport");if(!t.startsWith("pat_"))throw new Error("LEXIC_PAT must start with pat_");return{pat:t}}function TU(){let t=process.env.LEXIC_SUPABASE_URL,e=process.env.LEXIC_SUPABASE_ANON_KEY,r=process.env.LEXIC_SUPABASE_JWT_SECRET;if(!t)throw new Error("LEXIC_SUPABASE_URL is required for HTTP transport");if(!e)throw new Error("LEXIC_SUPABASE_ANON_KEY is required for HTTP transport");if(!r)throw new Error("LEXIC_SUPABASE_JWT_SECRET is required for HTTP transport");try{new URL(t)}catch{throw new Error("LEXIC_SUPABASE_URL must be a valid URL")}let n=parseInt(process.env.LEXIC_HTTP_PORT||String(3e3),10);if(isNaN(n)||n<1||n>65535)throw new Error("LEXIC_HTTP_PORT must be a valid port number (1-65535)");let i=process.env.LEXIC_HTTP_HOST||EU,o=process.env.LEXIC_BASE_URL;if(o)try{new URL(o)}catch{throw new Error("LEXIC_BASE_URL must be a valid URL")}let a=process.env.LEXIC_OAUTH_SCOPES,s=zU;if(a){let c=a.split(",").map(l=>l.trim()),u=new Set(["lexic:read","lexic:write","lexic:admin"]);for(let l of c)if(!u.has(l))throw new Error(`Invalid scope: ${l}. Valid scopes are: ${Array.from(u).join(", ")}`);s=c}return{supabaseUrl:t,supabaseAnonKey:e,supabaseJwtSecret:r,httpPort:n,httpHost:i,baseUrl:o,scopesSupported:s}}function Rv(){let e=process.env.LEXIC_TRANSPORT?.toLowerCase()==="http"?"http":"stdio",r=process.env.LEXIC_API_URL||SU,n=process.env.LOG_LEVEL||"info",i={transport:e,apiUrl:r,logLevel:n};return e==="stdio"?i.patConfig=IU():i.oauthConfig=TU(),i}function Nv(t){return t.transport==="http"&&t.oauthConfig!==void 0}function Dv(t){return t.baseUrl?t.baseUrl:`${t.httpHost==="localhost"||t.httpHost==="127.0.0.1"?"http":"https"}://${t.httpHost}:${t.httpPort}`}function Uv(t){let e=t.replace(/\/$/,"");return{authorizationUrl:`${e}/auth/v1/authorize`,tokenUrl:`${e}/auth/v1/token`,userInfoUrl:`${e}/auth/v1/user`,jwksUrl:`${e}/auth/v1/.well-known/jwks.json`}}function fl(t){let r=(t||process.env.LEXIC_API_URL||"https://app.lexic.io/api").replace(/\/api\/?$/,"");return{authorizationUrl:`${r}/cli/auth`,tokenUrl:`${r}/api/auth/token`}}var qv={debug:0,info:1,warn:2,error:3},Mv=class{level="info";setLevel(e){qv[e]!==void 0&&(this.level=e)}getLevel(){return this.level}shouldLog(e){return qv[e]>=qv[this.level]}format(e,r,n){let o=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${r}`;if(n){let a={...n};return"pat"in a&&(a.pat="[REDACTED]"),"token"in a&&(a.token="[REDACTED]"),"authorization"in a&&(a.authorization="[REDACTED]"),`${o} ${JSON.stringify(a)}`}return o}debug(e,r){this.shouldLog("debug")&&console.error(this.format("debug",e,r))}info(e,r){this.shouldLog("info")&&console.error(this.format("info",e,r))}warn(e,r){this.shouldLog("warn")&&console.error(this.format("warn",e,r))}error(e,r){this.shouldLog("error")&&console.error(this.format("error",e,r))}},w=new Mv;var oo=class extends Error{statusCode;correlationId;constructor(e,r,n){super(e),this.statusCode=r,this.correlationId=n,this.name="LexicApiError"}};var PU="0.1.19";function Fr(t){return typeof t=="object"&&t!==null&&"_meta"in t&&typeof t._meta=="object"&&t._meta!==null&&t._meta.dataType==="user_content"}var OU=3e4,Jk=1,jU=1e3;function Gk(t){return ml({apiUrl:t.apiUrl,auth:{type:"pat",token:t.pat}})}function ml(t){let{apiUrl:e,lexiconId:r}=t,n=t.auth.token,i=t.auth.type,o=null;function a(){let c={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Client-Version":`lexic-mcp/${PU}`};return r&&i==="oauth"&&(c["X-Lexicon-Id"]=r),c}async function s(c,u,l=Jk){let p=new AbortController,d=setTimeout(()=>p.abort(),OU);try{let f=await fetch(c,{...u,signal:p.signal,headers:{...a(),...u.headers}});if(clearTimeout(d),f.status>=500&&l>0){let m=jU*Math.pow(2,Jk-l);return w.debug("Retrying request after server error",{url:c,status:f.status,delay:m,retriesLeft:l-1}),await AU(m),s(c,u,l-1)}return f}catch(f){throw clearTimeout(d),f instanceof Error&&f.name==="AbortError"?new oo("Request timeout",408):f}}return{async executeTool(c,u){try{w.debug("Executing tool via API",{toolName:c,args:u});let l=await s(`${e}/mcp/execute`,{method:"POST",body:JSON.stringify({tool:c,arguments:u})}),p=await l.json();return l.ok?{success:p.success??!0,data:p.data,error:p.error}:{success:!1,error:p.error||`Tool execution failed with status ${l.status}`}}catch(l){return w.error("Tool execution failed",{toolName:c,error:l instanceof Error?l.message:String(l)}),{success:!1,error:l instanceof Error?l.message:"Unknown error"}}},async validateConnection(){try{let c=await fetch(`${e}/mcp/validate`,{method:"GET",headers:a()}),u=await c.json();return c.ok?(o={valid:u.valid??!0,lexiconId:u.lexiconId,userId:u.userId,isUserScoped:u.isUserScoped??!u.lexiconId,expiresAt:u.expiresAt?new Date(u.expiresAt):null},o):(o={valid:!1,isUserScoped:!1,error:u.error||"Authentication failed"},o)}catch(c){return o={valid:!1,isUserScoped:!1,error:`Network error: ${c instanceof Error?c.message:String(c)}`},o}},async fetchTriggers(c){let u=new URL(`${e}/mcp/triggers`);c!==void 0&&u.searchParams.set("since",c.toString());try{let l=await s(u.toString(),{method:"GET",headers:{Accept:"application/json","Accept-Encoding":"gzip"}});if(!l.ok)throw w.warn("Failed to fetch triggers",{status:l.status,statusText:l.statusText}),new oo(`HTTP ${l.status}`,l.status);return await l.json()}catch(l){throw w.error("Trigger fetch error",{error:l instanceof Error?l.message:String(l)}),l}},async fetchDomains(c){let u=new URL(`${e}/mcp/domains`);c!==void 0&&u.searchParams.set("since",c.toString());try{let l=await s(u.toString(),{method:"GET",headers:{Accept:"application/json","Accept-Encoding":"gzip"}});if(!l.ok)throw w.warn("Failed to fetch domains",{status:l.status,statusText:l.statusText}),new oo(`HTTP ${l.status}`,l.status);return await l.json()}catch(l){throw w.error("Domain fetch error",{error:l instanceof Error?l.message:String(l)}),l}},isUserScoped(){return o?.isUserScoped??!1},getCurrentLexiconId(){return o?.lexiconId},getExpiresAt(){return o?.expiresAt},updateToken(c){n=c,w.debug("Token updated")},getAuthType(){return i}}}function AU(t){return new Promise(e=>setTimeout(e,t))}var vt=require("fs"),Kk=require("os"),Lv=require("path");var CU=".lexic",RU="credentials.json",hl=1;function Zv(){return(0,Lv.join)((0,Kk.homedir)(),CU)}function gl(){return(0,Lv.join)(Zv(),RU)}function NU(){let t=Zv();(0,vt.existsSync)(t)||((0,vt.mkdirSync)(t,{recursive:!0,mode:448}),w.debug("Created Lexic config directory",{path:t}))}function ao(){let t=gl();if(!(0,vt.existsSync)(t))return{version:hl,credentials:{}};try{let e=(0,vt.readFileSync)(t,"utf8"),r=JSON.parse(e);return r.version!==hl&&w.warn("Credentials file version mismatch, may need migration",{fileVersion:r.version,currentVersion:hl}),r}catch(e){return w.warn("Failed to load credentials file, starting fresh",{error:e instanceof Error?e.message:String(e)}),{version:hl,credentials:{}}}}function Fv(t){NU();let e=gl(),r=JSON.stringify(t,null,2);(0,vt.writeFileSync)(e,r,{encoding:"utf8",mode:384});try{(0,vt.chmodSync)(e,384)}catch{}w.debug("Saved credentials file",{path:e})}function Vv(t,e,r){let n=ao(),i=t.replace(/\/$/,""),o={access_token:e.access_token,refresh_token:e.refresh_token,token_type:e.token_type,supabase_url:i,stored_at:Math.floor(Date.now()/1e3),user_id:r?.user_id,email:r?.email};e.expires_in&&(o.expires_at=o.stored_at+e.expires_in),n.credentials[i]=o,n.default_project=i,Fv(n),w.info("Stored OAuth credentials",{supabaseUrl:i,expiresAt:o.expires_at?new Date(o.expires_at*1e3).toISOString():"unknown"})}function nr(t){let e=ao(),r=t?.replace(/\/$/,"")||e.default_project;if(!r){w.debug("No Supabase URL provided and no default project set");return}let n=e.credentials[r];if(!n){w.debug("No credentials found for project",{supabaseUrl:r});return}return n}function yn(t){let e=nr(t);if(!e)return!1;if(e.expires_at){let r=Math.floor(Date.now()/1e3),n=5*60,i=e.expires_at-n;if(w.debug("Checking credential validity",{expiresAt:e.expires_at,expiresAtDate:new Date(e.expires_at*1e3).toISOString(),now:r,nowDate:new Date(r*1e3).toISOString(),expiresWithBuffer:i,isExpired:i<r}),i<r)return w.debug("Credentials expired or expiring soon",{expiresAt:new Date(e.expires_at*1e3).toISOString()}),!1}return!0}function Kn(t){let e=nr(t);if(!e||!e.expires_at||!e.refresh_token)return!1;let r=Math.floor(Date.now()/1e3),n=5*60;return e.expires_at-n<r}function $s(t,e){let r=ao(),n=t.replace(/\/$/,""),i=r.credentials[n];if(!i){w.warn("Cannot update tokens - no existing credentials",{supabaseUrl:n});return}i.access_token=e.access_token,i.token_type=e.token_type,i.stored_at=Math.floor(Date.now()/1e3),e.refresh_token&&(i.refresh_token=e.refresh_token),e.expires_in&&(i.expires_at=i.stored_at+e.expires_in),r.credentials[n]=i,Fv(r),w.info("Updated OAuth tokens",{supabaseUrl:n,expiresAt:i.expires_at?new Date(i.expires_at*1e3).toISOString():"unknown"})}function Bv(t){let e=ao(),r=t.replace(/\/$/,"");if(e.credentials[r]){if(delete e.credentials[r],e.default_project===r){let n=Object.keys(e.credentials);e.default_project=n.length>0?n[0]:void 0}Fv(e),w.info("Removed credentials",{supabaseUrl:r})}}function Hv(){let t=gl();(0,vt.existsSync)(t)&&((0,vt.unlinkSync)(t),w.info("Cleared all stored credentials"))}function vl(){let t=ao();return Object.keys(t.credentials)}function yl(){return ao().default_project}var ey=require("http"),Qv=require("url"),tS=require("child_process"),rS=require("os");var ks=require("crypto");function Wk(){return(0,ks.randomBytes)(32).toString("base64url")}function Xk(t){return(0,ks.createHash)("sha256").update(t,"ascii").digest().toString("base64url")}function Jv(){let t=Wk(),e=Xk(t);return{codeVerifier:t,codeChallenge:e}}function Gv(){return(0,ks.randomBytes)(16).toString("base64url")}function Kv(){return`<!DOCTYPE html>
100
100
  <html lang="en">
101
101
  <head>
102
102
  <meta charset="UTF-8">
@@ -477,7 +477,7 @@ AVOID: searching for general knowledge (use knowledge_query); looking for decisi
477
477
 
478
478
  TRIGGERS: "mark task as done", "complete that task", "that's done now", "change task priority"
479
479
 
480
- AVOID: creating new tasks (use task_create); storing general notes (use knowledge_store)`,inputSchema:{type:"object",properties:{task_id:{type:"string",description:"The ID of the task to update"},status:{type:"string",enum:["open","in_progress","done","cancelled"],description:"New status for the task"},priority:{type:"string",enum:["low","medium","high","urgent"],description:"New priority level"},title:{type:"string",description:"Updated task title"},due_date:{type:["string","null"],description:"Updated due date in ISO 8601 format, or null to clear"},assignee:{type:["string","null"],description:"Updated assignee, or null to unassign"}},required:["task_id"]}}]}}}var _H=5*60*1e3,wH=1e4,cr=null;async function Nb(t){let e=Date.now();if(cr&&e-cr.fetchedAt<_H)return cr.data;try{let r=new Promise((i,o)=>{setTimeout(()=>o(new Error("Domain fetch timeout")),wH)}),n=await Promise.race([t.fetchDomains(cr?.version),r]);return n.unchanged&&cr?(w.debug("Domains unchanged, refreshing TTL"),cr.fetchedAt=e,cr.data):(w.info("Domains loaded",{count:Object.keys(n.domains).length,version:n.version}),cr={data:n.domains,fetchedAt:e,version:n.version},cr.data)}catch(r){return cr?(w.warn("API error, using cached domains",{error:r instanceof Error?r.message:String(r)}),cr.data):(w.warn("API error, using default domains",{error:r instanceof Error?r.message:String(r)}),LP())}}var qp=Ce(require("readline"),1),ZP="0.1.18";async function FP(t,e,r){let n=new Map,i=u=>{let l=e[u];return l?$l(l):void 0},o=aS(t,{description:i("knowledge_query")}),a=sS(t,{description:i("knowledge_store")}),s=cS(t,{description:i("knowledge_get_context")});if(n.set(o.name,o),n.set(a.name,a),n.set(s.name,s),w.debug("Registered core tools",{tools:[o.name,a.name,s.name]}),t.isUserScoped()){let u=uS(t,{description:i("lexic_create_project")}),l=lS(t,{description:i("lexic_list_projects")}),p=pS(t,{description:i("lexic_get_project_info")});n.set(u.name,u),n.set(l.name,l),n.set(p.name,p),w.debug("Registered admin tools",{tools:[u.name,l.name,p.name]})}else w.debug("Skipping admin tools (PAT is lexicon-scoped)");let c=ny(r,e,t);for(let u of c)n.set(u.name,u);return w.debug("Registered domain tools",{count:c.length,tools:c.map(u=>u.name)}),n}async function $H(){let t=process.env.LOG_LEVEL||"info";w.setLevel(t),w.info("Starting Lexic MCP Server (stdio transport)");let e,r=process.env.LEXIC_API_URL||"https://app.lexic.io/api",n=yl(),i=n?yn(n):!1,o=n?Kn(n):!1,a=n&&(i||o);if(w.debug("OAuth credential check",{defaultProject:n,hasValidCredentials:i,hasExpiredCredentials:o,hasOAuth:a}),a&&n){w.info("Using OAuth authentication");let f=await Yv();f||(w.error("Failed to discover auth config for OAuth"),process.exit(1)),w.debug("Auth config discovered",{supabaseUrl:f.supabaseUrl,matchesDefaultProject:f.supabaseUrl===n});let m=await ry({supabaseUrl:n,supabaseAnonKey:f.supabaseAnonKey});f.supabaseUrl!==n&&w.warn("Supabase URL mismatch between discovery and stored credentials",{discoveredUrl:f.supabaseUrl,storedUrl:n}),w.debug("Token retrieval result",{hasToken:!!m,tokenLength:m?.length}),m||(w.error("Failed to get valid OAuth token. Please run: lexic-mcp login"),process.exit(1));let h=ml({apiUrl:r,auth:{type:"oauth",token:m}});e=oS(h,{supabaseUrl:n,supabaseAnonKey:f.supabaseAnonKey});let g=nr(n);g?.email&&w.info("Authenticated as",{email:g.email}),w.info("Connected to Lexic (OAuth mode with auto-refresh)")}else if(process.env.LEXIC_PAT){w.info("Using PAT authentication");let f=Hk();e=Gk(f);let m=await e.validateConnection();if(m.valid||(w.error("Failed to connect to Lexic",{error:m.error}),process.exit(1)),m.expiresAt){let h=new Date,g=Math.ceil((m.expiresAt.getTime()-h.getTime())/(1e3*60*60*24)),x=m.expiresAt.toISOString(),_=g===1?"day":"days";switch(!0){case g<=0:w.error("PAT has expired",{expiresAt:x});break;case g<=3:w.warn(`PAT expires in ${g} ${_}`,{expiresAt:x});break;case g<=7:w.info(`PAT expires in ${g} ${_}`,{expiresAt:x});break}}}else w.error("No authentication found. Please run: lexic-mcp login"),w.error("Or set LEXIC_PAT environment variable"),process.exit(1);let s=await e.validateConnection();s.valid||(w.error("Failed to connect to Lexic",{error:s.error}),process.exit(1)),w.info("Connected to Lexic",{lexiconId:s.lexiconId,isUserScoped:s.isUserScoped});let{domains:c,triggers:u}=await VP(e),l=await FP(e,u,c),p=new io({name:"lexic-mcp",version:ZP},{capabilities:{tools:{}}});p.setRequestHandler(Ba,async()=>({tools:Array.from(l.values()).map(f=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))})),p.setRequestHandler(Un,async f=>{let{name:m,arguments:h}=f.params,g=l.get(m);if(!g)return{content:[{type:"text",text:`Unknown tool: ${m}`}],isError:!0};try{w.debug("Executing tool",{name:m,args:h});let x=await g.handler(h||{});return w.debug("Tool executed successfully",{name:m}),{content:[{type:"text",text:typeof x=="string"?x:JSON.stringify(x,null,2)}]}}catch(x){let _=x instanceof Error?x.message:String(x);return w.error("Tool execution failed",{name:m,error:_}),{content:[{type:"text",text:`Error: ${_}`}],isError:!0}}});let d=new dl;await p.connect(d),w.info("Lexic MCP Server running (stdio)",{toolCount:l.size,tools:Array.from(l.keys())})}async function kH(){let t=Rv();if(!Nv(t))throw new Error("OAuth configuration required for HTTP transport");w.setLevel(t.logLevel),w.info("Starting Lexic MCP Server (HTTP transport with OAuth)");let e=ml({apiUrl:t.apiUrl,auth:{type:"oauth",token:t.oauthConfig.supabaseAnonKey}}),r={},n={};try{let a=await VP(e);r=a.domains,n=a.triggers}catch(a){w.warn("Could not load configuration during bootstrap, will use defaults",{error:a instanceof Error?a.message:String(a)})}let i=await FP(e,n,r),o=UP({oauthConfig:t.oauthConfig,tools:i,serverName:"lexic-mcp",serverVersion:"0.1.0"});process.on("SIGTERM",async()=>{w.info("Received SIGTERM, shutting down..."),await o.stop(),process.exit(0)}),process.on("SIGINT",async()=>{w.info("Received SIGINT, shutting down..."),await o.stop(),process.exit(0)}),await o.start(),w.info("Lexic MCP Server running (HTTP with OAuth)",{toolCount:i.size,tools:Array.from(i.keys()),port:t.oauthConfig.httpPort})}async function VP(t){w.info("Loading domains and triggers...");let e={},r={},n=!1;try{[e,r]=await Promise.all([Nb(t),MP(t)]),w.info("Loaded configuration",{domains:Object.keys(e).length,triggers:Object.keys(r).length})}catch(i){n=!0,w.warn("Failed to load dynamic configuration, starting in degraded mode",{error:i instanceof Error?i.message:String(i)});try{e=await Nb(t),w.info("Loaded domains only (triggers unavailable)",{domains:Object.keys(e).length})}catch(o){w.error("Failed to load domains - will use defaults",{error:o instanceof Error?o.message:String(o)})}}return n&&w.warn("Running in DEGRADED MODE - tool descriptions may be less helpful"),{domains:e,triggers:r}}var di=[{value:"google",label:"Google"},{value:"github",label:"GitHub"},{value:"azure",label:"Microsoft (Azure AD)"}];async function SH(){return new Promise(t=>{let e=0,r=qp.createInterface({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),qp.emitKeypressEvents(process.stdin);let n=()=>{e>=0&&(process.stdout.write(`\x1B[${di.length+1}A`),process.stdout.write("\x1B[0J")),console.log("Select an OAuth provider:"),di.forEach((a,s)=>{let c=s===e?"> ":" ",u=s===e?"\x1B[36m":"",l=s===e?"\x1B[0m":"";console.log(`${c}${u}${a.label}${l}`)})};console.log("Select an OAuth provider:"),di.forEach((a,s)=>{let c=s===e?"> ":" ",u=s===e?"\x1B[36m":"",l=s===e?"\x1B[0m":"";console.log(`${c}${u}${a.label}${l}`)});let i=()=>{process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("keypress",o),r.close()},o=(a,s)=>{s.name==="up"?(e=(e-1+di.length)%di.length,n()):s.name==="down"?(e=(e+1)%di.length,n()):s.name==="return"?(i(),console.log(""),t(di[e].value)):(s.name==="escape"||s.ctrl&&s.name==="c")&&(i(),console.log(`
480
+ AVOID: creating new tasks (use task_create); storing general notes (use knowledge_store)`,inputSchema:{type:"object",properties:{task_id:{type:"string",description:"The ID of the task to update"},status:{type:"string",enum:["open","in_progress","done","cancelled"],description:"New status for the task"},priority:{type:"string",enum:["low","medium","high","urgent"],description:"New priority level"},title:{type:"string",description:"Updated task title"},due_date:{type:["string","null"],description:"Updated due date in ISO 8601 format, or null to clear"},assignee:{type:["string","null"],description:"Updated assignee, or null to unassign"}},required:["task_id"]}}]}}}var _H=5*60*1e3,wH=1e4,cr=null;async function Nb(t){let e=Date.now();if(cr&&e-cr.fetchedAt<_H)return cr.data;try{let r=new Promise((i,o)=>{setTimeout(()=>o(new Error("Domain fetch timeout")),wH)}),n=await Promise.race([t.fetchDomains(cr?.version),r]);return n.unchanged&&cr?(w.debug("Domains unchanged, refreshing TTL"),cr.fetchedAt=e,cr.data):(w.info("Domains loaded",{count:Object.keys(n.domains).length,version:n.version}),cr={data:n.domains,fetchedAt:e,version:n.version},cr.data)}catch(r){return cr?(w.warn("API error, using cached domains",{error:r instanceof Error?r.message:String(r)}),cr.data):(w.warn("API error, using default domains",{error:r instanceof Error?r.message:String(r)}),LP())}}var qp=Ce(require("readline"),1),ZP="0.1.19";async function FP(t,e,r){let n=new Map,i=u=>{let l=e[u];return l?$l(l):void 0},o=aS(t,{description:i("knowledge_query")}),a=sS(t,{description:i("knowledge_store")}),s=cS(t,{description:i("knowledge_get_context")});if(n.set(o.name,o),n.set(a.name,a),n.set(s.name,s),w.debug("Registered core tools",{tools:[o.name,a.name,s.name]}),t.isUserScoped()){let u=uS(t,{description:i("lexic_create_project")}),l=lS(t,{description:i("lexic_list_projects")}),p=pS(t,{description:i("lexic_get_project_info")});n.set(u.name,u),n.set(l.name,l),n.set(p.name,p),w.debug("Registered admin tools",{tools:[u.name,l.name,p.name]})}else w.debug("Skipping admin tools (PAT is lexicon-scoped)");let c=ny(r,e,t);for(let u of c)n.set(u.name,u);return w.debug("Registered domain tools",{count:c.length,tools:c.map(u=>u.name)}),n}async function $H(){let t=process.env.LOG_LEVEL||"info";w.setLevel(t),w.info("Starting Lexic MCP Server (stdio transport)");let e,r=process.env.LEXIC_API_URL||"https://app.lexic.io/api",n=yl(),i=n?yn(n):!1,o=n?Kn(n):!1,a=n&&(i||o);if(w.debug("OAuth credential check",{defaultProject:n,hasValidCredentials:i,hasExpiredCredentials:o,hasOAuth:a}),a&&n){w.info("Using OAuth authentication");let f=await Yv();f||(w.error("Failed to discover auth config for OAuth"),process.exit(1)),w.debug("Auth config discovered",{supabaseUrl:f.supabaseUrl,matchesDefaultProject:f.supabaseUrl===n});let m=await ry({supabaseUrl:n,supabaseAnonKey:f.supabaseAnonKey});f.supabaseUrl!==n&&w.warn("Supabase URL mismatch between discovery and stored credentials",{discoveredUrl:f.supabaseUrl,storedUrl:n}),w.debug("Token retrieval result",{hasToken:!!m,tokenLength:m?.length}),m||(w.error("Failed to get valid OAuth token. Please run: lexic-mcp login"),process.exit(1));let h=ml({apiUrl:r,auth:{type:"oauth",token:m}});e=oS(h,{supabaseUrl:n,supabaseAnonKey:f.supabaseAnonKey});let g=nr(n);g?.email&&w.info("Authenticated as",{email:g.email}),w.info("Connected to Lexic (OAuth mode with auto-refresh)")}else if(process.env.LEXIC_PAT){w.info("Using PAT authentication");let f=Hk();e=Gk(f);let m=await e.validateConnection();if(m.valid||(w.error("Failed to connect to Lexic",{error:m.error}),process.exit(1)),m.expiresAt){let h=new Date,g=Math.ceil((m.expiresAt.getTime()-h.getTime())/(1e3*60*60*24)),x=m.expiresAt.toISOString(),_=g===1?"day":"days";switch(!0){case g<=0:w.error("PAT has expired",{expiresAt:x});break;case g<=3:w.warn(`PAT expires in ${g} ${_}`,{expiresAt:x});break;case g<=7:w.info(`PAT expires in ${g} ${_}`,{expiresAt:x});break}}}else w.error("No authentication found. Please run: lexic-mcp login"),w.error("Or set LEXIC_PAT environment variable"),process.exit(1);let s=await e.validateConnection();s.valid||(w.error("Failed to connect to Lexic",{error:s.error}),process.exit(1)),w.info("Connected to Lexic",{lexiconId:s.lexiconId,isUserScoped:s.isUserScoped});let{domains:c,triggers:u}=await VP(e),l=await FP(e,u,c),p=new io({name:"lexic-mcp",version:ZP},{capabilities:{tools:{}}});p.setRequestHandler(Ba,async()=>({tools:Array.from(l.values()).map(f=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))})),p.setRequestHandler(Un,async f=>{let{name:m,arguments:h}=f.params,g=l.get(m);if(!g)return{content:[{type:"text",text:`Unknown tool: ${m}`}],isError:!0};try{w.debug("Executing tool",{name:m,args:h});let x=await g.handler(h||{});return w.debug("Tool executed successfully",{name:m}),{content:[{type:"text",text:typeof x=="string"?x:JSON.stringify(x,null,2)}]}}catch(x){let _=x instanceof Error?x.message:String(x);return w.error("Tool execution failed",{name:m,error:_}),{content:[{type:"text",text:`Error: ${_}`}],isError:!0}}});let d=new dl;await p.connect(d),w.info("Lexic MCP Server running (stdio)",{toolCount:l.size,tools:Array.from(l.keys())})}async function kH(){let t=Rv();if(!Nv(t))throw new Error("OAuth configuration required for HTTP transport");w.setLevel(t.logLevel),w.info("Starting Lexic MCP Server (HTTP transport with OAuth)");let e=ml({apiUrl:t.apiUrl,auth:{type:"oauth",token:t.oauthConfig.supabaseAnonKey}}),r={},n={};try{let a=await VP(e);r=a.domains,n=a.triggers}catch(a){w.warn("Could not load configuration during bootstrap, will use defaults",{error:a instanceof Error?a.message:String(a)})}let i=await FP(e,n,r),o=UP({oauthConfig:t.oauthConfig,tools:i,serverName:"lexic-mcp",serverVersion:"0.1.0"});process.on("SIGTERM",async()=>{w.info("Received SIGTERM, shutting down..."),await o.stop(),process.exit(0)}),process.on("SIGINT",async()=>{w.info("Received SIGINT, shutting down..."),await o.stop(),process.exit(0)}),await o.start(),w.info("Lexic MCP Server running (HTTP with OAuth)",{toolCount:i.size,tools:Array.from(i.keys()),port:t.oauthConfig.httpPort})}async function VP(t){w.info("Loading domains and triggers...");let e={},r={},n=!1;try{[e,r]=await Promise.all([Nb(t),MP(t)]),w.info("Loaded configuration",{domains:Object.keys(e).length,triggers:Object.keys(r).length})}catch(i){n=!0,w.warn("Failed to load dynamic configuration, starting in degraded mode",{error:i instanceof Error?i.message:String(i)});try{e=await Nb(t),w.info("Loaded domains only (triggers unavailable)",{domains:Object.keys(e).length})}catch(o){w.error("Failed to load domains - will use defaults",{error:o instanceof Error?o.message:String(o)})}}return n&&w.warn("Running in DEGRADED MODE - tool descriptions may be less helpful"),{domains:e,triggers:r}}var di=[{value:"google",label:"Google"},{value:"github",label:"GitHub"},{value:"azure",label:"Microsoft (Azure AD)"}];async function SH(){return new Promise(t=>{let e=0,r=qp.createInterface({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),qp.emitKeypressEvents(process.stdin);let n=()=>{e>=0&&(process.stdout.write(`\x1B[${di.length+1}A`),process.stdout.write("\x1B[0J")),console.log("Select an OAuth provider:"),di.forEach((a,s)=>{let c=s===e?"> ":" ",u=s===e?"\x1B[36m":"",l=s===e?"\x1B[0m":"";console.log(`${c}${u}${a.label}${l}`)})};console.log("Select an OAuth provider:"),di.forEach((a,s)=>{let c=s===e?"> ":" ",u=s===e?"\x1B[36m":"",l=s===e?"\x1B[0m":"";console.log(`${c}${u}${a.label}${l}`)});let i=()=>{process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("keypress",o),r.close()},o=(a,s)=>{s.name==="up"?(e=(e-1+di.length)%di.length,n()):s.name==="down"?(e=(e+1)%di.length,n()):s.name==="return"?(i(),console.log(""),t(di[e].value)):(s.name==="escape"||s.ctrl&&s.name==="c")&&(i(),console.log(`
481
481
  Login cancelled.`),process.exit(0))};process.stdin.on("keypress",o)})}function EH(t){let e=t.toLowerCase();if(e==="google"||e==="github"||e==="azure")return e}function zH(){console.log(`
482
482
  Lexic MCP Server - Knowledge management for AI-assisted development
483
483
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lexic-mcp",
3
- "version": "0.1.18",
3
+ "version": "0.1.19",
4
4
  "description": "MCP server connecting Claude Code to Lexic knowledge management",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",