@whoz-oss/coday-server 0.104.7 → 0.105.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server.js +2 -2
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -1137,7 +1137,7 @@ Summary:
|
|
|
1137
1137
|
|
|
1138
1138
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of r.seen.entries()){let s=o[1];if(e===o[0]){a(o);continue}if(r.external){let u=r.external.registry.get(o[0])?.id;if(e!==o[0]&&u){a(o);continue}}if(r.metadataRegistry.get(o[0])?.id){a(o);continue}if(s.cycle){a(o);continue}if(s.count>1&&r.reused==="ref"){a(o);continue}}}function Pk(r,e){let t=r.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=o=>{let s=r.seen.get(o);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.ref=null,l){n(l);let p=r.seen.get(l),d=p.schema;if(d.$ref&&(r.target==="draft-07"||r.target==="draft-04"||r.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(d)):Object.assign(c,d),Object.assign(c,u),o._zod.parent===l)for(let h in c)h==="$ref"||h==="allOf"||h in u||delete c[h];if(d.$ref&&p.def)for(let h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}let f=o._zod.parent;if(f&&f!==l){n(f);let p=r.seen.get(f);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let d in c)d==="$ref"||d==="allOf"||d in p.def&&JSON.stringify(c[d])===JSON.stringify(p.def[d])&&delete c[d]}r.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(let o of[...r.seen.entries()].reverse())n(o[0]);let i={};if(r.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":r.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":r.target,r.external?.uri){let o=r.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=r.external.uri(o)}Object.assign(i,t.def??t.schema);let a=r.external?.defs??{};for(let o of r.seen.entries()){let s=o[1];s.def&&s.defId&&(a[s.defId]=s.def)}r.external||Object.keys(a).length>0&&(r.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:Jg(e,"input",r.processors),output:Jg(e,"output",r.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ka(r,e){let t=e??{seen:new Set};if(t.seen.has(r))return!1;t.seen.add(r);let n=r._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ka(n.element,t);if(n.type==="set")return ka(n.valueType,t);if(n.type==="lazy")return ka(n.getter(),t);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ka(n.innerType,t);if(n.type==="intersection")return ka(n.left,t)||ka(n.right,t);if(n.type==="record"||n.type==="map")return ka(n.keyType,t)||ka(n.valueType,t);if(n.type==="pipe")return ka(n.in,t)||ka(n.out,t);if(n.type==="object"){for(let i in n.shape)if(ka(n.shape[i],t))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(ka(i,t))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(ka(i,t))return!0;return!!(n.rest&&ka(n.rest,t))}return!1}var Ade=(r,e={})=>t=>{let n=Ck({...t,processors:e});return Xr(r,n),Tk(n,r),Pk(n,r)},Jg=(r,e,t={})=>n=>{let{libraryOptions:i,target:a}=n??{},o=Ck({...i??{},target:a,io:e,processors:t});return Xr(r,o),Tk(o,r),Pk(o,r)};var gut={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Cde=(r,e,t,n)=>{let i=t;i.type="string";let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:u}=r._zod.bag;if(typeof a=="number"&&(i.minLength=a),typeof o=="number"&&(i.maxLength=o),s&&(i.format=gut[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(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},Tde=(r,e,t,n)=>{let i=t,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=r._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 a=="number"&&(i.minimum=a,typeof l=="number"&&e.target!=="draft-04"&&(l>=a?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 o=="number"&&(i.maximum=o,typeof u=="number"&&e.target!=="draft-04"&&(u<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},Pde=(r,e,t,n)=>{t.type="boolean"},Dde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Ide=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Ode=(r,e,t,n)=>{e.target==="openapi-3.0"?(t.type="string",t.nullable=!0,t.enum=[null]):t.type="null"},$de=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},jde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Rde=(r,e,t,n)=>{t.not={}},Nde=(r,e,t,n)=>{},Fde=(r,e,t,n)=>{},Mde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Lde=(r,e,t,n)=>{let i=r._zod.def,a=vg(i.entries);a.every(o=>typeof o=="number")&&(t.type="number"),a.every(o=>typeof o=="string")&&(t.type="string"),t.enum=a},qde=(r,e,t,n)=>{let i=r._zod.def,a=[];for(let o of i.values)if(o===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(o))}else a.push(o);if(a.length!==0)if(a.length===1){let o=a[0];t.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?t.enum=[o]:t.const=o}else a.every(o=>typeof o=="number")&&(t.type="number"),a.every(o=>typeof o=="string")&&(t.type="string"),a.every(o=>typeof o=="boolean")&&(t.type="boolean"),a.every(o=>o===null)&&(t.type="null"),t.enum=a},Ude=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},zde=(r,e,t,n)=>{let i=t,a=r._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},Bde=(r,e,t,n)=>{let i=t,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:c}=r._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,a)},Hde=(r,e,t,n)=>{t.type="boolean"},Wde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Vde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Gde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Zde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Jde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Kde=(r,e,t,n)=>{let i=t,a=r._zod.def,{minimum:o,maximum:s}=r._zod.bag;typeof o=="number"&&(i.minItems=o),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=Xr(a.element,e,{...n,path:[...n.path,"items"]})},Yde=(r,e,t,n)=>{let i=t,a=r._zod.def;i.type="object",i.properties={};let o=a.shape;for(let u in o)i.properties[u]=Xr(o[u],e,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(u=>{let l=a.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Xr(a.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},xU=(r,e,t,n)=>{let i=r._zod.def,a=i.inclusive===!1,o=i.options.map((s,c)=>Xr(s,e,{...n,path:[...n.path,a?"oneOf":"anyOf",c]}));a?t.oneOf=o:t.anyOf=o},Xde=(r,e,t,n)=>{let i=r._zod.def,a=Xr(i.left,e,{...n,path:[...n.path,"allOf",0]}),o=Xr(i.right,e,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];t.allOf=c},Qde=(r,e,t,n)=>{let i=t,a=r._zod.def;i.type="array";let o=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((p,d)=>Xr(p,e,{...n,path:[...n.path,o,d]})),u=a.rest?Xr(a.rest,e,{...n,path:[...n.path,s,...e.target==="openapi-3.0"?[a.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:f}=r._zod.bag;typeof l=="number"&&(i.minItems=l),typeof f=="number"&&(i.maxItems=f)},e3e=(r,e,t,n)=>{let i=t,a=r._zod.def;i.type="object";let o=a.keyType,c=o._zod.bag?.patterns;if(a.mode==="loose"&&c&&c.size>0){let l=Xr(a.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let f of c)i.patternProperties[f.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=Xr(a.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Xr(a.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=o._zod.values;if(u){let l=[...u].filter(f=>typeof f=="string"||typeof f=="number");l.length>0&&(i.required=l)}},t3e=(r,e,t,n)=>{let i=r._zod.def,a=Xr(i.innerType,e,n),o=e.seen.get(r);e.target==="openapi-3.0"?(o.ref=i.innerType,t.nullable=!0):t.anyOf=[a,{type:"null"}]},r3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType},n3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType,t.default=JSON.parse(JSON.stringify(i.defaultValue))},i3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType,e.io==="input"&&(t._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},a3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=o},o3e=(r,e,t,n)=>{let i=r._zod.def,a=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Xr(a,e,n);let o=e.seen.get(r);o.ref=a},s3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType,t.readOnly=!0},c3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType},wU=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType},u3e=(r,e,t,n)=>{let i=r._zod.innerType;Xr(i,e,n);let a=e.seen.get(r);a.ref=i};function Km(r){return!!r._zod}function sd(r,e){return Km(r)?Wm(r,e):r.safeParse(e)}function Dk(r){var e,t;if(!r)return;let n;if(Km(r)?n=(t=(e=r._zod)===null||e===void 0?void 0:e.def)===null||t===void 0?void 0:t.shape:n=r.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function p3e(r){var e;if(Km(r)){let o=(e=r._zod)===null||e===void 0?void 0:e.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 n=r._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=r.value;if(i!==void 0)return i}var Yg={};Df(Yg,{ZodAny:()=>I3e,ZodArray:()=>R3e,ZodBase64:()=>WU,ZodBase64URL:()=>VU,ZodBigInt:()=>Lk,ZodBigIntFormat:()=>JU,ZodBoolean:()=>Mk,ZodCIDRv4:()=>BU,ZodCIDRv6:()=>HU,ZodCUID:()=>NU,ZodCUID2:()=>FU,ZodCatch:()=>t0e,ZodCodec:()=>nz,ZodCustom:()=>Bk,ZodCustomStringFormat:()=>Qg,ZodDate:()=>YU,ZodDefault:()=>J3e,ZodDiscriminatedUnion:()=>F3e,ZodE164:()=>GU,ZodEmail:()=>$U,ZodEmoji:()=>jU,ZodEnum:()=>Xg,ZodExactOptional:()=>V3e,ZodFile:()=>H3e,ZodFunction:()=>l0e,ZodGUID:()=>Ok,ZodIPv4:()=>UU,ZodIPv6:()=>zU,ZodIntersection:()=>M3e,ZodJWT:()=>ZU,ZodKSUID:()=>qU,ZodLazy:()=>s0e,ZodLiteral:()=>B3e,ZodMAC:()=>A3e,ZodMap:()=>U3e,ZodNaN:()=>n0e,ZodNanoID:()=>RU,ZodNever:()=>$3e,ZodNonOptional:()=>tz,ZodNull:()=>P3e,ZodNullable:()=>Z3e,ZodNumber:()=>Fk,ZodNumberFormat:()=>Ym,ZodObject:()=>qk,ZodOptional:()=>ez,ZodPipe:()=>rz,ZodPrefault:()=>Y3e,ZodPromise:()=>u0e,ZodReadonly:()=>i0e,ZodRecord:()=>zk,ZodSet:()=>z3e,ZodString:()=>Rk,ZodStringFormat:()=>Gr,ZodSuccess:()=>e0e,ZodSymbol:()=>C3e,ZodTemplateLiteral:()=>o0e,ZodTransform:()=>W3e,ZodTuple:()=>L3e,ZodType:()=>Bt,ZodULID:()=>MU,ZodURL:()=>Nk,ZodUUID:()=>nl,ZodUndefined:()=>T3e,ZodUnion:()=>Uk,ZodUnknown:()=>O3e,ZodVoid:()=>j3e,ZodXID:()=>LU,ZodXor:()=>N3e,_ZodString:()=>OU,_default:()=>K3e,_function:()=>Olt,any:()=>hlt,array:()=>or,base64:()=>Yut,base64url:()=>Xut,bigint:()=>ult,boolean:()=>si,catch:()=>r0e,check:()=>$lt,cidrv4:()=>Jut,cidrv6:()=>Kut,codec:()=>Plt,cuid:()=>Uut,cuid2:()=>zut,custom:()=>iz,date:()=>glt,describe:()=>jlt,discriminatedUnion:()=>XU,e164:()=>Qut,email:()=>Iut,emoji:()=>Lut,enum:()=>Za,exactOptional:()=>G3e,file:()=>klt,float32:()=>alt,float64:()=>olt,function:()=>Olt,guid:()=>Out,hash:()=>ilt,hex:()=>nlt,hostname:()=>rlt,httpUrl:()=>Mut,instanceof:()=>Nlt,int:()=>IU,int32:()=>slt,int64:()=>llt,intersection:()=>e8,ipv4:()=>Vut,ipv6:()=>Zut,json:()=>Mlt,jwt:()=>elt,keyof:()=>vlt,ksuid:()=>Wut,lazy:()=>c0e,literal:()=>ct,looseObject:()=>Bc,looseRecord:()=>wlt,mac:()=>Gut,map:()=>_lt,meta:()=>Rlt,nan:()=>Tlt,nanoid:()=>qut,nativeEnum:()=>Elt,never:()=>KU,nonoptional:()=>Q3e,null:()=>D3e,nullable:()=>$k,nullish:()=>Alt,number:()=>pn,object:()=>Je,optional:()=>zt,partialRecord:()=>xlt,pipe:()=>jk,prefault:()=>X3e,preprocess:()=>az,promise:()=>Ilt,readonly:()=>a0e,record:()=>dn,refine:()=>f0e,set:()=>Slt,strictObject:()=>ylt,string:()=>xe,stringFormat:()=>tlt,stringbool:()=>Flt,success:()=>Clt,superRefine:()=>p0e,symbol:()=>plt,templateLiteral:()=>Dlt,transform:()=>QU,tuple:()=>q3e,uint32:()=>clt,uint64:()=>flt,ulid:()=>But,undefined:()=>dlt,union:()=>an,unknown:()=>nn,url:()=>Fut,uuid:()=>$ut,uuidv4:()=>jut,uuidv6:()=>Rut,uuidv7:()=>Nut,void:()=>mlt,xid:()=>Hut,xor:()=>blt});var Ik={};Df(Ik,{endsWith:()=>Bg,gt:()=>tl,gte:()=>Ea,includes:()=>Ug,length:()=>Zm,lowercase:()=>Lg,lt:()=>el,lte:()=>Do,maxLength:()=>Gm,maxSize:()=>od,mime:()=>Hg,minLength:()=>ef,minSize:()=>rl,multipleOf:()=>ad,negative:()=>uU,nonnegative:()=>fU,nonpositive:()=>lU,normalize:()=>Wg,overwrite:()=>zc,positive:()=>cU,property:()=>pU,regex:()=>Mg,size:()=>Vm,slugify:()=>Ak,startsWith:()=>zg,toLowerCase:()=>Gg,toUpperCase:()=>Zg,trim:()=>Vg,uppercase:()=>qg});var Kg={};Df(Kg,{ZodISODate:()=>kU,ZodISODateTime:()=>SU,ZodISODuration:()=>PU,ZodISOTime:()=>CU,date:()=>AU,datetime:()=>EU,duration:()=>DU,time:()=>TU});var SU=ie("ZodISODateTime",(r,e)=>{FL.init(r,e),Gr.init(r,e)});function EU(r){return Lq(SU,r)}var kU=ie("ZodISODate",(r,e)=>{ML.init(r,e),Gr.init(r,e)});function AU(r){return qq(kU,r)}var CU=ie("ZodISOTime",(r,e)=>{LL.init(r,e),Gr.init(r,e)});function TU(r){return Uq(CU,r)}var PU=ie("ZodISODuration",(r,e)=>{qL.init(r,e),Gr.init(r,e)});function DU(r){return zq(PU,r)}var d3e=(r,e)=>{WE.init(r,e),r.name="ZodError",Object.defineProperties(r,{format:{value:t=>GE(r,t)},flatten:{value:t=>VE(r,t)},addIssue:{value:t=>{r.issues.push(t),r.message=JSON.stringify(r.issues,zm,2)}},addIssues:{value:t=>{r.issues.push(...t),r.message=JSON.stringify(r.issues,zm,2)}},isEmpty:{get(){return r.issues.length===0}}})},Rrr=ie("ZodError",d3e),Io=ie("ZodError",d3e,{Parent:Error});var h3e=Sg(Io),m3e=kg(Io),g3e=Cg(Io),v3e=Tg(Io),y3e=Cpe(Io),b3e=Tpe(Io),x3e=Ppe(Io),w3e=Dpe(Io),_3e=Ipe(Io),S3e=Ope(Io),E3e=$pe(Io),k3e=jpe(Io);var Bt=ie("ZodType",(r,e)=>(It.init(r,e),Object.assign(r["~standard"],{jsonSchema:{input:Jg(r,"input"),output:Jg(r,"output")}}),r.toJSONSchema=Ade(r,{}),r.def=e,r.type=e.type,Object.defineProperty(r,"_def",{value:e}),r.check=(...t)=>r.clone(Te.mergeDefs(e,{checks:[...e.checks??[],...t.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),r.with=r.check,r.clone=(t,n)=>_a(r,t,n),r.brand=()=>r,r.register=((t,n)=>(t.add(r,n),r)),r.parse=(t,n)=>h3e(r,t,n,{callee:r.parse}),r.safeParse=(t,n)=>g3e(r,t,n),r.parseAsync=async(t,n)=>m3e(r,t,n,{callee:r.parseAsync}),r.safeParseAsync=async(t,n)=>v3e(r,t,n),r.spa=r.safeParseAsync,r.encode=(t,n)=>y3e(r,t,n),r.decode=(t,n)=>b3e(r,t,n),r.encodeAsync=async(t,n)=>x3e(r,t,n),r.decodeAsync=async(t,n)=>w3e(r,t,n),r.safeEncode=(t,n)=>_3e(r,t,n),r.safeDecode=(t,n)=>S3e(r,t,n),r.safeEncodeAsync=async(t,n)=>E3e(r,t,n),r.safeDecodeAsync=async(t,n)=>k3e(r,t,n),r.refine=(t,n)=>r.check(f0e(t,n)),r.superRefine=t=>r.check(p0e(t)),r.overwrite=t=>r.check(zc(t)),r.optional=()=>zt(r),r.exactOptional=()=>G3e(r),r.nullable=()=>$k(r),r.nullish=()=>zt($k(r)),r.nonoptional=t=>Q3e(r,t),r.array=()=>or(r),r.or=t=>an([r,t]),r.and=t=>e8(r,t),r.transform=t=>jk(r,QU(t)),r.default=t=>K3e(r,t),r.prefault=t=>X3e(r,t),r.catch=t=>r0e(r,t),r.pipe=t=>jk(r,t),r.readonly=()=>a0e(r),r.describe=t=>{let n=r.clone();return Sa.add(n,{description:t}),n},Object.defineProperty(r,"description",{get(){return Sa.get(r)?.description},configurable:!0}),r.meta=(...t)=>{if(t.length===0)return Sa.get(r);let n=r.clone();return Sa.add(n,t[0]),n},r.isOptional=()=>r.safeParse(void 0).success,r.isNullable=()=>r.safeParse(null).success,r.apply=t=>t(r),r)),OU=ie("_ZodString",(r,e)=>{id.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Cde(r,n,i,a);let t=r._zod.bag;r.format=t.format??null,r.minLength=t.minimum??null,r.maxLength=t.maximum??null,r.regex=(...n)=>r.check(Mg(...n)),r.includes=(...n)=>r.check(Ug(...n)),r.startsWith=(...n)=>r.check(zg(...n)),r.endsWith=(...n)=>r.check(Bg(...n)),r.min=(...n)=>r.check(ef(...n)),r.max=(...n)=>r.check(Gm(...n)),r.length=(...n)=>r.check(Zm(...n)),r.nonempty=(...n)=>r.check(ef(1,...n)),r.lowercase=n=>r.check(Lg(n)),r.uppercase=n=>r.check(qg(n)),r.trim=()=>r.check(Vg()),r.normalize=(...n)=>r.check(Wg(...n)),r.toLowerCase=()=>r.check(Gg()),r.toUpperCase=()=>r.check(Zg()),r.slugify=()=>r.check(Ak())}),Rk=ie("ZodString",(r,e)=>{id.init(r,e),OU.init(r,e),r.email=t=>r.check(ok($U,t)),r.url=t=>r.check(Fg(Nk,t)),r.jwt=t=>r.check(kk(ZU,t)),r.emoji=t=>r.check(fk(jU,t)),r.guid=t=>r.check(Ng(Ok,t)),r.uuid=t=>r.check(sk(nl,t)),r.uuidv4=t=>r.check(ck(nl,t)),r.uuidv6=t=>r.check(uk(nl,t)),r.uuidv7=t=>r.check(lk(nl,t)),r.nanoid=t=>r.check(pk(RU,t)),r.guid=t=>r.check(Ng(Ok,t)),r.cuid=t=>r.check(dk(NU,t)),r.cuid2=t=>r.check(hk(FU,t)),r.ulid=t=>r.check(mk(MU,t)),r.base64=t=>r.check(_k(WU,t)),r.base64url=t=>r.check(Sk(VU,t)),r.xid=t=>r.check(gk(LU,t)),r.ksuid=t=>r.check(vk(qU,t)),r.ipv4=t=>r.check(yk(UU,t)),r.ipv6=t=>r.check(bk(zU,t)),r.cidrv4=t=>r.check(xk(BU,t)),r.cidrv6=t=>r.check(wk(HU,t)),r.e164=t=>r.check(Ek(GU,t)),r.datetime=t=>r.check(EU(t)),r.date=t=>r.check(AU(t)),r.time=t=>r.check(TU(t)),r.duration=t=>r.check(DU(t))});function xe(r){return Fq(Rk,r)}var Gr=ie("ZodStringFormat",(r,e)=>{zr.init(r,e),OU.init(r,e)}),$U=ie("ZodEmail",(r,e)=>{TL.init(r,e),Gr.init(r,e)});function Iut(r){return ok($U,r)}var Ok=ie("ZodGUID",(r,e)=>{AL.init(r,e),Gr.init(r,e)});function Out(r){return Ng(Ok,r)}var nl=ie("ZodUUID",(r,e)=>{CL.init(r,e),Gr.init(r,e)});function $ut(r){return sk(nl,r)}function jut(r){return ck(nl,r)}function Rut(r){return uk(nl,r)}function Nut(r){return lk(nl,r)}var Nk=ie("ZodURL",(r,e)=>{PL.init(r,e),Gr.init(r,e)});function Fut(r){return Fg(Nk,r)}function Mut(r){return Fg(Nk,{protocol:/^https?$/,hostname:is.domain,...Te.normalizeParams(r)})}var jU=ie("ZodEmoji",(r,e)=>{DL.init(r,e),Gr.init(r,e)});function Lut(r){return fk(jU,r)}var RU=ie("ZodNanoID",(r,e)=>{IL.init(r,e),Gr.init(r,e)});function qut(r){return pk(RU,r)}var NU=ie("ZodCUID",(r,e)=>{OL.init(r,e),Gr.init(r,e)});function Uut(r){return dk(NU,r)}var FU=ie("ZodCUID2",(r,e)=>{$L.init(r,e),Gr.init(r,e)});function zut(r){return hk(FU,r)}var MU=ie("ZodULID",(r,e)=>{jL.init(r,e),Gr.init(r,e)});function But(r){return mk(MU,r)}var LU=ie("ZodXID",(r,e)=>{RL.init(r,e),Gr.init(r,e)});function Hut(r){return gk(LU,r)}var qU=ie("ZodKSUID",(r,e)=>{NL.init(r,e),Gr.init(r,e)});function Wut(r){return vk(qU,r)}var UU=ie("ZodIPv4",(r,e)=>{UL.init(r,e),Gr.init(r,e)});function Vut(r){return yk(UU,r)}var A3e=ie("ZodMAC",(r,e)=>{BL.init(r,e),Gr.init(r,e)});function Gut(r){return Mq(A3e,r)}var zU=ie("ZodIPv6",(r,e)=>{zL.init(r,e),Gr.init(r,e)});function Zut(r){return bk(zU,r)}var BU=ie("ZodCIDRv4",(r,e)=>{HL.init(r,e),Gr.init(r,e)});function Jut(r){return xk(BU,r)}var HU=ie("ZodCIDRv6",(r,e)=>{WL.init(r,e),Gr.init(r,e)});function Kut(r){return wk(HU,r)}var WU=ie("ZodBase64",(r,e)=>{VL.init(r,e),Gr.init(r,e)});function Yut(r){return _k(WU,r)}var VU=ie("ZodBase64URL",(r,e)=>{GL.init(r,e),Gr.init(r,e)});function Xut(r){return Sk(VU,r)}var GU=ie("ZodE164",(r,e)=>{ZL.init(r,e),Gr.init(r,e)});function Qut(r){return Ek(GU,r)}var ZU=ie("ZodJWT",(r,e)=>{JL.init(r,e),Gr.init(r,e)});function elt(r){return kk(ZU,r)}var Qg=ie("ZodCustomStringFormat",(r,e)=>{KL.init(r,e),Gr.init(r,e)});function tlt(r,e,t={}){return Jm(Qg,r,e,t)}function rlt(r){return Jm(Qg,"hostname",is.hostname,r)}function nlt(r){return Jm(Qg,"hex",is.hex,r)}function ilt(r,e){let t=e?.enc??"hex",n=`${r}_${t}`,i=is[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return Jm(Qg,n,i,e)}var Fk=ie("ZodNumber",(r,e)=>{rk.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Tde(r,n,i,a),r.gt=(n,i)=>r.check(tl(n,i)),r.gte=(n,i)=>r.check(Ea(n,i)),r.min=(n,i)=>r.check(Ea(n,i)),r.lt=(n,i)=>r.check(el(n,i)),r.lte=(n,i)=>r.check(Do(n,i)),r.max=(n,i)=>r.check(Do(n,i)),r.int=n=>r.check(IU(n)),r.safe=n=>r.check(IU(n)),r.positive=n=>r.check(tl(0,n)),r.nonnegative=n=>r.check(Ea(0,n)),r.negative=n=>r.check(el(0,n)),r.nonpositive=n=>r.check(Do(0,n)),r.multipleOf=(n,i)=>r.check(ad(n,i)),r.step=(n,i)=>r.check(ad(n,i)),r.finite=()=>r;let t=r._zod.bag;r.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,r.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,r.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),r.isFinite=!0,r.format=t.format??null});function pn(r){return Bq(Fk,r)}var Ym=ie("ZodNumberFormat",(r,e)=>{YL.init(r,e),Fk.init(r,e)});function IU(r){return Hq(Ym,r)}function alt(r){return Wq(Ym,r)}function olt(r){return Vq(Ym,r)}function slt(r){return Gq(Ym,r)}function clt(r){return Zq(Ym,r)}var Mk=ie("ZodBoolean",(r,e)=>{$g.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Pde(r,t,n,i)});function si(r){return Jq(Mk,r)}var Lk=ie("ZodBigInt",(r,e)=>{nk.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Dde(r,n,i,a),r.gte=(n,i)=>r.check(Ea(n,i)),r.min=(n,i)=>r.check(Ea(n,i)),r.gt=(n,i)=>r.check(tl(n,i)),r.gte=(n,i)=>r.check(Ea(n,i)),r.min=(n,i)=>r.check(Ea(n,i)),r.lt=(n,i)=>r.check(el(n,i)),r.lte=(n,i)=>r.check(Do(n,i)),r.max=(n,i)=>r.check(Do(n,i)),r.positive=n=>r.check(tl(BigInt(0),n)),r.negative=n=>r.check(el(BigInt(0),n)),r.nonpositive=n=>r.check(Do(BigInt(0),n)),r.nonnegative=n=>r.check(Ea(BigInt(0),n)),r.multipleOf=(n,i)=>r.check(ad(n,i));let t=r._zod.bag;r.minValue=t.minimum??null,r.maxValue=t.maximum??null,r.format=t.format??null});function ult(r){return Kq(Lk,r)}var JU=ie("ZodBigIntFormat",(r,e)=>{XL.init(r,e),Lk.init(r,e)});function llt(r){return Yq(JU,r)}function flt(r){return Xq(JU,r)}var C3e=ie("ZodSymbol",(r,e)=>{QL.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Ide(r,t,n,i)});function plt(r){return Qq(C3e,r)}var T3e=ie("ZodUndefined",(r,e)=>{eq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>$de(r,t,n,i)});function dlt(r){return eU(T3e,r)}var P3e=ie("ZodNull",(r,e)=>{tq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Ode(r,t,n,i)});function D3e(r){return tU(P3e,r)}var I3e=ie("ZodAny",(r,e)=>{rq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Nde(r,t,n,i)});function hlt(){return rU(I3e)}var O3e=ie("ZodUnknown",(r,e)=>{nq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Fde(r,t,n,i)});function nn(){return nU(O3e)}var $3e=ie("ZodNever",(r,e)=>{iq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Rde(r,t,n,i)});function KU(r){return iU($3e,r)}var j3e=ie("ZodVoid",(r,e)=>{aq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>jde(r,t,n,i)});function mlt(r){return aU(j3e,r)}var YU=ie("ZodDate",(r,e)=>{oq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Mde(r,n,i,a),r.min=(n,i)=>r.check(Ea(n,i)),r.max=(n,i)=>r.check(Do(n,i));let t=r._zod.bag;r.minDate=t.minimum?new Date(t.minimum):null,r.maxDate=t.maximum?new Date(t.maximum):null});function glt(r){return oU(YU,r)}var R3e=ie("ZodArray",(r,e)=>{sq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Kde(r,t,n,i),r.element=e.element,r.min=(t,n)=>r.check(ef(t,n)),r.nonempty=t=>r.check(ef(1,t)),r.max=(t,n)=>r.check(Gm(t,n)),r.length=(t,n)=>r.check(Zm(t,n)),r.unwrap=()=>r.element});function or(r,e){return kde(R3e,r,e)}function vlt(r){let e=r._zod.def.shape;return Za(Object.keys(e))}var qk=ie("ZodObject",(r,e)=>{wde.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Yde(r,t,n,i),Te.defineLazy(r,"shape",()=>e.shape),r.keyof=()=>Za(Object.keys(r._zod.def.shape)),r.catchall=t=>r.clone({...r._zod.def,catchall:t}),r.passthrough=()=>r.clone({...r._zod.def,catchall:nn()}),r.loose=()=>r.clone({...r._zod.def,catchall:nn()}),r.strict=()=>r.clone({...r._zod.def,catchall:KU()}),r.strip=()=>r.clone({...r._zod.def,catchall:void 0}),r.extend=t=>Te.extend(r,t),r.safeExtend=t=>Te.safeExtend(r,t),r.merge=t=>Te.merge(r,t),r.pick=t=>Te.pick(r,t),r.omit=t=>Te.omit(r,t),r.partial=(...t)=>Te.partial(ez,r,t[0]),r.required=(...t)=>Te.required(tz,r,t[0])});function Je(r,e){let t={type:"object",shape:r??{},...Te.normalizeParams(e)};return new qk(t)}function ylt(r,e){return new qk({type:"object",shape:r,catchall:KU(),...Te.normalizeParams(e)})}function Bc(r,e){return new qk({type:"object",shape:r,catchall:nn(),...Te.normalizeParams(e)})}var Uk=ie("ZodUnion",(r,e)=>{jg.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>xU(r,t,n,i),r.options=e.options});function an(r,e){return new Uk({type:"union",options:r,...Te.normalizeParams(e)})}var N3e=ie("ZodXor",(r,e)=>{Uk.init(r,e),cq.init(r,e),r._zod.processJSONSchema=(t,n,i)=>xU(r,t,n,i),r.options=e.options});function blt(r,e){return new N3e({type:"union",options:r,inclusive:!1,...Te.normalizeParams(e)})}var F3e=ie("ZodDiscriminatedUnion",(r,e)=>{Uk.init(r,e),uq.init(r,e)});function XU(r,e,t){return new F3e({type:"union",options:e,discriminator:r,...Te.normalizeParams(t)})}var M3e=ie("ZodIntersection",(r,e)=>{lq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Xde(r,t,n,i)});function e8(r,e){return new M3e({type:"intersection",left:r,right:e})}var L3e=ie("ZodTuple",(r,e)=>{ik.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Qde(r,t,n,i),r.rest=t=>r.clone({...r._zod.def,rest:t})});function q3e(r,e,t){let n=e instanceof It,i=n?t:e,a=n?e:null;return new L3e({type:"tuple",items:r,rest:a,...Te.normalizeParams(i)})}var zk=ie("ZodRecord",(r,e)=>{fq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>e3e(r,t,n,i),r.keyType=e.keyType,r.valueType=e.valueType});function dn(r,e,t){return new zk({type:"record",keyType:r,valueType:e,...Te.normalizeParams(t)})}function xlt(r,e,t){let n=_a(r);return n._zod.values=void 0,new zk({type:"record",keyType:n,valueType:e,...Te.normalizeParams(t)})}function wlt(r,e,t){return new zk({type:"record",keyType:r,valueType:e,mode:"loose",...Te.normalizeParams(t)})}var U3e=ie("ZodMap",(r,e)=>{pq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Zde(r,t,n,i),r.keyType=e.keyType,r.valueType=e.valueType,r.min=(...t)=>r.check(rl(...t)),r.nonempty=t=>r.check(rl(1,t)),r.max=(...t)=>r.check(od(...t)),r.size=(...t)=>r.check(Vm(...t))});function _lt(r,e,t){return new U3e({type:"map",keyType:r,valueType:e,...Te.normalizeParams(t)})}var z3e=ie("ZodSet",(r,e)=>{dq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Jde(r,t,n,i),r.min=(...t)=>r.check(rl(...t)),r.nonempty=t=>r.check(rl(1,t)),r.max=(...t)=>r.check(od(...t)),r.size=(...t)=>r.check(Vm(...t))});function Slt(r,e){return new z3e({type:"set",valueType:r,...Te.normalizeParams(e)})}var Xg=ie("ZodEnum",(r,e)=>{hq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Lde(r,n,i,a),r.enum=e.entries,r.options=Object.values(e.entries);let t=new Set(Object.keys(e.entries));r.extract=(n,i)=>{let a={};for(let o of n)if(t.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Xg({...e,checks:[],...Te.normalizeParams(i),entries:a})},r.exclude=(n,i)=>{let a={...e.entries};for(let o of n)if(t.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Xg({...e,checks:[],...Te.normalizeParams(i),entries:a})}});function Za(r,e){let t=Array.isArray(r)?Object.fromEntries(r.map(n=>[n,n])):r;return new Xg({type:"enum",entries:t,...Te.normalizeParams(e)})}function Elt(r,e){return new Xg({type:"enum",entries:r,...Te.normalizeParams(e)})}var B3e=ie("ZodLiteral",(r,e)=>{mq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>qde(r,t,n,i),r.values=new Set(e.values),Object.defineProperty(r,"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 ct(r,e){return new B3e({type:"literal",values:Array.isArray(r)?r:[r],...Te.normalizeParams(e)})}var H3e=ie("ZodFile",(r,e)=>{gq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Bde(r,t,n,i),r.min=(t,n)=>r.check(rl(t,n)),r.max=(t,n)=>r.check(od(t,n)),r.mime=(t,n)=>r.check(Hg(Array.isArray(t)?t:[t],n))});function klt(r){return dU(H3e,r)}var W3e=ie("ZodTransform",(r,e)=>{vq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Gde(r,t,n,i),r._zod.parse=(t,n)=>{if(n.direction==="backward")throw new td(r.constructor.name);t.addIssue=a=>{if(typeof a=="string")t.issues.push(Te.issue(a,t.value,e));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=t.value),o.inst??(o.inst=r),t.issues.push(Te.issue(o))}};let i=e.transform(t.value,t);return i instanceof Promise?i.then(a=>(t.value=a,t)):(t.value=i,t)}});function QU(r){return new W3e({type:"transform",transform:r})}var ez=ie("ZodOptional",(r,e)=>{ak.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>wU(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function zt(r){return new ez({type:"optional",innerType:r})}var V3e=ie("ZodExactOptional",(r,e)=>{yq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>wU(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function G3e(r){return new V3e({type:"optional",innerType:r})}var Z3e=ie("ZodNullable",(r,e)=>{bq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>t3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function $k(r){return new Z3e({type:"nullable",innerType:r})}function Alt(r){return zt($k(r))}var J3e=ie("ZodDefault",(r,e)=>{xq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>n3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType,r.removeDefault=r.unwrap});function K3e(r,e){return new J3e({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():Te.shallowClone(e)}})}var Y3e=ie("ZodPrefault",(r,e)=>{wq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>i3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function X3e(r,e){return new Y3e({type:"prefault",innerType:r,get defaultValue(){return typeof e=="function"?e():Te.shallowClone(e)}})}var tz=ie("ZodNonOptional",(r,e)=>{_q.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>r3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function Q3e(r,e){return new tz({type:"nonoptional",innerType:r,...Te.normalizeParams(e)})}var e0e=ie("ZodSuccess",(r,e)=>{Sq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Hde(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function Clt(r){return new e0e({type:"success",innerType:r})}var t0e=ie("ZodCatch",(r,e)=>{Eq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>a3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType,r.removeCatch=r.unwrap});function r0e(r,e){return new t0e({type:"catch",innerType:r,catchValue:typeof e=="function"?e:()=>e})}var n0e=ie("ZodNaN",(r,e)=>{kq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Ude(r,t,n,i)});function Tlt(r){return sU(n0e,r)}var rz=ie("ZodPipe",(r,e)=>{Aq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>o3e(r,t,n,i),r.in=e.in,r.out=e.out});function jk(r,e){return new rz({type:"pipe",in:r,out:e})}var nz=ie("ZodCodec",(r,e)=>{rz.init(r,e),Rg.init(r,e)});function Plt(r,e,t){return new nz({type:"pipe",in:r,out:e,transform:t.decode,reverseTransform:t.encode})}var i0e=ie("ZodReadonly",(r,e)=>{Cq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>s3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function a0e(r){return new i0e({type:"readonly",innerType:r})}var o0e=ie("ZodTemplateLiteral",(r,e)=>{Tq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>zde(r,t,n,i)});function Dlt(r,e){return new o0e({type:"template_literal",parts:r,...Te.normalizeParams(e)})}var s0e=ie("ZodLazy",(r,e)=>{Iq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>u3e(r,t,n,i),r.unwrap=()=>r._zod.def.getter()});function c0e(r){return new s0e({type:"lazy",getter:r})}var u0e=ie("ZodPromise",(r,e)=>{Dq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>c3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function Ilt(r){return new u0e({type:"promise",innerType:r})}var l0e=ie("ZodFunction",(r,e)=>{Pq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Vde(r,t,n,i)});function Olt(r){return new l0e({type:"function",input:Array.isArray(r?.input)?q3e(r?.input):r?.input??or(nn()),output:r?.output??nn()})}var Bk=ie("ZodCustom",(r,e)=>{Oq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Wde(r,t,n,i)});function $lt(r){let e=new Vr({check:"custom"});return e._zod.check=r,e}function iz(r,e){return hU(Bk,r??(()=>!0),e)}function f0e(r,e={}){return mU(Bk,r,e)}function p0e(r){return gU(r)}var jlt=vU,Rlt=yU;function Nlt(r,e={}){let t=new Bk({type:"custom",check:"custom",fn:n=>n instanceof r,abort:!0,...Te.normalizeParams(e)});return t._zod.bag.Class=r,t._zod.check=n=>{n.value instanceof r||n.issues.push({code:"invalid_type",expected:r.name,input:n.value,inst:t,path:[...t._zod.def.path??[]]})},t}var Flt=(...r)=>bU({Codec:nz,Boolean:Mk,String:Rk},...r);function Mlt(r){let e=c0e(()=>an([xe(r),pn(),si(),D3e(),or(e),dn(xe(),e)]));return e}function az(r,e){return jk(QU(r),e)}var d0e;d0e||(d0e={});var Brr={...Yg,...Ik,iso:Kg};oi($q());var sz="2025-06-18";var h0e=[sz,"2025-03-26","2024-11-05","2024-10-07"],Wk="2.0",Hc=iz(r=>r!==null&&(typeof r=="object"||typeof r=="function")),m0e=an([xe(),pn().int()]),g0e=xe(),zlt=Bc({progressToken:m0e.optional()}),Ls=Bc({_meta:zlt.optional()}),Ja=Je({method:xe(),params:Ls.optional()}),Qm=Bc({_meta:dn(xe(),nn()).optional()}),qs=Je({method:xe(),params:Qm.optional()}),as=Bc({_meta:dn(xe(),nn()).optional()}),Vk=an([xe(),pn().int()]),v0e=Je({jsonrpc:ct(Wk),id:Vk,...Ja.shape}).strict(),y0e=r=>v0e.safeParse(r).success,b0e=Je({jsonrpc:ct(Wk),...qs.shape}).strict(),x0e=r=>b0e.safeParse(r).success,w0e=Je({jsonrpc:ct(Wk),id:Vk,result:as}).strict(),cz=r=>w0e.safeParse(r).success,xi;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(xi||(xi={}));var _0e=Je({jsonrpc:ct(Wk),id:Vk,error:Je({code:pn().int(),message:xe(),data:zt(nn())})}).strict(),S0e=r=>_0e.safeParse(r).success,E0e=an([v0e,b0e,w0e,_0e]),cd=as.strict(),Blt=Qm.extend({requestId:Vk,reason:xe().optional()}),Gk=qs.extend({method:ct("notifications/cancelled"),params:Blt}),Hlt=Je({src:xe(),mimeType:xe().optional(),sizes:or(xe()).optional()}),t8=Je({icons:or(Hlt).optional()}),Xm=Je({name:xe(),title:xe().optional()}),k0e=Xm.extend({...Xm.shape,...t8.shape,version:xe(),websiteUrl:xe().optional()}),Wlt=e8(Je({applyDefaults:si().optional()}),dn(xe(),nn())),Vlt=az(r=>r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0?{form:{}}:r,e8(Je({form:Wlt.optional(),url:Hc.optional()}),dn(xe(),nn()).optional())),Glt=Je({experimental:dn(xe(),Hc).optional(),sampling:Je({context:Hc.optional(),tools:Hc.optional()}).optional(),elicitation:Vlt.optional(),roots:Je({listChanged:si().optional()}).optional()}),Zlt=Ls.extend({protocolVersion:xe(),capabilities:Glt,clientInfo:k0e}),Jlt=Ja.extend({method:ct("initialize"),params:Zlt});var Klt=Je({experimental:dn(xe(),Hc).optional(),logging:Hc.optional(),completions:Hc.optional(),prompts:zt(Je({listChanged:zt(si())})),resources:Je({subscribe:si().optional(),listChanged:si().optional()}).optional(),tools:Je({listChanged:si().optional()}).optional()}),uz=as.extend({protocolVersion:xe(),capabilities:Klt,serverInfo:k0e,instructions:xe().optional()}),Ylt=qs.extend({method:ct("notifications/initialized")});var Zk=Ja.extend({method:ct("ping")}),Xlt=Je({progress:pn(),total:zt(pn()),message:zt(xe())}),Qlt=Je({...Qm.shape,...Xlt.shape,progressToken:m0e}),Jk=qs.extend({method:ct("notifications/progress"),params:Qlt}),e2t=Ls.extend({cursor:g0e.optional()}),Kk=Ja.extend({params:e2t.optional()}),Yk=as.extend({nextCursor:zt(g0e)}),A0e=Je({uri:xe(),mimeType:zt(xe()),_meta:dn(xe(),nn()).optional()}),C0e=A0e.extend({text:xe()}),lz=xe().refine(r=>{try{return atob(r),!0}catch{return!1}},{message:"Invalid Base64 string"}),T0e=A0e.extend({blob:lz}),P0e=Je({...Xm.shape,...t8.shape,uri:xe(),description:zt(xe()),mimeType:zt(xe()),_meta:zt(Bc({}))}),t2t=Je({...Xm.shape,...t8.shape,uriTemplate:xe(),description:zt(xe()),mimeType:zt(xe()),_meta:zt(Bc({}))}),r2t=Kk.extend({method:ct("resources/list")}),fz=Yk.extend({resources:or(P0e)}),n2t=Kk.extend({method:ct("resources/templates/list")}),pz=Yk.extend({resourceTemplates:or(t2t)}),dz=Ls.extend({uri:xe()}),i2t=dz,a2t=Ja.extend({method:ct("resources/read"),params:i2t}),hz=as.extend({contents:or(an([C0e,T0e]))}),o2t=qs.extend({method:ct("notifications/resources/list_changed")}),s2t=dz,c2t=Ja.extend({method:ct("resources/subscribe"),params:s2t}),u2t=dz,l2t=Ja.extend({method:ct("resources/unsubscribe"),params:u2t}),f2t=Qm.extend({uri:xe()}),p2t=qs.extend({method:ct("notifications/resources/updated"),params:f2t}),d2t=Je({name:xe(),description:zt(xe()),required:zt(si())}),h2t=Je({...Xm.shape,...t8.shape,description:zt(xe()),arguments:zt(or(d2t)),_meta:zt(Bc({}))}),m2t=Kk.extend({method:ct("prompts/list")}),mz=Yk.extend({prompts:or(h2t)}),g2t=Ls.extend({name:xe(),arguments:dn(xe(),xe()).optional()}),v2t=Ja.extend({method:ct("prompts/get"),params:g2t}),D0e=Je({type:ct("text"),text:xe(),_meta:dn(xe(),nn()).optional()}),I0e=Je({type:ct("image"),data:lz,mimeType:xe(),_meta:dn(xe(),nn()).optional()}),O0e=Je({type:ct("audio"),data:lz,mimeType:xe(),_meta:dn(xe(),nn()).optional()}),y2t=Je({type:ct("tool_use"),name:xe(),id:xe(),input:Je({}).passthrough(),_meta:zt(Je({}).passthrough())}).passthrough(),b2t=Je({type:ct("resource"),resource:an([C0e,T0e]),_meta:dn(xe(),nn()).optional()}),x2t=P0e.extend({type:ct("resource_link")}),gz=an([D0e,I0e,O0e,x2t,b2t]),w2t=Je({role:Za(["user","assistant"]),content:gz}),vz=as.extend({description:zt(xe()),messages:or(w2t)}),_2t=qs.extend({method:ct("notifications/prompts/list_changed")}),S2t=Je({title:xe().optional(),readOnlyHint:si().optional(),destructiveHint:si().optional(),idempotentHint:si().optional(),openWorldHint:si().optional()}),$0e=Je({...Xm.shape,...t8.shape,description:xe().optional(),inputSchema:Je({type:ct("object"),properties:dn(xe(),Hc).optional(),required:or(xe()).optional()}).catchall(nn()),outputSchema:Je({type:ct("object"),properties:dn(xe(),Hc).optional(),required:or(xe()).optional()}).catchall(nn()).optional(),annotations:zt(S2t),_meta:dn(xe(),nn()).optional()}),E2t=Kk.extend({method:ct("tools/list")}),yz=Yk.extend({tools:or($0e)}),Xk=as.extend({content:or(gz).default([]),structuredContent:dn(xe(),nn()).optional(),isError:zt(si())}),cnr=Xk.or(as.extend({toolResult:nn()})),k2t=Ls.extend({name:xe(),arguments:zt(dn(xe(),nn()))}),A2t=Ja.extend({method:ct("tools/call"),params:k2t}),C2t=qs.extend({method:ct("notifications/tools/list_changed")}),j0e=Za(["debug","info","notice","warning","error","critical","alert","emergency"]),T2t=Ls.extend({level:j0e}),P2t=Ja.extend({method:ct("logging/setLevel"),params:T2t}),D2t=Qm.extend({level:j0e,logger:xe().optional(),data:nn()}),I2t=qs.extend({method:ct("notifications/message"),params:D2t}),O2t=Je({name:xe().optional()}),$2t=Je({hints:zt(or(O2t)),costPriority:zt(pn().min(0).max(1)),speedPriority:zt(pn().min(0).max(1)),intelligencePriority:zt(pn().min(0).max(1))}),j2t=Je({mode:zt(Za(["auto","required","none"]))}),R2t=Je({type:ct("tool_result"),toolUseId:xe().describe("The unique identifier for the corresponding tool call."),content:or(gz).default([]),structuredContent:Je({}).passthrough().optional(),isError:zt(si()),_meta:zt(Je({}).passthrough())}).passthrough(),Hk=XU("type",[D0e,I0e,O0e,y2t,R2t]),N2t=Je({role:Za(["user","assistant"]),content:an([Hk,or(Hk)]),_meta:zt(Je({}).passthrough())}).passthrough(),F2t=Ls.extend({messages:or(N2t),modelPreferences:$2t.optional(),systemPrompt:xe().optional(),includeContext:Za(["none","thisServer","allServers"]).optional(),temperature:pn().optional(),maxTokens:pn().int(),stopSequences:or(xe()).optional(),metadata:Hc.optional(),tools:zt(or($0e)),toolChoice:zt(j2t)}),M2t=Ja.extend({method:ct("sampling/createMessage"),params:F2t}),L2t=as.extend({model:xe(),stopReason:zt(Za(["endTurn","stopSequence","maxTokens","toolUse"]).or(xe())),role:Za(["user","assistant"]),content:an([Hk,or(Hk)])}),q2t=Je({type:ct("boolean"),title:xe().optional(),description:xe().optional(),default:si().optional()}),U2t=Je({type:ct("string"),title:xe().optional(),description:xe().optional(),minLength:pn().optional(),maxLength:pn().optional(),format:Za(["email","uri","date","date-time"]).optional(),default:xe().optional()}),z2t=Je({type:Za(["number","integer"]),title:xe().optional(),description:xe().optional(),minimum:pn().optional(),maximum:pn().optional(),default:pn().optional()}),B2t=Je({type:ct("string"),title:xe().optional(),description:xe().optional(),enum:or(xe()),default:xe().optional()}),H2t=Je({type:ct("string"),title:xe().optional(),description:xe().optional(),oneOf:or(Je({const:xe(),title:xe()})),default:xe().optional()}),W2t=Je({type:ct("string"),title:xe().optional(),description:xe().optional(),enum:or(xe()),enumNames:or(xe()).optional(),default:xe().optional()}),V2t=an([B2t,H2t]),G2t=Je({type:ct("array"),title:xe().optional(),description:xe().optional(),minItems:pn().optional(),maxItems:pn().optional(),items:Je({type:ct("string"),enum:or(xe())}),default:or(xe()).optional()}),Z2t=Je({type:ct("array"),title:xe().optional(),description:xe().optional(),minItems:pn().optional(),maxItems:pn().optional(),items:Je({anyOf:or(Je({const:xe(),title:xe()}))}),default:or(xe()).optional()}),J2t=an([G2t,Z2t]),K2t=an([W2t,V2t,J2t]),Y2t=an([K2t,q2t,U2t,z2t]),X2t=Ls.extend({mode:ct("form").optional(),message:xe(),requestedSchema:Je({type:ct("object"),properties:dn(xe(),Y2t),required:or(xe()).optional()})}),Q2t=Ls.extend({mode:ct("url"),message:xe(),elicitationId:xe(),url:xe().url()}),eft=an([X2t,Q2t]),bz=Ja.extend({method:ct("elicitation/create"),params:eft}),tft=Qm.extend({elicitationId:xe()}),rft=qs.extend({method:ct("notifications/elicitation/complete"),params:tft}),xz=as.extend({action:Za(["accept","decline","cancel"]),content:dn(xe(),an([xe(),pn(),si(),or(xe())])).optional()}),nft=Je({type:ct("ref/resource"),uri:xe()});var ift=Je({type:ct("ref/prompt"),name:xe()}),aft=Ls.extend({ref:an([ift,nft]),argument:Je({name:xe(),value:xe()}),context:Je({arguments:dn(xe(),xe()).optional()}).optional()}),oft=Ja.extend({method:ct("completion/complete"),params:aft});var wz=as.extend({completion:Bc({values:or(xe()).max(100),total:zt(pn().int()),hasMore:zt(si())})}),sft=Je({uri:xe().startsWith("file://"),name:xe().optional(),_meta:dn(xe(),nn()).optional()}),cft=Ja.extend({method:ct("roots/list")}),uft=as.extend({roots:or(sft)}),lft=qs.extend({method:ct("notifications/roots/list_changed")}),unr=an([Zk,Jlt,oft,P2t,v2t,m2t,r2t,n2t,a2t,c2t,l2t,A2t,E2t]),lnr=an([Gk,Jk,Ylt,lft]),fnr=an([cd,L2t,xz,uft]),pnr=an([Zk,M2t,bz,cft]),dnr=an([Gk,Jk,I2t,p2t,o2t,C2t,_2t,rft]),hnr=an([cd,uz,wz,vz,mz,fz,pz,hz,Xk,yz]),Ui=class r extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===xi.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new oz(i.elicitations,t)}return new r(e,t,n)}},oz=class extends Ui{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(xi.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){var e,t;return(t=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&t!==void 0?t:[]}};var fft=Symbol("Let zodToJsonSchema decide on which parser to use");var Gnr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _z(r){let e=Dk(r),t=e?.method;if(!t)throw new Error("Schema is missing a method literal");let n=p3e(t);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Sz(r,e){let t=sd(r,e);if(!t.success)throw t.error;return t.data}var vft=6e4,Qk=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.setNotificationHandler(Gk,t=>{let n=this._requestHandlerAbortControllers.get(t.params.requestId);n?.abort(t.params.reason)}),this.setNotificationHandler(Jk,t=>{this._onprogress(t)}),this.setRequestHandler(Zk,t=>({}))}_setupTimeout(e,t,n,i,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ui.fromError(xi.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,n,i;this._transport=e;let a=(t=this.transport)===null||t===void 0?void 0:t.onclose;this._transport.onclose=()=>{a?.(),this._onclose()};let o=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{o?.(c),this._onerror(c)};let s=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{s?.(c,u),cz(c)||S0e(c)?this._onresponse(c):y0e(c)?this._onrequest(c,u):x0e(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=Ui.fromError(xi.ConnectionClosed,"Connection closed");for(let i of t.values())i(n)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let n=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){var n,i;let a=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,o=this._transport;if(a===void 0){o?.send({jsonrpc:"2.0",id:e.id,error:{code:xi.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let c={signal:s.signal,sessionId:o?.sessionId,_meta:(i=e.params)===null||i===void 0?void 0:i._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,l,f)=>this.request(u,l,{...f,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo};Promise.resolve().then(()=>a(e,c)).then(u=>{if(!s.signal.aborted)return o?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var l;if(!s.signal.aborted)return o?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:xi.InternalError,message:(l=u.message)!==null&&l!==void 0?l:"Internal error",...u.data!==void 0&&{data:u.data}}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,i=Number(t),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){o(c);return}a(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),cz(e))n(e);else{let i=Ui.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}=n??{};return new Promise((s,c)=>{var u,l,f,p,d,m;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(l=n?.signal)===null||l===void 0||l.throwIfAborted();let h=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),g.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:h}});let v=k=>{var S;this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(k)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(A=>this._onerror(new Error(`Failed to send cancellation: ${A}`))),c(k)};this._responseHandlers.set(h,k=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(k instanceof Error)return c(k);try{let A=sd(t,k.result);A.success?s(A.data):c(A.error)}catch(A){c(A)}}}),(p=n?.signal)===null||p===void 0||p.addEventListener("abort",()=>{var k;v((k=n?.signal)===null||k===void 0?void 0:k.reason)});let y=(d=n?.timeout)!==null&&d!==void 0?d:vft,x=()=>v(Ui.fromError(xi.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(h,y,n?.maxTotalTimeout,x,(m=n?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(g,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(k=>{this._cleanupTimeout(h),c(k)})})}async notification(e,t){var n,i;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((i=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&i!==void 0?i:[]).includes(e.method)&&!e.params&&!t?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,t).catch(l=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};await this._transport.send(s,t)}setRequestHandler(e,t){let n=_z(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=Sz(e,i);return Promise.resolve(t(o,a))})}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,t){let n=_z(e);this._notificationHandlers.set(n,i=>{let a=Sz(e,i);return Promise.resolve(t(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function R0e(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function N0e(r,e){let t={...r};for(let n in e){let i=n,a=e[i];if(a===void 0)continue;let o=t[i];R0e(o)&&R0e(a)?t[i]={...o,...a}:t[i]=a}return t}var _1e=ur(cH(),1),S1e=ur(w1e(),1);function cmt(){let r=new _1e.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,S1e.default)(r),r}var RA=class{constructor(e){this._ajv=e??cmt()}getValidator(e){var t;let n="$id"in e&&typeof e.$id=="string"?(t=this._ajv.getSchema(e.$id))!==null&&t!==void 0?t:this._ajv.compile(e):this._ajv.compile(e);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};function NA(r,e){if(!(!r||e===null||typeof e!="object")){if(r.type==="object"&&r.properties&&typeof r.properties=="object"){let t=e,n=r.properties;for(let i of Object.keys(n)){let a=n[i];t[i]===void 0&&Object.prototype.hasOwnProperty.call(a,"default")&&(t[i]=a.default),t[i]!==void 0&&NA(a,t[i])}}if(Array.isArray(r.anyOf))for(let t of r.anyOf)NA(t,e);if(Array.isArray(r.oneOf))for(let t of r.oneOf)NA(t,e)}}function umt(r){if(!r)return{supportsFormMode:!1,supportsUrlMode:!1};let e=r.form!==void 0,t=r.url!==void 0;return{supportsFormMode:e||!e&&!t,supportsUrlMode:t}}var FA=class extends Qk{constructor(e,t){var n,i;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=t?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(i=t?.jsonSchemaValidator)!==null&&i!==void 0?i:new RA}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=N0e(this._capabilities,e)}setRequestHandler(e,t){var n,i,a;let o=Dk(e),s=o?.method;if(!s)throw new Error("Schema is missing a method literal");let c;if(Km(s)){let l=s,f=(n=l._zod)===null||n===void 0?void 0:n.def;c=(i=f?.value)!==null&&i!==void 0?i:l.value}else{let l=s,f=l._def;c=(a=f?.value)!==null&&a!==void 0?a:l.value}if(typeof c!="string")throw new Error("Schema method literal must be a string");if(c==="elicitation/create"){let l=async(f,p)=>{var d,m,h;let g=sd(bz,f);if(!g.success){let w=g.error instanceof Error?g.error.message:String(g.error);throw new Ui(xi.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:v}=g.data,y=(d=v.mode)!==null&&d!==void 0?d:"form",{supportsFormMode:x,supportsUrlMode:k}=umt(this._capabilities.elicitation);if(y==="form"&&!x)throw new Ui(xi.InvalidParams,"Client does not support form-mode elicitation requests");if(y==="url"&&!k)throw new Ui(xi.InvalidParams,"Client does not support URL-mode elicitation requests");let S=await Promise.resolve(t(f,p)),A=sd(xz,S);if(!A.success){let w=A.error instanceof Error?A.error.message:String(A.error);throw new Ui(xi.InvalidParams,`Invalid elicitation result: ${w}`)}let $=A.data,O=y==="form"?v.requestedSchema:void 0;if(y==="form"&&$.action==="accept"&&$.content&&O&&!((h=(m=this._capabilities.elicitation)===null||m===void 0?void 0:m.form)===null||h===void 0)&&h.applyDefaults)try{NA(O,$.content)}catch{}return $};return super.setRequestHandler(e,l)}return super.setRequestHandler(e,t)}assertCapability(e,t){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:sz,capabilities:this._capabilities,clientInfo:this._clientInfo}},uz,t);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!h0e.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,n,i,a,o;switch(e){case"logging/setLevel":if(!(!((t=this._serverCapabilities)===null||t===void 0)&&t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var t;switch(e){case"notifications/roots/list_changed":if(!(!((t=this._capabilities.roots)===null||t===void 0)&&t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},cd,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},wz,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},cd,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},vz,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},mz,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},fz,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},pz,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},hz,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},cd,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},cd,t)}async callTool(e,t=Xk,n){let i=await this.request({method:"tools/call",params:e},t,n),a=this.getToolOutputValidator(e.name);if(a){if(!i.structuredContent&&!i.isError)throw new Ui(xi.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let o=a(i.structuredContent);if(!o.valid)throw new Ui(xi.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof Ui?o:new Ui(xi.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return i}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let t of e)if(t.outputSchema){let n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:"tools/list",params:e},yz,t);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var d4e=ur(f4e(),1);import UA from"node:process";import{PassThrough as Fmt}from"node:stream";var LA=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
1139
1139
|
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Nmt(t)}clear(){this._buffer=void 0}};function Nmt(r){return E0e.parse(JSON.parse(r))}function p4e(r){return JSON.stringify(r)+`
|
|
1140
|
-
`}var Mmt=UA.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Lmt(){let r={};for(let e of Mmt){let t=UA.env[e];t!==void 0&&(t.startsWith("()")||(r[e]=t))}return r}var qA=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new LA,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Fmt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{var n,i,a,o,s;this._process=(0,d4e.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...Lmt(),...this._serverParams.env},stdio:["pipe","pipe",(i=this._serverParams.stderr)!==null&&i!==void 0?i:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:UA.platform==="win32"&&qmt(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,l;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}t(c),(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(a=this._process.stdin)===null||a===void 0||a.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(o=this._process.stdout)===null||o===void 0||o.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,t;return this._stderrStream?this._stderrStream:(t=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&t!==void 0?t:null}get pid(){var e,t;return(t=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&t!==void 0?t:null}processReadBuffer(){for(var e,t;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(t=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let i=p4e(e);this._process.stdin.write(i)?t():this._process.stdin.once("drain",t)})}};function qmt(){return"type"in UA}import{spawn as Umt}from"child_process";var kH=15e3,zA=class extends Vt{constructor(t){super(new yc("not used"),t.name);this.serverConfig=t;this.name=t.name}clientPromise;toolsPromise;inspectorProcess;transport;serverProcessPid=null;name="Not defined yet";errorLogged=!1;lastUsed=Date.now();async kill(){if(this.tools=[],console.log(`Closing mcp client ${this.serverConfig.name}`),this.inspectorProcess){console.log(`Stopping MCP Inspector process for ${this.serverConfig.name}`);try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector process: ${t}`)}this.inspectorProcess=void 0}try{await(await this.clientPromise)?.close()}catch{console.log(`MCP client ${this.serverConfig.name} was already failed/closed`)}if(this.transport){try{await this.transport.close(),console.log(`Transport closed for ${this.serverConfig.name}`)}catch(t){console.log(`Error closing transport for ${this.serverConfig.name}: ${t}`)}this.transport=void 0}console.log(`Closed mcp client ${this.serverConfig.name}`)}async buildTools(t,n){if(this.tools.length)return this.tools;if(!this.serverConfig.enabled)return console.debug(`[MCP] Server ${this.serverConfig.name} is disabled, skipping`),[];try{this.clientPromise||(console.log(`Initializing MCP server ${this.serverConfig.name}...`),this.clientPromise=this.buildClient());let i=await this.clientPromise;this.toolsPromise||(this.toolsPromise=this.buildInternalTools(i));let a=await this.toolsPromise;return console.log(`MCP server ${this.serverConfig.name} loaded ${a.length} tools successfully`),a}catch(i){let a=i instanceof Error?i.message:String(i);return this.errorLogged||(this.errorLogged=!0,console.error(`[MCP] Server ${this.serverConfig.name} failed to initialize: ${a}`),console.warn(`[MCP] Server '${this.serverConfig.name}' is unavailable and will be skipped: ${a}`)),[]}}async buildClient(){let t=new FA({name:"Coday MCP Client",version:"1.0.0"},{capabilities:{}});if(this.serverConfig.url)throw new Error("Remote HTTP/HTTPS MCP servers are not supported yet. Use local command-based servers instead.");if(this.serverConfig.command){let n={};if(this.serverConfig.debug&&!this.inspectorProcess){let a=["@modelcontextprotocol/inspector",this.serverConfig.command,...this.serverConfig.args||[]],o={};this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(o.env=this.serverConfig.env),this.serverConfig.cwd&&(o.cwd=this.serverConfig.cwd),console.log(`Starting MCP Inspector process for ${this.serverConfig.name}}`),this.inspectorProcess=Umt("npx",a,{stdio:"inherit",...o}),this.inspectorProcess.on("exit",(s,c)=>{console.log(`MCP Inspector process for ${this.serverConfig.name} exited (code: ${s}, signal: ${c})`)})}n.command=this.serverConfig.command,n.args=this.serverConfig.args||[],this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(n.env=this.serverConfig.env,console.log(`Using custom environment variables for MCP server ${this.serverConfig.name}`)),this.serverConfig.cwd&&(n.cwd=this.serverConfig.cwd,console.log(`Using working directory: ${this.serverConfig.cwd}`)),this.transport=new qA(n),console.log(`Starting MCP server ${this.serverConfig.name} with command: ${n.command}`),this.transport.onerror=i=>{console.error(`MCP server ${this.serverConfig.name} transport error:`,i)},this.transport.onclose=()=>{console.log(`MCP server ${this.serverConfig.name} transport closed`),this.serverProcessPid=null}}else throw new Error(`MCP server ${this.serverConfig.name} has no command configured. Only local command-based servers are supported.`);try{let n=t.connect(this.transport),i=new Promise((a,o)=>setTimeout(()=>o(new Error(`Connection timeout after ${kH}ms`)),kH));return await Promise.race([n,i]),this.transport&&"pid"in this.transport?(this.serverProcessPid=this.transport.pid,console.log(`Successfully connected to MCP server ${this.serverConfig.name} (PID: ${this.serverProcessPid})`)):console.log(`Successfully connected to MCP server ${this.serverConfig.name}`),t}catch(n){await this.cleanupOnError();let i=n instanceof Error?n.message:String(n);throw console.error(`Failed to connect to MCP server ${this.serverConfig.name}: ${i}`),i.includes("docker")||i.includes("Docker")||i.includes("container")||i.includes("Container")?new Error(`MCP server ${this.serverConfig.name} failed to start. This may be because Docker is not available or the Docker container failed to start. Original error: ${i}`):i.includes("timeout")||i.includes("Connection timeout")?new Error(`MCP server ${this.serverConfig.name} did not respond within ${kH}ms. Check if the server command is correct and the server starts quickly. Original error: ${i}`):i.includes("ENOENT")||i.includes("command not found")?new Error(`MCP server ${this.serverConfig.name} command not found. Check that the command '${this.serverConfig.command}' is available in your PATH. Original error: ${i}`):new Error(`MCP server ${this.serverConfig.name} connection failed: ${i}`)}}async cleanupOnError(){if(console.log(`Cleaning up failed MCP connection for ${this.serverConfig.name}`),this.inspectorProcess){try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector during cleanup: ${t}`)}this.inspectorProcess=void 0}if(this.transport){try{await this.transport.close()}catch(t){console.log(`Error closing transport during cleanup: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}}async buildInternalTools(t){let n=[];try{let i=await t.listResourceTemplates();if(i&&i.templates&&Array.isArray(i.templates))for(let a of i.templates)n.push(this.createResourceTool(this.serverConfig,t,a))}catch(i){i instanceof Error&&!i.message.includes("-32601: Method not found")?console.warn(`[MCP] Error listing resource templates from server ${this.serverConfig.name}: ${i}`):console.debug(`[MCP] Server ${this.serverConfig.name} doesn't support resource templates, continuing with tools only.`)}try{let i=await t.listTools();if(i&&i.tools&&Array.isArray(i.tools))for(let a of i.tools)n.push(this.createFunctionTool(this.serverConfig,t,a))}catch(i){console.warn(`[MCP] Error listing tools from server ${this.serverConfig.name}: ${i}`)}if(this.serverConfig.debug){let i=n.map(a=>`- ${a.function.name}
|
|
1140
|
+
`}var Mmt=UA.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Lmt(){let r={};for(let e of Mmt){let t=UA.env[e];t!==void 0&&(t.startsWith("()")||(r[e]=t))}return r}var qA=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new LA,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Fmt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{var n,i,a,o,s;this._process=(0,d4e.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...Lmt(),...this._serverParams.env},stdio:["pipe","pipe",(i=this._serverParams.stderr)!==null&&i!==void 0?i:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:UA.platform==="win32"&&qmt(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,l;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}t(c),(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(a=this._process.stdin)===null||a===void 0||a.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(o=this._process.stdout)===null||o===void 0||o.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,t;return this._stderrStream?this._stderrStream:(t=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&t!==void 0?t:null}get pid(){var e,t;return(t=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&t!==void 0?t:null}processReadBuffer(){for(var e,t;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(t=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let i=p4e(e);this._process.stdin.write(i)?t():this._process.stdin.once("drain",t)})}};function qmt(){return"type"in UA}import{spawn as Umt}from"child_process";var kH=15e3,zA=class extends Vt{constructor(t){super(new yc("not used"),t.name);this.serverConfig=t;this.name=t.name}clientPromise;toolsPromise;inspectorProcess;transport;serverProcessPid=null;name="Not defined yet";errorLogged=!1;lastUsed=Date.now();async kill(){if(this.tools=[],console.log(`Closing mcp client ${this.serverConfig.name}`),this.inspectorProcess){console.log(`Stopping MCP Inspector process for ${this.serverConfig.name}`);try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector process: ${t}`)}this.inspectorProcess=void 0}try{await(await this.clientPromise)?.close()}catch{console.log(`MCP client ${this.serverConfig.name} was already failed/closed`)}if(this.transport){try{await this.transport.close(),console.log(`Transport closed for ${this.serverConfig.name}`),this.serverProcessPid=null}catch(t){console.log(`Error closing transport for ${this.serverConfig.name}: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}console.log(`Closed mcp client ${this.serverConfig.name}`)}async buildTools(t,n){if(this.tools.length)return this.tools;if(!this.serverConfig.enabled)return console.debug(`[MCP] Server ${this.serverConfig.name} is disabled, skipping`),[];try{this.clientPromise||(console.log(`Initializing MCP server ${this.serverConfig.name}...`),this.clientPromise=this.buildClient());let i=await this.clientPromise;this.toolsPromise||(this.toolsPromise=this.buildInternalTools(i));let a=await this.toolsPromise;return console.log(`MCP server ${this.serverConfig.name} loaded ${a.length} tools successfully`),a}catch(i){let a=i instanceof Error?i.message:String(i);return this.errorLogged||(this.errorLogged=!0,console.error(`[MCP] Server ${this.serverConfig.name} failed to initialize: ${a}`),console.warn(`[MCP] Server '${this.serverConfig.name}' is unavailable and will be skipped: ${a}`)),[]}}async buildClient(){let t=new FA({name:"Coday MCP Client",version:"1.0.0"},{capabilities:{}});if(this.serverConfig.url)throw new Error("Remote HTTP/HTTPS MCP servers are not supported yet. Use local command-based servers instead.");if(this.serverConfig.command){let n={};if(this.serverConfig.debug&&!this.inspectorProcess){let a=["@modelcontextprotocol/inspector",this.serverConfig.command,...this.serverConfig.args||[]],o={};this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(o.env=this.serverConfig.env),this.serverConfig.cwd&&(o.cwd=this.serverConfig.cwd),console.log(`Starting MCP Inspector process for ${this.serverConfig.name}}`),this.inspectorProcess=Umt("npx",a,{stdio:"inherit",...o}),this.inspectorProcess.on("exit",(s,c)=>{console.log(`MCP Inspector process for ${this.serverConfig.name} exited (code: ${s}, signal: ${c})`)})}n.command=this.serverConfig.command,n.args=this.serverConfig.args||[],this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(n.env=this.serverConfig.env,console.log(`Using custom environment variables for MCP server ${this.serverConfig.name}`)),this.serverConfig.cwd&&(n.cwd=this.serverConfig.cwd,console.log(`Using working directory: ${this.serverConfig.cwd}`)),this.transport=new qA(n),console.log(`Starting MCP server ${this.serverConfig.name} with command: ${n.command}`),this.transport.onerror=i=>{console.error(`MCP server ${this.serverConfig.name} transport error:`,i)},this.transport.onclose=()=>{console.log(`MCP server ${this.serverConfig.name} transport closed`),this.serverProcessPid=null}}else throw new Error(`MCP server ${this.serverConfig.name} has no command configured. Only local command-based servers are supported.`);try{let n=t.connect(this.transport),i,a=new Promise((o,s)=>{i=setTimeout(()=>s(new Error(`Connection timeout after ${kH}ms`)),kH)});try{await Promise.race([n,a])}finally{clearTimeout(i)}return this.transport&&"pid"in this.transport?(this.serverProcessPid=this.transport.pid,console.log(`Successfully connected to MCP server ${this.serverConfig.name} (PID: ${this.serverProcessPid})`)):console.log(`Successfully connected to MCP server ${this.serverConfig.name}`),t}catch(n){await this.cleanupOnError();let i=n instanceof Error?n.message:String(n);throw console.error(`Failed to connect to MCP server ${this.serverConfig.name}: ${i}`),i.includes("docker")||i.includes("Docker")||i.includes("container")||i.includes("Container")?new Error(`MCP server ${this.serverConfig.name} failed to start. This may be because Docker is not available or the Docker container failed to start. Original error: ${i}`):i.includes("timeout")||i.includes("Connection timeout")?new Error(`MCP server ${this.serverConfig.name} did not respond within ${kH}ms. Check if the server command is correct and the server starts quickly. Original error: ${i}`):i.includes("ENOENT")||i.includes("command not found")?new Error(`MCP server ${this.serverConfig.name} command not found. Check that the command '${this.serverConfig.command}' is available in your PATH. Original error: ${i}`):new Error(`MCP server ${this.serverConfig.name} connection failed: ${i}`)}}async cleanupOnError(){if(console.log(`Cleaning up failed MCP connection for ${this.serverConfig.name}`),this.inspectorProcess){try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector during cleanup: ${t}`)}this.inspectorProcess=void 0}if(this.transport){try{await this.transport.close()}catch(t){console.log(`Error closing transport during cleanup: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}}async buildInternalTools(t){let n=[];try{let i=await t.listResourceTemplates();if(i&&i.templates&&Array.isArray(i.templates))for(let a of i.templates)n.push(this.createResourceTool(this.serverConfig,t,a))}catch(i){i instanceof Error&&!i.message.includes("-32601: Method not found")?console.warn(`[MCP] Error listing resource templates from server ${this.serverConfig.name}: ${i}`):console.debug(`[MCP] Server ${this.serverConfig.name} doesn't support resource templates, continuing with tools only.`)}try{let i=await t.listTools();if(i&&i.tools&&Array.isArray(i.tools))for(let a of i.tools)n.push(this.createFunctionTool(this.serverConfig,t,a))}catch(i){console.warn(`[MCP] Error listing tools from server ${this.serverConfig.name}: ${i}`)}if(this.serverConfig.debug){let i=n.map(a=>`- ${a.function.name}
|
|
1141
1141
|
`).join();console.debug(`[MCP] ${this.serverConfig.name}:
|
|
1142
1142
|
${i}`)}return n}createResourceTool(t,n,i){let a=`mcp__${t.id}__${i.name}`,o=async u=>{try{this.lastUsed=Date.now();let l=i.uriTemplate.replace(/\{([^}]+)\}/g,(p,d)=>encodeURIComponent(u[d]||"")),f=await n.readResource({uri:l});if(!f||!f.contents)throw new Error(`No content returned from resource ${i.name}`);return f.contents.map(p=>"text"in p?{uri:p.uri,text:p.text,mimeType:p.mimeType||"text/plain"}:"blob"in p?{uri:p.uri,blob:p.blob,mimeType:p.mimeType||"application/octet-stream"}:p)}catch(l){throw console.error(`[MCP] Error retrieving resource ${i.name}: ${l}`),new Error(`Failed to retrieve resource: ${l}`)}},s={},c=i.uriTemplate.match(/\{([^}]+)\}/g)||[];for(let u of c){let l=u.slice(1,-1);s[l]={type:"string",description:`Parameter ${l} for resource ${i.name}`}}return{type:"function",function:{name:a,description:i.description||`Resource from MCP server ${t.name}`,parameters:{type:"object",properties:s},parse:JSON.parse,function:o}}}createFunctionTool(t,n,i){let a=`${t.name}__${i.name}`,o=async s=>{this.lastUsed=Date.now(),this.serverConfig.debug&&console.debug(`[MCP] ${a} input:
|
|
1143
1143
|
|
|
@@ -1417,7 +1417,7 @@ JSON:`,c,u;try{let p=(await this.aiClient.complete(s,{maxTokens:300})).replace(/
|
|
|
1417
1417
|
|
|
1418
1418
|
`;e.writableEnded||e.write(o)}}catch(t){ue("THREAD_CODAY","Error replaying thread history:",t)}}removeConnection(e){this.connections.delete(e),ue("THREAD_CODAY",`Removed SSE connection from thread ${this.threadId} (remaining: ${this.connections.size})`)}get connectionCount(){return this.connections.size}updateActivity(){this.lastActivity=Date.now(),this.resetInactivityTimeout()}resetInactivityTimeout(){this.inactivityTimeout&&clearTimeout(this.inactivityTimeout);let e=this.isOneshot?r.ONESHOT_TIMEOUT:r.INTERACTIVE_TIMEOUT;this.inactivityTimeout=setTimeout(()=>{let t=Date.now()-this.lastActivity;ue("THREAD_CODAY",`Inactivity timeout reached for thread ${this.threadId} after ${Math.round(t/1e3)}s`),this.onTimeout(this.threadId)},e)}markAsOneshot(){this.isOneshot=!0,this.resetInactivityTimeout()}getInactiveTime(){return Date.now()-this.lastActivity}prepareCoday(){if(this.updateActivity(),this.coday)return ue("THREAD_CODAY",`Coday already running for thread ${this.threadId}`),!1;ue("THREAD_CODAY",`Creating Coday instance for thread ${this.threadId}`),console.log(`[THREAD_CODAY] Preparing instance for thread '${this.threadId}' (project: ${this.projectName}, user: ${this.username})`);let e=new yc(this.threadId),t=new H2(this.options.configDir,this.username,e),n=new _m(e,this.projectService,this.options.configDir),i=new mm(n,t),a=new hm(t,n,e),o=new ym(n,t),s=new vm(t,n,e);return e.events.subscribe(c=>{this.broadcastEvent(c)}),this.coday=new fT(e,this.options,{user:t,project:n,projectService:this.projectService,integration:i,integrationConfig:a,memory:o,mcp:s,mcpPool:this.mcpPool,thread:this.threadService,prompt:this.promptService,logger:this.logger,options:this.options}),console.log(`[THREAD_CODAY] Instance created for thread '${this.threadId}'`),!0}startCoday(){this.updateActivity();let e=this.prepareCoday();return this.coday?(this.coday.run().catch(t=>{ue("THREAD_CODAY",`Error during Coday run for thread ${this.threadId}:`,t),console.error(`Coday run failed for thread ${this.threadId}:`,t)}).finally(()=>{ue("THREAD_CODAY",`Coday run finished for thread ${this.threadId}`)}),e):!1}sendHeartbeat(){if(this.connections.size!==0)try{let e=new _0({});this.broadcastEvent(e)}catch(e){ue("THREAD_CODAY",`Error sending heartbeat for thread ${this.threadId}:`,e)}}broadcastEvent(e){e instanceof gc&&(e.name||e.summary)&&(ue("THREAD_CODAY",`Updating thread cache for ${this.threadId} name/summary`),this.threadService.updateThread(this.projectName,this.threadId,{name:e.name,summary:e.summary}).catch(n=>{ue("THREAD_CODAY","Error updating thread cache:",n)}));let t=`data: ${JSON.stringify(e)}
|
|
1419
1419
|
|
|
1420
|
-
`;for(let n of this.connections)try{n.writableEnded?this.connections.delete(n):n.write(t)}catch(i){ue("THREAD_CODAY","Error broadcasting to connection:",i),this.connections.delete(n)}}stop(){this.coday?.stop()}async handleOAuthCallback(e){if(!this.coday){ue("THREAD_CODAY",`Cannot handle OAuth callback: Coday not initialized for thread ${this.threadId}`);return}if(!this.coday.services.agent){ue("THREAD_CODAY","Cannot handle OAuth callback: Agent service not initialized");return}let n=this.coday.services.agent?.toolbox;if(!n){ue("THREAD_CODAY","Cannot handle OAuth callback: Toolbox not initialized");return}ue("THREAD_CODAY",`Routing OAuth callback for ${e.integrationName}`),await n.handleOAuthCallback(e)}async cleanup(){ue("THREAD_CODAY",`Cleaning up thread ${this.threadId}`),this.inactivityTimeout&&(clearTimeout(this.inactivityTimeout),this.inactivityTimeout=void 0);for(let e of this.connections)try{e.end()}catch(t){ue("THREAD_CODAY","Error closing connection:",t)}if(this.connections.clear(),this.coday){let e=this.coday.context?.aiThread,t=this.coday.aiClientProvider,n=t?.getClient(void 0,"SMALL")??t?.getClient(void 0);e&&n?new pT(n,this.threadService).process(e,this.projectName):ue("THREAD_CODAY",`Skipping post-processing for thread ${this.threadId}: no thread or AI client`)}if(this.coday){try{await this.coday.kill()}catch(e){ue("THREAD_CODAY","Error during Coday kill:",e)}this.coday=void 0}}},hT=class r{constructor(e,t,n,i,a){this.logger=e;this.projectService=t;this.threadService=n;this.promptService=i;this.mcpPool=a;this.heartbeatInterval=setInterval(()=>this.sendHeartbeats(),r.HEARTBEAT_INTERVAL),ue("THREAD_CODAY_MANAGER","Heartbeat mechanism started")}instances=new Map;heartbeatInterval;static HEARTBEAT_INTERVAL=3e4;sendHeartbeats(){for(let e of this.instances.values())e.connectionCount>0&&e.sendHeartbeat()}handleInstanceTimeout=async e=>{ue("THREAD_CODAY_MANAGER",`Handling timeout for thread ${e}`),await this.cleanup(e)};getOrCreate(e,t,n,i,a){let o=this.instances.get(e);return o?ue("THREAD_CODAY",`Reusing existing instance for thread ${e}`):(ue("THREAD_CODAY",`Creating new instance for thread ${e}`),o=new dT(e,t,n,i,this.logger,this.projectService,this.threadService,this.promptService,this.mcpPool,this.handleInstanceTimeout),this.instances.set(e,o)),o.addConnection(a),o}createWithoutConnection(e,t,n,i){let a=this.instances.get(e);return a?ue("THREAD_CODAY",`Reusing existing instance for thread ${e}`):(ue("THREAD_CODAY",`Creating new instance for thread ${e} (no SSE connection)`),a=new dT(e,t,n,i,this.logger,this.projectService,this.threadService,this.promptService,this.mcpPool,this.handleInstanceTimeout),a.markAsOneshot(),this.instances.set(e,a)),a}get(e){return this.instances.get(e)}removeConnection(e,t){let n=this.instances.get(e);n&&(n.removeConnection(t),n.connectionCount===0&&ue("THREAD_CODAY",`Thread ${e} has no active connections but instance kept alive`))}stop(e){let t=this.instances.get(e);t&&t.stop()}async cleanup(e){let t=this.instances.get(e);t&&(await this.mcpPool.releaseThread(e),await t.cleanup(),this.instances.delete(e),ue("THREAD_CODAY",`Removed instance for thread ${e}`))}getStats(){let e=0,t=0;for(let n of this.instances.values())n.connectionCount>0&&e++,n.isOneshot&&t++;return{total:this.instances.size,withConnections:e,oneshot:t}}async shutdown(){ue("THREAD_CODAY_MANAGER",`Shutting down ${this.instances.size} thread instances`),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),ue("THREAD_CODAY_MANAGER","Heartbeat mechanism stopped"));let e=[];for(let[t,n]of this.instances.entries())ue("THREAD_CODAY_MANAGER",`Cleaning up thread ${t}`),e.push(n.cleanup());await Promise.all(e),this.instances.clear(),await this.mcpPool.shutdown(),ue("THREAD_CODAY_MANAGER","All thread instances cleaned up")}};async function I7e(r,e=100){let t=await import("node:net");return new Promise((n,i)=>{function a(o,s){let c=t.createServer();c.listen(o,()=>{c.close(()=>{ue("PORT",`Port ${o} is available`),n(o)})}),c.on("error",u=>{u.code==="EADDRINUSE"?s>0?(ue("PORT",`Port ${o} is in use, trying next`),a(o+1,s-1)):i(new Error(`Could not find an available port starting from ${r}`)):i(u)})}a(r,e)})}function O7e(r,e,t){r.get("/api/config/user",(n,i)=>{try{let a=t(n);if(!a){i.status(401).json({error:"Username not found in request headers"});return}ue("CONFIG",`GET user config for: ${a}`);let c={...e.getUserService(a).getConfigForClient(),username:a};i.status(200).json(c)}catch(a){console.error("Error retrieving user config:",a),i.status(500).json({error:"Failed to retrieve user configuration"})}}),r.put("/api/config/user",(n,i)=>{try{let a=t(n);if(!a){i.status(401).json({error:"Username not found in request headers"});return}let o=n.body;if(!o||typeof o!="object"){i.status(422).json({error:"Invalid configuration format"});return}if(typeof o.version!="number"){i.status(422).json({error:"Configuration must have a version number"});return}ue("CONFIG",`PUT user config for: ${a}`),e.getUserService(a).updateConfigFromClient(o),i.status(200).json({success:!0,message:"User configuration updated successfully"})}catch(a){console.error("Error updating user config:",a);let o=a instanceof Error?a.message:"Unknown error";i.status(500).json({error:`Failed to update user configuration: ${o}`})}})}function je(r){return Array.isArray(r)?r[0]||"":r||""}function $7e(r,e){r.get("/api/projects",(t,n)=>{try{ue("PROJECT","GET all projects");let i=e.listProjects(),a=e.getDefaultProject(),o=e.getForcedMode();n.status(200).json({projects:i,defaultProject:a,forcedProject:o?a:null})}catch(i){console.error("Error listing projects:",i),n.status(500).json({error:"Failed to list projects"})}}),r.get("/api/projects/:name",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`GET project: ${i}`);let a=e.getProject(i);if(!a){n.status(404).json({error:`Project '${i}' not found`});return}n.status(200).json(a)}catch(i){console.error("Error retrieving project:",i),n.status(500).json({error:"Failed to retrieve project"})}}),r.post("/api/projects",(t,n)=>{try{let{name:i,path:a}=t.body;if(!i||!a){n.status(400).json({error:"Project name and path are required"});return}ue("PROJECT",`POST create project: ${i} at ${a}`),e.createProject(i,a),n.status(201).json({success:!0,message:`Project '${i}' created successfully`})}catch(i){console.error("Error creating project:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to create project: ${a}`})}}),r.get("/api/projects/:name/config",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`GET project config: ${i}`);let a=e.getProjectConfigForClient(i);if(!a){n.status(404).json({error:`Project '${i}' not found`});return}n.status(200).json(a)}catch(i){console.error("Error retrieving project config:",i),n.status(500).json({error:"Failed to retrieve project configuration"})}}),r.put("/api/projects/:name/config",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}let a=t.body;if(!a||typeof a!="object"){n.status(422).json({error:"Invalid configuration format"});return}if(typeof a.version!="number"){n.status(422).json({error:"Configuration must have a version number"});return}if(!a.path||typeof a.path!="string"){n.status(422).json({error:"Configuration must have a valid path"});return}ue("PROJECT",`PUT project config: ${i}`),e.updateProjectConfigFromClient(i,a),n.status(200).json({success:!0,message:"Project configuration updated successfully"})}catch(i){console.error("Error updating project config:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to update project configuration: ${a}`})}}),r.delete("/api/projects/:name",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`DELETE project: ${i}`),e.deleteProject(i),n.status(200).json({success:!0,message:`Project '${i}' deleted successfully`})}catch(i){console.error("Error deleting project:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to delete project: ${a}`})}})}import{existsSync as Y9t,readFileSync as X9t}from"fs";function j7e(r,e,t,n,i,a){r.get("/api/projects/:projectName/threads",async(o,s)=>{try{let c=je(o.params.projectName);if(!c){s.status(400).json({error:"Project name is required"});return}let u=i(o);if(!u){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET threads for project: ${c}, user: ${u}`);let l=await e.listThreads(c,u);s.status(200).json(l)}catch(c){console.error("Error listing threads:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to list threads: ${u}`})}}),r.post("/api/projects/:projectName/threads",async(o,s)=>{try{let c=je(o.params.projectName);if(!c){s.status(400).json({error:"Project name is required"});return}let u=i(o);if(!u){s.status(401).json({error:"Authentication required"});return}let{name:l}=o.body;ue("THREAD",`POST create thread in project: ${c}, user: ${u}, name: ${l||"untitled"}`);let f=await e.createThread(c,u,l);s.status(201).json({success:!0,thread:{id:f.id,name:f.name,projectId:f.projectId,username:f.username,createdDate:f.createdDate,modifiedDate:f.modifiedDate}})}catch(c){console.error("Error creating thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to create thread: ${u}`})}}),r.get("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET thread: ${u} from project: ${c}`);let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}s.status(200).json({id:f.id,name:f.name,projectId:f.projectId,username:f.username,summary:f.summary,createdDate:f.createdDate,modifiedDate:f.modifiedDate,price:f.price,messageCount:f.messagesLength,users:f.users})}catch(c){console.error("Error retrieving thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to retrieve thread: ${u}`})}}),r.put("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let{name:f,users:p}=o.body,d=await e.getThread(c,u);if(!d){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(d,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}let m;if(p!==void 0){if(!rn(d,l)){s.status(403).json({error:"Access denied: only thread participants can modify the users list"});return}if(!Array.isArray(p)){s.status(400).json({error:"Invalid users format: must be an array"});return}for(let g of p)if(!g||typeof g.userId!="string"||g.userId.trim()===""){s.status(400).json({error:"Invalid users format: each user must have a non-empty userId string"});return}m=p}ue("THREAD",`PUT update thread: ${u} in project: ${c}`);let h=await e.updateThread(c,u,{name:f,users:m});if(m!==void 0){let v=n.get(u)?.coday?.context?.aiThread;v&&(v.users=m,ue("THREAD",`Synced users to live AiThread for thread ${u}`))}s.status(200).json({success:!0,thread:{id:h.id,name:h.name,projectId:h.projectId,modifiedDate:h.modifiedDate}})}catch(c){console.error("Error updating thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to update thread: ${u}`})}}),r.get("/api/projects/:projectName/threads/:threadId/messages",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET messages for thread: ${u} in project: ${c}`);let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}let{messages:p}=await f.getMessages(void 0,void 0);s.status(200).json({messages:p})}catch(c){console.error("Error retrieving thread messages:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to retrieve thread messages: ${u}`})}}),r.post("/api/projects/:projectName/threads/:threadId/star",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}if(!await e.getThread(c,u)){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}ue("THREAD",`POST star thread: ${u} in project: ${c} by user: ${l}`);let p=await e.starThread(c,u,l);s.status(200).json({success:!0,thread:{id:p.id,starring:p.starring,modifiedDate:p.modifiedDate}})}catch(c){console.error("Error starring thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to star thread: ${u}`})}}),r.delete("/api/projects/:projectName/threads/:threadId/star",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}if(!await e.getThread(c,u)){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}ue("THREAD",`DELETE unstar thread: ${u} in project: ${c} by user: ${l}`);let p=await e.unstarThread(c,u,l);s.status(200).json({success:!0,thread:{id:p.id,starring:p.starring,modifiedDate:p.modifiedDate}})}catch(c){console.error("Error unstarring thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to unstar thread: ${u}`})}}),r.post("/api/projects/:projectName/threads/:threadId/stop",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}ue("THREAD",`POST stop thread: ${u} in project: ${c}`),n.stop(u),s.status(200).json({success:!0,message:"Stop signal sent successfully"})}catch(c){console.error("Error stopping thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to stop thread: ${u}`})}}),r.delete("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}ue("THREAD",`DELETE
|
|
1420
|
+
`;for(let n of this.connections)try{n.writableEnded?this.connections.delete(n):n.write(t)}catch(i){ue("THREAD_CODAY","Error broadcasting to connection:",i),this.connections.delete(n)}}stop(){this.coday?.stop()}async handleOAuthCallback(e){if(!this.coday){ue("THREAD_CODAY",`Cannot handle OAuth callback: Coday not initialized for thread ${this.threadId}`);return}if(!this.coday.services.agent){ue("THREAD_CODAY","Cannot handle OAuth callback: Agent service not initialized");return}let n=this.coday.services.agent?.toolbox;if(!n){ue("THREAD_CODAY","Cannot handle OAuth callback: Toolbox not initialized");return}ue("THREAD_CODAY",`Routing OAuth callback for ${e.integrationName}`),await n.handleOAuthCallback(e)}async cleanup(){ue("THREAD_CODAY",`Cleaning up thread ${this.threadId}`),this.inactivityTimeout&&(clearTimeout(this.inactivityTimeout),this.inactivityTimeout=void 0);for(let e of this.connections)try{e.end()}catch(t){ue("THREAD_CODAY","Error closing connection:",t)}if(this.connections.clear(),this.coday){let e=this.coday.context?.aiThread,t=this.coday.aiClientProvider,n=t?.getClient(void 0,"SMALL")??t?.getClient(void 0);e&&n?new pT(n,this.threadService).process(e,this.projectName):ue("THREAD_CODAY",`Skipping post-processing for thread ${this.threadId}: no thread or AI client`)}if(this.coday){try{await this.coday.kill()}catch(e){ue("THREAD_CODAY","Error during Coday kill:",e)}this.coday=void 0}}},hT=class r{constructor(e,t,n,i,a){this.logger=e;this.projectService=t;this.threadService=n;this.promptService=i;this.mcpPool=a;this.heartbeatInterval=setInterval(()=>this.sendHeartbeats(),r.HEARTBEAT_INTERVAL),ue("THREAD_CODAY_MANAGER","Heartbeat mechanism started")}instances=new Map;heartbeatInterval;static HEARTBEAT_INTERVAL=3e4;sendHeartbeats(){for(let e of this.instances.values())e.connectionCount>0&&e.sendHeartbeat()}handleInstanceTimeout=async e=>{ue("THREAD_CODAY_MANAGER",`Handling timeout for thread ${e}`),await this.cleanup(e)};getOrCreate(e,t,n,i,a){let o=this.instances.get(e);return o?ue("THREAD_CODAY",`Reusing existing instance for thread ${e}`):(ue("THREAD_CODAY",`Creating new instance for thread ${e}`),o=new dT(e,t,n,i,this.logger,this.projectService,this.threadService,this.promptService,this.mcpPool,this.handleInstanceTimeout),this.instances.set(e,o)),o.addConnection(a),o}createWithoutConnection(e,t,n,i){let a=this.instances.get(e);return a?ue("THREAD_CODAY",`Reusing existing instance for thread ${e}`):(ue("THREAD_CODAY",`Creating new instance for thread ${e} (no SSE connection)`),a=new dT(e,t,n,i,this.logger,this.projectService,this.threadService,this.promptService,this.mcpPool,this.handleInstanceTimeout),a.markAsOneshot(),this.instances.set(e,a)),a}get(e){return this.instances.get(e)}removeConnection(e,t){let n=this.instances.get(e);n&&(n.removeConnection(t),n.connectionCount===0&&ue("THREAD_CODAY",`Thread ${e} has no active connections but instance kept alive`))}stop(e){let t=this.instances.get(e);t&&t.stop()}async cleanup(e){let t=this.instances.get(e);t&&(await t.cleanup(),await this.mcpPool.releaseThread(e),this.instances.delete(e),ue("THREAD_CODAY",`Removed instance for thread ${e}`))}getStats(){let e=0,t=0;for(let n of this.instances.values())n.connectionCount>0&&e++,n.isOneshot&&t++;return{total:this.instances.size,withConnections:e,oneshot:t}}async shutdown(){ue("THREAD_CODAY_MANAGER",`Shutting down ${this.instances.size} thread instances`),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),ue("THREAD_CODAY_MANAGER","Heartbeat mechanism stopped"));let e=[];for(let[t,n]of this.instances.entries())ue("THREAD_CODAY_MANAGER",`Cleaning up thread ${t}`),e.push(n.cleanup().then(()=>this.mcpPool.releaseThread(t)).catch(i=>{ue("THREAD_CODAY_MANAGER",`Error cleaning up thread ${t}:`,i)}));await Promise.all(e),this.instances.clear(),await this.mcpPool.shutdown(),ue("THREAD_CODAY_MANAGER","All thread instances cleaned up")}};async function I7e(r,e=100){let t=await import("node:net");return new Promise((n,i)=>{function a(o,s){let c=t.createServer();c.listen(o,()=>{c.close(()=>{ue("PORT",`Port ${o} is available`),n(o)})}),c.on("error",u=>{u.code==="EADDRINUSE"?s>0?(ue("PORT",`Port ${o} is in use, trying next`),a(o+1,s-1)):i(new Error(`Could not find an available port starting from ${r}`)):i(u)})}a(r,e)})}function O7e(r,e,t){r.get("/api/config/user",(n,i)=>{try{let a=t(n);if(!a){i.status(401).json({error:"Username not found in request headers"});return}ue("CONFIG",`GET user config for: ${a}`);let c={...e.getUserService(a).getConfigForClient(),username:a};i.status(200).json(c)}catch(a){console.error("Error retrieving user config:",a),i.status(500).json({error:"Failed to retrieve user configuration"})}}),r.put("/api/config/user",(n,i)=>{try{let a=t(n);if(!a){i.status(401).json({error:"Username not found in request headers"});return}let o=n.body;if(!o||typeof o!="object"){i.status(422).json({error:"Invalid configuration format"});return}if(typeof o.version!="number"){i.status(422).json({error:"Configuration must have a version number"});return}ue("CONFIG",`PUT user config for: ${a}`),e.getUserService(a).updateConfigFromClient(o),i.status(200).json({success:!0,message:"User configuration updated successfully"})}catch(a){console.error("Error updating user config:",a);let o=a instanceof Error?a.message:"Unknown error";i.status(500).json({error:`Failed to update user configuration: ${o}`})}})}function je(r){return Array.isArray(r)?r[0]||"":r||""}function $7e(r,e){r.get("/api/projects",(t,n)=>{try{ue("PROJECT","GET all projects");let i=e.listProjects(),a=e.getDefaultProject(),o=e.getForcedMode();n.status(200).json({projects:i,defaultProject:a,forcedProject:o?a:null})}catch(i){console.error("Error listing projects:",i),n.status(500).json({error:"Failed to list projects"})}}),r.get("/api/projects/:name",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`GET project: ${i}`);let a=e.getProject(i);if(!a){n.status(404).json({error:`Project '${i}' not found`});return}n.status(200).json(a)}catch(i){console.error("Error retrieving project:",i),n.status(500).json({error:"Failed to retrieve project"})}}),r.post("/api/projects",(t,n)=>{try{let{name:i,path:a}=t.body;if(!i||!a){n.status(400).json({error:"Project name and path are required"});return}ue("PROJECT",`POST create project: ${i} at ${a}`),e.createProject(i,a),n.status(201).json({success:!0,message:`Project '${i}' created successfully`})}catch(i){console.error("Error creating project:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to create project: ${a}`})}}),r.get("/api/projects/:name/config",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`GET project config: ${i}`);let a=e.getProjectConfigForClient(i);if(!a){n.status(404).json({error:`Project '${i}' not found`});return}n.status(200).json(a)}catch(i){console.error("Error retrieving project config:",i),n.status(500).json({error:"Failed to retrieve project configuration"})}}),r.put("/api/projects/:name/config",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}let a=t.body;if(!a||typeof a!="object"){n.status(422).json({error:"Invalid configuration format"});return}if(typeof a.version!="number"){n.status(422).json({error:"Configuration must have a version number"});return}if(!a.path||typeof a.path!="string"){n.status(422).json({error:"Configuration must have a valid path"});return}ue("PROJECT",`PUT project config: ${i}`),e.updateProjectConfigFromClient(i,a),n.status(200).json({success:!0,message:"Project configuration updated successfully"})}catch(i){console.error("Error updating project config:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to update project configuration: ${a}`})}}),r.delete("/api/projects/:name",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`DELETE project: ${i}`),e.deleteProject(i),n.status(200).json({success:!0,message:`Project '${i}' deleted successfully`})}catch(i){console.error("Error deleting project:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to delete project: ${a}`})}})}import{existsSync as Y9t,readFileSync as X9t}from"fs";function j7e(r,e,t,n,i,a){r.get("/api/projects/:projectName/threads",async(o,s)=>{try{let c=je(o.params.projectName);if(!c){s.status(400).json({error:"Project name is required"});return}let u=i(o);if(!u){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET threads for project: ${c}, user: ${u}`);let l=await e.listThreads(c,u);s.status(200).json(l)}catch(c){console.error("Error listing threads:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to list threads: ${u}`})}}),r.post("/api/projects/:projectName/threads",async(o,s)=>{try{let c=je(o.params.projectName);if(!c){s.status(400).json({error:"Project name is required"});return}let u=i(o);if(!u){s.status(401).json({error:"Authentication required"});return}let{name:l}=o.body;ue("THREAD",`POST create thread in project: ${c}, user: ${u}, name: ${l||"untitled"}`);let f=await e.createThread(c,u,l);s.status(201).json({success:!0,thread:{id:f.id,name:f.name,projectId:f.projectId,username:f.username,createdDate:f.createdDate,modifiedDate:f.modifiedDate}})}catch(c){console.error("Error creating thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to create thread: ${u}`})}}),r.get("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET thread: ${u} from project: ${c}`);let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}s.status(200).json({id:f.id,name:f.name,projectId:f.projectId,username:f.username,summary:f.summary,createdDate:f.createdDate,modifiedDate:f.modifiedDate,price:f.price,messageCount:f.messagesLength,users:f.users})}catch(c){console.error("Error retrieving thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to retrieve thread: ${u}`})}}),r.put("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let{name:f,users:p}=o.body,d=await e.getThread(c,u);if(!d){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(d,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}let m;if(p!==void 0){if(!rn(d,l)){s.status(403).json({error:"Access denied: only thread participants can modify the users list"});return}if(!Array.isArray(p)){s.status(400).json({error:"Invalid users format: must be an array"});return}for(let g of p)if(!g||typeof g.userId!="string"||g.userId.trim()===""){s.status(400).json({error:"Invalid users format: each user must have a non-empty userId string"});return}m=p}ue("THREAD",`PUT update thread: ${u} in project: ${c}`);let h=await e.updateThread(c,u,{name:f,users:m});if(m!==void 0){let v=n.get(u)?.coday?.context?.aiThread;v&&(v.users=m,ue("THREAD",`Synced users to live AiThread for thread ${u}`))}s.status(200).json({success:!0,thread:{id:h.id,name:h.name,projectId:h.projectId,modifiedDate:h.modifiedDate}})}catch(c){console.error("Error updating thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to update thread: ${u}`})}}),r.get("/api/projects/:projectName/threads/:threadId/messages",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET messages for thread: ${u} in project: ${c}`);let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}let{messages:p}=await f.getMessages(void 0,void 0);s.status(200).json({messages:p})}catch(c){console.error("Error retrieving thread messages:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to retrieve thread messages: ${u}`})}}),r.post("/api/projects/:projectName/threads/:threadId/star",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}if(!await e.getThread(c,u)){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}ue("THREAD",`POST star thread: ${u} in project: ${c} by user: ${l}`);let p=await e.starThread(c,u,l);s.status(200).json({success:!0,thread:{id:p.id,starring:p.starring,modifiedDate:p.modifiedDate}})}catch(c){console.error("Error starring thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to star thread: ${u}`})}}),r.delete("/api/projects/:projectName/threads/:threadId/star",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}if(!await e.getThread(c,u)){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}ue("THREAD",`DELETE unstar thread: ${u} in project: ${c} by user: ${l}`);let p=await e.unstarThread(c,u,l);s.status(200).json({success:!0,thread:{id:p.id,starring:p.starring,modifiedDate:p.modifiedDate}})}catch(c){console.error("Error unstarring thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to unstar thread: ${u}`})}}),r.post("/api/projects/:projectName/threads/:threadId/stop",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}ue("THREAD",`POST stop thread: ${u} in project: ${c}`),n.stop(u),s.status(200).json({success:!0,message:"Stop signal sent successfully"})}catch(c){console.error("Error stopping thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to stop thread: ${u}`})}}),r.delete("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}ue("THREAD",`DELETE
|
|
1421
1421
|
thread:
|
|
1422
1422
|
${u}
|
|
1423
1423
|
from
|