qlogicagent 2.16.10 → 2.17.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/dist/cli.js CHANGED
@@ -680,7 +680,7 @@ ${e}
680
680
 
681
681
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let l=t.external.registry.get(s[0])?.id;if(e!==s[0]&&l){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&t.reused==="ref"){i(s);continue}}}function wi(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,d={...l},p=c.ref;if(c.ref=null,p){r(p);let f=t.seen.get(p),g=f.schema;if(g.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(g)):Object.assign(l,g),Object.assign(l,d),a._zod.parent===p)for(let y in l)y==="$ref"||y==="allOf"||y in d||delete l[y];if(g.$ref&&f.def)for(let y in l)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(l[y])===JSON.stringify(f.def[y])&&delete l[y]}let m=a._zod.parent;if(m&&m!==p){r(m);let f=t.seen.get(m);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(let g in l)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(l[g])===JSON.stringify(f.def[g])&&delete l[g]}t.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&o.id===i&&delete o.id;let s=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,s[c.defId]=c.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:oc(e,"input",t.processors),output:oc(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Yt(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Yt(r.element,n);if(r.type==="set")return Yt(r.valueType,n);if(r.type==="lazy")return Yt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Yt(r.innerType,n);if(r.type==="intersection")return Yt(r.left,n)||Yt(r.right,n);if(r.type==="record"||r.type==="map")return Yt(r.keyType,n)||Yt(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Yt(r.in,n)||Yt(r.out,n);if(r.type==="object"){for(let o in r.shape)if(Yt(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(Yt(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(Yt(o,n))return!0;return!!(r.rest&&Yt(r.rest,n))}return!1}var hT=(t,e={})=>n=>{let r=vi({...n,processors:e});return Ae(t,r),ki(r,t),wi(r,t)},oc=(t,e,n={})=>r=>{let{libraryOptions:o,target:i}=r??{},s=vi({...o??{},target:i,io:e,processors:n});return Ae(t,s),ki(s,t),wi(s,t)};var mse={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yT=(t,e,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:l}=t._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=mse[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),l&&(o.contentEncoding=l),c&&c.size>0){let d=[...c];d.length===1?o.pattern=d[0].source:d.length>1&&(o.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},bT=(t,e,n,r)=>{let o=n,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let p=typeof d=="number"&&d>=(i??Number.NEGATIVE_INFINITY),m=typeof l=="number"&&l<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";p?f?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof i=="number"&&(o.minimum=i),m?f?(o.maximum=l,o.exclusiveMaximum=!0):o.exclusiveMaximum=l:typeof s=="number"&&(o.maximum=s),typeof c=="number"&&(o.multipleOf=c)},vT=(t,e,n,r)=>{n.type="boolean"},kT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},wT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},ST=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},xT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},RT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},TT=(t,e,n,r)=>{n.not={}},PT=(t,e,n,r)=>{},AT=(t,e,n,r)=>{},IT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},_T=(t,e,n,r)=>{let o=t._zod.def,i=id(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},CT=(t,e,n,r)=>{let o=t._zod.def,i=[];for(let s of o.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];n.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},ET=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},MT=(t,e,n,r)=>{let o=n,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},DT=(t,e,n,r)=>{let o=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=t._zod.bag;s!==void 0&&(i.minLength=s),a!==void 0&&(i.maxLength=a),c?c.length===1?(i.contentMediaType=c[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(o,i)},$T=(t,e,n,r)=>{n.type="boolean"},NT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},OT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},jT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},LT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},UT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},FT=(t,e,n,r)=>{let o=n,i=t._zod.def,{minimum:s,maximum:a}=t._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=Ae(i.element,e,{...r,path:[...r.path,"items"]})},HT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="object",o.properties={};let s=i.shape;for(let l in s)o.properties[l]=Ae(s[l],e,{...r,path:[...r.path,"properties",l]});let a=new Set(Object.keys(s)),c=new Set([...a].filter(l=>{let d=i.shape[l]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Ae(i.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Df=(t,e,n,r)=>{let o=t._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>Ae(a,e,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=s:n.anyOf=s},zT=(t,e,n,r)=>{let o=t._zod.def,i=Ae(o.left,e,{...r,path:[...r.path,"allOf",0]}),s=Ae(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=l=>"allOf"in l&&Object.keys(l).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c},BT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,f)=>Ae(m,e,{...r,path:[...r.path,s,f]})),l=i.rest?Ae(i.rest,e,{...r,path:[...r.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null;e.target==="draft-2020-12"?(o.prefixItems=c,l&&(o.items=l)):e.target==="openapi-3.0"?(o.items={anyOf:c},l&&o.items.anyOf.push(l),o.minItems=c.length,l||(o.maxItems=c.length)):(o.items=c,l&&(o.additionalItems=l));let{minimum:d,maximum:p}=t._zod.bag;typeof d=="number"&&(o.minItems=d),typeof p=="number"&&(o.maxItems=p)},qT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=Ae(i.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let p of c)o.patternProperties[p.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=Ae(i.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Ae(i.valueType,e,{...r,path:[...r.path,"additionalProperties"]});let l=s._zod.values;if(l){let d=[...l].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(o.required=d)}},WT=(t,e,n,r)=>{let o=t._zod.def,i=Ae(o.innerType,e,r),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},GT=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},KT=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},VT=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},JT=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},ZT=(t,e,n,r)=>{let o=t._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?o.out:o.in:o.out;Ae(s,e,r);let a=e.seen.get(t);a.ref=s},XT=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,n.readOnly=!0},YT=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},$f=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},QT=(t,e,n,r)=>{let o=t._zod.innerType;Ae(o,e,r);let i=e.seen.get(t);i.ref=o},Mf={string:yT,number:bT,boolean:vT,bigint:kT,symbol:wT,null:ST,undefined:xT,void:RT,never:TT,any:PT,unknown:AT,date:IT,enum:_T,literal:CT,nan:ET,template_literal:MT,file:DT,success:$T,custom:NT,function:OT,transform:jT,map:LT,set:UT,array:FT,object:HT,union:Df,intersection:zT,tuple:BT,record:qT,nullable:WT,nonoptional:GT,default:KT,prefault:VT,catch:JT,pipe:ZT,readonly:XT,promise:YT,optional:$f,lazy:QT};function Nf(t,e){if("_idmap"in t){let r=t,o=vi({...e,processors:Mf}),i={};for(let c of r._idmap.entries()){let[l,d]=c;Ae(d,o)}let s={},a={registry:r,uri:e?.uri,defs:i};o.external=a;for(let c of r._idmap.entries()){let[l,d]=c;ki(o,d),s[l]=wi(o,d)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let n=vi({...e,processors:Mf});return Ae(t,n),ki(n,t),wi(n,t)}var Of=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let n=e?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=vi({processors:Mf,target:n,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,n={path:[],schemaPath:[]}){return Ae(e,this.ctx,n)}emit(e,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),ki(this.ctx,e);let r=wi(this.ctx,e),{"~standard":o,...i}=r;return i}};var Lj={};var xd={};sn(xd,{ZodAny:()=>xP,ZodArray:()=>AP,ZodBase64:()=>rg,ZodBase64URL:()=>og,ZodBigInt:()=>pc,ZodBigIntFormat:()=>ag,ZodBoolean:()=>uc,ZodCIDRv4:()=>tg,ZodCIDRv6:()=>ng,ZodCUID:()=>Vf,ZodCUID2:()=>Jf,ZodCatch:()=>JP,ZodCodec:()=>Nd,ZodCustom:()=>Od,ZodCustomStringFormat:()=>lc,ZodDate:()=>Cd,ZodDefault:()=>BP,ZodDiscriminatedUnion:()=>_P,ZodE164:()=>ig,ZodEmail:()=>Wf,ZodEmoji:()=>Gf,ZodEnum:()=>ac,ZodExactOptional:()=>FP,ZodFile:()=>LP,ZodFunction:()=>iA,ZodGUID:()=>Td,ZodIPv4:()=>Qf,ZodIPv6:()=>eg,ZodIntersection:()=>CP,ZodJWT:()=>sg,ZodKSUID:()=>Yf,ZodLazy:()=>nA,ZodLiteral:()=>jP,ZodMAC:()=>hP,ZodMap:()=>NP,ZodNaN:()=>XP,ZodNanoID:()=>Kf,ZodNever:()=>TP,ZodNonOptional:()=>mg,ZodNull:()=>wP,ZodNullable:()=>zP,ZodNumber:()=>dc,ZodNumberFormat:()=>js,ZodObject:()=>Md,ZodOptional:()=>pg,ZodPipe:()=>$d,ZodPrefault:()=>WP,ZodPreprocess:()=>YP,ZodPromise:()=>oA,ZodReadonly:()=>QP,ZodRecord:()=>sc,ZodSet:()=>OP,ZodString:()=>cc,ZodStringFormat:()=>$e,ZodSuccess:()=>VP,ZodSymbol:()=>vP,ZodTemplateLiteral:()=>tA,ZodTransform:()=>UP,ZodTuple:()=>MP,ZodType:()=>ue,ZodULID:()=>Zf,ZodURL:()=>_d,ZodUUID:()=>Kr,ZodUndefined:()=>kP,ZodUnion:()=>Dd,ZodUnknown:()=>RP,ZodVoid:()=>PP,ZodXID:()=>Xf,ZodXor:()=>IP,_ZodString:()=>qf,_default:()=>qP,_function:()=>KL,any:()=>RL,array:()=>Ed,base64:()=>aL,base64url:()=>cL,bigint:()=>vL,boolean:()=>bP,catch:()=>ZP,check:()=>VL,cidrv4:()=>iL,cidrv6:()=>sL,codec:()=>BL,cuid:()=>Xj,cuid2:()=>Yj,custom:()=>JL,date:()=>PL,describe:()=>ZL,discriminatedUnion:()=>ML,e164:()=>lL,email:()=>Hj,emoji:()=>Jj,enum:()=>dg,exactOptional:()=>HP,file:()=>UL,float32:()=>gL,float64:()=>hL,function:()=>KL,guid:()=>zj,hash:()=>fL,hex:()=>mL,hostname:()=>pL,httpUrl:()=>Vj,instanceof:()=>YL,int:()=>zf,int32:()=>yL,int64:()=>kL,intersection:()=>EP,invertCodec:()=>qL,ipv4:()=>nL,ipv6:()=>oL,json:()=>eU,jwt:()=>dL,keyof:()=>AL,ksuid:()=>tL,lazy:()=>rA,literal:()=>LL,looseObject:()=>CL,looseRecord:()=>$L,mac:()=>rL,map:()=>NL,meta:()=>XL,nan:()=>zL,nanoid:()=>Zj,nativeEnum:()=>jL,never:()=>cg,nonoptional:()=>KP,null:()=>SP,nullable:()=>Ad,nullish:()=>FL,number:()=>yP,object:()=>IL,optional:()=>Pd,partialRecord:()=>DL,pipe:()=>Bf,prefault:()=>GP,preprocess:()=>tU,promise:()=>GL,readonly:()=>eA,record:()=>$P,refine:()=>sA,set:()=>OL,strictObject:()=>_L,string:()=>Rd,stringFormat:()=>uL,stringbool:()=>QL,success:()=>HL,superRefine:()=>aA,symbol:()=>SL,templateLiteral:()=>WL,transform:()=>ug,tuple:()=>DP,uint32:()=>bL,uint64:()=>wL,ulid:()=>Qj,undefined:()=>xL,union:()=>lg,unknown:()=>Os,url:()=>Kj,uuid:()=>Bj,uuidv4:()=>qj,uuidv6:()=>Wj,uuidv7:()=>Gj,void:()=>TL,xid:()=>eL,xor:()=>EL});var jf={};sn(jf,{endsWith:()=>Za,gt:()=>Wr,gte:()=>Xt,includes:()=>Va,length:()=>Ns,lowercase:()=>Ga,lt:()=>qr,lte:()=>jn,maxLength:()=>$s,maxSize:()=>bi,mime:()=>Xa,minLength:()=>Po,minSize:()=>Gr,multipleOf:()=>yi,negative:()=>If,nonnegative:()=>Cf,nonpositive:()=>_f,normalize:()=>Ya,overwrite:()=>br,positive:()=>Af,property:()=>Ef,regex:()=>Wa,size:()=>Ds,slugify:()=>nc,startsWith:()=>Ja,toLowerCase:()=>ec,toUpperCase:()=>tc,trim:()=>Qa,uppercase:()=>Ka});var ic={};sn(ic,{ZodISODate:()=>Uf,ZodISODateTime:()=>Lf,ZodISODuration:()=>Hf,ZodISOTime:()=>Ff,date:()=>tP,datetime:()=>eP,duration:()=>rP,time:()=>nP});var Lf=A("ZodISODateTime",(t,e)=>{Ex.init(t,e),$e.init(t,e)});function eP(t){return NR(Lf,t)}var Uf=A("ZodISODate",(t,e)=>{Mx.init(t,e),$e.init(t,e)});function tP(t){return OR(Uf,t)}var Ff=A("ZodISOTime",(t,e)=>{Dx.init(t,e),$e.init(t,e)});function nP(t){return jR(Ff,t)}var Hf=A("ZodISODuration",(t,e)=>{$x.init(t,e),$e.init(t,e)});function rP(t){return LR(Hf,t)}var Uj=(t,e)=>{dd.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>pd(t,n)},flatten:{value:n=>ud(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Oa,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Oa,2)}},isEmpty:{get(){return t.issues.length===0}}})},gse=A("ZodError",Uj),mn=A("ZodError",Uj,{Parent:Error});var oP=Ua(mn),iP=Fa(mn),sP=Ha(mn),aP=za(mn),cP=$m(mn),lP=Nm(mn),dP=Om(mn),uP=jm(mn),pP=Lm(mn),mP=Um(mn),fP=Fm(mn),gP=Hm(mn);var Fj=new WeakMap;function Id(t,e,n){let r=Object.getPrototypeOf(t),o=Fj.get(r);if(o||(o=new Set,Fj.set(r,o)),!o.has(e)){o.add(e);for(let i in n){let s=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var ue=A("ZodType",(t,e)=>(oe.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:oc(t,"input"),output:oc(t,"output")}}),t.toJSONSchema=hT(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>oP(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>sP(t,n,r),t.parseAsync=async(n,r)=>iP(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>aP(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>cP(t,n,r),t.decode=(n,r)=>lP(t,n,r),t.encodeAsync=async(n,r)=>dP(t,n,r),t.decodeAsync=async(n,r)=>uP(t,n,r),t.safeEncode=(n,r)=>pP(t,n,r),t.safeDecode=(n,r)=>mP(t,n,r),t.safeEncodeAsync=async(n,r)=>fP(t,n,r),t.safeDecodeAsync=async(n,r)=>gP(t,n,r),Id(t,"ZodType",{check(...n){let r=this.def;return this.clone(H.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Jt(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(sA(n,r))},superRefine(n,r){return this.check(aA(n,r))},overwrite(n){return this.check(br(n))},optional(){return Pd(this)},exactOptional(){return HP(this)},nullable(){return Ad(this)},nullish(){return Pd(Ad(this))},nonoptional(n){return KP(this,n)},array(){return Ed(this)},or(n){return lg([this,n])},and(n){return EP(this,n)},transform(n){return Bf(this,ug(n))},default(n){return qP(this,n)},prefault(n){return GP(this,n)},catch(n){return ZP(this,n)},pipe(n){return Bf(this,n)},readonly(){return eA(this)},describe(n){let r=this.clone();return _t.add(r,{description:n}),r},meta(...n){if(n.length===0)return _t.get(this);let r=this.clone();return _t.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return _t.get(t)?.description},configurable:!0}),t)),qf=A("_ZodString",(t,e)=>{Ms.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>yT(t,r,o,i);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,Id(t,"_ZodString",{regex(...r){return this.check(Wa(...r))},includes(...r){return this.check(Va(...r))},startsWith(...r){return this.check(Ja(...r))},endsWith(...r){return this.check(Za(...r))},min(...r){return this.check(Po(...r))},max(...r){return this.check($s(...r))},length(...r){return this.check(Ns(...r))},nonempty(...r){return this.check(Po(1,...r))},lowercase(r){return this.check(Ga(r))},uppercase(r){return this.check(Ka(r))},trim(){return this.check(Qa())},normalize(...r){return this.check(Ya(...r))},toLowerCase(){return this.check(ec())},toUpperCase(){return this.check(tc())},slugify(){return this.check(nc())}})}),cc=A("ZodString",(t,e)=>{Ms.init(t,e),qf.init(t,e),t.email=n=>t.check(af(Wf,n)),t.url=n=>t.check(Sd(_d,n)),t.jwt=n=>t.check(Pf(sg,n)),t.emoji=n=>t.check(pf(Gf,n)),t.guid=n=>t.check(wd(Td,n)),t.uuid=n=>t.check(cf(Kr,n)),t.uuidv4=n=>t.check(lf(Kr,n)),t.uuidv6=n=>t.check(df(Kr,n)),t.uuidv7=n=>t.check(uf(Kr,n)),t.nanoid=n=>t.check(mf(Kf,n)),t.guid=n=>t.check(wd(Td,n)),t.cuid=n=>t.check(ff(Vf,n)),t.cuid2=n=>t.check(gf(Jf,n)),t.ulid=n=>t.check(hf(Zf,n)),t.base64=n=>t.check(xf(rg,n)),t.base64url=n=>t.check(Rf(og,n)),t.xid=n=>t.check(yf(Xf,n)),t.ksuid=n=>t.check(bf(Yf,n)),t.ipv4=n=>t.check(vf(Qf,n)),t.ipv6=n=>t.check(kf(eg,n)),t.cidrv4=n=>t.check(wf(tg,n)),t.cidrv6=n=>t.check(Sf(ng,n)),t.e164=n=>t.check(Tf(ig,n)),t.datetime=n=>t.check(eP(n)),t.date=n=>t.check(tP(n)),t.time=n=>t.check(nP(n)),t.duration=n=>t.check(rP(n))});function Rd(t){return ER(cc,t)}var $e=A("ZodStringFormat",(t,e)=>{De.init(t,e),qf.init(t,e)}),Wf=A("ZodEmail",(t,e)=>{Sx.init(t,e),$e.init(t,e)});function Hj(t){return af(Wf,t)}var Td=A("ZodGUID",(t,e)=>{kx.init(t,e),$e.init(t,e)});function zj(t){return wd(Td,t)}var Kr=A("ZodUUID",(t,e)=>{wx.init(t,e),$e.init(t,e)});function Bj(t){return cf(Kr,t)}function qj(t){return lf(Kr,t)}function Wj(t){return df(Kr,t)}function Gj(t){return uf(Kr,t)}var _d=A("ZodURL",(t,e)=>{xx.init(t,e),$e.init(t,e)});function Kj(t){return Sd(_d,t)}function Vj(t){return Sd(_d,{protocol:On.httpProtocol,hostname:On.domain,...H.normalizeParams(t)})}var Gf=A("ZodEmoji",(t,e)=>{Rx.init(t,e),$e.init(t,e)});function Jj(t){return pf(Gf,t)}var Kf=A("ZodNanoID",(t,e)=>{Tx.init(t,e),$e.init(t,e)});function Zj(t){return mf(Kf,t)}var Vf=A("ZodCUID",(t,e)=>{Px.init(t,e),$e.init(t,e)});function Xj(t){return ff(Vf,t)}var Jf=A("ZodCUID2",(t,e)=>{Ax.init(t,e),$e.init(t,e)});function Yj(t){return gf(Jf,t)}var Zf=A("ZodULID",(t,e)=>{Ix.init(t,e),$e.init(t,e)});function Qj(t){return hf(Zf,t)}var Xf=A("ZodXID",(t,e)=>{_x.init(t,e),$e.init(t,e)});function eL(t){return yf(Xf,t)}var Yf=A("ZodKSUID",(t,e)=>{Cx.init(t,e),$e.init(t,e)});function tL(t){return bf(Yf,t)}var Qf=A("ZodIPv4",(t,e)=>{Nx.init(t,e),$e.init(t,e)});function nL(t){return vf(Qf,t)}var hP=A("ZodMAC",(t,e)=>{jx.init(t,e),$e.init(t,e)});function rL(t){return DR(hP,t)}var eg=A("ZodIPv6",(t,e)=>{Ox.init(t,e),$e.init(t,e)});function oL(t){return kf(eg,t)}var tg=A("ZodCIDRv4",(t,e)=>{Lx.init(t,e),$e.init(t,e)});function iL(t){return wf(tg,t)}var ng=A("ZodCIDRv6",(t,e)=>{Ux.init(t,e),$e.init(t,e)});function sL(t){return Sf(ng,t)}var rg=A("ZodBase64",(t,e)=>{Hx.init(t,e),$e.init(t,e)});function aL(t){return xf(rg,t)}var og=A("ZodBase64URL",(t,e)=>{zx.init(t,e),$e.init(t,e)});function cL(t){return Rf(og,t)}var ig=A("ZodE164",(t,e)=>{Bx.init(t,e),$e.init(t,e)});function lL(t){return Tf(ig,t)}var sg=A("ZodJWT",(t,e)=>{qx.init(t,e),$e.init(t,e)});function dL(t){return Pf(sg,t)}var lc=A("ZodCustomStringFormat",(t,e)=>{Wx.init(t,e),$e.init(t,e)});function uL(t,e,n={}){return rc(lc,t,e,n)}function pL(t){return rc(lc,"hostname",On.hostname,t)}function mL(t){return rc(lc,"hex",On.hex,t)}function fL(t,e){let n=e?.enc??"hex",r=`${t}_${n}`,o=On[r];if(!o)throw new Error(`Unrecognized hash format: ${r}`);return rc(lc,r,o,e)}var dc=A("ZodNumber",(t,e)=>{Zm.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>bT(t,r,o,i),Id(t,"ZodNumber",{gt(r,o){return this.check(Wr(r,o))},gte(r,o){return this.check(Xt(r,o))},min(r,o){return this.check(Xt(r,o))},lt(r,o){return this.check(qr(r,o))},lte(r,o){return this.check(jn(r,o))},max(r,o){return this.check(jn(r,o))},int(r){return this.check(zf(r))},safe(r){return this.check(zf(r))},positive(r){return this.check(Wr(0,r))},nonnegative(r){return this.check(Xt(0,r))},negative(r){return this.check(qr(0,r))},nonpositive(r){return this.check(jn(0,r))},multipleOf(r,o){return this.check(yi(r,o))},step(r,o){return this.check(yi(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function yP(t){return UR(dc,t)}var js=A("ZodNumberFormat",(t,e)=>{Gx.init(t,e),dc.init(t,e)});function zf(t){return HR(js,t)}function gL(t){return zR(js,t)}function hL(t){return BR(js,t)}function yL(t){return qR(js,t)}function bL(t){return WR(js,t)}var uc=A("ZodBoolean",(t,e)=>{hd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>vT(t,n,r,o)});function bP(t){return GR(uc,t)}var pc=A("ZodBigInt",(t,e)=>{Xm.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>kT(t,r,o,i),t.gte=(r,o)=>t.check(Xt(r,o)),t.min=(r,o)=>t.check(Xt(r,o)),t.gt=(r,o)=>t.check(Wr(r,o)),t.gte=(r,o)=>t.check(Xt(r,o)),t.min=(r,o)=>t.check(Xt(r,o)),t.lt=(r,o)=>t.check(qr(r,o)),t.lte=(r,o)=>t.check(jn(r,o)),t.max=(r,o)=>t.check(jn(r,o)),t.positive=r=>t.check(Wr(BigInt(0),r)),t.negative=r=>t.check(qr(BigInt(0),r)),t.nonpositive=r=>t.check(jn(BigInt(0),r)),t.nonnegative=r=>t.check(Xt(BigInt(0),r)),t.multipleOf=(r,o)=>t.check(yi(r,o));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});function vL(t){return VR(pc,t)}var ag=A("ZodBigIntFormat",(t,e)=>{Kx.init(t,e),pc.init(t,e)});function kL(t){return ZR(ag,t)}function wL(t){return XR(ag,t)}var vP=A("ZodSymbol",(t,e)=>{Vx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wT(t,n,r,o)});function SL(t){return YR(vP,t)}var kP=A("ZodUndefined",(t,e)=>{Jx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>xT(t,n,r,o)});function xL(t){return QR(kP,t)}var wP=A("ZodNull",(t,e)=>{Zx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ST(t,n,r,o)});function SP(t){return eT(wP,t)}var xP=A("ZodAny",(t,e)=>{Xx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>PT(t,n,r,o)});function RL(){return tT(xP)}var RP=A("ZodUnknown",(t,e)=>{Yx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>AT(t,n,r,o)});function Os(){return nT(RP)}var TP=A("ZodNever",(t,e)=>{Qx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>TT(t,n,r,o)});function cg(t){return rT(TP,t)}var PP=A("ZodVoid",(t,e)=>{eR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>RT(t,n,r,o)});function TL(t){return oT(PP,t)}var Cd=A("ZodDate",(t,e)=>{tR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>IT(t,r,o,i),t.min=(r,o)=>t.check(Xt(r,o)),t.max=(r,o)=>t.check(jn(r,o));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});function PL(t){return iT(Cd,t)}var AP=A("ZodArray",(t,e)=>{nR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>FT(t,n,r,o),t.element=e.element,Id(t,"ZodArray",{min(n,r){return this.check(Po(n,r))},nonempty(n){return this.check(Po(1,n))},max(n,r){return this.check($s(n,r))},length(n,r){return this.check(Ns(n,r))},unwrap(){return this.element}})});function Ed(t,e){return cT(AP,t,e)}function AL(t){let e=t._zod.def.shape;return dg(Object.keys(e))}var Md=A("ZodObject",(t,e)=>{rR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>HT(t,n,r,o),H.defineLazy(t,"shape",()=>e.shape),Id(t,"ZodObject",{keyof(){return dg(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Os()})},loose(){return this.clone({...this._zod.def,catchall:Os()})},strict(){return this.clone({...this._zod.def,catchall:cg()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return H.extend(this,n)},safeExtend(n){return H.safeExtend(this,n)},merge(n){return H.merge(this,n)},pick(n){return H.pick(this,n)},omit(n){return H.omit(this,n)},partial(...n){return H.partial(pg,this,n[0])},required(...n){return H.required(mg,this,n[0])}})});function IL(t,e){let n={type:"object",shape:t??{},...H.normalizeParams(e)};return new Md(n)}function _L(t,e){return new Md({type:"object",shape:t,catchall:cg(),...H.normalizeParams(e)})}function CL(t,e){return new Md({type:"object",shape:t,catchall:Os(),...H.normalizeParams(e)})}var Dd=A("ZodUnion",(t,e)=>{yd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Df(t,n,r,o),t.options=e.options});function lg(t,e){return new Dd({type:"union",options:t,...H.normalizeParams(e)})}var IP=A("ZodXor",(t,e)=>{Dd.init(t,e),oR.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Df(t,n,r,o),t.options=e.options});function EL(t,e){return new IP({type:"union",options:t,inclusive:!1,...H.normalizeParams(e)})}var _P=A("ZodDiscriminatedUnion",(t,e)=>{Dd.init(t,e),iR.init(t,e)});function ML(t,e,n){return new _P({type:"union",options:e,discriminator:t,...H.normalizeParams(n)})}var CP=A("ZodIntersection",(t,e)=>{sR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>zT(t,n,r,o)});function EP(t,e){return new CP({type:"intersection",left:t,right:e})}var MP=A("ZodTuple",(t,e)=>{Ym.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>BT(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function DP(t,e,n){let r=e instanceof oe,o=r?n:e,i=r?e:null;return new MP({type:"tuple",items:t,rest:i,...H.normalizeParams(o)})}var sc=A("ZodRecord",(t,e)=>{aR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function $P(t,e,n){return!e||!e._zod?new sc({type:"record",keyType:Rd(),valueType:t,...H.normalizeParams(e)}):new sc({type:"record",keyType:t,valueType:e,...H.normalizeParams(n)})}function DL(t,e,n){let r=Jt(t);return r._zod.values=void 0,new sc({type:"record",keyType:r,valueType:e,...H.normalizeParams(n)})}function $L(t,e,n){return new sc({type:"record",keyType:t,valueType:e,mode:"loose",...H.normalizeParams(n)})}var NP=A("ZodMap",(t,e)=>{cR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>LT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...n)=>t.check(Gr(...n)),t.nonempty=n=>t.check(Gr(1,n)),t.max=(...n)=>t.check(bi(...n)),t.size=(...n)=>t.check(Ds(...n))});function NL(t,e,n){return new NP({type:"map",keyType:t,valueType:e,...H.normalizeParams(n)})}var OP=A("ZodSet",(t,e)=>{lR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>UT(t,n,r,o),t.min=(...n)=>t.check(Gr(...n)),t.nonempty=n=>t.check(Gr(1,n)),t.max=(...n)=>t.check(bi(...n)),t.size=(...n)=>t.check(Ds(...n))});function OL(t,e){return new OP({type:"set",valueType:t,...H.normalizeParams(e)})}var ac=A("ZodEnum",(t,e)=>{dR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>_T(t,r,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let i={};for(let s of r)if(n.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ac({...e,checks:[],...H.normalizeParams(o),entries:i})},t.exclude=(r,o)=>{let i={...e.entries};for(let s of r)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new ac({...e,checks:[],...H.normalizeParams(o),entries:i})}});function dg(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new ac({type:"enum",entries:n,...H.normalizeParams(e)})}function jL(t,e){return new ac({type:"enum",entries:t,...H.normalizeParams(e)})}var jP=A("ZodLiteral",(t,e)=>{uR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>CT(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function LL(t,e){return new jP({type:"literal",values:Array.isArray(t)?t:[t],...H.normalizeParams(e)})}var LP=A("ZodFile",(t,e)=>{pR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>DT(t,n,r,o),t.min=(n,r)=>t.check(Gr(n,r)),t.max=(n,r)=>t.check(bi(n,r)),t.mime=(n,r)=>t.check(Xa(Array.isArray(n)?n:[n],r))});function UL(t){return lT(LP,t)}var UP=A("ZodTransform",(t,e)=>{mR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>jT(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new pi(t.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(H.issue(i,n.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),n.issues.push(H.issue(s))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function ug(t){return new UP({type:"transform",transform:t})}var pg=A("ZodOptional",(t,e)=>{Qm.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>$f(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Pd(t){return new pg({type:"optional",innerType:t})}var FP=A("ZodExactOptional",(t,e)=>{fR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>$f(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function HP(t){return new FP({type:"optional",innerType:t})}var zP=A("ZodNullable",(t,e)=>{gR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>WT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Ad(t){return new zP({type:"nullable",innerType:t})}function FL(t){return Pd(Ad(t))}var BP=A("ZodDefault",(t,e)=>{hR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>KT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function qP(t,e){return new BP({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():H.shallowClone(e)}})}var WP=A("ZodPrefault",(t,e)=>{yR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>VT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function GP(t,e){return new WP({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():H.shallowClone(e)}})}var mg=A("ZodNonOptional",(t,e)=>{bR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>GT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function KP(t,e){return new mg({type:"nonoptional",innerType:t,...H.normalizeParams(e)})}var VP=A("ZodSuccess",(t,e)=>{vR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>$T(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function HL(t){return new VP({type:"success",innerType:t})}var JP=A("ZodCatch",(t,e)=>{kR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>JT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function ZP(t,e){return new JP({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var XP=A("ZodNaN",(t,e)=>{wR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ET(t,n,r,o)});function zL(t){return aT(XP,t)}var $d=A("ZodPipe",(t,e)=>{ef.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ZT(t,n,r,o),t.in=e.in,t.out=e.out});function Bf(t,e){return new $d({type:"pipe",in:t,out:e})}var Nd=A("ZodCodec",(t,e)=>{$d.init(t,e),bd.init(t,e)});function BL(t,e,n){return new Nd({type:"pipe",in:t,out:e,transform:n.decode,reverseTransform:n.encode})}function qL(t){let e=t._zod.def;return new Nd({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var YP=A("ZodPreprocess",(t,e)=>{$d.init(t,e),SR.init(t,e)}),QP=A("ZodReadonly",(t,e)=>{xR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>XT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function eA(t){return new QP({type:"readonly",innerType:t})}var tA=A("ZodTemplateLiteral",(t,e)=>{RR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>MT(t,n,r,o)});function WL(t,e){return new tA({type:"template_literal",parts:t,...H.normalizeParams(e)})}var nA=A("ZodLazy",(t,e)=>{AR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>QT(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function rA(t){return new nA({type:"lazy",getter:t})}var oA=A("ZodPromise",(t,e)=>{PR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>YT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function GL(t){return new oA({type:"promise",innerType:t})}var iA=A("ZodFunction",(t,e)=>{TR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>OT(t,n,r,o)});function KL(t){return new iA({type:"function",input:Array.isArray(t?.input)?DP(t?.input):t?.input??Ed(Os()),output:t?.output??Os()})}var Od=A("ZodCustom",(t,e)=>{IR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>NT(t,n,r,o)});function VL(t){let e=new Le({check:"custom"});return e._zod.check=t,e}function JL(t,e){return dT(Od,t??(()=>!0),e)}function sA(t,e={}){return uT(Od,t,e)}function aA(t,e){return pT(t,e)}var ZL=mT,XL=fT;function YL(t,e={}){let n=new Od({type:"custom",check:"custom",fn:r=>r instanceof t,abort:!0,...H.normalizeParams(e)});return n._zod.bag.Class=t,n._zod.check=r=>{r.value instanceof t||r.issues.push({code:"invalid_type",expected:t.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var QL=(...t)=>gT({Codec:Nd,Boolean:uc,String:cc},...t);function eU(t){let e=rA(()=>lg([Rd(t),yP(),bP(),SP(),Ed(e),$P(Rd(),e)]));return e}function tU(t,e){return new YP({type:"pipe",in:ug(t),out:e})}var yse={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function bse(t){Ye({customError:t})}function vse(){return Ye().customError}var cA;cA||(cA={});var G={...xd,...jf,iso:ic},kse=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function wse(t,e){let n=t.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function Sse(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=t.slice(1).split("/").filter(Boolean);if(n.length===0)return e.rootSchema;let r=e.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let o=n[1];if(!o||!e.defs[o])throw new Error(`Reference not found: ${t}`);return e.defs[o]}throw new Error(`Reference not found: ${t}`)}function nU(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return G.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let o=t.$ref;if(e.refs.has(o))return e.refs.get(o);if(e.processing.has(o))return G.lazy(()=>{if(!e.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return e.refs.get(o)});e.processing.add(o);let i=Sse(o,e),s=Ft(i,e);return e.refs.set(o,s),e.processing.delete(o),s}if(t.enum!==void 0){let o=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&o.length===1&&o[0]===null)return G.null();if(o.length===0)return G.never();if(o.length===1)return G.literal(o[0]);if(o.every(s=>typeof s=="string"))return G.enum(o);let i=o.map(s=>G.literal(s));return i.length<2?i[0]:G.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return G.literal(t.const);let n=t.type;if(Array.isArray(n)){let o=n.map(i=>{let s={...t,type:i};return nU(s,e)});return o.length===0?G.never():o.length===1?o[0]:G.union(o)}if(!n)return G.any();let r;switch(n){case"string":{let o=G.string();if(t.format){let i=t.format;i==="email"?o=o.check(G.email()):i==="uri"||i==="uri-reference"?o=o.check(G.url()):i==="uuid"||i==="guid"?o=o.check(G.uuid()):i==="date-time"?o=o.check(G.iso.datetime()):i==="date"?o=o.check(G.iso.date()):i==="time"?o=o.check(G.iso.time()):i==="duration"?o=o.check(G.iso.duration()):i==="ipv4"?o=o.check(G.ipv4()):i==="ipv6"?o=o.check(G.ipv6()):i==="mac"?o=o.check(G.mac()):i==="cidr"?o=o.check(G.cidrv4()):i==="cidr-v6"?o=o.check(G.cidrv6()):i==="base64"?o=o.check(G.base64()):i==="base64url"?o=o.check(G.base64url()):i==="e164"?o=o.check(G.e164()):i==="jwt"?o=o.check(G.jwt()):i==="emoji"?o=o.check(G.emoji()):i==="nanoid"?o=o.check(G.nanoid()):i==="cuid"?o=o.check(G.cuid()):i==="cuid2"?o=o.check(G.cuid2()):i==="ulid"?o=o.check(G.ulid()):i==="xid"?o=o.check(G.xid()):i==="ksuid"&&(o=o.check(G.ksuid()))}typeof t.minLength=="number"&&(o=o.min(t.minLength)),typeof t.maxLength=="number"&&(o=o.max(t.maxLength)),t.pattern&&(o=o.regex(new RegExp(t.pattern))),r=o;break}case"number":case"integer":{let o=n==="integer"?G.number().int():G.number();typeof t.minimum=="number"&&(o=o.min(t.minimum)),typeof t.maximum=="number"&&(o=o.max(t.maximum)),typeof t.exclusiveMinimum=="number"?o=o.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(o=o.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?o=o.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(o=o.lt(t.maximum)),typeof t.multipleOf=="number"&&(o=o.multipleOf(t.multipleOf)),r=o;break}case"boolean":{r=G.boolean();break}case"null":{r=G.null();break}case"object":{let o={},i=t.properties||{},s=new Set(t.required||[]);for(let[c,l]of Object.entries(i)){let d=Ft(l,e);o[c]=s.has(c)?d:d.optional()}if(t.propertyNames){let c=Ft(t.propertyNames,e),l=t.additionalProperties&&typeof t.additionalProperties=="object"?Ft(t.additionalProperties,e):G.any();if(Object.keys(o).length===0){r=G.record(c,l);break}let d=G.object(o).passthrough(),p=G.looseRecord(c,l);r=G.intersection(d,p);break}if(t.patternProperties){let c=t.patternProperties,l=Object.keys(c),d=[];for(let m of l){let f=Ft(c[m],e),g=G.string().regex(new RegExp(m));d.push(G.looseRecord(g,f))}let p=[];if(Object.keys(o).length>0&&p.push(G.object(o).passthrough()),p.push(...d),p.length===0)r=G.object({}).passthrough();else if(p.length===1)r=p[0];else{let m=G.intersection(p[0],p[1]);for(let f=2;f<p.length;f++)m=G.intersection(m,p[f]);r=m}break}let a=G.object(o);t.additionalProperties===!1?r=a.strict():typeof t.additionalProperties=="object"?r=a.catchall(Ft(t.additionalProperties,e)):r=a.passthrough();break}case"array":{let o=t.prefixItems,i=t.items;if(o&&Array.isArray(o)){let s=o.map(c=>Ft(c,e)),a=i&&typeof i=="object"&&!Array.isArray(i)?Ft(i,e):void 0;a?r=G.tuple(s).rest(a):r=G.tuple(s),typeof t.minItems=="number"&&(r=r.check(G.minLength(t.minItems))),typeof t.maxItems=="number"&&(r=r.check(G.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=i.map(c=>Ft(c,e)),a=t.additionalItems&&typeof t.additionalItems=="object"?Ft(t.additionalItems,e):void 0;a?r=G.tuple(s).rest(a):r=G.tuple(s),typeof t.minItems=="number"&&(r=r.check(G.minLength(t.minItems))),typeof t.maxItems=="number"&&(r=r.check(G.maxLength(t.maxItems)))}else if(i!==void 0){let s=Ft(i,e),a=G.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),r=a}else r=G.array(G.any());break}default:throw new Error(`Unsupported type: ${n}`)}return r}function Ft(t,e){if(typeof t=="boolean")return t?G.any():G.never();let n=nU(t,e),r=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(l=>Ft(l,e)),c=G.union(a);n=r?G.intersection(n,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(l=>Ft(l,e)),c=G.xor(a);n=r?G.intersection(n,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)n=r?n:G.any();else{let a=r?n:Ft(t.allOf[0],e),c=r?0:1;for(let l=c;l<t.allOf.length;l++)a=G.intersection(a,Ft(t.allOf[l],e));n=a}t.nullable===!0&&e.version==="openapi-3.0"&&(n=G.nullable(n)),t.readOnly===!0&&(n=G.readonly(n)),t.default!==void 0&&(n=n.default(t.default));let o={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(o[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(o[a]=t[a]);for(let a of Object.keys(t))kse.has(a)||(o[a]=t[a]);return Object.keys(o).length>0&&e.registry.add(n,o),t.description&&(n=n.describe(t.description)),n}function rU(t,e){if(typeof t=="boolean")return t?G.any():G.never();let n;try{n=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let r=wse(n,e?.defaultTarget),o=n.$defs||n.definitions||{},i={version:r,defs:o,refs:new Map,processing:new Set,rootSchema:n,registry:e?.registry??_t};return Ft(n,i)}var lA={};sn(lA,{bigint:()=>Pse,boolean:()=>Tse,date:()=>Ase,number:()=>Rse,string:()=>xse});function xse(t){return MR(cc,t)}function Rse(t){return FR(dc,t)}function Tse(t){return KR(uc,t)}function Pse(t){return JR(pc,t)}function Ase(t){return sT(Cd,t)}Ye(tf());var Ne={authenticate:"authenticate",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_focus:"document/didFocus",document_did_open:"document/didOpen",document_did_save:"document/didSave",initialize:"initialize",logout:"logout",mcp_message:"mcp/message",nes_accept:"nes/accept",nes_close:"nes/close",nes_reject:"nes/reject",nes_start:"nes/start",nes_suggest:"nes/suggest",providers_disable:"providers/disable",providers_list:"providers/list",providers_set:"providers/set",session_cancel:"session/cancel",session_close:"session/close",session_delete:"session/delete",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode"},ar={elicitation_complete:"elicitation/complete",elicitation_create:"elicitation/create",fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",mcp_connect:"mcp/connect",mcp_disconnect:"mcp/disconnect",mcp_message:"mcp/message",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"};var oU=Symbol("skippedItem");function W(t,e){return t.catch(e)}function vr(t,e){let n=t.catch(e);return u.unknown().transform((r,o)=>r!==void 0?n.parse(r):(o.addIssue({code:"custom",message:"Required value is missing"}),u.NEVER))}function Ce(t){return u.array(t.catch(oU)).transform(e=>e.filter(n=>n!==oU))}var _se=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminal:u.boolean().optional().default(!1)}),Cse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),label:u.string().nullish(),name:u.string(),optional:u.boolean().optional().default(!1),secret:u.boolean().optional().default(!0)}),Ese=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),name:u.string()}),Mse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),link:u.string().nullish(),name:u.string(),vars:u.array(Cse)}),Dse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()).optional(),description:u.string().nullish(),env:u.record(u.string(),u.string()).optional(),id:u.string(),name:u.string()}),$se=u.union([Mse.and(u.object({type:u.literal("env_var")})),Dse.and(u.object({type:u.literal("terminal")})),Ese]),iU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),methodId:u.string()}),Nse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ose=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),blob:u.string(),mimeType:u.string().nullish(),uri:u.string()}),jse=u.object({default:u.boolean().nullish(),description:u.string().nullish(),title:u.string().nullish()}),Lse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Use=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Fse=u.object({amount:u.number(),currency:u.string()}),Hse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),zse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Bse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),newText:u.string(),oldText:u.string().nullish(),path:u.string()}),sU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string()}),qse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Wse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Gse=u.union([u.string(),u.number(),u.number(),u.boolean(),u.array(u.string())]),Kse=u.object({content:u.record(u.string(),Gse).nullish()}),Vse=u.intersection(u.union([Kse.and(u.object({action:u.literal("accept")})),u.object({action:u.literal("decline")}),u.object({action:u.literal("cancel")})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish()})),Jse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),aU=u.string(),uA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),elicitationId:aU}),Zse=u.literal("object"),Xse=u.literal("string"),Yse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Qse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),form:W(Jse.nullish(),()=>{}),url:W(Yse.nullish(),()=>{})}),cU=u.object({const:u.string(),title:u.string()}),lU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),eae=u.union([u.literal(-32700),u.literal(-32600),u.literal(-32601),u.literal(-32602),u.literal(-32603),u.literal(-32800),u.literal(-32e3),u.literal(-32002),u.literal(-32042),u.number().int().min(-2147483648,{message:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{message:"Invalid value: Expected int32 to be <= 2147483647"})]),dU=u.object({code:eae,data:u.unknown().optional(),message:u.string()}),uU=u.unknown(),pU=u.unknown(),mU=u.unknown(),tae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),readTextFile:u.boolean().optional().default(!1),writeTextFile:u.boolean().optional().default(!1)}),fU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),gU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),title:u.string().nullish(),version:u.string()}),nae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),rae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),hU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),yU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cursor:u.string().nullish(),cwd:u.string().nullish()}),pA=u.union([u.literal("anthropic"),u.literal("openai"),u.literal("azure"),u.literal("vertex"),u.literal("bedrock"),u.string()]),oae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),iae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),logout:W(oae.nullish(),()=>{})}),bU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),sae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),aae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acp:u.boolean().optional().default(!1),http:u.boolean().optional().default(!1),sse:u.boolean().optional().default(!1)}),fg=u.string(),cae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:fg}),lae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:fg}),vU=u.string(),dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acpId:vU}),uae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:vU,name:u.string()}),pae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(fU),name:u.string(),url:u.string()}),mae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(fU),name:u.string(),url:u.string()}),fae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()),command:u.string(),env:u.array(lU),name:u.string()}),gg=u.union([pae.and(u.object({type:u.literal("http")})),mae.and(u.object({type:u.literal("sse")})),uae.and(u.object({type:u.literal("acp")})),fae]),gae=u.string(),kU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:fg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),wU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:fg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),SU=u.unknown(),hae=u.union([u.literal("error"),u.literal("warning"),u.literal("information"),u.literal("hint")]),yae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),bae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),vae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),kae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),wae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Sae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),maxCount:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),xae=u.object({diff:u.string(),uri:u.string()}),Rae=u.object({endLine:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),startLine:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),text:u.string()}),Tae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Pae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Aae=u.object({languageId:u.string(),text:u.string(),uri:u.string()}),Iae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),maxCount:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),_ae=u.union([u.literal("rejected"),u.literal("ignored"),u.literal("replaced"),u.literal("cancelled")]),Cae=u.object({excerpts:u.array(Rae),uri:u.string()}),Eae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Mae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Dae=u.object({name:u.string(),owner:u.string(),remoteUrl:u.string()}),$ae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Nae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),jump:W(Tae.nullish(),()=>{}),rename:W(Mae.nullish(),()=>{}),searchAndReplace:W($ae.nullish(),()=>{})}),Oae=u.object({id:u.string(),isRegex:u.boolean().nullish(),replace:u.string(),search:u.string(),uri:u.string()}),jae=u.union([u.literal("automatic"),u.literal("diagnostic"),u.literal("manual")]),Lae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),maxCount:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),Uae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(yae.nullish(),()=>{}),editHistory:W(Sae.nullish(),()=>{}),openFiles:W(Pae.nullish(),()=>{}),recentFiles:W(Iae.nullish(),()=>{}),relatedSnippets:W(Eae.nullish(),()=>{}),userActions:W(Lae.nullish(),()=>{})}),xU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(gg)}),Fae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),RU=u.string(),Hae=u.union([u.literal("allow_once"),u.literal("allow_always"),u.literal("reject_once"),u.literal("reject_always")]),zae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),kind:Hae,name:u.string(),optionId:RU}),Bae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),qae=u.union([u.literal("high"),u.literal("medium"),u.literal("low")]),Wae=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed")]),TU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),priority:qae,status:Wae}),Gae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:vr(Ce(TU),()=>[])}),hg=u.string(),Kae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:hg,uri:u.string()}),Vae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:vr(Ce(TU),()=>[]),id:hg}),Jae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),id:hg}),Zae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:hg}),Xae=u.union([Vae.and(u.object({type:u.literal("items")})),Kae.and(u.object({type:u.literal("file")})),Jae.and(u.object({type:u.literal("markdown")}))]),Yae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),plan:Xae}),Si=u.object({character:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),line:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"})}),Qae=u.object({id:u.string(),position:Si,uri:u.string()}),ece=u.object({id:u.string(),newName:u.string(),position:Si,uri:u.string()}),tce=u.object({action:u.string(),position:Si,timestampMs:u.number(),uri:u.string()}),PU=u.union([u.literal("utf-16"),u.literal("utf-32"),u.literal("utf-8")]),nce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:_se.optional().default({terminal:!1}),elicitation:W(Qse.nullish(),()=>{}),fs:tae.optional().default({readTextFile:!1,writeTextFile:!1}),nes:W(Nae.nullish(),()=>{}),plan:W(Bae.nullish(),()=>{}),positionEncodings:W(Ce(PU).optional(),()=>[]),terminal:u.boolean().optional().default(!1)}),rce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audio:u.boolean().optional().default(!1),embeddedContext:u.boolean().optional().default(!1),image:u.boolean().optional().default(!1)}),AU=u.number().int().gte(0).lte(65535),IU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),clientCapabilities:nce.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:W(gU.nullish(),()=>{}),protocolVersion:AU}),oce=u.object({apiType:pA,baseUrl:u.string()}),ice=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),current:oce.nullish(),id:u.string(),required:u.boolean(),supported:vr(Ce(pA),()=>[])}),sce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),providers:vr(Ce(ice),()=>[])}),ace=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),mc=u.object({end:Si,start:Si}),cce=u.object({message:u.string(),range:mc,severity:hae,uri:u.string()}),lce=u.object({languageId:u.string(),lastFocusedMs:W(u.number().nullish(),()=>{}),uri:u.string(),visibleRange:W(mc.nullish(),()=>{})}),dce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(Ce(cce).nullish(),()=>{}),editHistory:W(Ce(xae).nullish(),()=>{}),openFiles:W(Ce(lce).nullish(),()=>{}),recentFiles:W(Ce(Aae).nullish(),()=>{}),relatedSnippets:W(Ce(Cae).nullish(),()=>{}),userActions:W(Ce(tce).nullish(),()=>{})}),uce=u.object({newText:u.string(),range:mc}),pce=u.object({cursorPosition:W(Si.nullish(),()=>{}),edits:u.array(uce),id:u.string(),uri:u.string()}),mce=u.union([pce.and(u.object({kind:u.literal("edit")})),Qae.and(u.object({kind:u.literal("jump")})),ece.and(u.object({kind:u.literal("rename")})),Oae.and(u.object({kind:u.literal("searchAndReplace")}))]),fce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string()}),gce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xi=u.union([u.number(),u.string()]).nullable(),xze=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),requestId:xi}),_U=u.object({requestId:xi}),hce=u.enum(["assistant","user"]),jd=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audience:W(Ce(hce).nullish(),()=>{}),lastModified:u.string().nullish(),priority:u.number().nullish()}),yce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),data:u.string(),mimeType:u.string()}),bce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),data:u.string(),mimeType:u.string(),uri:u.string().nullish()}),vce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),description:u.string().nullish(),mimeType:u.string().nullish(),name:u.string(),size:u.number().nullish(),title:u.string().nullish(),uri:u.string()}),kce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),optionId:RU}),wce=u.union([u.object({outcome:u.literal("cancelled")}),kce.and(u.object({outcome:u.literal("selected")}))]),Sce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),outcome:wce}),xce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Rce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Tce=u.object({currentValue:u.boolean()}),Pce=u.string(),CU=u.string(),Ace=u.union([u.literal("mode"),u.literal("model"),u.literal("thought_level"),u.string()]),mA=u.string(),EU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),name:u.string(),value:mA}),Ice=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),group:Pce,name:u.string(),options:u.array(EU)}),_ce=u.union([u.array(EU),u.array(Ice)]),Cce=u.object({currentValue:mA,options:_ce}),fc=u.intersection(u.union([Cce.and(u.object({type:u.literal("select")})),Tce.and(u.object({type:u.literal("boolean")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),category:W(Ace.nullish(),()=>{}),description:u.string().nullish(),id:CU,name:u.string()})),Ece=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:vr(Ce(fc),()=>[])}),Mce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Dce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Re=u.string(),MU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),sessionId:Re}),DU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re}),$U=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re}),NU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re}),fA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()).optional(),command:u.string(),cwd:u.string().nullish(),env:u.array(lU).optional(),outputByteLimit:u.number().nullish(),sessionId:Re}),OU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re}),jU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,uri:u.string()}),LU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),position:Si,sessionId:Re,uri:u.string(),version:u.number(),visibleRange:mc}),UU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),languageId:u.string(),sessionId:Re,text:u.string(),uri:u.string(),version:u.number()}),FU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,uri:u.string()}),HU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(gg).optional(),sessionId:Re}),gA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,terminalId:u.string()}),zU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(gg),sessionId:Re}),hA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),limit:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),line:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:u.string(),sessionId:Re}),BU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),reason:W(_ae.nullish(),()=>{}),sessionId:Re}),yA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,terminalId:u.string()}),qU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(gg).optional(),sessionId:Re}),$ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),sessionId:Re,title:W(u.string().nullish(),()=>{}),updatedAt:W(u.string().nullish(),()=>{})}),Nce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),nextCursor:u.string().nullish(),sessions:vr(Ce($ce),()=>[])}),Oce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),title:u.string().nullish(),updatedAt:u.string().nullish()}),jce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),yg=u.string(),Lce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),currentModeId:yg}),Uce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:yg,name:u.string()}),bg=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableModes:vr(Ce(Uce),()=>[]),currentModeId:yg}),Fce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(fc).nullish(),()=>{}),modes:W(bg.nullish(),()=>{}),sessionId:Re}),Hce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(fc).nullish(),()=>{}),modes:W(bg.nullish(),()=>{})}),zce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(fc).nullish(),()=>{}),modes:W(bg.nullish(),()=>{}),sessionId:Re}),Bce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(fc).nullish(),()=>{}),modes:W(bg.nullish(),()=>{})}),qce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Wce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:W(xce.nullish(),()=>{}),close:W(Rce.nullish(),()=>{}),delete:W(Mce.nullish(),()=>{}),fork:W(Dce.nullish(),()=>{}),list:W(jce.nullish(),()=>{}),resume:W(qce.nullish(),()=>{})}),WU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),apiType:pA,baseUrl:u.string(),headers:u.record(u.string(),u.string()).optional(),id:u.string()}),Gce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),GU=u.intersection(u.union([u.object({type:u.literal("boolean"),value:u.boolean()}),u.object({value:mA})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configId:CU,sessionId:Re})),Kce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:vr(Ce(fc),()=>[])}),KU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),modeId:yg,sessionId:Re}),Vce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Jce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re}),Zce=u.union([u.literal("end_turn"),u.literal("max_tokens"),u.literal("max_turn_requests"),u.literal("refusal"),u.literal("cancelled")]),Xce=u.union([u.literal("email"),u.literal("uri"),u.literal("date"),u.literal("date-time")]),Yce=u.object({default:u.string().nullish(),description:u.string().nullish(),enum:u.array(u.string()).nullish(),format:Xce.nullish(),maxLength:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),minLength:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),oneOf:u.array(cU).nullish(),pattern:u.string().nullish(),title:u.string().nullish()}),VU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(dce.nullish(),()=>{}),position:Si,selection:W(mc.nullish(),()=>{}),sessionId:Re,triggerKind:jae,uri:u.string(),version:u.number()}),Qce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),suggestions:vr(Ce(mce),()=>[])}),ele=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),tle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitCode:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:u.string().nullish()}),bA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,terminalId:u.string()}),nle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitStatus:tle.nullish(),output:u.string(),truncated:u.boolean()}),rle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),text:u.string()}),ole=u.object({range:mc.nullish(),text:u.string()}),JU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),contentChanges:u.array(ole),sessionId:Re,uri:u.string(),version:u.number()}),Rze=u.object({method:u.string(),params:u.union([DU,UU,JU,jU,FU,LU,MU,BU,kU,uU]).nullish()}),ile=u.union([u.literal("full"),u.literal("incremental")]),sle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),syncKind:ile}),ale=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),didChange:W(sle.nullish(),()=>{}),didClose:W(bae.nullish(),()=>{}),didFocus:W(vae.nullish(),()=>{}),didOpen:W(kae.nullish(),()=>{}),didSave:W(wae.nullish(),()=>{})}),cle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),document:W(ale.nullish(),()=>{})}),lle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(Uae.nullish(),()=>{}),events:W(cle.nullish(),()=>{})}),dle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:iae.optional().default({}),loadSession:u.boolean().optional().default(!1),mcpCapabilities:aae.optional().default({acp:!1,http:!1,sse:!1}),nes:W(lle.nullish(),()=>{}),positionEncoding:W(PU.nullish(),()=>{}),promptCapabilities:rce.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:W(ace.nullish(),()=>{}),sessionCapabilities:Wce.optional().default({})}),ule=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),agentCapabilities:dle.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:W(gU.nullish(),()=>{}),authMethods:W(Ce($se).optional().default([]),()=>[]),protocolVersion:AU}),ple=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),mimeType:u.string().nullish(),text:u.string(),uri:u.string()}),mle=u.union([ple,Ose]),fle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),resource:mle}),vA=u.union([rle.and(u.object({type:u.literal("text")})),bce.and(u.object({type:u.literal("image")})),yce.and(u.object({type:u.literal("audio")})),vce.and(u.object({type:u.literal("resource_link")})),fle.and(u.object({type:u.literal("resource")}))]),gle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:vA}),dA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:vA,messageId:gae.nullish()}),ZU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),prompt:u.array(vA),sessionId:Re}),hle=u.object({anyOf:u.array(cU)}),XU=u.union([gle.and(u.object({type:u.literal("content")})),Bse.and(u.object({type:u.literal("diff")})),ele.and(u.object({type:u.literal("terminal")}))]),kA=u.string(),YU=u.object({sessionId:Re,toolCallId:kA.nullish()}),yle=u.intersection(u.union([YU,_U]),u.object({elicitationId:aU,url:u.string().url()})),QU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),line:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:u.string()}),eF=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed"),u.literal("failed")]),tF=u.union([u.literal("read"),u.literal("edit"),u.literal("delete"),u.literal("move"),u.literal("search"),u.literal("execute"),u.literal("think"),u.literal("fetch"),u.literal("switch_mode"),u.literal("other")]),ble=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(XU).optional(),()=>[]),kind:tF.optional(),locations:W(Ce(QU).optional(),()=>[]),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:eF.optional(),title:u.string(),toolCallId:kA}),nF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(XU).nullish(),()=>{}),kind:W(tF.nullish(),()=>{}),locations:W(Ce(QU).nullish(),()=>{}),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:W(eF.nullish(),()=>{}),title:u.string().nullish(),toolCallId:kA}),wA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),options:u.array(zae),sessionId:Re,toolCall:nF}),vle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),hint:u.string()}),kle=vle,wle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string(),input:W(kle.nullish(),()=>{}),name:u.string()}),Sle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableCommands:vr(Ce(wle),()=>[])}),xle=u.object({enum:u.array(u.string()),type:Xse}),Rle=u.union([xle,hle]),Tle=u.object({default:u.array(u.string()).nullish(),description:u.string().nullish(),items:Rle,maxItems:u.number().nullish(),minItems:u.number().nullish(),title:u.string().nullish()}),Ple=u.union([Yce.and(u.object({type:u.literal("string")})),Fae.and(u.object({type:u.literal("number")})),nae.and(u.object({type:u.literal("integer")})),jse.and(u.object({type:u.literal("boolean")})),Tle.and(u.object({type:u.literal("array")}))]),Ale=u.object({description:u.string().nullish(),properties:u.record(u.string(),Ple).optional().default({}),required:u.array(u.string()).nullish(),title:u.string().nullish(),type:Zse.optional().default("object")}),Ile=u.intersection(u.union([YU,_U]),u.object({requestedSchema:Ale})),SA=u.intersection(u.union([Ile.and(u.object({mode:u.literal("form")})),yle.and(u.object({mode:u.literal("url")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),message:u.string()})),_le=u.object({cachedReadTokens:u.number().nullish(),cachedWriteTokens:u.number().nullish(),inputTokens:u.number(),outputTokens:u.number(),thoughtTokens:u.number().nullish(),totalTokens:u.number()}),Cle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),stopReason:Zce,usage:W(_le.nullish(),()=>{})}),Tze=u.union([u.object({id:xi,result:u.union([ule,Nse,sce,Gce,qse,sae,zce,Hce,Nce,zse,Fce,Bce,Use,Vce,Kce,Cle,Jce,Qce,Lse,mU,SU])}),u.object({error:dU,id:xi})]),Ele=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cost:W(Fse.nullish(),()=>{}),size:u.number(),used:u.number()}),Mle=u.union([dA.and(u.object({sessionUpdate:u.literal("user_message_chunk")})),dA.and(u.object({sessionUpdate:u.literal("agent_message_chunk")})),dA.and(u.object({sessionUpdate:u.literal("agent_thought_chunk")})),ble.and(u.object({sessionUpdate:u.literal("tool_call")})),nF.and(u.object({sessionUpdate:u.literal("tool_call_update")})),Gae.and(u.object({sessionUpdate:u.literal("plan")})),Yae.and(u.object({sessionUpdate:u.literal("plan_update")})),Zae.and(u.object({sessionUpdate:u.literal("plan_removed")})),Sle.and(u.object({sessionUpdate:u.literal("available_commands_update")})),Lce.and(u.object({sessionUpdate:u.literal("current_mode_update")})),Ece.and(u.object({sessionUpdate:u.literal("config_option_update")})),Oce.and(u.object({sessionUpdate:u.literal("session_info_update")})),Ele.and(u.object({sessionUpdate:u.literal("usage_update")}))]),xA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,update:Mle}),Pze=u.object({method:u.string(),params:u.union([xA,uA,kU,uU]).nullish()}),RA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,terminalId:u.string()}),Dle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitCode:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:u.string().nullish()}),$le=u.object({name:u.string(),uri:u.string()}),rF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),repository:W(Dae.nullish(),()=>{}),workspaceFolders:W(Ce($le).nullish(),()=>{}),workspaceUri:u.string().nullish()}),Aze=u.object({id:xi,method:u.string(),params:u.union([IU,iU,hU,WU,sU,bU,xU,zU,yU,OU,HU,qU,NU,KU,GU,ZU,rF,VU,$U,wU,pU]).nullish()}),TA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),path:u.string(),sessionId:Re}),Ize=u.object({id:xi,method:u.string(),params:u.union([TA,hA,wA,fA,bA,yA,RA,gA,SA,dae,wU,lae,pU]).nullish()}),Nle=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),_ze=u.union([u.object({id:xi,result:u.union([Nle,fce,Sce,Hse,nle,gce,Dle,rae,Vse,cae,Wse,mU,SU])}),u.object({error:dU,id:xi})]);function oF(t,e){let n=new TextEncoder,r=new TextDecoder,o=new ReadableStream({async start(s){let a="",c=e.getReader();try{for(;;){let{value:d,done:p}=await c.read();if(p){a+=r.decode();break}if(!d)continue;a+=r.decode(d,{stream:!0});let m=a.split(`
682
682
  `);a=m.pop()||"";for(let f of m){let g=f.trim();if(g)try{let h=JSON.parse(g);s.enqueue(h)}catch(h){console.error("Failed to parse JSON message:",g,h)}}}let l=a.trim();if(l)try{let d=JSON.parse(l);s.enqueue(d)}catch(d){console.error("Failed to parse JSON message:",l,d)}}catch(l){s.error(l);return}finally{c.releaseLock()}s.close()}}),i=new WritableStream({async write(s){let a=JSON.stringify(s)+`
683
- `,c=t.getWriter();try{await c.write(n.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Ri(t){return t??{}}function iF(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var vg=class{connection;constructor(e,n){let r=e(this),o=async(s,a)=>{switch(s){case ar.fs_write_text_file:{let c=TA.parse(a);return await r.writeTextFile?.(c)??{}}case ar.fs_read_text_file:{let c=hA.parse(a);return r.readTextFile?.(c)}case ar.session_request_permission:{let c=wA.parse(a);return r.requestPermission(c)}case ar.terminal_create:{let c=fA.parse(a);return r.createTerminal?.(c)}case ar.terminal_output:{let c=bA.parse(a);return r.terminalOutput?.(c)}case ar.terminal_release:{let c=yA.parse(a);return await r.releaseTerminal?.(c)??{}}case ar.terminal_wait_for_exit:{let c=RA.parse(a);return r.waitForTerminalExit?.(c)}case ar.terminal_kill:{let c=gA.parse(a);return await r.killTerminal?.(c)??{}}case ar.elicitation_create:{if(!r.unstable_createElicitation)throw fn.methodNotFound(s);let c=SA.parse(a);return r.unstable_createElicitation(c)}default:if(r.extMethod)return r.extMethod(s,a);throw fn.methodNotFound(s)}},i=async(s,a)=>{switch(s){case ar.session_update:{let c=xA.parse(a);return r.sessionUpdate(c)}case ar.elicitation_complete:{if(!r.unstable_completeElicitation)return;let c=uA.parse(a);return r.unstable_completeElicitation(c)}default:if(r.extNotification)return r.extNotification(s,a);throw fn.methodNotFound(s)}};this.connection=new PA(o,i,n)}initialize(e){return this.connection.sendRequest(Ne.initialize,e)}newSession(e){return this.connection.sendRequest(Ne.session_new,e)}loadSession(e){return this.connection.sendRequest(Ne.session_load,e,Ri)}unstable_forkSession(e){return this.connection.sendRequest(Ne.session_fork,e)}listSessions(e){return this.connection.sendRequest(Ne.session_list,e)}deleteSession(e){return this.connection.sendRequest(Ne.session_delete,e,Ri)}resumeSession(e){return this.connection.sendRequest(Ne.session_resume,e)}closeSession(e){return this.connection.sendRequest(Ne.session_close,e)}setSessionMode(e){return this.connection.sendRequest(Ne.session_set_mode,e,Ri)}setSessionConfigOption(e){return this.connection.sendRequest(Ne.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Ne.authenticate,e,Ri)}unstable_listProviders(e){return this.connection.sendRequest(Ne.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Ne.providers_set,e,Ri)}unstable_disableProvider(e){return this.connection.sendRequest(Ne.providers_disable,e,Ri)}logout(e){return this.connection.sendRequest(Ne.logout,e,Ri)}prompt(e){return this.connection.sendRequest(Ne.session_prompt,e)}cancel(e){return this.connection.sendNotification(Ne.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(Ne.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(Ne.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(Ne.nes_close,e,Ri)}unstable_didOpenDocument(e){return this.connection.sendNotification(Ne.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(Ne.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(Ne.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(Ne.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(Ne.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(Ne.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(Ne.nes_reject,e)}extMethod(e,n){return this.connection.sendRequest(e,n)}extNotification(e,n){return this.connection.sendNotification(e,n)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},PA=class{pendingResponses=new Map;nextRequestId=0;requestHandler;notificationHandler;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;constructor(e,n,r){this.requestHandler=e,this.notificationHandler=n,this.stream=r,this.closedPromise=new Promise(o=>{this.abortController.signal.addEventListener("abort",()=>o())}),this.receive()}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}async receive(){let e;try{let n=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:r,done:o}=await n.read();if(o)break;if(r)try{this.processMessage(r)}catch(i){console.error("Unexpected error during message processing:",r,i),"id"in r&&r.id!==void 0&&this.sendMessage({jsonrpc:"2.0",id:r.id,error:{code:-32700,message:"Parse error"}})}}}finally{n.releaseLock()}}catch(n){e=n}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let n=e??new Error("ACP connection closed");for(let r of this.pendingResponses.values())r.reject(n);this.pendingResponses.clear(),this.abortController.abort(n)}async processMessage(e){if("method"in e&&"id"in e){let n=await this.tryCallRequestHandler(e.method,e.params);"error"in n&&console.error("Error handling request",e,n.error),await this.sendMessage({jsonrpc:"2.0",id:e.id,...n})}else if("method"in e){let n=await this.tryCallNotificationHandler(e.method,e.params);"error"in n&&console.error("Error handling notification",e,n.error)}else"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}async tryCallRequestHandler(e,n){try{return{result:await this.requestHandler(e,n)??null}}catch(r){if(r instanceof fn)return r.toResult();if(r instanceof u.ZodError)return fn.invalidParams(r.format()).toResult();let o;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(o=r.message);try{return fn.internalError(o?JSON.parse(o):{}).toResult()}catch{return fn.internalError({details:o}).toResult()}}}async tryCallNotificationHandler(e,n){try{return await this.notificationHandler(e,n),{result:null}}catch(r){if(r instanceof fn)return r.toResult();if(r instanceof u.ZodError)return fn.invalidParams(r.format()).toResult();let o;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(o=r.message);try{return fn.internalError(o?JSON.parse(o):{}).toResult()}catch{return fn.internalError({details:o}).toResult()}}}handleResponse(e){let n=this.pendingResponses.get(e.id);if(n){if("result"in e)n.resolve(e.result);else if("error"in e){let{code:r,message:o,data:i}=e.error;n.reject(new fn(r,o,i))}this.pendingResponses.delete(e.id)}else console.error("Got response to unknown request",e.id)}sendRequest(e,n,r){if(this.abortController.signal.aborted)return iF(this.closedReason());let o=this.nextRequestId++,i=new Promise((s,a)=>{this.pendingResponses.set(o,{resolve:c=>{try{s(r?r(c):c)}catch(l){a(l)}},reject:a})});return i.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:o,method:e,params:n}),i}sendNotification(e,n){return this.abortController.signal.aborted?iF(this.closedReason()):this.sendMessage({jsonrpc:"2.0",method:e,params:n})}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let n=this.stream.writable.getWriter();try{await n.write(e)}finally{n.releaseLock()}}).catch(n=>{this.close(n)}),this.writeQueue}},fn=class t extends Error{code;data;constructor(e,n,r){super(n),this.code=e,this.name="RequestError",this.data=r}static parseError(e,n){return new t(-32700,`Parse error${n?`: ${n}`:""}`,e)}static invalidRequest(e,n){return new t(-32600,`Invalid request${n?`: ${n}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,n){return new t(-32602,`Invalid params${n?`: ${n}`:""}`,e)}static internalError(e,n){return new t(-32603,`Internal error${n?`: ${n}`:""}`,e)}static authRequired(e,n){return new t(-32e3,`Authentication required${n?`: ${n}`:""}`,e)}static resourceNotFound(e){return new t(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};var Ule=1,Fle=2e4,sF=3e4,Hle=3e5,kr={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",USAGE_UPDATE:"usage_update"};var Ld=class extends Error{retryable=!1;authMethods;constructor(e,n){super(e),this.name="AcpAuthRequiredError",this.authMethods=n}};function Ud(t,e){if(t instanceof Ld)return t;let n=t,r=Array.isArray(n?.data?.authMethods)?n.data.authMethods:[];if(n?.code===-32e3||r.length>0||/auth(?:entication|orization)?\s+required/i.test(n?.message??"")){let i=r[0],s=i?.description||(i?.name?`Use "${i.name}".`:"");return new Ld(`Authentication required.${s?` ${s}`:""}`,r)}if(e&&e.length>0){let i=e[0],s=n?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:n?.message||"Authentication required.");return new Ld(s,e)}return null}function zle(t){let e=t;if(!e||typeof e.message!="string")return t;let n=e.data,r=typeof n=="string"?n:typeof n?.details=="string"?n.details:typeof n?.error=="string"?n.error:typeof n?.message=="string"?n.message:"";if(!r||e.message.includes(r))return t;let o=new Error(`${e.message}: ${r}`);return o.name=t instanceof Error?t.name:"Error",Object.assign(o,{code:e.code,data:e.data}),o}var Ti=class{conn=null;child=null;onNotification=null;hostHandler=null;attach(e,n,r){if(this.child=e,this.onNotification=n??null,this.hostHandler=r??null,!e.stdin||!e.stdout)throw new Error("ACP adapter: child process has no stdio");let o=oF(Lle.toWeb(e.stdin),jle.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new vg(()=>this.buildClient(),{readable:i,writable:o.writable})}consumeExtensionNotification(e){let n=e;if(!n||n.method!=="session/update"||n.id!==void 0)return!1;let r=n.params?.update?.sessionUpdate;if(typeof r!="string"||!r.startsWith("x_"))return!1;try{this.onNotification?.("session/update",n.params)}catch{}return!0}buildClient(){let e=()=>this.hostHandler,n=(r,o)=>this.onNotification?.(r,o);return{async sessionUpdate(r){n("session/update",r)},async requestPermission(r){let o=e(),s=(o?.requestPermission?await o.requestPermission(r):{optionId:"allow"})?.optionId;return s?{outcome:{outcome:"selected",optionId:s}}:{outcome:{outcome:"cancelled"}}},async readTextFile(r){return{content:(await e()?.readTextFile?.(r))?.content??""}},async writeTextFile(r){return await e()?.writeTextFile?.(r),{}},async createTerminal(r){return await e()?.createTerminal?.(r)??{terminalId:""}},async terminalOutput(r){return await e()?.terminalOutput?.(r)??{output:"",truncated:!1}},async releaseTerminal(r){return await e()?.releaseTerminal?.(r),{}},async waitForTerminalExit(r){return await e()?.waitForTerminalExit?.(r)??{}},async killTerminal(r){return await e()?.killTerminal?.(r),{}},async extMethod(r,o){return await e()?.extMethod?.(r,o)??{}},async extNotification(r,o){n(r,o)}}}detach(){this.conn=null,this.hostHandler=null,this.onNotification=null,this.child=null}requireConn(){if(!this.conn)throw new Error("ACP adapter not attached");return this.conn}async withTimeout(e,n,r,o){let i,s=new Promise((a,c)=>{i=setTimeout(()=>{try{o?.()}catch{}c(new Error(`ACP ${r} timeout (${n}ms)`))},n)});try{return await Promise.race([e,s])}finally{i&&clearTimeout(i)}}async initialize(e){let n={protocolVersion:Ule,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}},clientInfo:{name:"qlogicagent",version:"1.0.0"}},r=await this.withTimeout(this.requireConn().initialize(n),Fle,"initialize").catch(i=>{throw Ud(i)??i}),o=r?.agentCapabilities??{};return{protocolVersion:typeof r?.protocolVersion=="number"?r.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:r?.agentInfo,authMethods:r?.authMethods}}async createSession(e,n){let r={cwd:n.cwd,mcpServers:n.mcpServers??[]};n.additionalDirectories?.length&&(r.additionalDirectories=n.additionalDirectories),n.systemPrompt&&(r._meta={qlogicagent:{systemPrompt:n.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(r),sF,"session/new").catch(i=>{throw Ud(i)??i});if(typeof o?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:o.sessionId}}async sendPrompt(e,n,r,o=Hle){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:n,prompt:[{type:"text",text:r}]}),o,"session/prompt",()=>{i.cancel({sessionId:n}).catch(()=>{})}).catch(a=>{throw Ud(a)??zle(a)});return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:void 0}}async resumeSession(e,n,r){let o={sessionId:n,cwd:r?.cwd??process.cwd(),mcpServers:r?.mcpServers??[]},i=await this.withTimeout(this.requireConn().loadSession(o),sF,"session/load");return{sessionId:typeof i?.sessionId=="string"?i.sessionId:n}}static translateNotification(e,n){let r=n;if(e==="session/update"){if(!r)return null;let o=r.update;if(!o)return null;let i=o.sessionUpdate,s=r.sessionId;switch(i){case kr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case kr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case kr.TOOL_CALL:return{method:"turn.tool_call",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"running",content:o.content,kind:o.kind,rawInput:o.rawInput,sessionId:s}};case kr.TOOL_CALL_UPDATE:return{method:"turn.tool_result",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"completed",content:o.content,rawOutput:o.rawOutput,sessionId:s}};case kr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case kr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case kr.AVAILABLE_COMMANDS_UPDATE:case kr.CURRENT_MODE_UPDATE:case kr.CONFIG_OPTION_UPDATE:case kr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case kr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as Ble}from"node:child_process";import{readFile as qle,writeFile as Wle}from"node:fs/promises";import{isAbsolute as aF,normalize as Gle,relative as Kle,resolve as Vle,sep as Jle}from"node:path";function Zle(t){let e=t.options;if(!Array.isArray(e)||e.length===0)return"allow";let n=e.filter(c=>!!c&&typeof c=="object"),r=c=>typeof c.optionId=="string"&&c.optionId.trim()?c.optionId:void 0;if(n.find(c=>r(c)==="allow"))return"allow";let i=n.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/allow/i.test(l)}),s=i?r(i):void 0;if(s)return s;let a=n.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/reject|deny|cancel/i.test(l)});return r(a??{})??r(n[0]??{})??"allow"}function AA(t){let e=new Map,n=0,r=i=>{let s=aF(i)?Gle(i):Vle(t.cwd,i),a=Kle(t.cwd,s);if(a===".."||a.startsWith(`..${Jle}`)||aF(a))throw new Error(`path escapes cwd: ${i}`);return s},o=i=>String(i.terminalId??"");return{async requestPermission(i){return t.requestPermission?t.requestPermission(i):{optionId:Zle(i)}},async readTextFile(i){return{content:await qle(r(i.path),"utf8")}},async writeTextFile(i){return await Wle(r(i.path),i.content,"utf8"),{}},async createTerminal(i){let s=String(i.command??""),a=i.args,c=Array.isArray(a)?a.map(String):[],l=i.cwd,d=l?r(String(l)):t.cwd,p=i.env,m={...process.env,...p&&typeof p=="object"?p:{}},f=Ble(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"]}),g=`term-${++n}`,h={child:f,output:"",exitStatus:null,exit:new Promise(y=>{f.on("exit",(v,b)=>{let k={exitCode:v,signal:b};h.exitStatus=k,y(k)}),f.on("error",()=>{let v={exitCode:null,signal:null};h.exitStatus=v,y(v)})})};return f.stdout?.on("data",y=>{h.output+=y.toString()}),f.stderr?.on("data",y=>{h.output+=y.toString()}),e.set(g,h),{terminalId:g}},async terminalOutput(i){let s=e.get(o(i));return s?{output:s.output,truncated:!1,exitStatus:s.exitStatus}:{output:"",truncated:!1,exitStatus:null}},async waitForTerminalExit(i){let s=e.get(o(i));return s?s.exit:{exitCode:null,signal:null}},async releaseTerminal(i){let s=o(i),a=e.get(s);if(a&&a.child.exitCode===null&&a.child.signalCode===null)try{a.child.kill()}catch{}return e.delete(s),{}},async killTerminal(i){let s=e.get(o(i));if(s)try{s.child.kill("SIGKILL")}catch{}return{}},disposeAll(){for(let i of e.values())try{i.child.kill("SIGKILL")}catch{}e.clear()}}}var Fd=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{exec as Yle,execFile as Qle,execFileSync as cF,execSync as wF}from"node:child_process";import{existsSync as _i,mkdirSync as SF,readFileSync as yc,readdirSync as xF,writeFileSync as RF}from"node:fs";import{homedir as NA,platform as ede,tmpdir as tde}from"node:os";import{dirname as Hd,join as kt}from"node:path";import{promisify as TF}from"node:util";function Pi(){let t=process.env.XIAOZHICLAW_NODE_EXE,e=process.env.XIAOZHICLAW_NPM_CLI;return!t||!e?null:{nodeExe:t,npmCli:e,prefix:process.env.XIAOZHICLAW_NPM_GLOBAL_PREFIX||void 0}}function Ai(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function IA(t){let e=t.trim().split(/\s+/)[0];return e==="npm"||e==="npm.cmd"}var Xle=/^(?:pip3?|pipx|uv|uvx|python3?|curl|wget|brew|sh|bash)\b/;function _A(t){return Xle.test(t.trim())}function CA(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var lF=TF(Qle),PF=TF(Yle),Ls={claude:{id:"claude",name:"Claude Code",cliCommand:"claude-agent-acp",acpArgs:[],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:["-c","sandbox_mode=danger-full-access","-c","approval_policy=untrusted"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!0,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!1},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--experimental-acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"GEMINI_API_KEY",baseUrlEnvVar:"GOOGLE_GEMINI_BASE_URL"},glm:{id:"glm",name:"GLM Agent",cliCommand:"glm-acp-agent",acpArgs:[],defaultCliPath:"npx glm-acp-agent",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"Z_AI_API_KEY",baseUrlEnvVar:"ACP_GLM_BASE_URL"},cline:{id:"cline",name:"Cline",cliCommand:"cline",acpArgs:["--acp"],defaultCliPath:"npx cline",authRequired:!0,supportsBaseUrlOverride:!0},nova:{id:"nova",name:"Nova",cliCommand:"nova",acpArgs:["acp"],defaultCliPath:"npx @compass-ai/nova",authRequired:!0,supportsBaseUrlOverride:!0},openclaw:{id:"openclaw",name:"OpenClaw",cliCommand:"openclaw",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENCLAW_API_KEY",baseUrlEnvVar:"OPENCLAW_BASE_URL"}},nde=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],dF={claude:{brandId:"claude",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @agentclientprotocol/claude-agent-acp",cliCommand:"claude-agent-acp",docsUrl:"https://github.com/agentclientprotocol/claude-agent-acp"},strengths:"\u590D\u6742\u63A8\u7406\u3001\u91CD\u6784\u3001\u957F\u94FE\u8DEF\u5B9E\u73B0"},codex:{brandId:"codex",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @zed-industries/codex-acp",cliCommand:"codex-acp",verifyCmd:"codex-acp --help",docsUrl:"https://github.com/zed-industries/codex-acp"},strengths:"\u4EE3\u7801\u751F\u6210\u3001\u8C03\u8BD5\u3001shell/\u5DE5\u5177\u94FE"},gemini:{brandId:"gemini",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @google/gemini-cli",cliCommand:"gemini",docsUrl:"https://github.com/google-gemini/gemini-cli"},strengths:"\u591A\u6A21\u6001\u3001\u957F\u4E0A\u4E0B\u6587\u3001\u7EFC\u5408\u5B9E\u73B0"},copilot:{brandId:"copilot",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9ED8\u8BA4\u9700 GitHub \u8D26\u53F7(\u4E5F\u652F\u6301 BYOK \u81EA\u5E26 key,\u540E\u7EED\u53EF\u63A5\u5165\u514D\u767B\u5F55\u6CE8\u5165)",install:{npm:"npm i -g @github/copilot",cliCommand:"copilot",setupCommand:"copilot",docsUrl:"https://docs.github.com/copilot/concepts/agents/about-copilot-cli"},strengths:"\u901A\u7528\u7F16\u7801\u3001GitHub \u751F\u6001"},cursor:{brandId:"cursor",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9700 Cursor \u8D26\u53F7",install:{curl:"curl https://cursor.com/install -fsS | bash",cliCommand:"cursor-agent",setupCommand:"cursor-agent login",docsUrl:"https://cursor.com/cli"},strengths:"\u901A\u7528\u7F16\u7801\u3001IDE \u96C6\u6210"},qwen:{brandId:"qwen",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @qwen-code/qwen-code",cliCommand:"qwen",docsUrl:"https://github.com/QwenLM/qwen-code"},strengths:"\u524D\u7AEF/UI\u3001\u4EA4\u4E92\u5B9E\u73B0\u3001\u901A\u7528\u7F16\u7801"},kimi:{brandId:"kimi",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9700 Kimi \u8D26\u53F7(\u5728\u7EC8\u7AEF\u8FD0\u884C kimi login \u767B\u5F55)",install:{pip:"uv tool install kimi-cli",cliCommand:"kimi",setupCommand:"kimi login",docsUrl:"https://github.com/MoonshotAI/kimi-cli"},strengths:"\u957F\u4E0A\u4E0B\u6587\u3001\u4E2D\u6587\u573A\u666F"},glm:{brandId:"glm",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g glm-acp-agent",cliCommand:"glm-acp-agent",docsUrl:"https://github.com/stefandevo/glm-acp-agent"},strengths:"\u901A\u7528\u7F16\u7801\u3001\u4E2D\u6587\u573A\u666F"},opencode:{brandId:"opencode",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g opencode-ai",cliCommand:"opencode",docsUrl:"https://opencode.ai/docs"},strengths:"\u7B97\u6CD5\u3001\u6570\u636E\u7ED3\u6784\u3001\u590D\u6742\u903B\u8F91"},kiro:{brandId:"kiro",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{cliCommand:"kiro-cli",docsUrl:"https://kiro.dev/docs"},strengths:"\u901A\u7528\u7F16\u7801"},qoder:{brandId:"qoder",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @qoder-ai/qodercli",cliCommand:"qodercli",docsUrl:"https://docs.qoder.com/cli/acp"},strengths:"\u901A\u7528\u7F16\u7801"},openclaw:{brandId:"openclaw",category:"assistant",integration:"acp",keySource:"direct",authMode:"key",note:"\u9AD8\u7EA7:\u9700\u81EA\u5907\u8FD0\u884C\u4E2D\u7684 openclaw Gateway + \u6709\u6548 ~/.openclaw \u914D\u7F6E(openclaw acp = \u6302\u5728 Gateway \u4E0A\u7684 ACP \u6865)",install:{npm:"npm i -g openclaw",cliCommand:"openclaw",deferUpdate:!0,setupCommand:"openclaw onboard",docsUrl:"https://github.com/openclaw/openclaw"},strengths:"\u52A9\u7406/\u7F16\u6392\u3001\u901A\u7528"},hermes:{brandId:"hermes",category:"assistant",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9996\u6B21\u9700\u5728\u7EC8\u7AEF\u8FD0\u884C hermes acp --setup \u914D\u7F6E provider/model",install:{pip:"uv tool install hermes-agent[acp] --python 3.13",cliCommand:"hermes",setupCommand:"hermes acp --setup",docsUrl:"https://github.com/NousResearch/hermes-agent"},strengths:"\u52A9\u7406\u3001\u901A\u7528"}};function Io(t){let e=Ls[t];if(e)return dF[t]?{...e,...dF[t]}:e}function zd(){return nde.map(t=>{let e=Io(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var _o=ede()==="win32",AF=5*6e4,rde=2e4,Ii,gc=new Map,EA=kt(process.env.QLOGICAGENT_HOME||kt(NA(),".qlogicagent"),"agent-update-cache.json"),uF=!1;function IF(){if(!uF){uF=!0;try{let t=JSON.parse(yc(EA,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!gc.has(e)&&gc.set(e,n)}catch{}}}var kg=null;function ode(){kg||(kg=setTimeout(()=>{kg=null;try{let t={};for(let[e,n]of gc)t[e]=n;SF(Hd(EA),{recursive:!0}),RF(EA,JSON.stringify(t),"utf8")}catch{}},1e3),kg.unref?.())}function MA(t){try{let e=_o?`where ${t}`:`which ${t}`;return wF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function DA(t){try{let e=_o?`where ${t}`:`which ${t}`,{stdout:n}=await PF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function _F(t,e){let n=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r[i]!==o[i])return o[i]-r[i];return e.localeCompare(t)}function ide(){if(!_o)return null;let t=[process.env.COPILOT_CACHE_HOME?kt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?kt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?kt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,kt(NA(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=xF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(_F);for(let r of n){let o=kt(e,r,"npm-loader.js");if(_i(o)&&NF(o))return o}}catch{}return null}function sde(t){return t.id==="copilot"?ide()??MA(t.cliCommand):MA(t.cliCommand)}async function ade(){if(!_o)return null;let t=[process.env.COPILOT_CACHE_HOME?kt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?kt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?kt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,kt(NA(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=xF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(_F);for(let r of n){let o=kt(e,r,"npm-loader.js");if(_i(o)&&await OF(o))return o}}catch{}return null}async function cde(t){return t.id==="copilot"?await ade()??await DA(t.cliCommand):DA(t.cliCommand)}function lde(t,e){let n=Pi();return n?cF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:Ai(n)}).trim():cF(_o?"cmd.exe":"npm",_o?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"]}).trim()}async function CF(t,e){let n=Pi();if(n){let{stdout:o}=await lF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:Ai(n)});return o.trim()}let{stdout:r}=await lF(_o?"cmd.exe":"npm",_o?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function dde(t){let e=t.trim().replace(/^["']|["']$/g,"");if(!e||e.startsWith("-"))return null;if(e.startsWith("@")){let r=e.indexOf("@",1);return r>0?e.slice(0,r):e}let n=e.indexOf("@");return n>0?e.slice(0,n):e}function Tg(t){if(!t)return null;let e=t.trim().split(/\s+/).filter(Boolean);if(e[0]!=="npm"&&e[0]!=="npm.cmd")return null;let n=e.findIndex(r=>r==="i"||r==="install"||r==="add");if(n<0)return null;for(let r=n+1;r<e.length;r+=1){let o=e[r];if(!(o==="-g"||o==="--global")){if(o.startsWith("--")&&!o.includes("=")){r+=1;continue}if(!o.startsWith("-"))return dde(o)}}return null}function Bd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function ude(t,e){let n=i=>{let s=Bd(i)??i,[a,c=""]=s.replace(/^v/,"").split("-",2),l=a.split(".").map(d=>Number.parseInt(d,10)||0);for(;l.length<3;)l.push(0);return{nums:l,pre:c}},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r.nums[i]!==o.nums[i])return r.nums[i]-o.nums[i];return r.pre===o.pre?0:r.pre?o.pre?r.pre.localeCompare(o.pre):-1:1}function EF(t,e){return!t||!e?!1:ude(t,e)>0}function pde(){if(Ii!==void 0)return Ii;try{Ii=lde(["root","-g"],3e3)||null}catch{Ii=null}return Ii}async function mde(){if(Ii===void 0)try{Ii=await CF(["root","-g"],3e3)||null}catch{Ii=null}}function Pg(t){if(!t)return null;let e=pde();if(!e)return null;let n=kt(e,...t.split("/"),"package.json");try{let r=JSON.parse(yc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function pF(t){let e=Tg(t?.npm);return Pg(e)}function MF(t,e){return Pg(Tg(t.install?.npm))??Bd(e)??e??void 0}async function fde(t,e){if(!t)return null;IF();let n=e?`${t}\0${e}`:t,r=gc.get(n);if(r){let i=r.version?AF:rde;if(Date.now()-r.timestamp<i)return r.version}let o=null;try{let i=["view",t,"version","--json"];e&&i.push("--registry",e);let s=await CF(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Bd(s)}catch{o=null}return gc.set(n,{timestamp:Date.now(),version:o}),ode(),o}async function DF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=Tg(i.install?.npm),c=Pg(a)??Bd(s)??s??void 0;if(!a||!c)return null;let l=await fde(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:EF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function $F(t,e){IF();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=Tg(i.install?.npm),c=Pg(a)??Bd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=gc.get(l);d?.version&&Date.now()-d.timestamp<AF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:EF(d.version,c)})}return{updates:n,stale:r}}function NF(t){let e=t.endsWith("npm-loader.js");for(let n of["--version","version","-v"])try{let r=e?`"${process.execPath}" "${t}" ${n}`:`"${t}" ${n}`,i=wF(r,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}async function OF(t){let e=t.endsWith("npm-loader.js");for(let n of["--version","version","-v"])try{let r=e?`"${process.execPath}" "${t}" ${n}`:`"${t}" ${n}`,{stdout:o}=await PF(r,{encoding:"utf8",timeout:5e3,windowsHide:!0}),i=String(o).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}function gde(t,e){if(!_o)return{cliPath:t,acpArgs:e};if(t.endsWith("npm-loader.js")){let o=e.includes("--no-auto-update");return{cliPath:process.execPath,acpArgs:[t,...e,...o?[]:["--no-auto-update"]]}}let n=jF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=hde(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function jF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!_i(r))continue;let o;try{o=yc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=kt(Hd(e),s);if(_i(a))return a}return null}function hde(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!_i(r))continue;let o;try{o=yc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=kt(Hd(e),s);if(_i(a))return a}return null}function mF(t){let e=jF(t);if(!e)return null;let n=Hd(e);for(let r=0;r<6;r+=1){let o=kt(n,"package.json");try{if(_i(o)){let s=JSON.parse(yc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=Hd(n);if(i===n)break;n=i}return null}var fF=6e4;function yde(t,e,n){let r={};return t?.env&&Object.assign(r,t.env),n&&Object.assign(r,n),t?.apiKeyEnvVar&&e?.apiKey&&(r[t.apiKeyEnvVar]=e.apiKey),t?.baseUrlEnvVar&&e?.baseUrl&&(r[t.baseUrlEnvVar]=e.baseUrl),e?.env&&Object.assign(r,e.env),Object.keys(r).length>0?r:void 0}var LF=new Set(["codex","qwen","opencode"]),Sg=new Set(["qwen","opencode"]),xg=new Set(["gemini"]),$A=new Set(["glm"]),gF={claude:"anthropic",codex:"openai"};function bde(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function vde(t){let e=kt(tde(),"qlogicagent-codex-model-catalog");SF(e,{recursive:!0});let n=kt(e,`${bde(t)}.json`),r=JSON.stringify({models:[{slug:t,display_name:t,supported_reasoning_levels:[],shell_type:"shell_command",visibility:"list",priority:0,base_instructions:"You are Codex, a coding agent. Follow the user's instructions and use tools only when needed.",supports_reasoning_summaries:!1,support_verbosity:!1,truncation_policy:{mode:"tokens",limit:1e6},supports_parallel_tool_calls:!1,experimental_supported_tools:[],supported_in_api:!0}]});return(!_i(n)||yc(n,"utf8")!==r)&&RF(n,r,"utf8"),n}function OA(t){return t.id!=="claude"}function Rg(t,e){return e==="account"&&!OA(t)?"auto":e}function UF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&OA(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||Sg.has(t.id)||xg.has(t.id)||$A.has(t.id))&&e.push("managed"),e}function jA(t,e,n){let r=Rg(t,e);return!!(r==="account"||r==="auto"&&OA(t)&&n?.hasSubscription?.(t.id)===!0)}var FF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},kde={glm:"ACP_GLM_AVAILABLE_MODELS"};function wg(t,e,n){let{apiKeyEnvVar:r,baseUrlEnvVar:o}=t;r&&e.llmrouterKey&&(n[r]=e.llmrouterKey);let i=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;o&&i&&(n[o]=i);let s=FF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=kde[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function hF(t,e,n){e.llmrouterKey&&(n.OPENAI_API_KEY=e.llmrouterKey);let r=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;r&&(n.OPENAI_BASE_URL=r),e.llmrouterModel&&(n.OPENAI_MODEL=e.llmrouterModel)}var yF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function bF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...yF]:yF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function vF(t){return!!t.apiKeyEnvVar||Sg.has(t.id)||xg.has(t.id)}function kF(t,e,n="auto"){let r={};if(!t)return r;let o=Rg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=gF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||xg.has(t.id)||$A.has(t.id)?wg(t,e,r):Sg.has(t.id)&&hF(t,e,r),r;if(jA(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=gF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:wg(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:Sg.has(t.id)?hF(t,e,r):(xg.has(t.id)||$A.has(t.id))&&wg(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&LF.has(t.id)){let a=e.passthroughModel;r.OPENAI_API_KEY=a.apiKey,a.baseUrl&&(r.OPENAI_BASE_URL=a.baseUrl),a.model&&(r.OPENAI_MODEL=a.model)}return r}function wde(t,e,n){if(!t||!jA(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),LF.has(t.id)&&r.push("OPENAI_MODEL"),r}function Sde(t,e,n,r,o="auto"){if(!t)return e;if(t.id==="qwen")return!n.OPENAI_API_KEY||e.some(a=>a==="--auth-type"||a.startsWith("--auth-type="))?e:[...e,"--auth-type=openai"];if(t.id!=="codex")return e;if(jA(t,o,r))return e.some(a=>a.includes("preferred_auth_method"))?e:[...e,"-c","preferred_auth_method=chatgpt"];if(t.keySource!=="llmrouter"||!n.OPENAI_API_KEY||e.some(a=>a.includes("model_provider")||a.includes("model_providers.")))return e;let i=n.OPENAI_BASE_URL,s=r.llmrouterModel||n.OPENAI_MODEL||"deepseek-v4-flash";return i?[...e,"-c","model_providers.llmrouter.name=llmrouter","-c",`model_providers.llmrouter.base_url=${i}`,"-c","model_providers.llmrouter.wire_api=responses","-c","model_providers.llmrouter.env_key=OPENAI_API_KEY","-c","model_provider=llmrouter","-c",`model=${s}`,"-c",`model_catalog_json=${vde(s)}`]:e}var hc=class{cache=null;configStore=null;keySources={};scanInFlight=null;setConfigStore(e){this.configStore=e}setKeySources(e){this.keySources=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<fF)return this.cache.agents;let n=[];for(let r of Object.values(Ls))n.push(this.detectBackend(r));if(this.configStore?.customAgents)for(let r of Object.values(this.configStore.customAgents))n.push(this.detectCustomAgent(r));return this.cache={agents:n,timestamp:Date.now()},n}async scanAsync(e=!1){return!e&&this.cache&&Date.now()-this.cache.timestamp<fF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await mde();let n=[...await Promise.all(Object.values(Ls).map(r=>this.detectBackendAsync(r)))];if(this.configStore?.customAgents){let r=await Promise.all(Object.values(this.configStore.customAgents).map(o=>this.detectCustomAgentAsync(o)));n.push(...r)}return this.cache={agents:n,timestamp:Date.now()},n}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let n=sde(e),r=n?NF(n)??mF(n)??pF(Io(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await cde(e),r=n?await OF(n)??mF(n)??pF(Io(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}assembleBackendDescriptor(e,n,r){let o=this.hasAgentConfig(e.id);return n?e.id==="copilot"&&!r?{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}:{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"available",cliPath:n,version:r??void 0,authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:e.id==="claude"||e.id==="goose"||e.id==="copilot",supportsUsageUpdate:e.id==="claude"||e.id==="codex"||e.id==="copilot",skillsDirs:e.skillsDirs}}:{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}}}detectCustomAgent(e){return this.assembleCustomAgentDescriptor(e,MA(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await DA(e.cliCommand))}assembleCustomAgentDescriptor(e,n){let r=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:n?"available":"not_installed",cliPath:n??void 0,authRequired:e.authRequired??!1,hasConfig:r,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let n=this.configStore.agents[e];return!!(n?.apiKey||n?.baseUrl||n?.customCliPath)}buildSelfDescriptor(){let e=["QLOGIC_LLMROUTER_USER_ID","QLOGIC_IMPLICIT_OWNER_ID","QLOGIC_DEVICE_ID","QLOGICAGENT_HOME","QLOGIC_LLMROUTER_BASE_URL","QLOGIC_LLMROUTER_ACCESS_TOKEN"],n={};for(let r of e){let o=process.env[r];o&&(n[r]=o)}return{id:"qlogicagent",cliPath:process.execPath,acpArgs:[process.argv[1]??""],env:Object.keys(n).length>0?n:void 0,protocol:"acp"}}buildExternalDescriptor(e){if(e==="qlogicagent")return this.buildSelfDescriptor();let n=this.list().find(m=>m.id===e);if(!n||n.protocol!=="acp"||n.status!=="available"||!n.cliPath)return null;let r=Io(e)??Ls[e],o=this.configStore?.agents[e],i=this.configStore?.customAgents?.[e],s=o?.customArgs?.length?o.customArgs:i?.acpArgs??r?.acpArgs??[],a=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:s}:gde(n.cliPath,s),c=o?.authPreference??"auto",l=kF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:Sde(r,a.acpArgs,l,this.keySources,c),p=r?wde(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:yde(r,o,l),suppressEnvKeys:p.length>0?p:void 0,protocol:"acp"}}getNativeLoginState(e){if(e!=="qlogicagent")return this.keySources.hasSubscription?.(e)}isAgentReady(e){if(e==="qlogicagent")return!0;let n=this.buildExternalDescriptor(e);if(!n)return!1;let r=Io(e)??Ls[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Rg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&vF(r)?bF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Io(e)??Ls[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Rg(n,r);if(o==="account"||n.authMode==="oauth"||n.keySource==="none"){if(this.keySources.hasSubscription?.(e)===!1){let s=n.name??e,a=n.install?.setupCommand;return a?`${s} \u9700\u8981\u5148\u5B8C\u6210\u767B\u5F55/\u8BBE\u7F6E: \u8BF7\u8FD0\u884C ${a}\u3002`:`${s} \u9700\u8981\u5148\u5B8C\u6210\u767B\u5F55/\u8BBE\u7F6E\u3002`}return null}if(!vF(n)||bF(kF(n,this.keySources,r),n))return null;let i=n.name??e;return o==="managed"?`${i} \u7684\u300C\u5E73\u53F0\u989D\u5EA6\u300D\u6682\u4E0D\u53EF\u7528:\u672A\u83B7\u53D6\u5230\u5E73\u53F0\u63A8\u7406\u5BC6\u94A5(\u8BF7\u786E\u8BA4\u8D26\u53F7\u5DF2\u767B\u5F55;\u79BB\u7EBF\u65F6\u5E73\u53F0\u989D\u5EA6\u4E0D\u53EF\u7528)\u3002`:`${i} \u7F3A\u5C11\u53EF\u7528\u7684 API Key:\u8BF7\u5728\u300C\u53C2\u6570\u914D\u7F6E \u2192 \u51ED\u636E\u6765\u6E90\u300D\u586B\u5165\u5B98\u65B9 Key,\u6216\u5207\u6362\u5230\u300C\u5E73\u53F0\u989D\u5EA6\u300D\u3002`}};function HF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=FF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var qd="https://registry.npmmirror.com",bc="https://pypi.tuna.tsinghua.edu.cn/simple",LA="https://registry.npmmirror.com/-/binary";function xde(){return{npm_config_registry:qd,PIP_INDEX_URL:bc,UV_DEFAULT_INDEX:bc,UV_INDEX_URL:bc,UV_PYTHON_INSTALL_MIRROR:`${LA}/python-build-standalone`,NODEJS_ORG_MIRROR:`${LA}/node`,npm_config_disturl:`${LA}/node`}}var zF=Object.keys(xde());import{readFileSync as Dde}from"node:fs";import{randomUUID as $de}from"node:crypto";le();Sa();import{readdirSync as Rde,readFileSync as Tde,statSync as UA,writeFileSync as Pde}from"node:fs";import{join as Wd}from"node:path";var Ade=["auto-skill-","test-skill-"],Ide=".skills_prompt_snapshot.json";function _de(t){return Ade.some(e=>t.startsWith(e))}function Cde(t){let e=t.replace(/\r\n/g,`
683
+ `,c=t.getWriter();try{await c.write(n.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Ri(t){return t??{}}function iF(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var vg=class{connection;constructor(e,n){let r=e(this),o=async(s,a)=>{switch(s){case ar.fs_write_text_file:{let c=TA.parse(a);return await r.writeTextFile?.(c)??{}}case ar.fs_read_text_file:{let c=hA.parse(a);return r.readTextFile?.(c)}case ar.session_request_permission:{let c=wA.parse(a);return r.requestPermission(c)}case ar.terminal_create:{let c=fA.parse(a);return r.createTerminal?.(c)}case ar.terminal_output:{let c=bA.parse(a);return r.terminalOutput?.(c)}case ar.terminal_release:{let c=yA.parse(a);return await r.releaseTerminal?.(c)??{}}case ar.terminal_wait_for_exit:{let c=RA.parse(a);return r.waitForTerminalExit?.(c)}case ar.terminal_kill:{let c=gA.parse(a);return await r.killTerminal?.(c)??{}}case ar.elicitation_create:{if(!r.unstable_createElicitation)throw fn.methodNotFound(s);let c=SA.parse(a);return r.unstable_createElicitation(c)}default:if(r.extMethod)return r.extMethod(s,a);throw fn.methodNotFound(s)}},i=async(s,a)=>{switch(s){case ar.session_update:{let c=xA.parse(a);return r.sessionUpdate(c)}case ar.elicitation_complete:{if(!r.unstable_completeElicitation)return;let c=uA.parse(a);return r.unstable_completeElicitation(c)}default:if(r.extNotification)return r.extNotification(s,a);throw fn.methodNotFound(s)}};this.connection=new PA(o,i,n)}initialize(e){return this.connection.sendRequest(Ne.initialize,e)}newSession(e){return this.connection.sendRequest(Ne.session_new,e)}loadSession(e){return this.connection.sendRequest(Ne.session_load,e,Ri)}unstable_forkSession(e){return this.connection.sendRequest(Ne.session_fork,e)}listSessions(e){return this.connection.sendRequest(Ne.session_list,e)}deleteSession(e){return this.connection.sendRequest(Ne.session_delete,e,Ri)}resumeSession(e){return this.connection.sendRequest(Ne.session_resume,e)}closeSession(e){return this.connection.sendRequest(Ne.session_close,e)}setSessionMode(e){return this.connection.sendRequest(Ne.session_set_mode,e,Ri)}setSessionConfigOption(e){return this.connection.sendRequest(Ne.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Ne.authenticate,e,Ri)}unstable_listProviders(e){return this.connection.sendRequest(Ne.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Ne.providers_set,e,Ri)}unstable_disableProvider(e){return this.connection.sendRequest(Ne.providers_disable,e,Ri)}logout(e){return this.connection.sendRequest(Ne.logout,e,Ri)}prompt(e){return this.connection.sendRequest(Ne.session_prompt,e)}cancel(e){return this.connection.sendNotification(Ne.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(Ne.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(Ne.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(Ne.nes_close,e,Ri)}unstable_didOpenDocument(e){return this.connection.sendNotification(Ne.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(Ne.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(Ne.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(Ne.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(Ne.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(Ne.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(Ne.nes_reject,e)}extMethod(e,n){return this.connection.sendRequest(e,n)}extNotification(e,n){return this.connection.sendNotification(e,n)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},PA=class{pendingResponses=new Map;nextRequestId=0;requestHandler;notificationHandler;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;constructor(e,n,r){this.requestHandler=e,this.notificationHandler=n,this.stream=r,this.closedPromise=new Promise(o=>{this.abortController.signal.addEventListener("abort",()=>o())}),this.receive()}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}async receive(){let e;try{let n=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:r,done:o}=await n.read();if(o)break;if(r)try{this.processMessage(r)}catch(i){console.error("Unexpected error during message processing:",r,i),"id"in r&&r.id!==void 0&&this.sendMessage({jsonrpc:"2.0",id:r.id,error:{code:-32700,message:"Parse error"}})}}}finally{n.releaseLock()}}catch(n){e=n}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let n=e??new Error("ACP connection closed");for(let r of this.pendingResponses.values())r.reject(n);this.pendingResponses.clear(),this.abortController.abort(n)}async processMessage(e){if("method"in e&&"id"in e){let n=await this.tryCallRequestHandler(e.method,e.params);"error"in n&&console.error("Error handling request",e,n.error),await this.sendMessage({jsonrpc:"2.0",id:e.id,...n})}else if("method"in e){let n=await this.tryCallNotificationHandler(e.method,e.params);"error"in n&&console.error("Error handling notification",e,n.error)}else"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}async tryCallRequestHandler(e,n){try{return{result:await this.requestHandler(e,n)??null}}catch(r){if(r instanceof fn)return r.toResult();if(r instanceof u.ZodError)return fn.invalidParams(r.format()).toResult();let o;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(o=r.message);try{return fn.internalError(o?JSON.parse(o):{}).toResult()}catch{return fn.internalError({details:o}).toResult()}}}async tryCallNotificationHandler(e,n){try{return await this.notificationHandler(e,n),{result:null}}catch(r){if(r instanceof fn)return r.toResult();if(r instanceof u.ZodError)return fn.invalidParams(r.format()).toResult();let o;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(o=r.message);try{return fn.internalError(o?JSON.parse(o):{}).toResult()}catch{return fn.internalError({details:o}).toResult()}}}handleResponse(e){let n=this.pendingResponses.get(e.id);if(n){if("result"in e)n.resolve(e.result);else if("error"in e){let{code:r,message:o,data:i}=e.error;n.reject(new fn(r,o,i))}this.pendingResponses.delete(e.id)}else console.error("Got response to unknown request",e.id)}sendRequest(e,n,r){if(this.abortController.signal.aborted)return iF(this.closedReason());let o=this.nextRequestId++,i=new Promise((s,a)=>{this.pendingResponses.set(o,{resolve:c=>{try{s(r?r(c):c)}catch(l){a(l)}},reject:a})});return i.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:o,method:e,params:n}),i}sendNotification(e,n){return this.abortController.signal.aborted?iF(this.closedReason()):this.sendMessage({jsonrpc:"2.0",method:e,params:n})}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let n=this.stream.writable.getWriter();try{await n.write(e)}finally{n.releaseLock()}}).catch(n=>{this.close(n)}),this.writeQueue}},fn=class t extends Error{code;data;constructor(e,n,r){super(n),this.code=e,this.name="RequestError",this.data=r}static parseError(e,n){return new t(-32700,`Parse error${n?`: ${n}`:""}`,e)}static invalidRequest(e,n){return new t(-32600,`Invalid request${n?`: ${n}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,n){return new t(-32602,`Invalid params${n?`: ${n}`:""}`,e)}static internalError(e,n){return new t(-32603,`Internal error${n?`: ${n}`:""}`,e)}static authRequired(e,n){return new t(-32e3,`Authentication required${n?`: ${n}`:""}`,e)}static resourceNotFound(e){return new t(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};var Ule=1,Fle=2e4,sF=3e4,Hle=3e5,kr={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",USAGE_UPDATE:"usage_update"};var Ld=class extends Error{retryable=!1;authMethods;constructor(e,n){super(e),this.name="AcpAuthRequiredError",this.authMethods=n}};function Ud(t,e){if(t instanceof Ld)return t;let n=t,r=Array.isArray(n?.data?.authMethods)?n.data.authMethods:[];if(n?.code===-32e3||r.length>0||/auth(?:entication|orization)?\s+required/i.test(n?.message??"")){let i=r[0],s=i?.description||(i?.name?`Use "${i.name}".`:"");return new Ld(`Authentication required.${s?` ${s}`:""}`,r)}if(e&&e.length>0){let i=e[0],s=n?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:n?.message||"Authentication required.");return new Ld(s,e)}return null}function zle(t){let e=t;if(!e||typeof e.message!="string")return t;let n=e.data,r=typeof n=="string"?n:typeof n?.details=="string"?n.details:typeof n?.error=="string"?n.error:typeof n?.message=="string"?n.message:"";if(!r||e.message.includes(r))return t;let o=new Error(`${e.message}: ${r}`);return o.name=t instanceof Error?t.name:"Error",Object.assign(o,{code:e.code,data:e.data}),o}var Ti=class{conn=null;child=null;onNotification=null;hostHandler=null;attach(e,n,r){if(this.child=e,this.onNotification=n??null,this.hostHandler=r??null,!e.stdin||!e.stdout)throw new Error("ACP adapter: child process has no stdio");let o=oF(Lle.toWeb(e.stdin),jle.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new vg(()=>this.buildClient(),{readable:i,writable:o.writable})}consumeExtensionNotification(e){let n=e;if(!n||n.method!=="session/update"||n.id!==void 0)return!1;let r=n.params?.update?.sessionUpdate;if(typeof r!="string"||!r.startsWith("x_"))return!1;try{this.onNotification?.("session/update",n.params)}catch{}return!0}buildClient(){let e=()=>this.hostHandler,n=(r,o)=>this.onNotification?.(r,o);return{async sessionUpdate(r){n("session/update",r)},async requestPermission(r){let o=e(),s=(o?.requestPermission?await o.requestPermission(r):{optionId:"allow"})?.optionId;return s?{outcome:{outcome:"selected",optionId:s}}:{outcome:{outcome:"cancelled"}}},async readTextFile(r){return{content:(await e()?.readTextFile?.(r))?.content??""}},async writeTextFile(r){return await e()?.writeTextFile?.(r),{}},async createTerminal(r){return await e()?.createTerminal?.(r)??{terminalId:""}},async terminalOutput(r){return await e()?.terminalOutput?.(r)??{output:"",truncated:!1}},async releaseTerminal(r){return await e()?.releaseTerminal?.(r),{}},async waitForTerminalExit(r){return await e()?.waitForTerminalExit?.(r)??{}},async killTerminal(r){return await e()?.killTerminal?.(r),{}},async extMethod(r,o){return await e()?.extMethod?.(r,o)??{}},async extNotification(r,o){n(r,o)}}}detach(){this.conn=null,this.hostHandler=null,this.onNotification=null,this.child=null}requireConn(){if(!this.conn)throw new Error("ACP adapter not attached");return this.conn}async withTimeout(e,n,r,o){let i,s=new Promise((a,c)=>{i=setTimeout(()=>{try{o?.()}catch{}c(new Error(`ACP ${r} timeout (${n}ms)`))},n)});try{return await Promise.race([e,s])}finally{i&&clearTimeout(i)}}async initialize(e){let n={protocolVersion:Ule,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}},clientInfo:{name:"qlogicagent",version:"1.0.0"}},r=await this.withTimeout(this.requireConn().initialize(n),Fle,"initialize").catch(i=>{throw Ud(i)??i}),o=r?.agentCapabilities??{};return{protocolVersion:typeof r?.protocolVersion=="number"?r.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:r?.agentInfo,authMethods:r?.authMethods}}async createSession(e,n){let r={cwd:n.cwd,mcpServers:n.mcpServers??[]};n.additionalDirectories?.length&&(r.additionalDirectories=n.additionalDirectories),n.systemPrompt&&(r._meta={qlogicagent:{systemPrompt:n.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(r),sF,"session/new").catch(i=>{throw Ud(i)??i});if(typeof o?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:o.sessionId}}async sendPrompt(e,n,r,o=Hle){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:n,prompt:[{type:"text",text:r}]}),o,"session/prompt",()=>{i.cancel({sessionId:n}).catch(()=>{})}).catch(a=>{throw Ud(a)??zle(a)});return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:void 0}}async resumeSession(e,n,r){let o={sessionId:n,cwd:r?.cwd??process.cwd(),mcpServers:r?.mcpServers??[]},i=await this.withTimeout(this.requireConn().loadSession(o),sF,"session/load");return{sessionId:typeof i?.sessionId=="string"?i.sessionId:n}}static translateNotification(e,n){let r=n;if(e==="session/update"){if(!r)return null;let o=r.update;if(!o)return null;let i=o.sessionUpdate,s=r.sessionId;switch(i){case kr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case kr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case kr.TOOL_CALL:return{method:"turn.tool_call",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"running",content:o.content,kind:o.kind,rawInput:o.rawInput,sessionId:s}};case kr.TOOL_CALL_UPDATE:return{method:"turn.tool_result",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"completed",content:o.content,rawOutput:o.rawOutput,sessionId:s}};case kr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case kr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case kr.AVAILABLE_COMMANDS_UPDATE:case kr.CURRENT_MODE_UPDATE:case kr.CONFIG_OPTION_UPDATE:case kr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case kr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as Ble}from"node:child_process";import{readFile as qle,writeFile as Wle}from"node:fs/promises";import{isAbsolute as aF,normalize as Gle,relative as Kle,resolve as Vle,sep as Jle}from"node:path";function Zle(t){let e=t.options;if(!Array.isArray(e)||e.length===0)return"allow";let n=e.filter(c=>!!c&&typeof c=="object"),r=c=>typeof c.optionId=="string"&&c.optionId.trim()?c.optionId:void 0;if(n.find(c=>r(c)==="allow"))return"allow";let i=n.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/allow/i.test(l)}),s=i?r(i):void 0;if(s)return s;let a=n.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/reject|deny|cancel/i.test(l)});return r(a??{})??r(n[0]??{})??"allow"}function AA(t){let e=new Map,n=0,r=i=>{let s=aF(i)?Gle(i):Vle(t.cwd,i),a=Kle(t.cwd,s);if(a===".."||a.startsWith(`..${Jle}`)||aF(a))throw new Error(`path escapes cwd: ${i}`);return s},o=i=>String(i.terminalId??"");return{async requestPermission(i){return t.requestPermission?t.requestPermission(i):{optionId:Zle(i)}},async readTextFile(i){return{content:await qle(r(i.path),"utf8")}},async writeTextFile(i){return await Wle(r(i.path),i.content,"utf8"),{}},async createTerminal(i){let s=String(i.command??""),a=i.args,c=Array.isArray(a)?a.map(String):[],l=i.cwd,d=l?r(String(l)):t.cwd,p=i.env,m={...process.env,...p&&typeof p=="object"?p:{}},f=Ble(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"]}),g=`term-${++n}`,h={child:f,output:"",exitStatus:null,exit:new Promise(y=>{f.on("exit",(v,b)=>{let k={exitCode:v,signal:b};h.exitStatus=k,y(k)}),f.on("error",()=>{let v={exitCode:null,signal:null};h.exitStatus=v,y(v)})})};return f.stdout?.on("data",y=>{h.output+=y.toString()}),f.stderr?.on("data",y=>{h.output+=y.toString()}),e.set(g,h),{terminalId:g}},async terminalOutput(i){let s=e.get(o(i));return s?{output:s.output,truncated:!1,exitStatus:s.exitStatus}:{output:"",truncated:!1,exitStatus:null}},async waitForTerminalExit(i){let s=e.get(o(i));return s?s.exit:{exitCode:null,signal:null}},async releaseTerminal(i){let s=o(i),a=e.get(s);if(a&&a.child.exitCode===null&&a.child.signalCode===null)try{a.child.kill()}catch{}return e.delete(s),{}},async killTerminal(i){let s=e.get(o(i));if(s)try{s.child.kill("SIGKILL")}catch{}return{}},disposeAll(){for(let i of e.values())try{i.child.kill("SIGKILL")}catch{}e.clear()}}}var Fd=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{exec as Yle,execFile as Qle,execFileSync as cF,execSync as wF}from"node:child_process";import{existsSync as _i,mkdirSync as SF,readFileSync as yc,readdirSync as xF,writeFileSync as RF}from"node:fs";import{homedir as NA,platform as ede,tmpdir as tde}from"node:os";import{dirname as Hd,join as kt}from"node:path";import{promisify as TF}from"node:util";function Pi(){let t=process.env.XIAOZHICLAW_NODE_EXE,e=process.env.XIAOZHICLAW_NPM_CLI;return!t||!e?null:{nodeExe:t,npmCli:e,prefix:process.env.XIAOZHICLAW_NPM_GLOBAL_PREFIX||void 0}}function Ai(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function IA(t){let e=t.trim().split(/\s+/)[0];return e==="npm"||e==="npm.cmd"}var Xle=/^(?:pip3?|pipx|uv|uvx|python3?|curl|wget|brew|sh|bash)\b/;function _A(t){return Xle.test(t.trim())}function CA(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var lF=TF(Qle),PF=TF(Yle),Ls={claude:{id:"claude",name:"Claude Code",cliCommand:"claude-agent-acp",acpArgs:[],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:["-c","sandbox_mode=danger-full-access","-c","approval_policy=untrusted"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!0,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!1},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--experimental-acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"GEMINI_API_KEY",baseUrlEnvVar:"GOOGLE_GEMINI_BASE_URL"},glm:{id:"glm",name:"GLM Agent",cliCommand:"glm-acp-agent",acpArgs:[],defaultCliPath:"npx glm-acp-agent",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"Z_AI_API_KEY",baseUrlEnvVar:"ACP_GLM_BASE_URL"},cline:{id:"cline",name:"Cline",cliCommand:"cline",acpArgs:["--acp"],defaultCliPath:"npx cline",authRequired:!0,supportsBaseUrlOverride:!0},nova:{id:"nova",name:"Nova",cliCommand:"nova",acpArgs:["acp"],defaultCliPath:"npx @compass-ai/nova",authRequired:!0,supportsBaseUrlOverride:!0},openclaw:{id:"openclaw",name:"OpenClaw",cliCommand:"openclaw",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENCLAW_API_KEY",baseUrlEnvVar:"OPENCLAW_BASE_URL"}},nde=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],dF={claude:{brandId:"claude",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @agentclientprotocol/claude-agent-acp",cliCommand:"claude-agent-acp",docsUrl:"https://github.com/agentclientprotocol/claude-agent-acp"},strengths:"\u590D\u6742\u63A8\u7406\u3001\u91CD\u6784\u3001\u957F\u94FE\u8DEF\u5B9E\u73B0"},codex:{brandId:"codex",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @zed-industries/codex-acp",cliCommand:"codex-acp",verifyCmd:"codex-acp --help",docsUrl:"https://github.com/zed-industries/codex-acp"},strengths:"\u4EE3\u7801\u751F\u6210\u3001\u8C03\u8BD5\u3001shell/\u5DE5\u5177\u94FE"},gemini:{brandId:"gemini",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @google/gemini-cli",cliCommand:"gemini",docsUrl:"https://github.com/google-gemini/gemini-cli"},strengths:"\u591A\u6A21\u6001\u3001\u957F\u4E0A\u4E0B\u6587\u3001\u7EFC\u5408\u5B9E\u73B0"},copilot:{brandId:"copilot",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9ED8\u8BA4\u9700 GitHub \u8D26\u53F7(\u4E5F\u652F\u6301 BYOK \u81EA\u5E26 key,\u540E\u7EED\u53EF\u63A5\u5165\u514D\u767B\u5F55\u6CE8\u5165)",install:{npm:"npm i -g @github/copilot",cliCommand:"copilot",setupCommand:"copilot",docsUrl:"https://docs.github.com/copilot/concepts/agents/about-copilot-cli"},strengths:"\u901A\u7528\u7F16\u7801\u3001GitHub \u751F\u6001"},cursor:{brandId:"cursor",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9700 Cursor \u8D26\u53F7",install:{curl:"curl https://cursor.com/install -fsS | bash",cliCommand:"cursor-agent",setupCommand:"cursor-agent login",docsUrl:"https://cursor.com/cli"},strengths:"\u901A\u7528\u7F16\u7801\u3001IDE \u96C6\u6210"},qwen:{brandId:"qwen",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @qwen-code/qwen-code",cliCommand:"qwen",docsUrl:"https://github.com/QwenLM/qwen-code"},strengths:"\u524D\u7AEF/UI\u3001\u4EA4\u4E92\u5B9E\u73B0\u3001\u901A\u7528\u7F16\u7801"},kimi:{brandId:"kimi",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9700 Kimi \u8D26\u53F7(\u5728\u7EC8\u7AEF\u8FD0\u884C kimi login \u767B\u5F55)",install:{pip:"uv tool install kimi-cli",cliCommand:"kimi",setupCommand:"kimi login",docsUrl:"https://github.com/MoonshotAI/kimi-cli"},strengths:"\u957F\u4E0A\u4E0B\u6587\u3001\u4E2D\u6587\u573A\u666F"},glm:{brandId:"glm",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g glm-acp-agent",cliCommand:"glm-acp-agent",docsUrl:"https://github.com/stefandevo/glm-acp-agent"},strengths:"\u901A\u7528\u7F16\u7801\u3001\u4E2D\u6587\u573A\u666F"},opencode:{brandId:"opencode",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g opencode-ai",cliCommand:"opencode",docsUrl:"https://opencode.ai/docs"},strengths:"\u7B97\u6CD5\u3001\u6570\u636E\u7ED3\u6784\u3001\u590D\u6742\u903B\u8F91"},kiro:{brandId:"kiro",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{cliCommand:"kiro-cli",docsUrl:"https://kiro.dev/docs"},strengths:"\u901A\u7528\u7F16\u7801"},qoder:{brandId:"qoder",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @qoder-ai/qodercli",cliCommand:"qodercli",docsUrl:"https://docs.qoder.com/cli/acp"},strengths:"\u901A\u7528\u7F16\u7801"},openclaw:{brandId:"openclaw",category:"assistant",integration:"acp",keySource:"direct",authMode:"key",note:"\u9AD8\u7EA7:\u9700\u81EA\u5907\u8FD0\u884C\u4E2D\u7684 openclaw Gateway + \u6709\u6548 ~/.openclaw \u914D\u7F6E(openclaw acp = \u6302\u5728 Gateway \u4E0A\u7684 ACP \u6865)",install:{npm:"npm i -g openclaw",cliCommand:"openclaw",setupCommand:"openclaw onboard",docsUrl:"https://github.com/openclaw/openclaw"},strengths:"\u52A9\u7406/\u7F16\u6392\u3001\u901A\u7528"},hermes:{brandId:"hermes",category:"assistant",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9996\u6B21\u9700\u5728\u7EC8\u7AEF\u8FD0\u884C hermes acp --setup \u914D\u7F6E provider/model",install:{pip:"uv tool install hermes-agent[acp] --python 3.13",cliCommand:"hermes",setupCommand:"hermes acp --setup",docsUrl:"https://github.com/NousResearch/hermes-agent"},strengths:"\u52A9\u7406\u3001\u901A\u7528"}};function Io(t){let e=Ls[t];if(e)return dF[t]?{...e,...dF[t]}:e}function zd(){return nde.map(t=>{let e=Io(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var _o=ede()==="win32",AF=5*6e4,rde=2e4,Ii,gc=new Map,EA=kt(process.env.QLOGICAGENT_HOME||kt(NA(),".qlogicagent"),"agent-update-cache.json"),uF=!1;function IF(){if(!uF){uF=!0;try{let t=JSON.parse(yc(EA,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!gc.has(e)&&gc.set(e,n)}catch{}}}var kg=null;function ode(){kg||(kg=setTimeout(()=>{kg=null;try{let t={};for(let[e,n]of gc)t[e]=n;SF(Hd(EA),{recursive:!0}),RF(EA,JSON.stringify(t),"utf8")}catch{}},1e3),kg.unref?.())}function MA(t){try{let e=_o?`where ${t}`:`which ${t}`;return wF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function DA(t){try{let e=_o?`where ${t}`:`which ${t}`,{stdout:n}=await PF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function _F(t,e){let n=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r[i]!==o[i])return o[i]-r[i];return e.localeCompare(t)}function ide(){if(!_o)return null;let t=[process.env.COPILOT_CACHE_HOME?kt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?kt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?kt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,kt(NA(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=xF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(_F);for(let r of n){let o=kt(e,r,"npm-loader.js");if(_i(o)&&NF(o))return o}}catch{}return null}function sde(t){return t.id==="copilot"?ide()??MA(t.cliCommand):MA(t.cliCommand)}async function ade(){if(!_o)return null;let t=[process.env.COPILOT_CACHE_HOME?kt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?kt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?kt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,kt(NA(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=xF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(_F);for(let r of n){let o=kt(e,r,"npm-loader.js");if(_i(o)&&await OF(o))return o}}catch{}return null}async function cde(t){return t.id==="copilot"?await ade()??await DA(t.cliCommand):DA(t.cliCommand)}function lde(t,e){let n=Pi();return n?cF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:Ai(n)}).trim():cF(_o?"cmd.exe":"npm",_o?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"]}).trim()}async function CF(t,e){let n=Pi();if(n){let{stdout:o}=await lF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:Ai(n)});return o.trim()}let{stdout:r}=await lF(_o?"cmd.exe":"npm",_o?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function dde(t){let e=t.trim().replace(/^["']|["']$/g,"");if(!e||e.startsWith("-"))return null;if(e.startsWith("@")){let r=e.indexOf("@",1);return r>0?e.slice(0,r):e}let n=e.indexOf("@");return n>0?e.slice(0,n):e}function Tg(t){if(!t)return null;let e=t.trim().split(/\s+/).filter(Boolean);if(e[0]!=="npm"&&e[0]!=="npm.cmd")return null;let n=e.findIndex(r=>r==="i"||r==="install"||r==="add");if(n<0)return null;for(let r=n+1;r<e.length;r+=1){let o=e[r];if(!(o==="-g"||o==="--global")){if(o.startsWith("--")&&!o.includes("=")){r+=1;continue}if(!o.startsWith("-"))return dde(o)}}return null}function Bd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function ude(t,e){let n=i=>{let s=Bd(i)??i,[a,c=""]=s.replace(/^v/,"").split("-",2),l=a.split(".").map(d=>Number.parseInt(d,10)||0);for(;l.length<3;)l.push(0);return{nums:l,pre:c}},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r.nums[i]!==o.nums[i])return r.nums[i]-o.nums[i];return r.pre===o.pre?0:r.pre?o.pre?r.pre.localeCompare(o.pre):-1:1}function EF(t,e){return!t||!e?!1:ude(t,e)>0}function pde(){if(Ii!==void 0)return Ii;try{Ii=lde(["root","-g"],3e3)||null}catch{Ii=null}return Ii}async function mde(){if(Ii===void 0)try{Ii=await CF(["root","-g"],3e3)||null}catch{Ii=null}}function Pg(t){if(!t)return null;let e=pde();if(!e)return null;let n=kt(e,...t.split("/"),"package.json");try{let r=JSON.parse(yc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function pF(t){let e=Tg(t?.npm);return Pg(e)}function MF(t,e){return Pg(Tg(t.install?.npm))??Bd(e)??e??void 0}async function fde(t,e){if(!t)return null;IF();let n=e?`${t}\0${e}`:t,r=gc.get(n);if(r){let i=r.version?AF:rde;if(Date.now()-r.timestamp<i)return r.version}let o=null;try{let i=["view",t,"version","--json"];e&&i.push("--registry",e);let s=await CF(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Bd(s)}catch{o=null}return gc.set(n,{timestamp:Date.now(),version:o}),ode(),o}async function DF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=Tg(i.install?.npm),c=Pg(a)??Bd(s)??s??void 0;if(!a||!c)return null;let l=await fde(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:EF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function $F(t,e){IF();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=Tg(i.install?.npm),c=Pg(a)??Bd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=gc.get(l);d?.version&&Date.now()-d.timestamp<AF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:EF(d.version,c)})}return{updates:n,stale:r}}function NF(t){let e=t.endsWith("npm-loader.js");for(let n of["--version","version","-v"])try{let r=e?`"${process.execPath}" "${t}" ${n}`:`"${t}" ${n}`,i=wF(r,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}async function OF(t){let e=t.endsWith("npm-loader.js");for(let n of["--version","version","-v"])try{let r=e?`"${process.execPath}" "${t}" ${n}`:`"${t}" ${n}`,{stdout:o}=await PF(r,{encoding:"utf8",timeout:5e3,windowsHide:!0}),i=String(o).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}function gde(t,e){if(!_o)return{cliPath:t,acpArgs:e};if(t.endsWith("npm-loader.js")){let o=e.includes("--no-auto-update");return{cliPath:process.execPath,acpArgs:[t,...e,...o?[]:["--no-auto-update"]]}}let n=jF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=hde(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function jF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!_i(r))continue;let o;try{o=yc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=kt(Hd(e),s);if(_i(a))return a}return null}function hde(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!_i(r))continue;let o;try{o=yc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=kt(Hd(e),s);if(_i(a))return a}return null}function mF(t){let e=jF(t);if(!e)return null;let n=Hd(e);for(let r=0;r<6;r+=1){let o=kt(n,"package.json");try{if(_i(o)){let s=JSON.parse(yc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=Hd(n);if(i===n)break;n=i}return null}var fF=6e4;function yde(t,e,n){let r={};return t?.env&&Object.assign(r,t.env),n&&Object.assign(r,n),t?.apiKeyEnvVar&&e?.apiKey&&(r[t.apiKeyEnvVar]=e.apiKey),t?.baseUrlEnvVar&&e?.baseUrl&&(r[t.baseUrlEnvVar]=e.baseUrl),e?.env&&Object.assign(r,e.env),Object.keys(r).length>0?r:void 0}var LF=new Set(["codex","qwen","opencode"]),Sg=new Set(["qwen","opencode"]),xg=new Set(["gemini"]),$A=new Set(["glm"]),gF={claude:"anthropic",codex:"openai"};function bde(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function vde(t){let e=kt(tde(),"qlogicagent-codex-model-catalog");SF(e,{recursive:!0});let n=kt(e,`${bde(t)}.json`),r=JSON.stringify({models:[{slug:t,display_name:t,supported_reasoning_levels:[],shell_type:"shell_command",visibility:"list",priority:0,base_instructions:"You are Codex, a coding agent. Follow the user's instructions and use tools only when needed.",supports_reasoning_summaries:!1,support_verbosity:!1,truncation_policy:{mode:"tokens",limit:1e6},supports_parallel_tool_calls:!1,experimental_supported_tools:[],supported_in_api:!0}]});return(!_i(n)||yc(n,"utf8")!==r)&&RF(n,r,"utf8"),n}function OA(t){return t.id!=="claude"}function Rg(t,e){return e==="account"&&!OA(t)?"auto":e}function UF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&OA(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||Sg.has(t.id)||xg.has(t.id)||$A.has(t.id))&&e.push("managed"),e}function jA(t,e,n){let r=Rg(t,e);return!!(r==="account"||r==="auto"&&OA(t)&&n?.hasSubscription?.(t.id)===!0)}var FF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},kde={glm:"ACP_GLM_AVAILABLE_MODELS"};function wg(t,e,n){let{apiKeyEnvVar:r,baseUrlEnvVar:o}=t;r&&e.llmrouterKey&&(n[r]=e.llmrouterKey);let i=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;o&&i&&(n[o]=i);let s=FF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=kde[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function hF(t,e,n){e.llmrouterKey&&(n.OPENAI_API_KEY=e.llmrouterKey);let r=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;r&&(n.OPENAI_BASE_URL=r),e.llmrouterModel&&(n.OPENAI_MODEL=e.llmrouterModel)}var yF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function bF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...yF]:yF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function vF(t){return!!t.apiKeyEnvVar||Sg.has(t.id)||xg.has(t.id)}function kF(t,e,n="auto"){let r={};if(!t)return r;let o=Rg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=gF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||xg.has(t.id)||$A.has(t.id)?wg(t,e,r):Sg.has(t.id)&&hF(t,e,r),r;if(jA(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=gF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:wg(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:Sg.has(t.id)?hF(t,e,r):(xg.has(t.id)||$A.has(t.id))&&wg(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&LF.has(t.id)){let a=e.passthroughModel;r.OPENAI_API_KEY=a.apiKey,a.baseUrl&&(r.OPENAI_BASE_URL=a.baseUrl),a.model&&(r.OPENAI_MODEL=a.model)}return r}function wde(t,e,n){if(!t||!jA(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),LF.has(t.id)&&r.push("OPENAI_MODEL"),r}function Sde(t,e,n,r,o="auto"){if(!t)return e;if(t.id==="qwen")return!n.OPENAI_API_KEY||e.some(a=>a==="--auth-type"||a.startsWith("--auth-type="))?e:[...e,"--auth-type=openai"];if(t.id!=="codex")return e;if(jA(t,o,r))return e.some(a=>a.includes("preferred_auth_method"))?e:[...e,"-c","preferred_auth_method=chatgpt"];if(t.keySource!=="llmrouter"||!n.OPENAI_API_KEY||e.some(a=>a.includes("model_provider")||a.includes("model_providers.")))return e;let i=n.OPENAI_BASE_URL,s=r.llmrouterModel||n.OPENAI_MODEL||"deepseek-v4-flash";return i?[...e,"-c","model_providers.llmrouter.name=llmrouter","-c",`model_providers.llmrouter.base_url=${i}`,"-c","model_providers.llmrouter.wire_api=responses","-c","model_providers.llmrouter.env_key=OPENAI_API_KEY","-c","model_provider=llmrouter","-c",`model=${s}`,"-c",`model_catalog_json=${vde(s)}`]:e}var hc=class{cache=null;configStore=null;keySources={};scanInFlight=null;setConfigStore(e){this.configStore=e}setKeySources(e){this.keySources=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<fF)return this.cache.agents;let n=[];for(let r of Object.values(Ls))n.push(this.detectBackend(r));if(this.configStore?.customAgents)for(let r of Object.values(this.configStore.customAgents))n.push(this.detectCustomAgent(r));return this.cache={agents:n,timestamp:Date.now()},n}async scanAsync(e=!1){return!e&&this.cache&&Date.now()-this.cache.timestamp<fF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await mde();let n=[...await Promise.all(Object.values(Ls).map(r=>this.detectBackendAsync(r)))];if(this.configStore?.customAgents){let r=await Promise.all(Object.values(this.configStore.customAgents).map(o=>this.detectCustomAgentAsync(o)));n.push(...r)}return this.cache={agents:n,timestamp:Date.now()},n}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let n=sde(e),r=n?NF(n)??mF(n)??pF(Io(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await cde(e),r=n?await OF(n)??mF(n)??pF(Io(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}assembleBackendDescriptor(e,n,r){let o=this.hasAgentConfig(e.id);return n?e.id==="copilot"&&!r?{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}:{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"available",cliPath:n,version:r??void 0,authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:e.id==="claude"||e.id==="goose"||e.id==="copilot",supportsUsageUpdate:e.id==="claude"||e.id==="codex"||e.id==="copilot",skillsDirs:e.skillsDirs}}:{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}}}detectCustomAgent(e){return this.assembleCustomAgentDescriptor(e,MA(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await DA(e.cliCommand))}assembleCustomAgentDescriptor(e,n){let r=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:n?"available":"not_installed",cliPath:n??void 0,authRequired:e.authRequired??!1,hasConfig:r,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let n=this.configStore.agents[e];return!!(n?.apiKey||n?.baseUrl||n?.customCliPath)}buildSelfDescriptor(){let e=["QLOGIC_LLMROUTER_USER_ID","QLOGIC_IMPLICIT_OWNER_ID","QLOGIC_DEVICE_ID","QLOGICAGENT_HOME","QLOGIC_LLMROUTER_BASE_URL","QLOGIC_LLMROUTER_ACCESS_TOKEN"],n={};for(let r of e){let o=process.env[r];o&&(n[r]=o)}return{id:"qlogicagent",cliPath:process.execPath,acpArgs:[process.argv[1]??""],env:Object.keys(n).length>0?n:void 0,protocol:"acp"}}buildExternalDescriptor(e){if(e==="qlogicagent")return this.buildSelfDescriptor();let n=this.list().find(m=>m.id===e);if(!n||n.protocol!=="acp"||n.status!=="available"||!n.cliPath)return null;let r=Io(e)??Ls[e],o=this.configStore?.agents[e],i=this.configStore?.customAgents?.[e],s=o?.customArgs?.length?o.customArgs:i?.acpArgs??r?.acpArgs??[],a=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:s}:gde(n.cliPath,s),c=o?.authPreference??"auto",l=kF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:Sde(r,a.acpArgs,l,this.keySources,c),p=r?wde(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:yde(r,o,l),suppressEnvKeys:p.length>0?p:void 0,protocol:"acp"}}getNativeLoginState(e){if(e!=="qlogicagent")return this.keySources.hasSubscription?.(e)}isAgentReady(e){if(e==="qlogicagent")return!0;let n=this.buildExternalDescriptor(e);if(!n)return!1;let r=Io(e)??Ls[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Rg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&vF(r)?bF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Io(e)??Ls[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Rg(n,r);if(o==="account"||n.authMode==="oauth"||n.keySource==="none"){if(this.keySources.hasSubscription?.(e)===!1){let s=n.name??e,a=n.install?.setupCommand;return a?`${s} \u9700\u8981\u5148\u5B8C\u6210\u767B\u5F55/\u8BBE\u7F6E: \u8BF7\u8FD0\u884C ${a}\u3002`:`${s} \u9700\u8981\u5148\u5B8C\u6210\u767B\u5F55/\u8BBE\u7F6E\u3002`}return null}if(!vF(n)||bF(kF(n,this.keySources,r),n))return null;let i=n.name??e;return o==="managed"?`${i} \u7684\u300C\u5E73\u53F0\u989D\u5EA6\u300D\u6682\u4E0D\u53EF\u7528:\u672A\u83B7\u53D6\u5230\u5E73\u53F0\u63A8\u7406\u5BC6\u94A5(\u8BF7\u786E\u8BA4\u8D26\u53F7\u5DF2\u767B\u5F55;\u79BB\u7EBF\u65F6\u5E73\u53F0\u989D\u5EA6\u4E0D\u53EF\u7528)\u3002`:`${i} \u7F3A\u5C11\u53EF\u7528\u7684 API Key:\u8BF7\u5728\u300C\u53C2\u6570\u914D\u7F6E \u2192 \u51ED\u636E\u6765\u6E90\u300D\u586B\u5165\u5B98\u65B9 Key,\u6216\u5207\u6362\u5230\u300C\u5E73\u53F0\u989D\u5EA6\u300D\u3002`}};function HF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=FF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var qd="https://registry.npmmirror.com",bc="https://pypi.tuna.tsinghua.edu.cn/simple",LA="https://registry.npmmirror.com/-/binary";function xde(){return{npm_config_registry:qd,PIP_INDEX_URL:bc,UV_DEFAULT_INDEX:bc,UV_INDEX_URL:bc,UV_PYTHON_INSTALL_MIRROR:`${LA}/python-build-standalone`,NODEJS_ORG_MIRROR:`${LA}/node`,npm_config_disturl:`${LA}/node`}}var zF=Object.keys(xde());import{readFileSync as Dde}from"node:fs";import{randomUUID as $de}from"node:crypto";le();Sa();import{readdirSync as Rde,readFileSync as Tde,statSync as UA,writeFileSync as Pde}from"node:fs";import{join as Wd}from"node:path";var Ade=["auto-skill-","test-skill-"],Ide=".skills_prompt_snapshot.json";function _de(t){return Ade.some(e=>t.startsWith(e))}function Cde(t){let e=t.replace(/\r\n/g,`
684
684
  `),n=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),r=e.match(/^---\n[\s\S]*?^description:\s*(.+)/m),o=e.match(/^---\n[\s\S]*?^category:\s*(.+)/m),i=e.match(/^---\n[\s\S]*?^author:\s*(.+)/m),s=e.match(/^---\n[\s\S]*?^requires:\s*(.+)/m),a=e.match(/^---\n[\s\S]*?^environments:\s*(.+)/m);return{version:n?.[1],description:r?.[1]?.trim(),category:o?.[1]?.trim()||void 0,author:i?.[1]?.trim()||void 0,requiredTools:BF(s?.[1]),environments:BF(a?.[1])}}function Gd(t,e){let n=An(),r=GM(),o=t?KM(t):new Set,i=[],s;try{s=Rde(n,{withFileTypes:!0})}catch{s=[]}for(let a of s){if(!a.isDirectory()||a.name.startsWith("."))continue;let c=Wd(n,a.name),l=Wd(c,"SKILL.md"),d;try{if(!UA(l).isFile())continue;d=Tde(l,"utf8")}catch{continue}let p=r.has(a.name),m=o.has(a.name),f=Cde(d),g=!Ede(f,e);i.push({name:a.name,filePath:l,baseDir:c,globallyDisabled:p,projectDisabled:m,active:!p&&!m&&!g,systemGenerated:_de(a.name),description:f.description,version:f.version,category:f.category,author:f.author,requiredTools:f.requiredTools,environments:f.environments})}return Mde(n,i),i}function Co(t,e){return Gd(t,e).filter(n=>n.active)}function Ln(t){let e=An(),n=Wd(e,t),r=Wd(n,"SKILL.md");try{if(UA(r).isFile())return{baseDir:n,filePath:r}}catch{}return null}function BF(t){if(!t)return;let e=t.replace(/^\[|\]$/g,"").split(/[,\s]+/).map(n=>n.replace(/^["']|["']$/g,"").trim()).filter(Boolean);return e.length>0?e:void 0}function Ede(t,e){if(t.environments&&e?.currentEnvironment&&!t.environments.includes(e.currentEnvironment))return!1;if(t.requiredTools){if(!e?.availableToolNames)return!1;let n=new Set(e.availableToolNames);return t.requiredTools.every(r=>n.has(r))}return!0}function Mde(t,e){try{let r={version:1,entries:e.map(o=>{let i=UA(o.filePath);return{name:o.name,size:i.size,mtimeMs:i.mtimeMs,description:o.description,version:o.version,requiredTools:o.requiredTools,environments:o.environments}})};Pde(Wd(t,Ide),JSON.stringify(r,null,2),"utf8")}catch{}}var Nde="astraclaw_capabilities",Ci=[Nde,"astraclaw"];function Ag(t){let e=Co(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform}).filter(r=>!r.systemGenerated);if(e.length===0&&!t.mcpAvailable)return;let n=["# AstraClaw shared skills","AstraClaw shares the user's installed skills with this external agent for the current workspace."];if(t.mcpAvailable?n.push("The injected MCP server is named `astraclaw_capabilities`; some ACP clients display it as `astraclaw`.","When you need the live list, use the MCP tool `skills_list` (also shown by some clients as `astraclaw:acp://skills_list` or `astraclaw_capabilities.skills_list`).","When you need the full workflow for one skill, use `skill_view` with its `name` (also shown by some clients as `astraclaw:acp://skill_view` or `astraclaw_capabilities.skill_view`).","When you need connectors installed from AstraClaw's Plugins page, use `mcp_connectors_list` to discover shared MCP tools, then call one through `mcp_tool_call` with its `toolName` and `args`.","Do not look for a separate qlogicagent MCP server or local `mcp` CLI; these tools are injected into this ACP session by AstraClaw."):n.push("This ACP agent did not advertise stdio MCP support, so the live `skills_list`/`skill_view` tools are not available in this session. Use the catalog below as read-only shared skill context."),e.length>0){n.push("","Active shared skills:");for(let r of e.slice(0,40))n.push(`- ${r.name}${r.description?`: ${r.description}`:""}`);e.length>40&&n.push(`- ...and ${e.length-40} more`)}return n.join(`
685
685
  `)}function qF(t){let e=Ag(t);if(e)return["<astraclaw_capabilities>","Host-provided context from AstraClaw. This is not the user's request; use it only to discover shared skills available in the current workspace.",e,"</astraclaw_capabilities>","","<user_request>"].join(`
686
686
  `)}async function Ig(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:Co(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform}).map(Ode)}};if(t.tool==="skill_view"){let e=typeof t.args.name=="string"?t.args.name.trim():"";if(!e)throw new Error("skill_view requires a skill name");let n=Ln(e);if(!n)throw new Error(`Skill not found: ${e}`);return{handled:!0,result:{name:e,content:Dde(n.filePath,"utf8")}}}if(t.tool==="mcp_connectors_list"){if(!t.toolCatalog)return{handled:!0,result:{tools:[],note:"AstraClaw MCP connector catalog is not attached to this capability server instance."}};let e=t.toolCatalog.getToolManifest().filter(n=>n.function.name.startsWith("mcp__")).map(n=>({toolName:n.function.name,server:Lde(n.function.name),name:Ude(n.function.name),description:n.function.description,inputSchema:n.function.parameters}));return{handled:!0,result:{tools:e,count:e.length}}}if(t.tool==="mcp_tool_call"){if(!t.toolCatalog)throw new Error("AstraClaw MCP connector catalog is not attached");let e=typeof t.args.toolName=="string"?t.args.toolName.trim():"";if(!e.startsWith("mcp__"))throw new Error("mcp_tool_call requires a connector toolName returned by mcp_connectors_list");let n=t.toolCatalog.findTool(e);if(!n?.execute)throw new Error(`MCP connector tool not found or not executable: ${e}`);let r=jde(t.args.args),o=`astraclaw_mcp_${$de().slice(0,8)}`,i=await n.execute(o,r);return{handled:!0,result:{toolName:e,content:i.content,details:i.details,imageUrls:i.imageUrls}}}return{handled:!1}}function Ode(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function jde(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Lde(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function Ude(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import{existsSync as Cg,mkdirSync as Eg,readFileSync as Kd,writeFileSync as Mg}from"node:fs";import{homedir as Fde}from"node:os";import{dirname as Dg,join as Us}from"node:path";le();var Hde={qwen:[".qwen","settings.json"],gemini:[".gemini","settings.json"]},_g="# BEGIN ASTRACLAW MANAGED MCP",zA="# END ASTRACLAW MANAGED MCP",WF=" # BEGIN ASTRACLAW MANAGED MCP",GF=" # END ASTRACLAW MANAGED MCP";function KF(t){let e=t.agentId.trim().toLowerCase(),n=t.homeDir||Fde(),r=zde(t),o=Hde[e];if(o){let i=Us(n,...o);return Wde({agentId:e,configPath:i,server:r})}if(e==="codex"){let i=Us(t.codexHome||process.env.CODEX_HOME?.trim()||Us(n,".codex"),"config.toml");return Kde({agentId:e,configPath:i,server:r})}if(e==="kimi"){let i=Us(n,".kimi","mcp.json");return Gde({agentId:e,configPath:i,server:r})}if(e==="hermes"){let i=Us(Bde(n),"config.yaml");return Vde({agentId:e,configPath:i,server:r})}return{agentId:e,status:"unsupported",reason:`No native MCP config adapter for agent "${e}"`}}function zde(t){return{command:t.nodePath||process.execPath,args:[t.serverScriptPath],env:qde({ASTRACLAW_PROJECT_ROOT:t.projectRoot,ASTRACLAW_MANAGED:"1",ASTRACLAW_MCP_CONFIG_PATH:xl(),QLOGICAGENT_HOME:process.env.QLOGICAGENT_HOME,QLOGIC_LLMROUTER_USER_ID:process.env.QLOGIC_LLMROUTER_USER_ID,QLOGIC_IMPLICIT_OWNER_ID:process.env.QLOGIC_IMPLICIT_OWNER_ID,QLOGIC_DEVICE_ID:process.env.QLOGIC_DEVICE_ID})}}function Bde(t){let e=process.env.HERMES_HOME?.trim();if(e)return e;let n=process.env.LOCALAPPDATA?.trim();return process.platform==="win32"&&n?Us(n,"hermes"):Us(t,".hermes")}function qde(t){return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"&&e[1].length>0))}function Wde(t){let e=VF(t.configPath),n={...e,mcpServers:{...BA(e.mcpServers)?e.mcpServers:{}}},r=n.mcpServers;for(let s of Ci)r[s]=t.server;let o=`${JSON.stringify(n,null,2)}
@@ -715,10 +715,10 @@ ${n}
715
715
  `;try{r.write(i)}catch{}}}async attemptRuntimeRestart(e,n,r){let o=this.callbacks.log,i=this.processes.get(e.memberId),s=i?.ipcServer,a=i?.ipcPath,c=i?.stderrStream;this.processes.delete(e.memberId);try{let l={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now(),stderrLogPath:i?.handle.stderrLogPath},d=e.external,p=[...d.acpArgs];this.syncNativeMcpConfig(e),a&&(n.QLOGICAGENT_PARENT_RPC=a);let m=qA(d.cliPath,p,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});l.pid=m.pid??-1;let f=new Map,g=new Ti,h=new Fd,y=AA({cwd:e.cwd,requestPermission:this.callbacks.onPermissionRequest?T=>this.callbacks.onPermissionRequest(e.memberId,T):void 0});this.processes.set(e.memberId,{handle:l,child:m,pendingRpc:f,acpAdapter:g,usageTracker:h,ipcServer:s,ipcPath:a,stderrStream:c,hostHandler:y,runtimeRestartCount:r}),g.attach(m,(T,D)=>{if(T==="session/update"){let I=D?.update?.sessionUpdate;if(typeof I=="string"){let _=this.processes.get(e.memberId),$=_?.handle.acpUpdateTypes??[];_&&!$.includes(I)&&(_.handle.acpUpdateTypes=[...$,I])}}this.feedUsageFromNotification(h,T,D);let C=Ti.translateNotification(T,D);C?(this.captureChildProgress(e.memberId,C.method,C.params),this.callbacks.onNotification?.(e.memberId,C.method,C.params)):(this.captureChildProgress(e.memberId,T,D),this.callbacks.onNotification?.(e.memberId,T,D))},y),m.stderr&&$g({input:m.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",D=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${D}`),c?.write(`${new Date().toISOString()} ${D}
716
716
  `)}),m.on("exit",(T,D)=>{g.detach(),y.disposeAll();let C=l.state;if(C!=="killed"&&C!=="completed"&&T!==0){let _=this.processes.get(e.memberId)?.runtimeRestartCount??r;if(_<kc){let $=ZF*2**_;this.slog("warn",e.memberId,"crash",`crashed again (code=${T}), restart ${_+1}/${kc}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${T}), restarting`,retriesLeft:kc-_-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,n,_+1).catch(O=>{this.slog("warn",e.memberId,"restart",`failed: ${O instanceof Error?O.message:String(O)}`)})},$);return}}C!=="killed"&&(l.state=T===0?"completed":"failed"),l.endedAt=Date.now(),T!==0&&!l.error&&(l.error=`ACP process exited with code ${T} (signal: ${D})`),this.callbacks.onStateChange?.(e.memberId,l.state),this.callbacks.onExit?.(e.memberId,T,D)}),m.on("error",T=>{g.detach(),y.disposeAll(),l.state="failed",l.error=T.message,l.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let v=await g.initialize(m);l.state="ready",l.supportsResume=v.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${r}, protocol=${v.protocolVersion}, loadSession=${l.supportsResume}, pid=${l.pid})`);let b=[...e.mcpServers??[]],S=v.agentCapabilities.mcpCapabilities?.stdio===!0;if(l.supportsStdioMcp=S,a&&S)for(let T of Ci)b.push({name:T,command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(l.supportsResume&&l.sessionId){let T=await g.resumeSession(m,l.sessionId,{cwd:e.cwd,mcpServers:b.length>0?b:void 0});l.sessionId=T.sessionId,this.slog("info",e.memberId,"session",`session resumed (id=${l.sessionId})`)}else{let T={cwd:e.cwd};b.length>0&&(T.mcpServers=b);let D=Ag({projectRoot:e.cwd,mcpAvailable:S}),C=[e.systemPrompt,D].filter(Boolean).join(`
717
717
 
718
- `);C&&(T.systemPrompt=C);let I=await g.createSession(m,T);l.sessionId=I.sessionId,this.slog("info",e.memberId,"session",`new session on restart (id=${l.sessionId})`)}}catch{this.slog("warn",e.memberId,"session","session re-creation failed on restart")}this.startHeartbeat(e.memberId,T=>{this.slog("warn",T,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(T,"agents.error",{agentId:T,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(T)})}catch(l){let d=this.processes.get(e.memberId);d&&(d.handle.state="failed",d.handle.error=`Runtime restart failed: ${l instanceof Error?l.message:String(l)}`,d.handle.endedAt=Date.now()),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Restart failed after ${r} attempts: ${l instanceof Error?l.message:String(l)}`,retriesLeft:0})}}getMcpIpcPath(e){return this.processes.get(e)?.ipcPath}heartbeatTimers=new Map;missedBeats=new Map;static HEARTBEAT_INTERVAL=3e4;static MAX_MISSED_BEATS=3;startHeartbeat(e,n){this.stopHeartbeat(e),this.missedBeats.set(e,0);let r=setInterval(async()=>{let o=this.processes.get(e);if(!o||o.handle.state==="completed"||o.handle.state==="failed"||o.handle.state==="killed"){this.stopHeartbeat(e);return}if(await this.ping(e,1e4)){this.missedBeats.set(e,0);return}let s=(this.missedBeats.get(e)??0)+1;this.missedBeats.set(e,s),this.slog("warn",e,"heartbeat",`missed (${s}/${t.MAX_MISSED_BEATS})`),s>=t.MAX_MISSED_BEATS&&(this.slog("warn",e,"heartbeat","hang detected, force-killing"),this.stopHeartbeat(e),o.handle.error=`Hang detected: ${s} consecutive heartbeat failures`,this.kill(e),n?.(e))},t.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,r)}stopHeartbeat(e){let n=this.heartbeatTimers.get(e);n&&(clearInterval(n),this.heartbeatTimers.delete(e)),this.missedBeats.delete(e)}getMissedBeats(e){return this.missedBeats.get(e)??0}activeCount(){return[...this.processes.values()].filter(e=>e.handle.state==="starting"||e.handle.state==="ready"||e.handle.state==="running").length}remove(e){let n=this.processes.get(e);n&&(this.stopHeartbeat(e),(n.handle.state==="running"||n.handle.state==="starting"||n.handle.state==="ready")&&this.kill(e),this.processes.delete(e))}dispose(){for(let e of this.heartbeatTimers.keys())this.stopHeartbeat(e);for(let e of this.processes.values()){try{e.ipcServer?.close()}catch{}try{e.stderrStream?.end()}catch{}}this.killAll(),this.processes.clear()}};import{spawn as Mi}from"node:child_process";var YF=/[|&;><$`(){}]/;function QF(t,e){let n=e==="win32",r=e==="darwin",o=r?[t.brew,t.npm,t.pip,t.curl]:[t.npm,t.pip,t.brew,t.curl];for(let i of o){if(!i)continue;let s=YF.test(i);if(!(s&&n)&&!(i.startsWith("brew ")&&!r))return{command:i,shell:s}}return null}function eH(t,e){if(e!=="cn")return t;let n=t.trim();return/^npm\b/.test(n)&&!/(?:^|\s)--registry(?:\s|=)/.test(n)?`${n} --registry ${qd}`:/^uv\b/.test(n)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(n)?`${n} --default-index ${bc}`:/^(?:pipx|pip3?|python -m pip)\b/.test(n)&&!/(?:^|\s)--index-url(?:\s|=)/.test(n)?`${n} --index-url ${bc}`:n}function XF(t,e,n,r){return new Promise(o=>{let i;try{i=n(t,e)}catch(s){r({type:"log",stream:"stderr",chunk:s instanceof Error?s.message:String(s)}),o(1);return}i.stdout?.on("data",s=>r({type:"log",stream:"stdout",chunk:s.toString()})),i.stderr?.on("data",s=>r({type:"log",stream:"stderr",chunk:s.toString()})),i.on("error",s=>{r({type:"log",stream:"stderr",chunk:s.message}),o(1)}),i.on("close",s=>o(s))})}var wue=(t,e)=>{let n=Pi();if(n&&IA(t)){let i=t.trim().split(/\s+/).slice(1);return Mi(n.nodeExe,[n.npmCli,...i],{env:Ai(n),stdio:["ignore","pipe","pipe"],windowsHide:!0})}let r=_A(t)?CA():void 0;if(e||process.platform==="win32")return Mi(t,{shell:!0,...r?{env:r}:{},stdio:["ignore","pipe","pipe"]});let o=t.split(/\s+/).filter(Boolean);return Mi(o[0],o.slice(1),{...r?{env:r}:{},stdio:["ignore","pipe","pipe"]})};async function tH(t,e,n={}){let r=n.platform??process.platform,o=n.spawnImpl??wue,i=QF(t,r);if(!i){let d=`No install command available for ${r}`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}let s=eH(i.command,n.mirror);e({type:"state",state:"installing"});let a=await XF(s,i.shell,o,e);if(a!==0){let d=`Install command exited with code ${a}`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}let c=t.verifyCmd??`${t.cliCommand} --version`;if(e({type:"state",state:"verifying"}),await XF(c,YF.test(c),o,e)!==0){let d=`Installed but verification failed (${t.cliCommand})`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}return e({type:"state",state:"installed"}),e({type:"done",ok:!0}),{ok:!0}}function nH(t,e=process.platform){try{return e==="win32"?Mi("cmd.exe",["/c","start","","cmd","/k",t],{detached:!0,stdio:"ignore",windowsHide:!1}).unref():e==="darwin"?Mi("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(t)}`,"-e",'tell application "Terminal" to activate'],{detached:!0,stdio:"ignore"}).unref():Mi("x-terminal-emulator",["-e","bash","-lc",`${t}; exec bash`],{detached:!0,stdio:"ignore"}).unref(),{ok:!0}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}function rH(t,e={}){let n=e.platform??process.platform,r=QF(t,n);if(!r)return{ok:!1,error:`No install command available for ${n}`};let o=eH(r.command,e.mirror);try{let i=Pi(),s;if(i&&IA(o)){let a=o.trim().split(/\s+/).slice(1);s=Mi(i.nodeExe,[i.npmCli,...a],{env:Ai(i),detached:!0,stdio:"ignore",windowsHide:!0})}else{let a=_A(o)?CA():void 0;s=Mi(o,{shell:!0,...a?{env:a}:{},detached:!0,stdio:"ignore",windowsHide:!0})}return s.unref(),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}}var mt=new Map,Sue=10*6e4,xue=6e4,Rue=6,Fs=null;function Ng(t,e,n){return`${t}\0${e}\0${n??"default"}`}function Vd(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function oH(t){let e=mt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){mt.delete(t),Vd(e);return}return e}}function iH(t,e){let n=mt.get(t);n&&n!==e&&(mt.delete(t),Vd(n)),mt.set(t,e),Tue(),Aue()}function sH(t,e){let n=mt.get(t);if(!n)return;if(!n.manager.isAlive(n.memberId)){mt.delete(t),Vd(n);return}mt.delete(t);let r=mt.get(e);return r&&r!==n&&(mt.delete(e),Vd(r)),mt.set(e,n),n.lastUsed=Date.now(),n}var Og="__warm__";function Hs(t){let e=mt.get(t);e&&(mt.delete(t),Vd(e))}function Jd(t){let e=`${t}\0`,n=0,r=0;for(let[o,i]of[...mt.entries()])o.startsWith(e)&&(i.holder.current?(i.pendingRecredential=!0,r+=1):(Hs(o),n+=1));return{evicted:n,deferred:r}}function aH(t){mt.get(t)?.pendingRecredential&&Hs(t)}function cH(){for(let t of[...mt.keys()])Hs(t);Fs&&(clearInterval(Fs),Fs=null)}function Tue(){for(;mt.size>Rue;){let t=null,e=Number.POSITIVE_INFINITY;for(let[n,r]of mt)r.holder.current||r.lastUsed<e&&(e=r.lastUsed,t=n);if(!t)break;Hs(t)}}function Pue(t){for(let[e,n]of[...mt.entries()])n.holder.current||t-n.lastUsed>Sue&&Hs(e)}function Aue(){Fs||(Fs=setInterval(()=>Pue(Date.now()),xue),typeof Fs.unref=="function"&&Fs.unref())}import{randomUUID as Iue}from"node:crypto";var wc=new Map;function _ue(t,e){let n=wc.get(t);return n&&(clearTimeout(n.timer),n.resolve(null),wc.delete(t)),new Promise(r=>{let o=setTimeout(()=>{wc.delete(t),r(null)},e);typeof o.unref=="function"&&o.unref(),wc.set(t,{resolve:r,timer:o})})}function lH(t,e){let n=wc.get(t);return n?(clearTimeout(n.timer),wc.delete(t),n.resolve(e),!0):!1}function Cue(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}function Eue(t){let e=o=>typeof o?.optionId=="string"&&o.optionId.trim()?o.optionId:void 0;if(t.find(o=>e(o)==="allow"))return"allow";let r=t.find(o=>/allow/i.test([o.optionId,o.kind,o.name].filter(i=>typeof i=="string").join(" ")));return e(r)??e(t[0])??"allow"}function GA(t,e=[]){if(typeof t=="string")return e.push(t),e;if(!t||typeof t!="object")return e;if(Array.isArray(t)){for(let n of t)GA(n,e);return e}for(let n of Object.values(t))GA(n,e);return e}function Mue(t){let e=GA(t).join(`
718
+ `);C&&(T.systemPrompt=C);let I=await g.createSession(m,T);l.sessionId=I.sessionId,this.slog("info",e.memberId,"session",`new session on restart (id=${l.sessionId})`)}}catch{this.slog("warn",e.memberId,"session","session re-creation failed on restart")}this.startHeartbeat(e.memberId,T=>{this.slog("warn",T,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(T,"agents.error",{agentId:T,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(T)})}catch(l){let d=this.processes.get(e.memberId);d&&(d.handle.state="failed",d.handle.error=`Runtime restart failed: ${l instanceof Error?l.message:String(l)}`,d.handle.endedAt=Date.now()),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Restart failed after ${r} attempts: ${l instanceof Error?l.message:String(l)}`,retriesLeft:0})}}getMcpIpcPath(e){return this.processes.get(e)?.ipcPath}heartbeatTimers=new Map;missedBeats=new Map;static HEARTBEAT_INTERVAL=3e4;static MAX_MISSED_BEATS=3;startHeartbeat(e,n){this.stopHeartbeat(e),this.missedBeats.set(e,0);let r=setInterval(async()=>{let o=this.processes.get(e);if(!o||o.handle.state==="completed"||o.handle.state==="failed"||o.handle.state==="killed"){this.stopHeartbeat(e);return}if(await this.ping(e,1e4)){this.missedBeats.set(e,0);return}let s=(this.missedBeats.get(e)??0)+1;this.missedBeats.set(e,s),this.slog("warn",e,"heartbeat",`missed (${s}/${t.MAX_MISSED_BEATS})`),s>=t.MAX_MISSED_BEATS&&(this.slog("warn",e,"heartbeat","hang detected, force-killing"),this.stopHeartbeat(e),o.handle.error=`Hang detected: ${s} consecutive heartbeat failures`,this.kill(e),n?.(e))},t.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,r)}stopHeartbeat(e){let n=this.heartbeatTimers.get(e);n&&(clearInterval(n),this.heartbeatTimers.delete(e)),this.missedBeats.delete(e)}getMissedBeats(e){return this.missedBeats.get(e)??0}activeCount(){return[...this.processes.values()].filter(e=>e.handle.state==="starting"||e.handle.state==="ready"||e.handle.state==="running").length}remove(e){let n=this.processes.get(e);n&&(this.stopHeartbeat(e),(n.handle.state==="running"||n.handle.state==="starting"||n.handle.state==="ready")&&this.kill(e),this.processes.delete(e))}dispose(){for(let e of this.heartbeatTimers.keys())this.stopHeartbeat(e);for(let e of this.processes.values()){try{e.ipcServer?.close()}catch{}try{e.stderrStream?.end()}catch{}}this.killAll(),this.processes.clear()}};import{spawn as Mi}from"node:child_process";var YF=/[|&;><$`(){}]/;function QF(t,e){let n=e==="win32",r=e==="darwin",o=r?[t.brew,t.npm,t.pip,t.curl]:[t.npm,t.pip,t.brew,t.curl];for(let i of o){if(!i)continue;let s=YF.test(i);if(!(s&&n)&&!(i.startsWith("brew ")&&!r))return{command:i,shell:s}}return null}function eH(t,e){if(e!=="cn")return t;let n=t.trim();return/^npm\b/.test(n)&&!/(?:^|\s)--registry(?:\s|=)/.test(n)?`${n} --registry ${qd}`:/^uv\b/.test(n)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(n)?`${n} --default-index ${bc}`:/^(?:pipx|pip3?|python -m pip)\b/.test(n)&&!/(?:^|\s)--index-url(?:\s|=)/.test(n)?`${n} --index-url ${bc}`:n}function XF(t,e,n,r){return new Promise(o=>{let i;try{i=n(t,e)}catch(s){r({type:"log",stream:"stderr",chunk:s instanceof Error?s.message:String(s)}),o(1);return}i.stdout?.on("data",s=>r({type:"log",stream:"stdout",chunk:s.toString()})),i.stderr?.on("data",s=>r({type:"log",stream:"stderr",chunk:s.toString()})),i.on("error",s=>{r({type:"log",stream:"stderr",chunk:s.message}),o(1)}),i.on("close",s=>o(s))})}var wue=(t,e)=>{let n=Pi();if(n&&IA(t)){let i=t.trim().split(/\s+/).slice(1);return Mi(n.nodeExe,[n.npmCli,...i],{env:Ai(n),stdio:["ignore","pipe","pipe"],windowsHide:!0})}let r=_A(t)?CA():void 0;if(e||process.platform==="win32")return Mi(t,{shell:!0,...r?{env:r}:{},stdio:["ignore","pipe","pipe"],windowsHide:!0});let o=t.split(/\s+/).filter(Boolean);return Mi(o[0],o.slice(1),{...r?{env:r}:{},stdio:["ignore","pipe","pipe"]})};async function tH(t,e,n={}){let r=n.platform??process.platform,o=n.spawnImpl??wue,i=QF(t,r);if(!i){let d=`No install command available for ${r}`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}let s=eH(i.command,n.mirror);e({type:"state",state:"installing"});let a=await XF(s,i.shell,o,e);if(a!==0){let d=`Install command exited with code ${a}`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}let c=t.verifyCmd??`${t.cliCommand} --version`;if(e({type:"state",state:"verifying"}),await XF(c,YF.test(c),o,e)!==0){let d=`Installed but verification failed (${t.cliCommand})`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}return e({type:"state",state:"installed"}),e({type:"done",ok:!0}),{ok:!0}}function nH(t,e=process.platform){try{return e==="win32"?Mi("cmd.exe",["/c","start","","cmd","/k",t],{detached:!0,stdio:"ignore",windowsHide:!1}).unref():e==="darwin"?Mi("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(t)}`,"-e",'tell application "Terminal" to activate'],{detached:!0,stdio:"ignore"}).unref():Mi("x-terminal-emulator",["-e","bash","-lc",`${t}; exec bash`],{detached:!0,stdio:"ignore"}).unref(),{ok:!0}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}function rH(t,e={}){let n=e.platform??process.platform,r=QF(t,n);if(!r)return{ok:!1,error:`No install command available for ${n}`};let o=eH(r.command,e.mirror);try{let i=Pi(),s;if(i&&IA(o)){let a=o.trim().split(/\s+/).slice(1);s=Mi(i.nodeExe,[i.npmCli,...a],{env:Ai(i),detached:!0,stdio:"ignore",windowsHide:!0})}else{let a=_A(o)?CA():void 0;s=Mi(o,{shell:!0,...a?{env:a}:{},detached:!0,stdio:"ignore",windowsHide:!0})}return s.unref(),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}}var mt=new Map,Sue=10*6e4,xue=6e4,Rue=6,Fs=null;function Ng(t,e,n){return`${t}\0${e}\0${n??"default"}`}function Vd(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function oH(t){let e=mt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){mt.delete(t),Vd(e);return}return e}}function iH(t,e){let n=mt.get(t);n&&n!==e&&(mt.delete(t),Vd(n)),mt.set(t,e),Tue(),Aue()}function sH(t,e){let n=mt.get(t);if(!n)return;if(!n.manager.isAlive(n.memberId)){mt.delete(t),Vd(n);return}mt.delete(t);let r=mt.get(e);return r&&r!==n&&(mt.delete(e),Vd(r)),mt.set(e,n),n.lastUsed=Date.now(),n}var Og="__warm__";function Hs(t){let e=mt.get(t);e&&(mt.delete(t),Vd(e))}function Jd(t){let e=`${t}\0`,n=0,r=0;for(let[o,i]of[...mt.entries()])o.startsWith(e)&&(i.holder.current?(i.pendingRecredential=!0,r+=1):(Hs(o),n+=1));return{evicted:n,deferred:r}}function aH(t){mt.get(t)?.pendingRecredential&&Hs(t)}function cH(){for(let t of[...mt.keys()])Hs(t);Fs&&(clearInterval(Fs),Fs=null)}function Tue(){for(;mt.size>Rue;){let t=null,e=Number.POSITIVE_INFINITY;for(let[n,r]of mt)r.holder.current||r.lastUsed<e&&(e=r.lastUsed,t=n);if(!t)break;Hs(t)}}function Pue(t){for(let[e,n]of[...mt.entries()])n.holder.current||t-n.lastUsed>Sue&&Hs(e)}function Aue(){Fs||(Fs=setInterval(()=>Pue(Date.now()),xue),typeof Fs.unref=="function"&&Fs.unref())}import{randomUUID as Iue}from"node:crypto";var wc=new Map;function _ue(t,e){let n=wc.get(t);return n&&(clearTimeout(n.timer),n.resolve(null),wc.delete(t)),new Promise(r=>{let o=setTimeout(()=>{wc.delete(t),r(null)},e);typeof o.unref=="function"&&o.unref(),wc.set(t,{resolve:r,timer:o})})}function lH(t,e){let n=wc.get(t);return n?(clearTimeout(n.timer),wc.delete(t),n.resolve(e),!0):!1}function Cue(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}function Eue(t){let e=o=>typeof o?.optionId=="string"&&o.optionId.trim()?o.optionId:void 0;if(t.find(o=>e(o)==="allow"))return"allow";let r=t.find(o=>/allow/i.test([o.optionId,o.kind,o.name].filter(i=>typeof i=="string").join(" ")));return e(r)??e(t[0])??"allow"}function GA(t,e=[]){if(typeof t=="string")return e.push(t),e;if(!t||typeof t!="object")return e;if(Array.isArray(t)){for(let n of t)GA(n,e);return e}for(let n of Object.values(t))GA(n,e);return e}function Mue(t){let e=GA(t).join(`
719
719
  `);return/astraclaw/i.test(e)&&/\b(?:skills_list|skill_view|mcp_connectors_list|mcp_tool_call)\b/.test(e)}async function dH(t,e){let n=e.turnContext(),r=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:Iue(),i=Array.isArray(t.options)?t.options:[];if(Mue(t))return{optionId:Eue(i)};if(n?.turnId&&e.sendNotification){e.sendNotification("agents.prompt.approval",{agentId:e.agentId,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,approvalId:o,callId:typeof r.toolCallId=="string"?r.toolCallId:o,toolName:typeof r.title=="string"?r.title:typeof t.toolName=="string"?t.toolName:"operation",arguments:Cue(r.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await _ue(o,e.timeoutMs??5*6e4);if(a)return{optionId:a}}return{optionId:i.find(a=>a?.kind==="reject_once"||a?.kind==="reject"||/reject|deny|no|cancel/i.test(String(a?.optionId??a?.name??"")))?.optionId??i[0]?.optionId??"reject"}}function $ue(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function Nue(t){let e=t?.content;if(Array.isArray(e)){let n=e.map(r=>{if(!r||typeof r!="object")return"";let o=r;return typeof o.text=="string"?o.text:typeof o.content=="string"?o.content:""}).join("");if(n)return n.slice(0,2e3)}if(typeof e=="string")return e.slice(0,2e3);if(t?.rawOutput!==void 0)try{return JSON.stringify(t.rawOutput).slice(0,2e3)}catch{return}}function Oue(t){let{agentId:e,turn:n,method:r,payload:o,sendNotification:i}=t;if(!n||!i)return;let s=o;if(r==="turn.delta"){let c=typeof s?.text=="string"?s.text:"";if(!c)return;n.deltas.push(c),n.turnId&&(i("agents.prompt.delta",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,text:c}),n.streamedAny=!0);return}if(r==="turn.thought_delta"){let c=typeof s?.text=="string"?s.text:"";c&&n.turnId&&i("agents.prompt.delta",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,text:c,reasoning:!0});return}if(r==="turn.plan"){n.turnId&&i("agents.prompt.plan",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,steps:Array.isArray(s?.steps)?s.steps:[]});return}if(r==="turn.tool_use_summary"){if(!n.turnId||!Array.isArray(s?.availableToolNames)||!Array.isArray(s?.enabledToolNames)||!Array.isArray(s?.toolCallNames)||!Array.isArray(s?.blockedToolCalls))return;i("turn.tool_use_summary",{...s,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId});return}if(r==="turn.tool_selection_policy"){if(!n.turnId||!Array.isArray(s?.availableToolNames)||!Array.isArray(s?.enabledToolNamesBefore)||!Array.isArray(s?.enabledToolNamesAfter)||!Array.isArray(s?.suppressedToolNames))return;i("turn.tool_selection_policy",{...s,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId});return}if(!n.turnId)return;let a=typeof s?.callId=="string"?s.callId:String(s?.callId??"");r==="turn.tool_call"?i("agents.prompt.tool",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,event:{kind:"call",callId:a,name:typeof s?.toolName=="string"?s.toolName:typeof s?.name=="string"?s.name:"tool",arguments:$ue(s)}}):r==="turn.tool_result"&&i("agents.prompt.tool",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,event:{kind:"result",callId:a,name:typeof s?.toolName=="string"?s.toolName:"tool",ok:s?.status!=="failed"&&s?.status!=="error",outputPreview:Nue(s)}})}function pH(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function mH(t){return t instanceof Error?t.message:String(t)}async function jue(t){let e=pH(t.error);if(!t.sessionId||!e)return;let n=mH(t.error);await gr(t.sessionId,{role:"user",content:t.prompt},t.projectRoot,t.turnId),await gr(t.sessionId,{role:"assistant",content:n,blocks:[{type:"auth_prompt",agentId:t.agentId,message:n,authMethods:e}]},t.projectRoot,t.turnId);let r=Kt(t.sessionId,t.projectRoot),o=await Ra(t.sessionId,t.projectRoot);await bt(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...r?.title?{}:{title:El(t.prompt,"External agent login required")},...t.lockSessionOwner===!1||r?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function fH(t){let e=t.params,n=typeof e?.approvalId=="string"?e.approvalId:"",r=typeof e?.optionId=="string"?e.optionId:"",o=n&&r?lH(n,r):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function gH(t){try{let e=t.params,n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let r=await this.acpDetector.scanAsync(e?.force);t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function hH(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let n=await this.acpDetector.scanAsync(!1);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function yH(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let n=new Map(this.acpDetector.list().map(o=>[o.id,o])),r=zd().map(o=>{let i=n.get(o.id);return{id:o.id,name:o.name,brandId:o.brandId??o.id,category:o.category??"code",integration:o.integration??"acp",authMode:o.authMode??"key",keySource:o.keySource??"none",note:o.note,availableModes:UF(o),authPreference:e.getAgentConfig(o.id)?.authPreference??"auto",credentialReady:i?.status==="available"?this.acpDetector.isAgentReady(o.id):!1,accountConnected:i?.status==="available"?this.acpDetector.getNativeLoginState(o.id):void 0,status:i?.status??"not_installed",version:MF(o,i?.version),install:{docsUrl:o.install?.docsUrl,command:o.install?.npm??o.install?.pip??o.install?.brew??o.install?.curl,setupCommand:o.install?.setupCommand}}});t.id!==void 0&&this.sendResponse(t.id,{catalog:r})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}var KA=new Set;async function bH(t){try{let e=t.params,r=(typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR)==="cn"?qd:void 0,o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData());let i=new Map(this.acpDetector.list().map(l=>[l.id,l])),s=zd().map(l=>({id:l.id,entry:l,detectedVersion:i.get(l.id)?.version})),{updates:a,stale:c}=$F(s,r);if(t.id!==void 0&&this.sendResponse(t.id,{updates:a,refreshing:c}),c){let l=r??"";KA.has(l)||(KA.add(l),DF(s,r).catch(()=>{}).finally(()=>KA.delete(l)))}}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function vH(t){let e=t.params,n=typeof e?.agentId=="string"?e.agentId:void 0,r=typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR;if(!n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId (string) required"});return}let o=Io(n);if(!o?.install){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:`Unknown or non-installable agent: ${n}`});return}if(o.install.deferUpdate){let i=rH(o.install,{mirror:r});t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error,deferred:i.ok});return}try{let i=await tH(o.install,s=>{this.sendNotification?.("agent.install.progress",{agentId:n,event:s})},{mirror:r});this.acpDetector.clearCache(),t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error})}catch(i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:i instanceof Error?i.message:String(i)})}}async function kH(t){let e=t.params,n=typeof e?.agentId=="string"?e.agentId:void 0;if(!n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId (string) required"});return}let o=Io(n)?.install?.setupCommand;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:`No terminal setup command for agent: ${n}`});return}let i=nH(o);t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error,command:o})}async function wH(t){try{let e=t.params;if(!e?.action||!e?.agent){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"action and agent are required."});return}let n=await this.ensureAgentConfigStore();switch(e.action){case"register":await n.registerCustomAgent(e.agent);break;case"unregister":await n.unregisterCustomAgent(e.agent.id);break;case"update":await n.registerCustomAgent(e.agent);break}this.acpDetector.setConfigStore(n.getData()),this.acpDetector.clearCache(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function SH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore(),{agentId:r,...o}=e;await n.setAgentConfig(r,o),this.acpDetector.setConfigStore(n.getData());let{deferred:i}=Jd(r);t.id!==void 0&&this.sendResponse(t.id,{ok:!0,pendingTurn:i>0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function xH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let r=(await this.ensureAgentConfigStore()).getAgentConfig(e.agentId);t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function RH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();await n.removeAgentConfig(e.agentId),this.acpDetector.setConfigStore(n.getData()),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function Lue(t){let e=uH.homedir();if(t==="codex"){let n=process.env.CODEX_HOME?.trim()||Sc.join(e,".codex");return[Sc.join(n,"auth.json")]}return[]}async function TH(t){try{let e=t.params,n=typeof e?.agentId=="string"?e.agentId.trim():"";if(!n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let r=!1;for(let o of Lue(n))try{xc.existsSync(o)&&(xc.rmSync(o,{force:!0}),r=!0)}catch{}Jd(n),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,cleared:r,hint:r?void 0:`\u5728\u7EC8\u7AEF\u8FD0\u884C \`${n} logout\` \u9000\u51FA\u8BE5 Agent \u7684\u8D26\u53F7`})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function PH(t){try{let e=t.params;if(!e?.url){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"url is required."});return}await(await this.ensureAgentConfigStore()).setGatewayUrl(e.url),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function AH(t){try{let n=(await this.ensureAgentConfigStore()).getGatewayUrl();t.id!==void 0&&this.sendResponse(t.id,{url:n})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function IH(t){try{let n=(await this.ensureAgentConfigStore()).getData(),r=Object.entries(n.agents).map(([o,i])=>({agentId:o,hasApiKey:!!i.apiKey,hasBaseUrl:!!i.baseUrl,hasModel:!!i.model}));t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function _H(t){try{let e=[],n=(r,o)=>{if(r)for(let i of r.getAllHandles())e.push({memberId:i.memberId,name:i.name,pid:i.pid,state:i.state,startedAt:i.startedAt,endedAt:i.endedAt,source:o})};n(this.soloProcessManager,"solo"),n(this.productProcessManager,"product"),t.id!==void 0&&this.sendResponse(t.id,e)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function CH(t){try{let e=t.params;if(!e?.memberId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"memberId is required."});return}let n=!1;for(let r of[this.soloProcessManager,this.productProcessManager])if(r?.getHandle(e.memberId)){r.kill(e.memberId),n=!0;break}t.id!==void 0&&this.sendResponse(t.id,{ok:n})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function EH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=Sc.join(_e(),"agent-logs"),r=Sc.join(n,`${e.agentId}.stderr.log`),o="";try{o=xc.readFileSync(r,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
720
720
  `).slice(-e.tail).join(`
721
- `)),t.id!==void 0&&this.sendResponse(t.id,{log:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function MH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let o=this.acpDetector.list().find(s=>s.id===e.agentId);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:`Agent ${e.agentId} not found`,durationMs:0});return}if(o.status==="not_installed"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:`Agent ${e.agentId} is not installed`,durationMs:0});return}let i=Date.now();t.id!==void 0&&this.sendResponse(t.id,{ok:o.status==="available",version:o.version,capabilities:o.capabilities,error:o.status!=="available"?`Agent status: ${o.status}`:void 0,durationMs:Date.now()-i})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function DH(t,e,n,r,o,i){let s=Ng(e,r,o),a=oH(s);if(a)return a;if(o!==Og){let f=sH(Ng(e,r,Og),s);if(f)return f}let c=`chat-${e}-${Due().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Vr({onNotification:(f,g,h)=>{Oue({agentId:e,turn:l.current,method:g,payload:h,sendNotification:d})},onMcpToolCall:async(f,g,h)=>{if(typeof t.handleMcpToolCall=="function")return t.handleMcpToolCall(f,g,h);let y=await Ig({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>dH(g,{agentId:e,turnContext:()=>l.current,sendNotification:d}),log:{info:f=>t.log?.(`[agents.prompt] ${f}`),warn:f=>t.log?.(`[agents.prompt] WARN: ${f}`),debug:f=>t.log?.(`[agents.prompt] ${f}`)},sessionDir:Sc.join(_e(),"agent-logs")});await p.spawn({memberId:c,name:`chat-${e}`,cwd:r,prompt:"",external:n,systemPrompt:i});let m={manager:p,memberId:c,holder:l,lastUsed:Date.now()};return iH(s,m),m}async function $H(t){try{let e=t.params??{},n=typeof e.agentId=="string"?e.agentId.trim():"";if(!n||n==="qlogicagent"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}let r=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(r.getData()),await this.acpDetector.scanAsync(!1);let o=this.acpDetector.buildExternalDescriptor(n);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}if(this.acpDetector.resolveCredentialError(n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,warmed:!1});return}let i=typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd();await DH(this,n,o,i,Og),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,warmed:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1,error:e instanceof Error?e.message:String(e)})}}async function NH(t){try{let e=t.params??{},n=typeof e.agentId=="string"?e.agentId.trim():"",r=typeof e.prompt=="string"?e.prompt:"";if(!n||!r.trim()){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId and prompt are required."});return}let o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData()),await this.acpDetector.scanAsync(!1);let i=this.acpDetector.buildExternalDescriptor(n);if(!i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:`Agent ${n} is not available or not ACP-compatible.`});return}let s=this.acpDetector.resolveCredentialError(n);if(s){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:s});return}let a=typeof e.cwd=="string"&&e.cwd?e.cwd:typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd(),c=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:3e5,l=typeof e.sessionId=="string"?e.sessionId:void 0,d=typeof e.turnId=="string"?e.turnId:void 0,p=typeof e.requestId=="string"?e.requestId:void 0,m=typeof e.projectId=="string"?e.projectId:void 0,f=e.lockSessionOwner!==!1,g=Ng(n,a,l),h=await DH(this,n,i,a,l,typeof e.systemPrompt=="string"?e.systemPrompt:void 0),y={sessionId:l,turnId:d,requestId:p,deltas:[],streamedAny:!1};h.holder.current=y,h.lastUsed=Date.now();let v;try{v=await h.manager.sendTask(h.memberId,r,{timeout:c})}catch(S){throw await jue({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),Hs(g),S}finally{h.holder.current=null,aH(g)}let b=y.deltas.join("")||(typeof v?.content=="string"?v.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){gr(l,{role:"user",content:r},a,d),b&&gr(l,{role:"assistant",content:b},a,d);let S=Kt(l,a);bt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:El(r,"External agent session")},...f&&!S?.agentId?{agentId:n}:{}},a)}t.id!==void 0&&this.sendResponse(t.id,{ok:!0,agentId:n,content:b,streamed:y.streamedAny,stopReason:v?.stopReason,usage:k?{inputTokens:k.inputTokens,outputTokens:k.outputTokens,totalTokens:k.totalTokens,cacheRead:k.cachedReadTokens,thoughtTokens:k.thoughtTokens,cost:k.cost}:void 0})}catch(e){if(t.id!==void 0){let n=pH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:mH(e),...n?{data:{authMethods:n}}:{}})}}}Gp();function Uue(t){let e=zue(t.fetchFn??fetch,t.clientVersion),n=t.token.trim();return{async matchRegistry(r){let o=r.intent.trim();if(!o)throw new Error("intent is required.");let i=que(r.topK),s=await Lg(e,jg(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(Rc(s)&&Array.isArray(s.matches)?s.matches:[]).map(Wue).filter(c=>!!c).slice(0,i)},async resolveInstall(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("resourceId is required.");let s=o?.trim(),a=s?`?version=${encodeURIComponent(s)}`:"",c=await Lg(e,jg(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=LH(c);if(!l)throw new Error("Community hub returned an invalid install resolution.");return l},async listResourceVersions(r){let o=encodeURIComponent(r.trim());if(!o)throw new Error("resourceId is required.");let i=await Lg(e,jg(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(Rc(i)&&Array.isArray(i.versions)?i.versions:[]).map(Gue).filter(a=>!!a)},async resolveRuntime(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("runtime id is required.");let s=encodeURIComponent(o.trim());if(!s)throw new Error("platform is required.");let a=await Lg(e,jg(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=Kue(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Tc(t=ti()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=Fue(t);return Uue({baseUrl:Hue(t),token:e,clientVersion:n})}function Fue(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.16.10"}function Hue(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function jg(t,e){let n=t.trim().replace(/\/+$/,"");return n.endsWith("/v1")&&(n=n.slice(0,-3)),n.endsWith("/api")&&(n=n.slice(0,-4)),`${n}${e}`}function zue(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function Lg(t,e,n,r,o){let i,s=o!==void 0;try{i=await t(e,{method:r,headers:{accept:"application/json",authorization:`Bearer ${n}`,...s?{"content-type":"application/json"}:{}},...s?{body:JSON.stringify(o)}:{},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Community hub is unavailable.")}if(!i.ok)throw new Error(`Community hub rejected registry request: ${i.status}${await Bue(i)}`);return i.json().catch(()=>null)}async function Bue(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function Rc(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function que(t){if(t===void 0)return 3;if(typeof t!="number"||!Number.isSafeInteger(t)||t<1||t>3)throw new Error("registry match topK must be an integer between 1 and 3.");return t}function Wue(t){if(!Rc(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=OH(t.sourceTier),n=jH(t.trustStage),r=Ug(t.resourceRiskTier),o=Ug(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.title!="string"||!e||!n||!r||!o)return null;let i=Array.isArray(t.capabilityTags)?t.capabilityTags:[];return{id:t.id,type:typeof t.type=="string"?t.type:"skill",title:VA(t.title,80),summary:VA(typeof t.summary=="string"?t.summary:"",160),category:typeof t.category=="string"?t.category:null,capabilityTags:i.filter(s=>typeof s=="string"&&s.trim().length>0).slice(0,6).map(s=>VA(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function VA(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function Gue(t){return!Rc(t)||typeof t.version!="string"||!t.version?null:{version:t.version,createdAt:typeof t.createdAt=="string"?t.createdAt:"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,yanked:t.yanked===!0}}function Kue(t){if(!Rc(t))return null;let e=typeof t.id=="string"?t.id:"",n=typeof t.version=="string"?t.version:"",r=typeof t.downloadUrl=="string"?t.downloadUrl:"",o=typeof t.checksum=="string"?t.checksum:"",i=typeof t.sizeBytes=="number"?t.sizeBytes:0;return!e||!n||!r||!/^[a-f0-9]{64}$/.test(o)||!Number.isSafeInteger(i)||i<=0?null:{id:e,version:n,downloadUrl:r,checksum:o,sizeBytes:i}}var Vue=new Set(["R0","R1","R2","R3"]),Jue=new Set(["official","community"]),Zue=new Set(["quarantine","trial","trusted"]),Xue=new Set(["pending","approved","rejected"]);function Ug(t){return typeof t=="string"&&Vue.has(t)?t:null}function OH(t){return typeof t=="string"&&Jue.has(t)?t:null}function jH(t){return typeof t=="string"&&Zue.has(t)?t:null}function Yue(t){return typeof t=="string"&&Xue.has(t)?t:null}function LH(t){if(!Rc(t))return null;let e=OH(t.sourceTier),n=jH(t.trustStage),r=Yue(t.reviewStatus),o=Ug(t.resourceRiskTier),i=Ug(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.type!="string"||typeof t.kind!="string"||!e||!n||!r||!o||!i||typeof t.version!="string"||typeof t.checksum!="string"||typeof t.sizeBytes!="number"||typeof t.downloadUrl!="string")return null;let s=Array.isArray(t.requires)?t.requires:null,a=Array.isArray(t.dependencies)?t.dependencies:null;if(!s||!a||s.some(l=>typeof l!="string"))return null;let c=a.map(LH);return c.some(l=>!l)?null:{id:t.id,type:t.type,kind:t.kind,sourceTier:e,trustStage:n,reviewStatus:r,resourceRiskTier:o,effectiveRiskTier:i,requires:s,dependencies:c,version:t.version,checksum:t.checksum,sizeBytes:t.sizeBytes,downloadUrl:t.downloadUrl,manifest:t.manifest,minClientVersion:typeof t.minClientVersion=="string"&&t.minClientVersion.trim()?t.minClientVersion.trim():void 0,signature:typeof t.signature=="string"&&t.signature.trim()?t.signature:null,signingKeyId:typeof t.signingKeyId=="string"&&t.signingKeyId.trim()?t.signingKeyId:null}}le();var JA={enabled:!0},Que=new Set(["R2","R3"]);function UH(t,e=JA){return Que.has(t.effectiveRiskTier)?{mode:"high-risk-ask",requiresInstallConsent:!0,requiresHighRiskConsent:!0,reason:`effectiveRiskTier=${t.effectiveRiskTier} \u9AD8\u5371,\u5FC5\u987B\u9AD8\u5371\u95EE\u4EBA`}:e.enabled?t.effectiveRiskTier==="R0"?{mode:"silent",requiresInstallConsent:!1,requiresHighRiskConsent:!1,reason:"R0 \u4F4E\u98CE\u9669 inert,\u81EA\u6CBB\u9759\u9ED8\u83B7\u53D6"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"R1 \u4F4E\u98CE\u9669\u4F46\u975E\u96F6,\u95EE\u4EBA\u4E00\u6B21"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"\u81EA\u6CBB\u9884\u7B97\u5173\u95ED,\u56DE\u9000\u663E\u5F0F\u540C\u610F"}}import{createPublicKey as epe,verify as tpe}from"node:crypto";function npe(t){return`id=${t.id}
721
+ `)),t.id!==void 0&&this.sendResponse(t.id,{log:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function MH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let o=this.acpDetector.list().find(s=>s.id===e.agentId);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:`Agent ${e.agentId} not found`,durationMs:0});return}if(o.status==="not_installed"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:`Agent ${e.agentId} is not installed`,durationMs:0});return}let i=Date.now();t.id!==void 0&&this.sendResponse(t.id,{ok:o.status==="available",version:o.version,capabilities:o.capabilities,error:o.status!=="available"?`Agent status: ${o.status}`:void 0,durationMs:Date.now()-i})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function DH(t,e,n,r,o,i){let s=Ng(e,r,o),a=oH(s);if(a)return a;if(o!==Og){let f=sH(Ng(e,r,Og),s);if(f)return f}let c=`chat-${e}-${Due().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Vr({onNotification:(f,g,h)=>{Oue({agentId:e,turn:l.current,method:g,payload:h,sendNotification:d})},onMcpToolCall:async(f,g,h)=>{if(typeof t.handleMcpToolCall=="function")return t.handleMcpToolCall(f,g,h);let y=await Ig({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>dH(g,{agentId:e,turnContext:()=>l.current,sendNotification:d}),log:{info:f=>t.log?.(`[agents.prompt] ${f}`),warn:f=>t.log?.(`[agents.prompt] WARN: ${f}`),debug:f=>t.log?.(`[agents.prompt] ${f}`)},sessionDir:Sc.join(_e(),"agent-logs")});await p.spawn({memberId:c,name:`chat-${e}`,cwd:r,prompt:"",external:n,systemPrompt:i});let m={manager:p,memberId:c,holder:l,lastUsed:Date.now()};return iH(s,m),m}async function $H(t){try{let e=t.params??{},n=typeof e.agentId=="string"?e.agentId.trim():"";if(!n||n==="qlogicagent"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}let r=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(r.getData()),await this.acpDetector.scanAsync(!1);let o=this.acpDetector.buildExternalDescriptor(n);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}if(this.acpDetector.resolveCredentialError(n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,warmed:!1});return}let i=typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd();await DH(this,n,o,i,Og),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,warmed:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1,error:e instanceof Error?e.message:String(e)})}}async function NH(t){try{let e=t.params??{},n=typeof e.agentId=="string"?e.agentId.trim():"",r=typeof e.prompt=="string"?e.prompt:"";if(!n||!r.trim()){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId and prompt are required."});return}let o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData()),await this.acpDetector.scanAsync(!1);let i=this.acpDetector.buildExternalDescriptor(n);if(!i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:`Agent ${n} is not available or not ACP-compatible.`});return}let s=this.acpDetector.resolveCredentialError(n);if(s){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:s});return}let a=typeof e.cwd=="string"&&e.cwd?e.cwd:typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd(),c=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:3e5,l=typeof e.sessionId=="string"?e.sessionId:void 0,d=typeof e.turnId=="string"?e.turnId:void 0,p=typeof e.requestId=="string"?e.requestId:void 0,m=typeof e.projectId=="string"?e.projectId:void 0,f=e.lockSessionOwner!==!1,g=Ng(n,a,l),h=await DH(this,n,i,a,l,typeof e.systemPrompt=="string"?e.systemPrompt:void 0),y={sessionId:l,turnId:d,requestId:p,deltas:[],streamedAny:!1};h.holder.current=y,h.lastUsed=Date.now();let v;try{v=await h.manager.sendTask(h.memberId,r,{timeout:c})}catch(S){throw await jue({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),Hs(g),S}finally{h.holder.current=null,aH(g)}let b=y.deltas.join("")||(typeof v?.content=="string"?v.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){gr(l,{role:"user",content:r},a,d),b&&gr(l,{role:"assistant",content:b},a,d);let S=Kt(l,a);bt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:El(r,"External agent session")},...f&&!S?.agentId?{agentId:n}:{}},a)}t.id!==void 0&&this.sendResponse(t.id,{ok:!0,agentId:n,content:b,streamed:y.streamedAny,stopReason:v?.stopReason,usage:k?{inputTokens:k.inputTokens,outputTokens:k.outputTokens,totalTokens:k.totalTokens,cacheRead:k.cachedReadTokens,thoughtTokens:k.thoughtTokens,cost:k.cost}:void 0})}catch(e){if(t.id!==void 0){let n=pH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:mH(e),...n?{data:{authMethods:n}}:{}})}}}Gp();function Uue(t){let e=zue(t.fetchFn??fetch,t.clientVersion),n=t.token.trim();return{async matchRegistry(r){let o=r.intent.trim();if(!o)throw new Error("intent is required.");let i=que(r.topK),s=await Lg(e,jg(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(Rc(s)&&Array.isArray(s.matches)?s.matches:[]).map(Wue).filter(c=>!!c).slice(0,i)},async resolveInstall(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("resourceId is required.");let s=o?.trim(),a=s?`?version=${encodeURIComponent(s)}`:"",c=await Lg(e,jg(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=LH(c);if(!l)throw new Error("Community hub returned an invalid install resolution.");return l},async listResourceVersions(r){let o=encodeURIComponent(r.trim());if(!o)throw new Error("resourceId is required.");let i=await Lg(e,jg(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(Rc(i)&&Array.isArray(i.versions)?i.versions:[]).map(Gue).filter(a=>!!a)},async resolveRuntime(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("runtime id is required.");let s=encodeURIComponent(o.trim());if(!s)throw new Error("platform is required.");let a=await Lg(e,jg(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=Kue(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Tc(t=ti()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=Fue(t);return Uue({baseUrl:Hue(t),token:e,clientVersion:n})}function Fue(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.17.1"}function Hue(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function jg(t,e){let n=t.trim().replace(/\/+$/,"");return n.endsWith("/v1")&&(n=n.slice(0,-3)),n.endsWith("/api")&&(n=n.slice(0,-4)),`${n}${e}`}function zue(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function Lg(t,e,n,r,o){let i,s=o!==void 0;try{i=await t(e,{method:r,headers:{accept:"application/json",authorization:`Bearer ${n}`,...s?{"content-type":"application/json"}:{}},...s?{body:JSON.stringify(o)}:{},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Community hub is unavailable.")}if(!i.ok)throw new Error(`Community hub rejected registry request: ${i.status}${await Bue(i)}`);return i.json().catch(()=>null)}async function Bue(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function Rc(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function que(t){if(t===void 0)return 3;if(typeof t!="number"||!Number.isSafeInteger(t)||t<1||t>3)throw new Error("registry match topK must be an integer between 1 and 3.");return t}function Wue(t){if(!Rc(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=OH(t.sourceTier),n=jH(t.trustStage),r=Ug(t.resourceRiskTier),o=Ug(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.title!="string"||!e||!n||!r||!o)return null;let i=Array.isArray(t.capabilityTags)?t.capabilityTags:[];return{id:t.id,type:typeof t.type=="string"?t.type:"skill",title:VA(t.title,80),summary:VA(typeof t.summary=="string"?t.summary:"",160),category:typeof t.category=="string"?t.category:null,capabilityTags:i.filter(s=>typeof s=="string"&&s.trim().length>0).slice(0,6).map(s=>VA(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function VA(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function Gue(t){return!Rc(t)||typeof t.version!="string"||!t.version?null:{version:t.version,createdAt:typeof t.createdAt=="string"?t.createdAt:"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,yanked:t.yanked===!0}}function Kue(t){if(!Rc(t))return null;let e=typeof t.id=="string"?t.id:"",n=typeof t.version=="string"?t.version:"",r=typeof t.downloadUrl=="string"?t.downloadUrl:"",o=typeof t.checksum=="string"?t.checksum:"",i=typeof t.sizeBytes=="number"?t.sizeBytes:0;return!e||!n||!r||!/^[a-f0-9]{64}$/.test(o)||!Number.isSafeInteger(i)||i<=0?null:{id:e,version:n,downloadUrl:r,checksum:o,sizeBytes:i}}var Vue=new Set(["R0","R1","R2","R3"]),Jue=new Set(["official","community"]),Zue=new Set(["quarantine","trial","trusted"]),Xue=new Set(["pending","approved","rejected"]);function Ug(t){return typeof t=="string"&&Vue.has(t)?t:null}function OH(t){return typeof t=="string"&&Jue.has(t)?t:null}function jH(t){return typeof t=="string"&&Zue.has(t)?t:null}function Yue(t){return typeof t=="string"&&Xue.has(t)?t:null}function LH(t){if(!Rc(t))return null;let e=OH(t.sourceTier),n=jH(t.trustStage),r=Yue(t.reviewStatus),o=Ug(t.resourceRiskTier),i=Ug(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.type!="string"||typeof t.kind!="string"||!e||!n||!r||!o||!i||typeof t.version!="string"||typeof t.checksum!="string"||typeof t.sizeBytes!="number"||typeof t.downloadUrl!="string")return null;let s=Array.isArray(t.requires)?t.requires:null,a=Array.isArray(t.dependencies)?t.dependencies:null;if(!s||!a||s.some(l=>typeof l!="string"))return null;let c=a.map(LH);return c.some(l=>!l)?null:{id:t.id,type:t.type,kind:t.kind,sourceTier:e,trustStage:n,reviewStatus:r,resourceRiskTier:o,effectiveRiskTier:i,requires:s,dependencies:c,version:t.version,checksum:t.checksum,sizeBytes:t.sizeBytes,downloadUrl:t.downloadUrl,manifest:t.manifest,minClientVersion:typeof t.minClientVersion=="string"&&t.minClientVersion.trim()?t.minClientVersion.trim():void 0,signature:typeof t.signature=="string"&&t.signature.trim()?t.signature:null,signingKeyId:typeof t.signingKeyId=="string"&&t.signingKeyId.trim()?t.signingKeyId:null}}le();var JA={enabled:!0},Que=new Set(["R2","R3"]);function UH(t,e=JA){return Que.has(t.effectiveRiskTier)?{mode:"high-risk-ask",requiresInstallConsent:!0,requiresHighRiskConsent:!0,reason:`effectiveRiskTier=${t.effectiveRiskTier} \u9AD8\u5371,\u5FC5\u987B\u9AD8\u5371\u95EE\u4EBA`}:e.enabled?t.effectiveRiskTier==="R0"?{mode:"silent",requiresInstallConsent:!1,requiresHighRiskConsent:!1,reason:"R0 \u4F4E\u98CE\u9669 inert,\u81EA\u6CBB\u9759\u9ED8\u83B7\u53D6"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"R1 \u4F4E\u98CE\u9669\u4F46\u975E\u96F6,\u95EE\u4EBA\u4E00\u6B21"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"\u81EA\u6CBB\u9884\u7B97\u5173\u95ED,\u56DE\u9000\u663E\u5F0F\u540C\u610F"}}import{createPublicKey as epe,verify as tpe}from"node:crypto";function npe(t){return`id=${t.id}
722
722
  version=${t.version}
723
723
  checksum=${t.checksum}
724
724
  sizeBytes=${t.sizeBytes}`}function rpe(t){return t.includes("\\n")?t.replace(/\\n/g,`