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/index.js CHANGED
@@ -679,7 +679,7 @@ ${e}
679
679
 
680
680
  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 ki(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:ec(e,"input",t.processors),output:ec(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 fT=(t,e={})=>n=>{let r=bi({...n,processors:e});return Ae(t,r),vi(r,t),ki(r,t)},ec=(t,e,n={})=>r=>{let{libraryOptions:o,target:i}=r??{},s=bi({...o??{},target:i,io:e,processors:n});return Ae(t,s),vi(s,t),ki(s,t)};var ose={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},gT=(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=ose[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}))])}},hT=(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)},yT=(t,e,n,r)=>{n.type="boolean"},bT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},vT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},kT=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},wT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},ST=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},xT=(t,e,n,r)=>{n.not={}},RT=(t,e,n,r)=>{},TT=(t,e,n,r)=>{},PT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},AT=(t,e,n,r)=>{let o=t._zod.def,i=nd(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},IT=(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},_T=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},CT=(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},ET=(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)},MT=(t,e,n,r)=>{n.type="boolean"},DT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},$T=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},NT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},OT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},jT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},LT=(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"]})},UT=(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)},Ef=(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},FT=(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},HT=(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)},zT=(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)}},BT=(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"}]},qT=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},WT=(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))},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,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},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;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},VT=(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},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,n.readOnly=!0},ZT=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},Mf=(t,e,n,r)=>{let o=t._zod.def;Ae(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},XT=(t,e,n,r)=>{let o=t._zod.innerType;Ae(o,e,r);let i=e.seen.get(t);i.ref=o},Cf={string:gT,number:hT,boolean:yT,bigint:bT,symbol:vT,null:kT,undefined:wT,void:ST,never:xT,any:RT,unknown:TT,date:PT,enum:AT,literal:IT,nan:_T,template_literal:CT,file:ET,success:MT,custom:DT,function:$T,transform:NT,map:OT,set:jT,array:LT,object:UT,union:Ef,intersection:FT,tuple:HT,record:zT,nullable:BT,nonoptional:qT,default:WT,prefault:GT,catch:KT,pipe:VT,readonly:JT,promise:ZT,optional:Mf,lazy:XT};function Df(t,e){if("_idmap"in t){let r=t,o=bi({...e,processors:Cf}),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;vi(o,d),s[l]=ki(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=bi({...e,processors:Cf});return Ae(t,n),vi(n,t),ki(n,t)}var $f=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=bi({processors:Cf,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)),vi(this.ctx,e);let r=ki(this.ctx,e),{"~standard":o,...i}=r;return i}};var jj={};var kd={};sn(kd,{ZodAny:()=>wP,ZodArray:()=>TP,ZodBase64:()=>tg,ZodBase64URL:()=>ng,ZodBigInt:()=>cc,ZodBigIntFormat:()=>ig,ZodBoolean:()=>ac,ZodCIDRv4:()=>Qf,ZodCIDRv6:()=>eg,ZodCUID:()=>Gf,ZodCUID2:()=>Kf,ZodCatch:()=>KP,ZodCodec:()=>Md,ZodCustom:()=>Dd,ZodCustomStringFormat:()=>ic,ZodDate:()=>Ad,ZodDefault:()=>HP,ZodDiscriminatedUnion:()=>AP,ZodE164:()=>rg,ZodEmail:()=>Bf,ZodEmoji:()=>qf,ZodEnum:()=>rc,ZodExactOptional:()=>LP,ZodFile:()=>OP,ZodFunction:()=>rA,ZodGUID:()=>Sd,ZodIPv4:()=>Xf,ZodIPv6:()=>Yf,ZodIntersection:()=>IP,ZodJWT:()=>og,ZodKSUID:()=>Zf,ZodLazy:()=>eA,ZodLiteral:()=>NP,ZodMAC:()=>fP,ZodMap:()=>DP,ZodNaN:()=>JP,ZodNanoID:()=>Wf,ZodNever:()=>xP,ZodNonOptional:()=>ug,ZodNull:()=>vP,ZodNullable:()=>FP,ZodNumber:()=>sc,ZodNumberFormat:()=>js,ZodObject:()=>_d,ZodOptional:()=>dg,ZodPipe:()=>Ed,ZodPrefault:()=>BP,ZodPreprocess:()=>ZP,ZodPromise:()=>nA,ZodReadonly:()=>XP,ZodRecord:()=>nc,ZodSet:()=>$P,ZodString:()=>oc,ZodStringFormat:()=>$e,ZodSuccess:()=>GP,ZodSymbol:()=>yP,ZodTemplateLiteral:()=>QP,ZodTransform:()=>jP,ZodTuple:()=>CP,ZodType:()=>ue,ZodULID:()=>Vf,ZodURL:()=>Pd,ZodUUID:()=>Gr,ZodUndefined:()=>bP,ZodUnion:()=>Cd,ZodUnknown:()=>SP,ZodVoid:()=>RP,ZodXID:()=>Jf,ZodXor:()=>PP,_ZodString:()=>zf,_default:()=>zP,_function:()=>GL,any:()=>xL,array:()=>Id,base64:()=>sL,base64url:()=>aL,bigint:()=>bL,boolean:()=>hP,catch:()=>VP,check:()=>KL,cidrv4:()=>oL,cidrv6:()=>iL,codec:()=>zL,cuid:()=>Zj,cuid2:()=>Xj,custom:()=>VL,date:()=>TL,describe:()=>JL,discriminatedUnion:()=>EL,e164:()=>cL,email:()=>Fj,emoji:()=>Vj,enum:()=>cg,exactOptional:()=>UP,file:()=>LL,float32:()=>fL,float64:()=>gL,function:()=>GL,guid:()=>Hj,hash:()=>mL,hex:()=>pL,hostname:()=>uL,httpUrl:()=>Kj,instanceof:()=>XL,int:()=>Ff,int32:()=>hL,int64:()=>vL,intersection:()=>_P,invertCodec:()=>BL,ipv4:()=>tL,ipv6:()=>rL,json:()=>QL,jwt:()=>lL,keyof:()=>PL,ksuid:()=>eL,lazy:()=>tA,literal:()=>jL,looseObject:()=>_L,looseRecord:()=>DL,mac:()=>nL,map:()=>$L,meta:()=>ZL,nan:()=>HL,nanoid:()=>Jj,nativeEnum:()=>OL,never:()=>sg,nonoptional:()=>WP,null:()=>kP,nullable:()=>Rd,nullish:()=>UL,number:()=>gP,object:()=>AL,optional:()=>xd,partialRecord:()=>ML,pipe:()=>Hf,prefault:()=>qP,preprocess:()=>eU,promise:()=>WL,readonly:()=>YP,record:()=>MP,refine:()=>oA,set:()=>NL,strictObject:()=>IL,string:()=>wd,stringFormat:()=>dL,stringbool:()=>YL,success:()=>FL,superRefine:()=>iA,symbol:()=>wL,templateLiteral:()=>qL,transform:()=>lg,tuple:()=>EP,uint32:()=>yL,uint64:()=>kL,ulid:()=>Yj,undefined:()=>SL,union:()=>ag,unknown:()=>Os,url:()=>Gj,uuid:()=>zj,uuidv4:()=>Bj,uuidv6:()=>qj,uuidv7:()=>Wj,void:()=>RL,xid:()=>Qj,xor:()=>CL});var Nf={};sn(Nf,{endsWith:()=>Ga,gt:()=>qr,gte:()=>Xt,includes:()=>qa,length:()=>Ns,lowercase:()=>za,lt:()=>Br,lte:()=>jn,maxLength:()=>$s,maxSize:()=>yi,mime:()=>Ka,minLength:()=>To,minSize:()=>Wr,multipleOf:()=>hi,negative:()=>Pf,nonnegative:()=>If,nonpositive:()=>Af,normalize:()=>Va,overwrite:()=>yr,positive:()=>Tf,property:()=>_f,regex:()=>Ha,size:()=>Ds,slugify:()=>Ya,startsWith:()=>Wa,toLowerCase:()=>Za,toUpperCase:()=>Xa,trim:()=>Ja,uppercase:()=>Ba});var tc={};sn(tc,{ZodISODate:()=>jf,ZodISODateTime:()=>Of,ZodISODuration:()=>Uf,ZodISOTime:()=>Lf,date:()=>QT,datetime:()=>YT,duration:()=>tP,time:()=>eP});var Of=A("ZodISODateTime",(t,e)=>{_x.init(t,e),$e.init(t,e)});function YT(t){return DR(Of,t)}var jf=A("ZodISODate",(t,e)=>{Cx.init(t,e),$e.init(t,e)});function QT(t){return $R(jf,t)}var Lf=A("ZodISOTime",(t,e)=>{Ex.init(t,e),$e.init(t,e)});function eP(t){return NR(Lf,t)}var Uf=A("ZodISODuration",(t,e)=>{Mx.init(t,e),$e.init(t,e)});function tP(t){return OR(Uf,t)}var Lj=(t,e)=>{ad.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ld(t,n)},flatten:{value:n=>cd(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Ma,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Ma,2)}},isEmpty:{get(){return t.issues.length===0}}})},sse=A("ZodError",Lj),mn=A("ZodError",Lj,{Parent:Error});var nP=Na(mn),rP=Oa(mn),oP=ja(mn),iP=La(mn),sP=Mm(mn),aP=Dm(mn),cP=$m(mn),lP=Nm(mn),dP=Om(mn),uP=jm(mn),pP=Lm(mn),mP=Um(mn);var Uj=new WeakMap;function Td(t,e,n){let r=Object.getPrototypeOf(t),o=Uj.get(r);if(o||(o=new Set,Uj.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:ec(t,"input"),output:ec(t,"output")}}),t.toJSONSchema=fT(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>nP(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>oP(t,n,r),t.parseAsync=async(n,r)=>rP(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>iP(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>sP(t,n,r),t.decode=(n,r)=>aP(t,n,r),t.encodeAsync=async(n,r)=>cP(t,n,r),t.decodeAsync=async(n,r)=>lP(t,n,r),t.safeEncode=(n,r)=>dP(t,n,r),t.safeDecode=(n,r)=>uP(t,n,r),t.safeEncodeAsync=async(n,r)=>pP(t,n,r),t.safeDecodeAsync=async(n,r)=>mP(t,n,r),Td(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(oA(n,r))},superRefine(n,r){return this.check(iA(n,r))},overwrite(n){return this.check(yr(n))},optional(){return xd(this)},exactOptional(){return UP(this)},nullable(){return Rd(this)},nullish(){return xd(Rd(this))},nonoptional(n){return WP(this,n)},array(){return Id(this)},or(n){return ag([this,n])},and(n){return _P(this,n)},transform(n){return Hf(this,lg(n))},default(n){return zP(this,n)},prefault(n){return qP(this,n)},catch(n){return VP(this,n)},pipe(n){return Hf(this,n)},readonly(){return YP(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)),zf=A("_ZodString",(t,e)=>{Ms.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>gT(t,r,o,i);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,Td(t,"_ZodString",{regex(...r){return this.check(Ha(...r))},includes(...r){return this.check(qa(...r))},startsWith(...r){return this.check(Wa(...r))},endsWith(...r){return this.check(Ga(...r))},min(...r){return this.check(To(...r))},max(...r){return this.check($s(...r))},length(...r){return this.check(Ns(...r))},nonempty(...r){return this.check(To(1,...r))},lowercase(r){return this.check(za(r))},uppercase(r){return this.check(Ba(r))},trim(){return this.check(Ja())},normalize(...r){return this.check(Va(...r))},toLowerCase(){return this.check(Za())},toUpperCase(){return this.check(Xa())},slugify(){return this.check(Ya())}})}),oc=A("ZodString",(t,e)=>{Ms.init(t,e),zf.init(t,e),t.email=n=>t.check(of(Bf,n)),t.url=n=>t.check(vd(Pd,n)),t.jwt=n=>t.check(Rf(og,n)),t.emoji=n=>t.check(df(qf,n)),t.guid=n=>t.check(bd(Sd,n)),t.uuid=n=>t.check(sf(Gr,n)),t.uuidv4=n=>t.check(af(Gr,n)),t.uuidv6=n=>t.check(cf(Gr,n)),t.uuidv7=n=>t.check(lf(Gr,n)),t.nanoid=n=>t.check(uf(Wf,n)),t.guid=n=>t.check(bd(Sd,n)),t.cuid=n=>t.check(pf(Gf,n)),t.cuid2=n=>t.check(mf(Kf,n)),t.ulid=n=>t.check(ff(Vf,n)),t.base64=n=>t.check(wf(tg,n)),t.base64url=n=>t.check(Sf(ng,n)),t.xid=n=>t.check(gf(Jf,n)),t.ksuid=n=>t.check(hf(Zf,n)),t.ipv4=n=>t.check(yf(Xf,n)),t.ipv6=n=>t.check(bf(Yf,n)),t.cidrv4=n=>t.check(vf(Qf,n)),t.cidrv6=n=>t.check(kf(eg,n)),t.e164=n=>t.check(xf(rg,n)),t.datetime=n=>t.check(YT(n)),t.date=n=>t.check(QT(n)),t.time=n=>t.check(eP(n)),t.duration=n=>t.check(tP(n))});function wd(t){return _R(oc,t)}var $e=A("ZodStringFormat",(t,e)=>{De.init(t,e),zf.init(t,e)}),Bf=A("ZodEmail",(t,e)=>{kx.init(t,e),$e.init(t,e)});function Fj(t){return of(Bf,t)}var Sd=A("ZodGUID",(t,e)=>{bx.init(t,e),$e.init(t,e)});function Hj(t){return bd(Sd,t)}var Gr=A("ZodUUID",(t,e)=>{vx.init(t,e),$e.init(t,e)});function zj(t){return sf(Gr,t)}function Bj(t){return af(Gr,t)}function qj(t){return cf(Gr,t)}function Wj(t){return lf(Gr,t)}var Pd=A("ZodURL",(t,e)=>{wx.init(t,e),$e.init(t,e)});function Gj(t){return vd(Pd,t)}function Kj(t){return vd(Pd,{protocol:On.httpProtocol,hostname:On.domain,...H.normalizeParams(t)})}var qf=A("ZodEmoji",(t,e)=>{Sx.init(t,e),$e.init(t,e)});function Vj(t){return df(qf,t)}var Wf=A("ZodNanoID",(t,e)=>{xx.init(t,e),$e.init(t,e)});function Jj(t){return uf(Wf,t)}var Gf=A("ZodCUID",(t,e)=>{Rx.init(t,e),$e.init(t,e)});function Zj(t){return pf(Gf,t)}var Kf=A("ZodCUID2",(t,e)=>{Tx.init(t,e),$e.init(t,e)});function Xj(t){return mf(Kf,t)}var Vf=A("ZodULID",(t,e)=>{Px.init(t,e),$e.init(t,e)});function Yj(t){return ff(Vf,t)}var Jf=A("ZodXID",(t,e)=>{Ax.init(t,e),$e.init(t,e)});function Qj(t){return gf(Jf,t)}var Zf=A("ZodKSUID",(t,e)=>{Ix.init(t,e),$e.init(t,e)});function eL(t){return hf(Zf,t)}var Xf=A("ZodIPv4",(t,e)=>{Dx.init(t,e),$e.init(t,e)});function tL(t){return yf(Xf,t)}var fP=A("ZodMAC",(t,e)=>{Nx.init(t,e),$e.init(t,e)});function nL(t){return ER(fP,t)}var Yf=A("ZodIPv6",(t,e)=>{$x.init(t,e),$e.init(t,e)});function rL(t){return bf(Yf,t)}var Qf=A("ZodCIDRv4",(t,e)=>{Ox.init(t,e),$e.init(t,e)});function oL(t){return vf(Qf,t)}var eg=A("ZodCIDRv6",(t,e)=>{jx.init(t,e),$e.init(t,e)});function iL(t){return kf(eg,t)}var tg=A("ZodBase64",(t,e)=>{Ux.init(t,e),$e.init(t,e)});function sL(t){return wf(tg,t)}var ng=A("ZodBase64URL",(t,e)=>{Fx.init(t,e),$e.init(t,e)});function aL(t){return Sf(ng,t)}var rg=A("ZodE164",(t,e)=>{Hx.init(t,e),$e.init(t,e)});function cL(t){return xf(rg,t)}var og=A("ZodJWT",(t,e)=>{zx.init(t,e),$e.init(t,e)});function lL(t){return Rf(og,t)}var ic=A("ZodCustomStringFormat",(t,e)=>{Bx.init(t,e),$e.init(t,e)});function dL(t,e,n={}){return Qa(ic,t,e,n)}function uL(t){return Qa(ic,"hostname",On.hostname,t)}function pL(t){return Qa(ic,"hex",On.hex,t)}function mL(t,e){let n=e?.enc??"hex",r=`${t}_${n}`,o=On[r];if(!o)throw new Error(`Unrecognized hash format: ${r}`);return Qa(ic,r,o,e)}var sc=A("ZodNumber",(t,e)=>{Vm.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>hT(t,r,o,i),Td(t,"ZodNumber",{gt(r,o){return this.check(qr(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(Br(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(Ff(r))},safe(r){return this.check(Ff(r))},positive(r){return this.check(qr(0,r))},nonnegative(r){return this.check(Xt(0,r))},negative(r){return this.check(Br(0,r))},nonpositive(r){return this.check(jn(0,r))},multipleOf(r,o){return this.check(hi(r,o))},step(r,o){return this.check(hi(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 gP(t){return jR(sc,t)}var js=A("ZodNumberFormat",(t,e)=>{qx.init(t,e),sc.init(t,e)});function Ff(t){return UR(js,t)}function fL(t){return FR(js,t)}function gL(t){return HR(js,t)}function hL(t){return zR(js,t)}function yL(t){return BR(js,t)}var ac=A("ZodBoolean",(t,e)=>{md.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yT(t,n,r,o)});function hP(t){return qR(ac,t)}var cc=A("ZodBigInt",(t,e)=>{Jm.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>bT(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(qr(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(Br(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(qr(BigInt(0),r)),t.negative=r=>t.check(Br(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(hi(r,o));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});function bL(t){return GR(cc,t)}var ig=A("ZodBigIntFormat",(t,e)=>{Wx.init(t,e),cc.init(t,e)});function vL(t){return VR(ig,t)}function kL(t){return JR(ig,t)}var yP=A("ZodSymbol",(t,e)=>{Gx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>vT(t,n,r,o)});function wL(t){return ZR(yP,t)}var bP=A("ZodUndefined",(t,e)=>{Kx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wT(t,n,r,o)});function SL(t){return XR(bP,t)}var vP=A("ZodNull",(t,e)=>{Vx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>kT(t,n,r,o)});function kP(t){return YR(vP,t)}var wP=A("ZodAny",(t,e)=>{Jx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>RT(t,n,r,o)});function xL(){return QR(wP)}var SP=A("ZodUnknown",(t,e)=>{Zx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>TT(t,n,r,o)});function Os(){return eT(SP)}var xP=A("ZodNever",(t,e)=>{Xx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>xT(t,n,r,o)});function sg(t){return tT(xP,t)}var RP=A("ZodVoid",(t,e)=>{Yx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ST(t,n,r,o)});function RL(t){return nT(RP,t)}var Ad=A("ZodDate",(t,e)=>{Qx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>PT(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 TL(t){return rT(Ad,t)}var TP=A("ZodArray",(t,e)=>{eR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>LT(t,n,r,o),t.element=e.element,Td(t,"ZodArray",{min(n,r){return this.check(To(n,r))},nonempty(n){return this.check(To(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 Id(t,e){return sT(TP,t,e)}function PL(t){let e=t._zod.def.shape;return cg(Object.keys(e))}var _d=A("ZodObject",(t,e)=>{tR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>UT(t,n,r,o),H.defineLazy(t,"shape",()=>e.shape),Td(t,"ZodObject",{keyof(){return cg(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:sg()})},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(dg,this,n[0])},required(...n){return H.required(ug,this,n[0])}})});function AL(t,e){let n={type:"object",shape:t??{},...H.normalizeParams(e)};return new _d(n)}function IL(t,e){return new _d({type:"object",shape:t,catchall:sg(),...H.normalizeParams(e)})}function _L(t,e){return new _d({type:"object",shape:t,catchall:Os(),...H.normalizeParams(e)})}var Cd=A("ZodUnion",(t,e)=>{fd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ef(t,n,r,o),t.options=e.options});function ag(t,e){return new Cd({type:"union",options:t,...H.normalizeParams(e)})}var PP=A("ZodXor",(t,e)=>{Cd.init(t,e),nR.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ef(t,n,r,o),t.options=e.options});function CL(t,e){return new PP({type:"union",options:t,inclusive:!1,...H.normalizeParams(e)})}var AP=A("ZodDiscriminatedUnion",(t,e)=>{Cd.init(t,e),rR.init(t,e)});function EL(t,e,n){return new AP({type:"union",options:e,discriminator:t,...H.normalizeParams(n)})}var IP=A("ZodIntersection",(t,e)=>{oR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>FT(t,n,r,o)});function _P(t,e){return new IP({type:"intersection",left:t,right:e})}var CP=A("ZodTuple",(t,e)=>{Zm.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>HT(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function EP(t,e,n){let r=e instanceof oe,o=r?n:e,i=r?e:null;return new CP({type:"tuple",items:t,rest:i,...H.normalizeParams(o)})}var nc=A("ZodRecord",(t,e)=>{iR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>zT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function MP(t,e,n){return!e||!e._zod?new nc({type:"record",keyType:wd(),valueType:t,...H.normalizeParams(e)}):new nc({type:"record",keyType:t,valueType:e,...H.normalizeParams(n)})}function ML(t,e,n){let r=Jt(t);return r._zod.values=void 0,new nc({type:"record",keyType:r,valueType:e,...H.normalizeParams(n)})}function DL(t,e,n){return new nc({type:"record",keyType:t,valueType:e,mode:"loose",...H.normalizeParams(n)})}var DP=A("ZodMap",(t,e)=>{sR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>OT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...n)=>t.check(Wr(...n)),t.nonempty=n=>t.check(Wr(1,n)),t.max=(...n)=>t.check(yi(...n)),t.size=(...n)=>t.check(Ds(...n))});function $L(t,e,n){return new DP({type:"map",keyType:t,valueType:e,...H.normalizeParams(n)})}var $P=A("ZodSet",(t,e)=>{aR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>jT(t,n,r,o),t.min=(...n)=>t.check(Wr(...n)),t.nonempty=n=>t.check(Wr(1,n)),t.max=(...n)=>t.check(yi(...n)),t.size=(...n)=>t.check(Ds(...n))});function NL(t,e){return new $P({type:"set",valueType:t,...H.normalizeParams(e)})}var rc=A("ZodEnum",(t,e)=>{cR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>AT(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 rc({...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 rc({...e,checks:[],...H.normalizeParams(o),entries:i})}});function cg(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new rc({type:"enum",entries:n,...H.normalizeParams(e)})}function OL(t,e){return new rc({type:"enum",entries:t,...H.normalizeParams(e)})}var NP=A("ZodLiteral",(t,e)=>{lR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>IT(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 jL(t,e){return new NP({type:"literal",values:Array.isArray(t)?t:[t],...H.normalizeParams(e)})}var OP=A("ZodFile",(t,e)=>{dR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ET(t,n,r,o),t.min=(n,r)=>t.check(Wr(n,r)),t.max=(n,r)=>t.check(yi(n,r)),t.mime=(n,r)=>t.check(Ka(Array.isArray(n)?n:[n],r))});function LL(t){return aT(OP,t)}var jP=A("ZodTransform",(t,e)=>{uR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>NT(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new ui(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 lg(t){return new jP({type:"transform",transform:t})}var dg=A("ZodOptional",(t,e)=>{Xm.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Mf(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function xd(t){return new dg({type:"optional",innerType:t})}var LP=A("ZodExactOptional",(t,e)=>{pR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Mf(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function UP(t){return new LP({type:"optional",innerType:t})}var FP=A("ZodNullable",(t,e)=>{mR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>BT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Rd(t){return new FP({type:"nullable",innerType:t})}function UL(t){return xd(Rd(t))}var HP=A("ZodDefault",(t,e)=>{fR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>WT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function zP(t,e){return new HP({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():H.shallowClone(e)}})}var BP=A("ZodPrefault",(t,e)=>{gR.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 qP(t,e){return new BP({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():H.shallowClone(e)}})}var ug=A("ZodNonOptional",(t,e)=>{hR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function WP(t,e){return new ug({type:"nonoptional",innerType:t,...H.normalizeParams(e)})}var GP=A("ZodSuccess",(t,e)=>{yR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>MT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function FL(t){return new GP({type:"success",innerType:t})}var KP=A("ZodCatch",(t,e)=>{bR.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.removeCatch=t.unwrap});function VP(t,e){return new KP({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var JP=A("ZodNaN",(t,e)=>{vR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>_T(t,n,r,o)});function HL(t){return iT(JP,t)}var Ed=A("ZodPipe",(t,e)=>{Ym.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>VT(t,n,r,o),t.in=e.in,t.out=e.out});function Hf(t,e){return new Ed({type:"pipe",in:t,out:e})}var Md=A("ZodCodec",(t,e)=>{Ed.init(t,e),gd.init(t,e)});function zL(t,e,n){return new Md({type:"pipe",in:t,out:e,transform:n.decode,reverseTransform:n.encode})}function BL(t){let e=t._zod.def;return new Md({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var ZP=A("ZodPreprocess",(t,e)=>{Ed.init(t,e),kR.init(t,e)}),XP=A("ZodReadonly",(t,e)=>{wR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>JT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function YP(t){return new XP({type:"readonly",innerType:t})}var QP=A("ZodTemplateLiteral",(t,e)=>{SR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>CT(t,n,r,o)});function qL(t,e){return new QP({type:"template_literal",parts:t,...H.normalizeParams(e)})}var eA=A("ZodLazy",(t,e)=>{TR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>XT(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function tA(t){return new eA({type:"lazy",getter:t})}var nA=A("ZodPromise",(t,e)=>{RR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ZT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function WL(t){return new nA({type:"promise",innerType:t})}var rA=A("ZodFunction",(t,e)=>{xR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>$T(t,n,r,o)});function GL(t){return new rA({type:"function",input:Array.isArray(t?.input)?EP(t?.input):t?.input??Id(Os()),output:t?.output??Os()})}var Dd=A("ZodCustom",(t,e)=>{PR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>DT(t,n,r,o)});function KL(t){let e=new Le({check:"custom"});return e._zod.check=t,e}function VL(t,e){return cT(Dd,t??(()=>!0),e)}function oA(t,e={}){return lT(Dd,t,e)}function iA(t,e){return dT(t,e)}var JL=uT,ZL=pT;function XL(t,e={}){let n=new Dd({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 YL=(...t)=>mT({Codec:Md,Boolean:ac,String:oc},...t);function QL(t){let e=tA(()=>ag([wd(t),gP(),hP(),kP(),Id(e),MP(wd(),e)]));return e}function eU(t,e){return new ZP({type:"pipe",in:lg(t),out:e})}var cse={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 lse(t){Ye({customError:t})}function dse(){return Ye().customError}var sA;sA||(sA={});var G={...kd,...Nf,iso:tc},use=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 pse(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 mse(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 tU(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=mse(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 tU(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=tU(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))use.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 nU(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=pse(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 aA={};sn(aA,{bigint:()=>yse,boolean:()=>hse,date:()=>bse,number:()=>gse,string:()=>fse});function fse(t){return CR(oc,t)}function gse(t){return LR(sc,t)}function hse(t){return WR(ac,t)}function yse(t){return KR(cc,t)}function bse(t){return oT(Ad,t)}Ye(Qm());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"},sr={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 rU=Symbol("skippedItem");function W(t,e){return t.catch(e)}function br(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(rU)).transform(e=>e.filter(n=>n!==rU))}var kse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminal:u.boolean().optional().default(!1)}),wse=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)}),Sse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),name:u.string()}),xse=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(wse)}),Rse=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()}),Tse=u.union([xse.and(u.object({type:u.literal("env_var")})),Rse.and(u.object({type:u.literal("terminal")})),Sse]),oU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),methodId:u.string()}),Pse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ase=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),blob:u.string(),mimeType:u.string().nullish(),uri:u.string()}),Ise=u.object({default:u.boolean().nullish(),description:u.string().nullish(),title:u.string().nullish()}),_se=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Cse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ese=u.object({amount:u.number(),currency:u.string()}),Mse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),Dse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),$se=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),newText:u.string(),oldText:u.string().nullish(),path:u.string()}),iU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string()}),Nse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ose=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),jse=u.union([u.string(),u.number(),u.number(),u.boolean(),u.array(u.string())]),Lse=u.object({content:u.record(u.string(),jse).nullish()}),Use=u.intersection(u.union([Lse.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()})),Fse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),sU=u.string(),lA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),elicitationId:sU}),Hse=u.literal("object"),zse=u.literal("string"),Bse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),qse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),form:W(Fse.nullish(),()=>{}),url:W(Bse.nullish(),()=>{})}),aU=u.object({const:u.string(),title:u.string()}),cU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),Wse=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"})]),lU=u.object({code:Wse,data:u.unknown().optional(),message:u.string()}),dU=u.unknown(),uU=u.unknown(),pU=u.unknown(),Gse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),readTextFile:u.boolean().optional().default(!1),writeTextFile:u.boolean().optional().default(!1)}),mU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),fU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),title:u.string().nullish(),version:u.string()}),Kse=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),Vse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),gU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),hU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cursor:u.string().nullish(),cwd:u.string().nullish()}),dA=u.union([u.literal("anthropic"),u.literal("openai"),u.literal("azure"),u.literal("vertex"),u.literal("bedrock"),u.string()]),Jse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Zse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),logout:W(Jse.nullish(),()=>{})}),yU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Xse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Yse=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)}),pg=u.string(),Qse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:pg}),eae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:pg}),bU=u.string(),tae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acpId:bU}),nae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:bU,name:u.string()}),rae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(mU),name:u.string(),url:u.string()}),oae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(mU),name:u.string(),url:u.string()}),iae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()),command:u.string(),env:u.array(cU),name:u.string()}),mg=u.union([rae.and(u.object({type:u.literal("http")})),oae.and(u.object({type:u.literal("sse")})),nae.and(u.object({type:u.literal("acp")})),iae]),sae=u.string(),vU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:pg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),kU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:pg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),wU=u.unknown(),aae=u.union([u.literal("error"),u.literal("warning"),u.literal("information"),u.literal("hint")]),cae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),lae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),uae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),pae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),mae=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()}),fae=u.object({diff:u.string(),uri:u.string()}),gae=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()}),hae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),yae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),bae=u.object({languageId:u.string(),text:u.string(),uri:u.string()}),vae=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()}),kae=u.union([u.literal("rejected"),u.literal("ignored"),u.literal("replaced"),u.literal("cancelled")]),wae=u.object({excerpts:u.array(gae),uri:u.string()}),Sae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Rae=u.object({name:u.string(),owner:u.string(),remoteUrl:u.string()}),Tae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Pae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),jump:W(hae.nullish(),()=>{}),rename:W(xae.nullish(),()=>{}),searchAndReplace:W(Tae.nullish(),()=>{})}),Aae=u.object({id:u.string(),isRegex:u.boolean().nullish(),replace:u.string(),search:u.string(),uri:u.string()}),Iae=u.union([u.literal("automatic"),u.literal("diagnostic"),u.literal("manual")]),_ae=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()}),Cae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(cae.nullish(),()=>{}),editHistory:W(mae.nullish(),()=>{}),openFiles:W(yae.nullish(),()=>{}),recentFiles:W(vae.nullish(),()=>{}),relatedSnippets:W(Sae.nullish(),()=>{}),userActions:W(_ae.nullish(),()=>{})}),SU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(mg)}),Eae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),xU=u.string(),Mae=u.union([u.literal("allow_once"),u.literal("allow_always"),u.literal("reject_once"),u.literal("reject_always")]),Dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),kind:Mae,name:u.string(),optionId:xU}),$ae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Nae=u.union([u.literal("high"),u.literal("medium"),u.literal("low")]),Oae=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed")]),RU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),priority:Nae,status:Oae}),jae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:br(Ce(RU),()=>[])}),fg=u.string(),Lae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:fg,uri:u.string()}),Uae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:br(Ce(RU),()=>[]),id:fg}),Fae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),id:fg}),Hae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:fg}),zae=u.union([Uae.and(u.object({type:u.literal("items")})),Lae.and(u.object({type:u.literal("file")})),Fae.and(u.object({type:u.literal("markdown")}))]),Bae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),plan:zae}),wi=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:wi,uri:u.string()}),Wae=u.object({id:u.string(),newName:u.string(),position:wi,uri:u.string()}),Gae=u.object({action:u.string(),position:wi,timestampMs:u.number(),uri:u.string()}),TU=u.union([u.literal("utf-16"),u.literal("utf-32"),u.literal("utf-8")]),Kae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:kse.optional().default({terminal:!1}),elicitation:W(qse.nullish(),()=>{}),fs:Gse.optional().default({readTextFile:!1,writeTextFile:!1}),nes:W(Pae.nullish(),()=>{}),plan:W($ae.nullish(),()=>{}),positionEncodings:W(Ce(TU).optional(),()=>[]),terminal:u.boolean().optional().default(!1)}),Vae=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)}),PU=u.number().int().gte(0).lte(65535),AU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),clientCapabilities:Kae.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:W(fU.nullish(),()=>{}),protocolVersion:PU}),Jae=u.object({apiType:dA,baseUrl:u.string()}),Zae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),current:Jae.nullish(),id:u.string(),required:u.boolean(),supported:br(Ce(dA),()=>[])}),Xae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),providers:br(Ce(Zae),()=>[])}),Yae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),lc=u.object({end:wi,start:wi}),Qae=u.object({message:u.string(),range:lc,severity:aae,uri:u.string()}),ece=u.object({languageId:u.string(),lastFocusedMs:W(u.number().nullish(),()=>{}),uri:u.string(),visibleRange:W(lc.nullish(),()=>{})}),tce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(Ce(Qae).nullish(),()=>{}),editHistory:W(Ce(fae).nullish(),()=>{}),openFiles:W(Ce(ece).nullish(),()=>{}),recentFiles:W(Ce(bae).nullish(),()=>{}),relatedSnippets:W(Ce(wae).nullish(),()=>{}),userActions:W(Ce(Gae).nullish(),()=>{})}),nce=u.object({newText:u.string(),range:lc}),rce=u.object({cursorPosition:W(wi.nullish(),()=>{}),edits:u.array(nce),id:u.string(),uri:u.string()}),oce=u.union([rce.and(u.object({kind:u.literal("edit")})),qae.and(u.object({kind:u.literal("jump")})),Wae.and(u.object({kind:u.literal("rename")})),Aae.and(u.object({kind:u.literal("searchAndReplace")}))]),ice=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string()}),sce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Si=u.union([u.number(),u.string()]).nullable(),lze=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),requestId:Si}),IU=u.object({requestId:Si}),ace=u.enum(["assistant","user"]),$d=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audience:W(Ce(ace).nullish(),()=>{}),lastModified:u.string().nullish(),priority:u.number().nullish()}),cce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W($d.nullish(),()=>{}),data:u.string(),mimeType:u.string()}),lce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W($d.nullish(),()=>{}),data:u.string(),mimeType:u.string(),uri:u.string().nullish()}),dce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W($d.nullish(),()=>{}),description:u.string().nullish(),mimeType:u.string().nullish(),name:u.string(),size:u.number().nullish(),title:u.string().nullish(),uri:u.string()}),uce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),optionId:xU}),pce=u.union([u.object({outcome:u.literal("cancelled")}),uce.and(u.object({outcome:u.literal("selected")}))]),mce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),outcome:pce}),fce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),gce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),hce=u.object({currentValue:u.boolean()}),yce=u.string(),_U=u.string(),bce=u.union([u.literal("mode"),u.literal("model"),u.literal("thought_level"),u.string()]),uA=u.string(),CU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),name:u.string(),value:uA}),vce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),group:yce,name:u.string(),options:u.array(CU)}),kce=u.union([u.array(CU),u.array(vce)]),wce=u.object({currentValue:uA,options:kce}),dc=u.intersection(u.union([wce.and(u.object({type:u.literal("select")})),hce.and(u.object({type:u.literal("boolean")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),category:W(bce.nullish(),()=>{}),description:u.string().nullish(),id:_U,name:u.string()})),Sce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:br(Ce(dc),()=>[])}),xce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Rce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Re=u.string(),EU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),sessionId:Re}),MU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),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}),pA=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(cU).optional(),outputByteLimit:u.number().nullish(),sessionId:Re}),NU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re}),OU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,uri:u.string()}),jU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),position:wi,sessionId:Re,uri:u.string(),version:u.number(),visibleRange:lc}),LU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),languageId:u.string(),sessionId:Re,text:u.string(),uri:u.string(),version:u.number()}),UU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,uri:u.string()}),FU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(mg).optional(),sessionId:Re}),mA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,terminalId: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(mg),sessionId:Re}),fA=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}),zU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),reason:W(kae.nullish(),()=>{}),sessionId:Re}),gA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,terminalId:u.string()}),BU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(mg).optional(),sessionId:Re}),Tce=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(),()=>{})}),Pce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),nextCursor:u.string().nullish(),sessions:br(Ce(Tce),()=>[])}),Ace=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),title:u.string().nullish(),updatedAt:u.string().nullish()}),Ice=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),gg=u.string(),_ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),currentModeId:gg}),Cce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:gg,name:u.string()}),hg=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableModes:br(Ce(Cce),()=>[]),currentModeId:gg}),Ece=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(dc).nullish(),()=>{}),modes:W(hg.nullish(),()=>{}),sessionId:Re}),Mce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(dc).nullish(),()=>{}),modes:W(hg.nullish(),()=>{})}),Dce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(dc).nullish(),()=>{}),modes:W(hg.nullish(),()=>{}),sessionId:Re}),$ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(dc).nullish(),()=>{}),modes:W(hg.nullish(),()=>{})}),Nce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Oce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:W(fce.nullish(),()=>{}),close:W(gce.nullish(),()=>{}),delete:W(xce.nullish(),()=>{}),fork:W(Rce.nullish(),()=>{}),list:W(Ice.nullish(),()=>{}),resume:W(Nce.nullish(),()=>{})}),qU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),apiType:dA,baseUrl:u.string(),headers:u.record(u.string(),u.string()).optional(),id:u.string()}),jce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),WU=u.intersection(u.union([u.object({type:u.literal("boolean"),value:u.boolean()}),u.object({value:uA})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configId:_U,sessionId:Re})),Lce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:br(Ce(dc),()=>[])}),GU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),modeId:gg,sessionId:Re}),Uce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Fce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re}),Hce=u.union([u.literal("end_turn"),u.literal("max_tokens"),u.literal("max_turn_requests"),u.literal("refusal"),u.literal("cancelled")]),zce=u.union([u.literal("email"),u.literal("uri"),u.literal("date"),u.literal("date-time")]),Bce=u.object({default:u.string().nullish(),description:u.string().nullish(),enum:u.array(u.string()).nullish(),format:zce.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(aU).nullish(),pattern:u.string().nullish(),title:u.string().nullish()}),KU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(tce.nullish(),()=>{}),position:wi,selection:W(lc.nullish(),()=>{}),sessionId:Re,triggerKind:Iae,uri:u.string(),version:u.number()}),qce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),suggestions:br(Ce(oce),()=>[])}),Wce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),Gce=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()}),hA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,terminalId:u.string()}),Kce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitStatus:Gce.nullish(),output:u.string(),truncated:u.boolean()}),Vce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W($d.nullish(),()=>{}),text:u.string()}),Jce=u.object({range:lc.nullish(),text:u.string()}),VU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),contentChanges:u.array(Jce),sessionId:Re,uri:u.string(),version:u.number()}),dze=u.object({method:u.string(),params:u.union([MU,LU,VU,OU,UU,jU,EU,zU,vU,dU]).nullish()}),Zce=u.union([u.literal("full"),u.literal("incremental")]),Xce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),syncKind:Zce}),Yce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),didChange:W(Xce.nullish(),()=>{}),didClose:W(lae.nullish(),()=>{}),didFocus:W(dae.nullish(),()=>{}),didOpen:W(uae.nullish(),()=>{}),didSave:W(pae.nullish(),()=>{})}),Qce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),document:W(Yce.nullish(),()=>{})}),ele=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(Cae.nullish(),()=>{}),events:W(Qce.nullish(),()=>{})}),tle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:Zse.optional().default({}),loadSession:u.boolean().optional().default(!1),mcpCapabilities:Yse.optional().default({acp:!1,http:!1,sse:!1}),nes:W(ele.nullish(),()=>{}),positionEncoding:W(TU.nullish(),()=>{}),promptCapabilities:Vae.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:W(Yae.nullish(),()=>{}),sessionCapabilities:Oce.optional().default({})}),nle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),agentCapabilities:tle.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:W(fU.nullish(),()=>{}),authMethods:W(Ce(Tse).optional().default([]),()=>[]),protocolVersion:PU}),rle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),mimeType:u.string().nullish(),text:u.string(),uri:u.string()}),ole=u.union([rle,Ase]),ile=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W($d.nullish(),()=>{}),resource:ole}),yA=u.union([Vce.and(u.object({type:u.literal("text")})),lce.and(u.object({type:u.literal("image")})),cce.and(u.object({type:u.literal("audio")})),dce.and(u.object({type:u.literal("resource_link")})),ile.and(u.object({type:u.literal("resource")}))]),sle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:yA}),cA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:yA,messageId:sae.nullish()}),JU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),prompt:u.array(yA),sessionId:Re}),ale=u.object({anyOf:u.array(aU)}),ZU=u.union([sle.and(u.object({type:u.literal("content")})),$se.and(u.object({type:u.literal("diff")})),Wce.and(u.object({type:u.literal("terminal")}))]),bA=u.string(),XU=u.object({sessionId:Re,toolCallId:bA.nullish()}),cle=u.intersection(u.union([XU,IU]),u.object({elicitationId:sU,url:u.string().url()})),YU=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()}),QU=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed"),u.literal("failed")]),eF=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")]),lle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(ZU).optional(),()=>[]),kind:eF.optional(),locations:W(Ce(YU).optional(),()=>[]),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:QU.optional(),title:u.string(),toolCallId:bA}),tF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(ZU).nullish(),()=>{}),kind:W(eF.nullish(),()=>{}),locations:W(Ce(YU).nullish(),()=>{}),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:W(QU.nullish(),()=>{}),title:u.string().nullish(),toolCallId:bA}),vA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),options:u.array(Dae),sessionId:Re,toolCall:tF}),dle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),hint:u.string()}),ule=dle,ple=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string(),input:W(ule.nullish(),()=>{}),name:u.string()}),mle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableCommands:br(Ce(ple),()=>[])}),fle=u.object({enum:u.array(u.string()),type:zse}),gle=u.union([fle,ale]),hle=u.object({default:u.array(u.string()).nullish(),description:u.string().nullish(),items:gle,maxItems:u.number().nullish(),minItems:u.number().nullish(),title:u.string().nullish()}),yle=u.union([Bce.and(u.object({type:u.literal("string")})),Eae.and(u.object({type:u.literal("number")})),Kse.and(u.object({type:u.literal("integer")})),Ise.and(u.object({type:u.literal("boolean")})),hle.and(u.object({type:u.literal("array")}))]),ble=u.object({description:u.string().nullish(),properties:u.record(u.string(),yle).optional().default({}),required:u.array(u.string()).nullish(),title:u.string().nullish(),type:Hse.optional().default("object")}),vle=u.intersection(u.union([XU,IU]),u.object({requestedSchema:ble})),kA=u.intersection(u.union([vle.and(u.object({mode:u.literal("form")})),cle.and(u.object({mode:u.literal("url")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),message:u.string()})),kle=u.object({cachedReadTokens:u.number().nullish(),cachedWriteTokens:u.number().nullish(),inputTokens:u.number(),outputTokens:u.number(),thoughtTokens:u.number().nullish(),totalTokens:u.number()}),wle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),stopReason:Hce,usage:W(kle.nullish(),()=>{})}),uze=u.union([u.object({id:Si,result:u.union([nle,Pse,Xae,jce,Nse,Xse,Dce,Mce,Pce,Dse,Ece,$ce,Cse,Uce,Lce,wle,Fce,qce,_se,pU,wU])}),u.object({error:lU,id:Si})]),Sle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cost:W(Ese.nullish(),()=>{}),size:u.number(),used:u.number()}),xle=u.union([cA.and(u.object({sessionUpdate:u.literal("user_message_chunk")})),cA.and(u.object({sessionUpdate:u.literal("agent_message_chunk")})),cA.and(u.object({sessionUpdate:u.literal("agent_thought_chunk")})),lle.and(u.object({sessionUpdate:u.literal("tool_call")})),tF.and(u.object({sessionUpdate:u.literal("tool_call_update")})),jae.and(u.object({sessionUpdate:u.literal("plan")})),Bae.and(u.object({sessionUpdate:u.literal("plan_update")})),Hae.and(u.object({sessionUpdate:u.literal("plan_removed")})),mle.and(u.object({sessionUpdate:u.literal("available_commands_update")})),_ce.and(u.object({sessionUpdate:u.literal("current_mode_update")})),Sce.and(u.object({sessionUpdate:u.literal("config_option_update")})),Ace.and(u.object({sessionUpdate:u.literal("session_info_update")})),Sle.and(u.object({sessionUpdate:u.literal("usage_update")}))]),wA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,update:xle}),pze=u.object({method:u.string(),params:u.union([wA,lA,vU,dU]).nullish()}),SA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:Re,terminalId:u.string()}),Rle=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()}),Tle=u.object({name:u.string(),uri:u.string()}),nF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),repository:W(Rae.nullish(),()=>{}),workspaceFolders:W(Ce(Tle).nullish(),()=>{}),workspaceUri:u.string().nullish()}),mze=u.object({id:Si,method:u.string(),params:u.union([AU,oU,gU,qU,iU,yU,SU,HU,hU,NU,FU,BU,$U,GU,WU,JU,nF,KU,DU,kU,uU]).nullish()}),xA=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),path:u.string(),sessionId:Re}),fze=u.object({id:Si,method:u.string(),params:u.union([xA,fA,vA,pA,hA,gA,SA,mA,kA,tae,kU,eae,uU]).nullish()}),Ple=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),gze=u.union([u.object({id:Si,result:u.union([Ple,ice,mce,Mse,Kce,sce,Rle,Vse,Use,Qse,Ose,pU,wU])}),u.object({error:lU,id:Si})]);function rF(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(`
681
681
  `);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)+`
682
- `,c=t.getWriter();try{await c.write(n.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function xi(t){return t??{}}function oF(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var yg=class{connection;constructor(e,n){let r=e(this),o=async(s,a)=>{switch(s){case sr.fs_write_text_file:{let c=xA.parse(a);return await r.writeTextFile?.(c)??{}}case sr.fs_read_text_file:{let c=fA.parse(a);return r.readTextFile?.(c)}case sr.session_request_permission:{let c=vA.parse(a);return r.requestPermission(c)}case sr.terminal_create:{let c=pA.parse(a);return r.createTerminal?.(c)}case sr.terminal_output:{let c=hA.parse(a);return r.terminalOutput?.(c)}case sr.terminal_release:{let c=gA.parse(a);return await r.releaseTerminal?.(c)??{}}case sr.terminal_wait_for_exit:{let c=SA.parse(a);return r.waitForTerminalExit?.(c)}case sr.terminal_kill:{let c=mA.parse(a);return await r.killTerminal?.(c)??{}}case sr.elicitation_create:{if(!r.unstable_createElicitation)throw fn.methodNotFound(s);let c=kA.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 sr.session_update:{let c=wA.parse(a);return r.sessionUpdate(c)}case sr.elicitation_complete:{if(!r.unstable_completeElicitation)return;let c=lA.parse(a);return r.unstable_completeElicitation(c)}default:if(r.extNotification)return r.extNotification(s,a);throw fn.methodNotFound(s)}};this.connection=new RA(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,xi)}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,xi)}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,xi)}setSessionConfigOption(e){return this.connection.sendRequest(Ne.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Ne.authenticate,e,xi)}unstable_listProviders(e){return this.connection.sendRequest(Ne.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Ne.providers_set,e,xi)}unstable_disableProvider(e){return this.connection.sendRequest(Ne.providers_disable,e,xi)}logout(e){return this.connection.sendRequest(Ne.logout,e,xi)}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,xi)}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}},RA=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 oF(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?oF(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 Cle=1,Ele=2e4,iF=3e4,Mle=3e5,vr={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 Nd=class extends Error{retryable=!1;authMethods;constructor(e,n){super(e),this.name="AcpAuthRequiredError",this.authMethods=n}};function Od(t,e){if(t instanceof Nd)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 Nd(`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 Nd(s,e)}return null}function Dle(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 Ri=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=rF(_le.toWeb(e.stdin),Ile.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new yg(()=>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:Cle,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),Ele,"initialize").catch(i=>{throw Od(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),iF,"session/new").catch(i=>{throw Od(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=Mle){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 Od(a)??Dle(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),iF,"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 vr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case vr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case vr.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 vr.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 vr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case vr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case vr.AVAILABLE_COMMANDS_UPDATE:case vr.CURRENT_MODE_UPDATE:case vr.CONFIG_OPTION_UPDATE:case vr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case vr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as $le}from"node:child_process";import{readFile as Nle,writeFile as Ole}from"node:fs/promises";import{isAbsolute as sF,normalize as jle,relative as Lle,resolve as Ule,sep as Fle}from"node:path";function Hle(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 TA(t){let e=new Map,n=0,r=i=>{let s=sF(i)?jle(i):Ule(t.cwd,i),a=Lle(t.cwd,s);if(a===".."||a.startsWith(`..${Fle}`)||sF(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:Hle(i)}},async readTextFile(i){return{content:await Nle(r(i.path),"utf8")}},async writeTextFile(i){return await Ole(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=$le(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 jd=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 Ble,execFile as qle,execFileSync as aF,execSync as kF}from"node:child_process";import{existsSync as Ii,mkdirSync as wF,readFileSync as mc,readdirSync as SF,writeFileSync as xF}from"node:fs";import{homedir as DA,platform as Wle,tmpdir as Gle}from"node:os";import{dirname as Ld,join as vt}from"node:path";import{promisify as RF}from"node:util";function Ti(){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 Pi(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function PA(t){let e=t.trim().split(/\s+/)[0];return e==="npm"||e==="npm.cmd"}var zle=/^(?:pip3?|pipx|uv|uvx|python3?|curl|wget|brew|sh|bash)\b/;function AA(t){return zle.test(t.trim())}function IA(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var cF=RF(qle),TF=RF(Ble),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"}},Kle=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],lF={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 Ao(t){let e=Ls[t];if(e)return lF[t]?{...e,...lF[t]}:e}function Ud(){return Kle.map(t=>{let e=Ao(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Io=Wle()==="win32",PF=5*6e4,Vle=2e4,Ai,uc=new Map,_A=vt(process.env.QLOGICAGENT_HOME||vt(DA(),".qlogicagent"),"agent-update-cache.json"),dF=!1;function AF(){if(!dF){dF=!0;try{let t=JSON.parse(mc(_A,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!uc.has(e)&&uc.set(e,n)}catch{}}}var bg=null;function Jle(){bg||(bg=setTimeout(()=>{bg=null;try{let t={};for(let[e,n]of uc)t[e]=n;wF(Ld(_A),{recursive:!0}),xF(_A,JSON.stringify(t),"utf8")}catch{}},1e3),bg.unref?.())}function CA(t){try{let e=Io?`where ${t}`:`which ${t}`;return kF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function EA(t){try{let e=Io?`where ${t}`:`which ${t}`,{stdout:n}=await TF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function IF(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 Zle(){if(!Io)return null;let t=[process.env.COPILOT_CACHE_HOME?vt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?vt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?vt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,vt(DA(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=SF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(IF);for(let r of n){let o=vt(e,r,"npm-loader.js");if(Ii(o)&&$F(o))return o}}catch{}return null}function Xle(t){return t.id==="copilot"?Zle()??CA(t.cliCommand):CA(t.cliCommand)}async function Yle(){if(!Io)return null;let t=[process.env.COPILOT_CACHE_HOME?vt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?vt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?vt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,vt(DA(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=SF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(IF);for(let r of n){let o=vt(e,r,"npm-loader.js");if(Ii(o)&&await NF(o))return o}}catch{}return null}async function Qle(t){return t.id==="copilot"?await Yle()??await EA(t.cliCommand):EA(t.cliCommand)}function ede(t,e){let n=Ti();return n?aF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:Pi(n)}).trim():aF(Io?"cmd.exe":"npm",Io?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"]}).trim()}async function _F(t,e){let n=Ti();if(n){let{stdout:o}=await cF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:Pi(n)});return o.trim()}let{stdout:r}=await cF(Io?"cmd.exe":"npm",Io?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function tde(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 xg(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 tde(o)}}return null}function Fd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function nde(t,e){let n=i=>{let s=Fd(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 CF(t,e){return!t||!e?!1:nde(t,e)>0}function rde(){if(Ai!==void 0)return Ai;try{Ai=ede(["root","-g"],3e3)||null}catch{Ai=null}return Ai}async function ode(){if(Ai===void 0)try{Ai=await _F(["root","-g"],3e3)||null}catch{Ai=null}}function Rg(t){if(!t)return null;let e=rde();if(!e)return null;let n=vt(e,...t.split("/"),"package.json");try{let r=JSON.parse(mc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function uF(t){let e=xg(t?.npm);return Rg(e)}function EF(t,e){return Rg(xg(t.install?.npm))??Fd(e)??e??void 0}async function ide(t,e){if(!t)return null;AF();let n=e?`${t}\0${e}`:t,r=uc.get(n);if(r){let i=r.version?PF:Vle;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 _F(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Fd(s)}catch{o=null}return uc.set(n,{timestamp:Date.now(),version:o}),Jle(),o}async function MF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=xg(i.install?.npm),c=Rg(a)??Fd(s)??s??void 0;if(!a||!c)return null;let l=await ide(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:CF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function DF(t,e){AF();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=xg(i.install?.npm),c=Rg(a)??Fd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=uc.get(l);d?.version&&Date.now()-d.timestamp<PF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:CF(d.version,c)})}return{updates:n,stale:r}}function $F(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=kF(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 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}`,{stdout:o}=await TF(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 sde(t,e){if(!Io)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=OF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=ade(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function OF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ii(r))continue;let o;try{o=mc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=vt(Ld(e),s);if(Ii(a))return a}return null}function ade(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ii(r))continue;let o;try{o=mc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=vt(Ld(e),s);if(Ii(a))return a}return null}function pF(t){let e=OF(t);if(!e)return null;let n=Ld(e);for(let r=0;r<6;r+=1){let o=vt(n,"package.json");try{if(Ii(o)){let s=JSON.parse(mc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=Ld(n);if(i===n)break;n=i}return null}var mF=6e4;function cde(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 jF=new Set(["codex","qwen","opencode"]),kg=new Set(["qwen","opencode"]),wg=new Set(["gemini"]),MA=new Set(["glm"]),fF={claude:"anthropic",codex:"openai"};function lde(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function dde(t){let e=vt(Gle(),"qlogicagent-codex-model-catalog");wF(e,{recursive:!0});let n=vt(e,`${lde(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(!Ii(n)||mc(n,"utf8")!==r)&&xF(n,r,"utf8"),n}function $A(t){return t.id!=="claude"}function Sg(t,e){return e==="account"&&!$A(t)?"auto":e}function LF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&$A(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||kg.has(t.id)||wg.has(t.id)||MA.has(t.id))&&e.push("managed"),e}function NA(t,e,n){let r=Sg(t,e);return!!(r==="account"||r==="auto"&&$A(t)&&n?.hasSubscription?.(t.id)===!0)}var UF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},ude={glm:"ACP_GLM_AVAILABLE_MODELS"};function vg(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=UF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=ude[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function gF(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 hF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function yF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...hF]:hF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function bF(t){return!!t.apiKeyEnvVar||kg.has(t.id)||wg.has(t.id)}function vF(t,e,n="auto"){let r={};if(!t)return r;let o=Sg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=fF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||wg.has(t.id)||MA.has(t.id)?vg(t,e,r):kg.has(t.id)&&gF(t,e,r),r;if(NA(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=fF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:vg(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:kg.has(t.id)?gF(t,e,r):(wg.has(t.id)||MA.has(t.id))&&vg(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&jF.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 pde(t,e,n){if(!t||!NA(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),jF.has(t.id)&&r.push("OPENAI_MODEL"),r}function mde(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(NA(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=${dde(s)}`]:e}var pc=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<mF)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<mF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await ode();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=Xle(e),r=n?$F(n)??pF(n)??uF(Ao(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await Qle(e),r=n?await NF(n)??pF(n)??uF(Ao(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,CA(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await EA(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=Ao(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}:sde(n.cliPath,s),c=o?.authPreference??"auto",l=vF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:mde(r,a.acpArgs,l,this.keySources,c),p=r?pde(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:cde(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=Ao(e)??Ls[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Sg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&bF(r)?yF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Ao(e)??Ls[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Sg(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(!bF(n)||yF(vF(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 FF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=UF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var Hd="https://registry.npmmirror.com",fc="https://pypi.tuna.tsinghua.edu.cn/simple",OA="https://registry.npmmirror.com/-/binary";function HF(){return{npm_config_registry:Hd,PIP_INDEX_URL:fc,UV_DEFAULT_INDEX:fc,UV_INDEX_URL:fc,UV_PYTHON_INSTALL_MIRROR:`${OA}/python-build-standalone`,NODEJS_ORG_MIRROR:`${OA}/node`,npm_config_disturl:`${OA}/node`}}var jA=Object.keys(HF());import{readFileSync as xde}from"node:fs";import{randomUUID as Rde}from"node:crypto";de();Ta();import{readdirSync as fde,readFileSync as gde,statSync as LA,writeFileSync as hde}from"node:fs";import{join as zd}from"node:path";var yde=["auto-skill-","test-skill-"],bde=".skills_prompt_snapshot.json";function vde(t){return yde.some(e=>t.startsWith(e))}function kde(t){let e=t.replace(/\r\n/g,`
682
+ `,c=t.getWriter();try{await c.write(n.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function xi(t){return t??{}}function oF(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var yg=class{connection;constructor(e,n){let r=e(this),o=async(s,a)=>{switch(s){case sr.fs_write_text_file:{let c=xA.parse(a);return await r.writeTextFile?.(c)??{}}case sr.fs_read_text_file:{let c=fA.parse(a);return r.readTextFile?.(c)}case sr.session_request_permission:{let c=vA.parse(a);return r.requestPermission(c)}case sr.terminal_create:{let c=pA.parse(a);return r.createTerminal?.(c)}case sr.terminal_output:{let c=hA.parse(a);return r.terminalOutput?.(c)}case sr.terminal_release:{let c=gA.parse(a);return await r.releaseTerminal?.(c)??{}}case sr.terminal_wait_for_exit:{let c=SA.parse(a);return r.waitForTerminalExit?.(c)}case sr.terminal_kill:{let c=mA.parse(a);return await r.killTerminal?.(c)??{}}case sr.elicitation_create:{if(!r.unstable_createElicitation)throw fn.methodNotFound(s);let c=kA.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 sr.session_update:{let c=wA.parse(a);return r.sessionUpdate(c)}case sr.elicitation_complete:{if(!r.unstable_completeElicitation)return;let c=lA.parse(a);return r.unstable_completeElicitation(c)}default:if(r.extNotification)return r.extNotification(s,a);throw fn.methodNotFound(s)}};this.connection=new RA(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,xi)}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,xi)}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,xi)}setSessionConfigOption(e){return this.connection.sendRequest(Ne.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Ne.authenticate,e,xi)}unstable_listProviders(e){return this.connection.sendRequest(Ne.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Ne.providers_set,e,xi)}unstable_disableProvider(e){return this.connection.sendRequest(Ne.providers_disable,e,xi)}logout(e){return this.connection.sendRequest(Ne.logout,e,xi)}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,xi)}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}},RA=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 oF(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?oF(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 Cle=1,Ele=2e4,iF=3e4,Mle=3e5,vr={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 Nd=class extends Error{retryable=!1;authMethods;constructor(e,n){super(e),this.name="AcpAuthRequiredError",this.authMethods=n}};function Od(t,e){if(t instanceof Nd)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 Nd(`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 Nd(s,e)}return null}function Dle(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 Ri=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=rF(_le.toWeb(e.stdin),Ile.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new yg(()=>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:Cle,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),Ele,"initialize").catch(i=>{throw Od(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),iF,"session/new").catch(i=>{throw Od(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=Mle){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 Od(a)??Dle(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),iF,"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 vr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case vr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case vr.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 vr.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 vr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case vr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case vr.AVAILABLE_COMMANDS_UPDATE:case vr.CURRENT_MODE_UPDATE:case vr.CONFIG_OPTION_UPDATE:case vr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case vr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as $le}from"node:child_process";import{readFile as Nle,writeFile as Ole}from"node:fs/promises";import{isAbsolute as sF,normalize as jle,relative as Lle,resolve as Ule,sep as Fle}from"node:path";function Hle(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 TA(t){let e=new Map,n=0,r=i=>{let s=sF(i)?jle(i):Ule(t.cwd,i),a=Lle(t.cwd,s);if(a===".."||a.startsWith(`..${Fle}`)||sF(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:Hle(i)}},async readTextFile(i){return{content:await Nle(r(i.path),"utf8")}},async writeTextFile(i){return await Ole(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=$le(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 jd=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 Ble,execFile as qle,execFileSync as aF,execSync as kF}from"node:child_process";import{existsSync as Ii,mkdirSync as wF,readFileSync as mc,readdirSync as SF,writeFileSync as xF}from"node:fs";import{homedir as DA,platform as Wle,tmpdir as Gle}from"node:os";import{dirname as Ld,join as vt}from"node:path";import{promisify as RF}from"node:util";function Ti(){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 Pi(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function PA(t){let e=t.trim().split(/\s+/)[0];return e==="npm"||e==="npm.cmd"}var zle=/^(?:pip3?|pipx|uv|uvx|python3?|curl|wget|brew|sh|bash)\b/;function AA(t){return zle.test(t.trim())}function IA(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var cF=RF(qle),TF=RF(Ble),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"}},Kle=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],lF={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 Ao(t){let e=Ls[t];if(e)return lF[t]?{...e,...lF[t]}:e}function Ud(){return Kle.map(t=>{let e=Ao(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Io=Wle()==="win32",PF=5*6e4,Vle=2e4,Ai,uc=new Map,_A=vt(process.env.QLOGICAGENT_HOME||vt(DA(),".qlogicagent"),"agent-update-cache.json"),dF=!1;function AF(){if(!dF){dF=!0;try{let t=JSON.parse(mc(_A,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!uc.has(e)&&uc.set(e,n)}catch{}}}var bg=null;function Jle(){bg||(bg=setTimeout(()=>{bg=null;try{let t={};for(let[e,n]of uc)t[e]=n;wF(Ld(_A),{recursive:!0}),xF(_A,JSON.stringify(t),"utf8")}catch{}},1e3),bg.unref?.())}function CA(t){try{let e=Io?`where ${t}`:`which ${t}`;return kF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function EA(t){try{let e=Io?`where ${t}`:`which ${t}`,{stdout:n}=await TF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function IF(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 Zle(){if(!Io)return null;let t=[process.env.COPILOT_CACHE_HOME?vt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?vt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?vt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,vt(DA(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=SF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(IF);for(let r of n){let o=vt(e,r,"npm-loader.js");if(Ii(o)&&$F(o))return o}}catch{}return null}function Xle(t){return t.id==="copilot"?Zle()??CA(t.cliCommand):CA(t.cliCommand)}async function Yle(){if(!Io)return null;let t=[process.env.COPILOT_CACHE_HOME?vt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?vt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?vt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,vt(DA(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=SF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(IF);for(let r of n){let o=vt(e,r,"npm-loader.js");if(Ii(o)&&await NF(o))return o}}catch{}return null}async function Qle(t){return t.id==="copilot"?await Yle()??await EA(t.cliCommand):EA(t.cliCommand)}function ede(t,e){let n=Ti();return n?aF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:Pi(n)}).trim():aF(Io?"cmd.exe":"npm",Io?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"]}).trim()}async function _F(t,e){let n=Ti();if(n){let{stdout:o}=await cF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:Pi(n)});return o.trim()}let{stdout:r}=await cF(Io?"cmd.exe":"npm",Io?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function tde(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 xg(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 tde(o)}}return null}function Fd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function nde(t,e){let n=i=>{let s=Fd(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 CF(t,e){return!t||!e?!1:nde(t,e)>0}function rde(){if(Ai!==void 0)return Ai;try{Ai=ede(["root","-g"],3e3)||null}catch{Ai=null}return Ai}async function ode(){if(Ai===void 0)try{Ai=await _F(["root","-g"],3e3)||null}catch{Ai=null}}function Rg(t){if(!t)return null;let e=rde();if(!e)return null;let n=vt(e,...t.split("/"),"package.json");try{let r=JSON.parse(mc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function uF(t){let e=xg(t?.npm);return Rg(e)}function EF(t,e){return Rg(xg(t.install?.npm))??Fd(e)??e??void 0}async function ide(t,e){if(!t)return null;AF();let n=e?`${t}\0${e}`:t,r=uc.get(n);if(r){let i=r.version?PF:Vle;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 _F(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Fd(s)}catch{o=null}return uc.set(n,{timestamp:Date.now(),version:o}),Jle(),o}async function MF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=xg(i.install?.npm),c=Rg(a)??Fd(s)??s??void 0;if(!a||!c)return null;let l=await ide(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:CF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function DF(t,e){AF();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=xg(i.install?.npm),c=Rg(a)??Fd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=uc.get(l);d?.version&&Date.now()-d.timestamp<PF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:CF(d.version,c)})}return{updates:n,stale:r}}function $F(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=kF(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 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}`,{stdout:o}=await TF(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 sde(t,e){if(!Io)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=OF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=ade(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function OF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ii(r))continue;let o;try{o=mc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=vt(Ld(e),s);if(Ii(a))return a}return null}function ade(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ii(r))continue;let o;try{o=mc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=vt(Ld(e),s);if(Ii(a))return a}return null}function pF(t){let e=OF(t);if(!e)return null;let n=Ld(e);for(let r=0;r<6;r+=1){let o=vt(n,"package.json");try{if(Ii(o)){let s=JSON.parse(mc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=Ld(n);if(i===n)break;n=i}return null}var mF=6e4;function cde(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 jF=new Set(["codex","qwen","opencode"]),kg=new Set(["qwen","opencode"]),wg=new Set(["gemini"]),MA=new Set(["glm"]),fF={claude:"anthropic",codex:"openai"};function lde(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function dde(t){let e=vt(Gle(),"qlogicagent-codex-model-catalog");wF(e,{recursive:!0});let n=vt(e,`${lde(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(!Ii(n)||mc(n,"utf8")!==r)&&xF(n,r,"utf8"),n}function $A(t){return t.id!=="claude"}function Sg(t,e){return e==="account"&&!$A(t)?"auto":e}function LF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&$A(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||kg.has(t.id)||wg.has(t.id)||MA.has(t.id))&&e.push("managed"),e}function NA(t,e,n){let r=Sg(t,e);return!!(r==="account"||r==="auto"&&$A(t)&&n?.hasSubscription?.(t.id)===!0)}var UF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},ude={glm:"ACP_GLM_AVAILABLE_MODELS"};function vg(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=UF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=ude[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function gF(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 hF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function yF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...hF]:hF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function bF(t){return!!t.apiKeyEnvVar||kg.has(t.id)||wg.has(t.id)}function vF(t,e,n="auto"){let r={};if(!t)return r;let o=Sg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=fF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||wg.has(t.id)||MA.has(t.id)?vg(t,e,r):kg.has(t.id)&&gF(t,e,r),r;if(NA(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=fF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:vg(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:kg.has(t.id)?gF(t,e,r):(wg.has(t.id)||MA.has(t.id))&&vg(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&jF.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 pde(t,e,n){if(!t||!NA(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),jF.has(t.id)&&r.push("OPENAI_MODEL"),r}function mde(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(NA(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=${dde(s)}`]:e}var pc=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<mF)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<mF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await ode();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=Xle(e),r=n?$F(n)??pF(n)??uF(Ao(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await Qle(e),r=n?await NF(n)??pF(n)??uF(Ao(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,CA(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await EA(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=Ao(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}:sde(n.cliPath,s),c=o?.authPreference??"auto",l=vF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:mde(r,a.acpArgs,l,this.keySources,c),p=r?pde(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:cde(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=Ao(e)??Ls[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Sg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&bF(r)?yF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Ao(e)??Ls[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Sg(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(!bF(n)||yF(vF(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 FF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=UF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var Hd="https://registry.npmmirror.com",fc="https://pypi.tuna.tsinghua.edu.cn/simple",OA="https://registry.npmmirror.com/-/binary";function HF(){return{npm_config_registry:Hd,PIP_INDEX_URL:fc,UV_DEFAULT_INDEX:fc,UV_INDEX_URL:fc,UV_PYTHON_INSTALL_MIRROR:`${OA}/python-build-standalone`,NODEJS_ORG_MIRROR:`${OA}/node`,npm_config_disturl:`${OA}/node`}}var jA=Object.keys(HF());import{readFileSync as xde}from"node:fs";import{randomUUID as Rde}from"node:crypto";de();Ta();import{readdirSync as fde,readFileSync as gde,statSync as LA,writeFileSync as hde}from"node:fs";import{join as zd}from"node:path";var yde=["auto-skill-","test-skill-"],bde=".skills_prompt_snapshot.json";function vde(t){return yde.some(e=>t.startsWith(e))}function kde(t){let e=t.replace(/\r\n/g,`
683
683
  `),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:zF(s?.[1]),environments:zF(a?.[1])}}function Bd(t,e){let n=_n(),r=G0(),o=t?K0(t):new Set,i=[],s;try{s=fde(n,{withFileTypes:!0})}catch{s=[]}for(let a of s){if(!a.isDirectory()||a.name.startsWith("."))continue;let c=zd(n,a.name),l=zd(c,"SKILL.md"),d;try{if(!LA(l).isFile())continue;d=gde(l,"utf8")}catch{continue}let p=r.has(a.name),m=o.has(a.name),f=kde(d),g=!wde(f,e);i.push({name:a.name,filePath:l,baseDir:c,globallyDisabled:p,projectDisabled:m,active:!p&&!m&&!g,systemGenerated:vde(a.name),description:f.description,version:f.version,category:f.category,author:f.author,requiredTools:f.requiredTools,environments:f.environments})}return Sde(n,i),i}function _o(t,e){return Bd(t,e).filter(n=>n.active)}function Ln(t){let e=_n(),n=zd(e,t),r=zd(n,"SKILL.md");try{if(LA(r).isFile())return{baseDir:n,filePath:r}}catch{}return null}function zF(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 wde(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 Sde(t,e){try{let r={version:1,entries:e.map(o=>{let i=LA(o.filePath);return{name:o.name,size:i.size,mtimeMs:i.mtimeMs,description:o.description,version:o.version,requiredTools:o.requiredTools,environments:o.environments}})};hde(zd(t,bde),JSON.stringify(r,null,2),"utf8")}catch{}}var Tde="astraclaw_capabilities",_i=[Tde,"astraclaw"];function Tg(t){let e=_o(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(`
684
684
  `)}function BF(t){let e=Tg(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(`
685
685
  `)}async function Pg(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:_o(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform}).map(Pde)}};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:xde(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:Ide(n.function.name),name:_de(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=Ade(t.args.args),o=`astraclaw_mcp_${Rde().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 Pde(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function Ade(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Ide(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function _de(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import{existsSync as Ig,mkdirSync as _g,readFileSync as qd,writeFileSync as Cg}from"node:fs";import{homedir as Cde}from"node:os";import{dirname as Eg,join as Us}from"node:path";de();var Ede={qwen:[".qwen","settings.json"],gemini:[".gemini","settings.json"]},Ag="# BEGIN ASTRACLAW MANAGED MCP",HA="# END ASTRACLAW MANAGED MCP",qF=" # BEGIN ASTRACLAW MANAGED MCP",WF=" # END ASTRACLAW MANAGED MCP";function GF(t){let e=t.agentId.trim().toLowerCase(),n=t.homeDir||Cde(),r=Mde(t),o=Ede[e];if(o){let i=Us(n,...o);return Nde({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 jde({agentId:e,configPath:i,server:r})}if(e==="kimi"){let i=Us(n,".kimi","mcp.json");return Ode({agentId:e,configPath:i,server:r})}if(e==="hermes"){let i=Us(Dde(n),"config.yaml");return Lde({agentId:e,configPath:i,server:r})}return{agentId:e,status:"unsupported",reason:`No native MCP config adapter for agent "${e}"`}}function Mde(t){return{command:t.nodePath||process.execPath,args:[t.serverScriptPath],env:$de({ASTRACLAW_PROJECT_ROOT:t.projectRoot,ASTRACLAW_MANAGED:"1",ASTRACLAW_MCP_CONFIG_PATH:Ml(),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 Dde(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 $de(t){return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"&&e[1].length>0))}function Nde(t){let e=KF(t.configPath),n={...e,mcpServers:{...zA(e.mcpServers)?e.mcpServers:{}}},r=n.mcpServers;for(let s of _i)r[s]=t.server;let o=`${JSON.stringify(n,null,2)}
@@ -714,10 +714,10 @@ ${n}
714
714
  `;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=BA(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 Ri,h=new jd,y=TA({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=Ri.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&&Mg({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}
715
715
  `)}),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(_<hc){let $=JF*2**_;this.slog("warn",e.memberId,"crash",`crashed again (code=${T}), restart ${_+1}/${hc}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${T}), restarting`,retriesLeft:hc-_-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 _i)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=Tg({projectRoot:e.cwd,mcpAvailable:S}),C=[e.systemPrompt,D].filter(Boolean).join(`
716
716
 
717
- `);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 Ei}from"node:child_process";var XF=/[|&;><$`(){}]/;function YF(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=XF.test(i);if(!(s&&n)&&!(i.startsWith("brew ")&&!r))return{command:i,shell:s}}return null}function QF(t,e){if(e!=="cn")return t;let n=t.trim();return/^npm\b/.test(n)&&!/(?:^|\s)--registry(?:\s|=)/.test(n)?`${n} --registry ${Hd}`:/^uv\b/.test(n)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(n)?`${n} --default-index ${fc}`:/^(?:pipx|pip3?|python -m pip)\b/.test(n)&&!/(?:^|\s)--index-url(?:\s|=)/.test(n)?`${n} --index-url ${fc}`:n}function ZF(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 uue=(t,e)=>{let n=Ti();if(n&&PA(t)){let i=t.trim().split(/\s+/).slice(1);return Ei(n.nodeExe,[n.npmCli,...i],{env:Pi(n),stdio:["ignore","pipe","pipe"],windowsHide:!0})}let r=AA(t)?IA():void 0;if(e||process.platform==="win32")return Ei(t,{shell:!0,...r?{env:r}:{},stdio:["ignore","pipe","pipe"]});let o=t.split(/\s+/).filter(Boolean);return Ei(o[0],o.slice(1),{...r?{env:r}:{},stdio:["ignore","pipe","pipe"]})};async function eH(t,e,n={}){let r=n.platform??process.platform,o=n.spawnImpl??uue,i=YF(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=QF(i.command,n.mirror);e({type:"state",state:"installing"});let a=await ZF(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 ZF(c,XF.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 tH(t,e=process.platform){try{return e==="win32"?Ei("cmd.exe",["/c","start","","cmd","/k",t],{detached:!0,stdio:"ignore",windowsHide:!1}).unref():e==="darwin"?Ei("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(t)}`,"-e",'tell application "Terminal" to activate'],{detached:!0,stdio:"ignore"}).unref():Ei("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 nH(t,e={}){let n=e.platform??process.platform,r=YF(t,n);if(!r)return{ok:!1,error:`No install command available for ${n}`};let o=QF(r.command,e.mirror);try{let i=Ti(),s;if(i&&PA(o)){let a=o.trim().split(/\s+/).slice(1);s=Ei(i.nodeExe,[i.npmCli,...a],{env:Pi(i),detached:!0,stdio:"ignore",windowsHide:!0})}else{let a=AA(o)?IA():void 0;s=Ei(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 kt=new Map,pue=10*6e4,mue=6e4,fue=6,Dg=null;function $g(t,e,n){return`${t}\0${e}\0${n??"default"}`}function Wd(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function rH(t){let e=kt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){kt.delete(t),Wd(e);return}return e}}function oH(t,e){let n=kt.get(t);n&&n!==e&&(kt.delete(t),Wd(n)),kt.set(t,e),gue(),yue()}function iH(t,e){let n=kt.get(t);if(!n)return;if(!n.manager.isAlive(n.memberId)){kt.delete(t),Wd(n);return}kt.delete(t);let r=kt.get(e);return r&&r!==n&&(kt.delete(e),Wd(r)),kt.set(e,n),n.lastUsed=Date.now(),n}var Ng="__warm__";function yc(t){let e=kt.get(t);e&&(kt.delete(t),Wd(e))}function Gd(t){let e=`${t}\0`,n=0,r=0;for(let[o,i]of[...kt.entries()])o.startsWith(e)&&(i.holder.current?(i.pendingRecredential=!0,r+=1):(yc(o),n+=1));return{evicted:n,deferred:r}}function sH(t){kt.get(t)?.pendingRecredential&&yc(t)}function gue(){for(;kt.size>fue;){let t=null,e=Number.POSITIVE_INFINITY;for(let[n,r]of kt)r.holder.current||r.lastUsed<e&&(e=r.lastUsed,t=n);if(!t)break;yc(t)}}function hue(t){for(let[e,n]of[...kt.entries()])n.holder.current||t-n.lastUsed>pue&&yc(e)}function yue(){Dg||(Dg=setInterval(()=>hue(Date.now()),mue),typeof Dg.unref=="function"&&Dg.unref())}import{randomUUID as bue}from"node:crypto";var bc=new Map;function vue(t,e){let n=bc.get(t);return n&&(clearTimeout(n.timer),n.resolve(null),bc.delete(t)),new Promise(r=>{let o=setTimeout(()=>{bc.delete(t),r(null)},e);typeof o.unref=="function"&&o.unref(),bc.set(t,{resolve:r,timer:o})})}function aH(t,e){let n=bc.get(t);return n?(clearTimeout(n.timer),bc.delete(t),n.resolve(e),!0):!1}function kue(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}function wue(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 WA(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)WA(n,e);return e}for(let n of Object.values(t))WA(n,e);return e}function Sue(t){let e=WA(t).join(`
717
+ `);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 Ei}from"node:child_process";var XF=/[|&;><$`(){}]/;function YF(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=XF.test(i);if(!(s&&n)&&!(i.startsWith("brew ")&&!r))return{command:i,shell:s}}return null}function QF(t,e){if(e!=="cn")return t;let n=t.trim();return/^npm\b/.test(n)&&!/(?:^|\s)--registry(?:\s|=)/.test(n)?`${n} --registry ${Hd}`:/^uv\b/.test(n)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(n)?`${n} --default-index ${fc}`:/^(?:pipx|pip3?|python -m pip)\b/.test(n)&&!/(?:^|\s)--index-url(?:\s|=)/.test(n)?`${n} --index-url ${fc}`:n}function ZF(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 uue=(t,e)=>{let n=Ti();if(n&&PA(t)){let i=t.trim().split(/\s+/).slice(1);return Ei(n.nodeExe,[n.npmCli,...i],{env:Pi(n),stdio:["ignore","pipe","pipe"],windowsHide:!0})}let r=AA(t)?IA():void 0;if(e||process.platform==="win32")return Ei(t,{shell:!0,...r?{env:r}:{},stdio:["ignore","pipe","pipe"],windowsHide:!0});let o=t.split(/\s+/).filter(Boolean);return Ei(o[0],o.slice(1),{...r?{env:r}:{},stdio:["ignore","pipe","pipe"]})};async function eH(t,e,n={}){let r=n.platform??process.platform,o=n.spawnImpl??uue,i=YF(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=QF(i.command,n.mirror);e({type:"state",state:"installing"});let a=await ZF(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 ZF(c,XF.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 tH(t,e=process.platform){try{return e==="win32"?Ei("cmd.exe",["/c","start","","cmd","/k",t],{detached:!0,stdio:"ignore",windowsHide:!1}).unref():e==="darwin"?Ei("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(t)}`,"-e",'tell application "Terminal" to activate'],{detached:!0,stdio:"ignore"}).unref():Ei("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 nH(t,e={}){let n=e.platform??process.platform,r=YF(t,n);if(!r)return{ok:!1,error:`No install command available for ${n}`};let o=QF(r.command,e.mirror);try{let i=Ti(),s;if(i&&PA(o)){let a=o.trim().split(/\s+/).slice(1);s=Ei(i.nodeExe,[i.npmCli,...a],{env:Pi(i),detached:!0,stdio:"ignore",windowsHide:!0})}else{let a=AA(o)?IA():void 0;s=Ei(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 kt=new Map,pue=10*6e4,mue=6e4,fue=6,Dg=null;function $g(t,e,n){return`${t}\0${e}\0${n??"default"}`}function Wd(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function rH(t){let e=kt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){kt.delete(t),Wd(e);return}return e}}function oH(t,e){let n=kt.get(t);n&&n!==e&&(kt.delete(t),Wd(n)),kt.set(t,e),gue(),yue()}function iH(t,e){let n=kt.get(t);if(!n)return;if(!n.manager.isAlive(n.memberId)){kt.delete(t),Wd(n);return}kt.delete(t);let r=kt.get(e);return r&&r!==n&&(kt.delete(e),Wd(r)),kt.set(e,n),n.lastUsed=Date.now(),n}var Ng="__warm__";function yc(t){let e=kt.get(t);e&&(kt.delete(t),Wd(e))}function Gd(t){let e=`${t}\0`,n=0,r=0;for(let[o,i]of[...kt.entries()])o.startsWith(e)&&(i.holder.current?(i.pendingRecredential=!0,r+=1):(yc(o),n+=1));return{evicted:n,deferred:r}}function sH(t){kt.get(t)?.pendingRecredential&&yc(t)}function gue(){for(;kt.size>fue;){let t=null,e=Number.POSITIVE_INFINITY;for(let[n,r]of kt)r.holder.current||r.lastUsed<e&&(e=r.lastUsed,t=n);if(!t)break;yc(t)}}function hue(t){for(let[e,n]of[...kt.entries()])n.holder.current||t-n.lastUsed>pue&&yc(e)}function yue(){Dg||(Dg=setInterval(()=>hue(Date.now()),mue),typeof Dg.unref=="function"&&Dg.unref())}import{randomUUID as bue}from"node:crypto";var bc=new Map;function vue(t,e){let n=bc.get(t);return n&&(clearTimeout(n.timer),n.resolve(null),bc.delete(t)),new Promise(r=>{let o=setTimeout(()=>{bc.delete(t),r(null)},e);typeof o.unref=="function"&&o.unref(),bc.set(t,{resolve:r,timer:o})})}function aH(t,e){let n=bc.get(t);return n?(clearTimeout(n.timer),bc.delete(t),n.resolve(e),!0):!1}function kue(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}function wue(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 WA(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)WA(n,e);return e}for(let n of Object.values(t))WA(n,e);return e}function Sue(t){let e=WA(t).join(`
718
718
  `);return/astraclaw/i.test(e)&&/\b(?:skills_list|skill_view|mcp_connectors_list|mcp_tool_call)\b/.test(e)}async function cH(t,e){let n=e.turnContext(),r=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:bue(),i=Array.isArray(t.options)?t.options:[];if(Sue(t))return{optionId:wue(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:kue(r.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await vue(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 Rue(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function Tue(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 Pue(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:Rue(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:Tue(s)}})}function dH(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function uH(t){return t instanceof Error?t.message:String(t)}async function Aue(t){let e=dH(t.error);if(!t.sessionId||!e)return;let n=uH(t.error);await fr(t.sessionId,{role:"user",content:t.prompt},t.projectRoot,t.turnId),await fr(t.sessionId,{role:"assistant",content:n,blocks:[{type:"auth_prompt",agentId:t.agentId,message:n,authMethods:e}]},t.projectRoot,t.turnId);let r=Vt(t.sessionId,t.projectRoot),o=await Aa(t.sessionId,t.projectRoot);await yt(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...r?.title?{}:{title:Fl(t.prompt,"External agent login required")},...t.lockSessionOwner===!1||r?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function pH(t){let e=t.params,n=typeof e?.approvalId=="string"?e.approvalId:"",r=typeof e?.optionId=="string"?e.optionId:"",o=n&&r?aH(n,r):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function mH(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 fH(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 gH(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=Ud().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:LF(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:EF(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 GA=new Set;async function hH(t){try{let e=t.params,r=(typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR)==="cn"?Hd:void 0,o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData());let i=new Map(this.acpDetector.list().map(l=>[l.id,l])),s=Ud().map(l=>({id:l.id,entry:l,detectedVersion:i.get(l.id)?.version})),{updates:a,stale:c}=DF(s,r);if(t.id!==void 0&&this.sendResponse(t.id,{updates:a,refreshing:c}),c){let l=r??"";GA.has(l)||(GA.add(l),MF(s,r).catch(()=>{}).finally(()=>GA.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 yH(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=Ao(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=nH(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 eH(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 bH(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=Ao(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=tH(o);t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error,command:o})}async function vH(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 kH(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}=Gd(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 wH(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 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();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 Iue(t){let e=lH.homedir();if(t==="codex"){let n=process.env.CODEX_HOME?.trim()||vc.join(e,".codex");return[vc.join(n,"auth.json")]}return[]}async function xH(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 Iue(n))try{kc.existsSync(o)&&(kc.rmSync(o,{force:!0}),r=!0)}catch{}Gd(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 RH(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 TH(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 PH(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 AH(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 IH(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 _H(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=vc.join(_e(),"agent-logs"),r=vc.join(n,`${e.agentId}.stderr.log`),o="";try{o=kc.readFileSync(r,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
719
719
  `).slice(-e.tail).join(`
720
- `)),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 CH(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 EH(t,e,n,r,o,i){let s=$g(e,r,o),a=rH(s);if(a)return a;if(o!==Ng){let f=iH($g(e,r,Ng),s);if(f)return f}let c=`chat-${e}-${xue().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Kr({onNotification:(f,g,h)=>{Pue({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 Pg({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>cH(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:vc.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 oH(s,m),m}async function MH(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 EH(this,n,o,i,Ng),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 DH(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=$g(n,a,l),h=await EH(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 Aue({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),yc(g),S}finally{h.holder.current=null,sH(g)}let b=y.deltas.join("")||(typeof v?.content=="string"?v.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){fr(l,{role:"user",content:r},a,d),b&&fr(l,{role:"assistant",content:b},a,d);let S=Vt(l,a);yt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:Fl(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=dH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:uH(e),...n?{data:{authMethods:n}}:{}})}}}hm();function _ue(t){let e=Mue(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=$ue(r.topK),s=await jg(e,Og(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(wc(s)&&Array.isArray(s.matches)?s.matches:[]).map(Nue).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 jg(e,Og(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=OH(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 jg(e,Og(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(wc(i)&&Array.isArray(i.versions)?i.versions:[]).map(Oue).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 jg(e,Og(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=jue(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Sc(t=si()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=Cue(t);return _ue({baseUrl:Eue(t),token:e,clientVersion:n})}function Cue(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.16.10"}function Eue(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Og(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 Mue(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function jg(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 Due(i)}`);return i.json().catch(()=>null)}async function Due(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function wc(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function $ue(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 Nue(t){if(!wc(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=$H(t.sourceTier),n=NH(t.trustStage),r=Lg(t.resourceRiskTier),o=Lg(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:KA(t.title,80),summary:KA(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=>KA(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function KA(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function Oue(t){return!wc(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 jue(t){if(!wc(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 Lue=new Set(["R0","R1","R2","R3"]),Uue=new Set(["official","community"]),Fue=new Set(["quarantine","trial","trusted"]),Hue=new Set(["pending","approved","rejected"]);function Lg(t){return typeof t=="string"&&Lue.has(t)?t:null}function $H(t){return typeof t=="string"&&Uue.has(t)?t:null}function NH(t){return typeof t=="string"&&Fue.has(t)?t:null}function zue(t){return typeof t=="string"&&Hue.has(t)?t:null}function OH(t){if(!wc(t))return null;let e=$H(t.sourceTier),n=NH(t.trustStage),r=zue(t.reviewStatus),o=Lg(t.resourceRiskTier),i=Lg(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(OH);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}}de();var VA={enabled:!0},Bue=new Set(["R2","R3"]);function jH(t,e=VA){return Bue.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 que,verify as Wue}from"node:crypto";function Gue(t){return`id=${t.id}
720
+ `)),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 CH(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 EH(t,e,n,r,o,i){let s=$g(e,r,o),a=rH(s);if(a)return a;if(o!==Ng){let f=iH($g(e,r,Ng),s);if(f)return f}let c=`chat-${e}-${xue().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Kr({onNotification:(f,g,h)=>{Pue({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 Pg({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>cH(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:vc.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 oH(s,m),m}async function MH(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 EH(this,n,o,i,Ng),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 DH(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=$g(n,a,l),h=await EH(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 Aue({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),yc(g),S}finally{h.holder.current=null,sH(g)}let b=y.deltas.join("")||(typeof v?.content=="string"?v.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){fr(l,{role:"user",content:r},a,d),b&&fr(l,{role:"assistant",content:b},a,d);let S=Vt(l,a);yt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:Fl(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=dH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:uH(e),...n?{data:{authMethods:n}}:{}})}}}hm();function _ue(t){let e=Mue(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=$ue(r.topK),s=await jg(e,Og(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(wc(s)&&Array.isArray(s.matches)?s.matches:[]).map(Nue).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 jg(e,Og(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=OH(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 jg(e,Og(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(wc(i)&&Array.isArray(i.versions)?i.versions:[]).map(Oue).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 jg(e,Og(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=jue(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Sc(t=si()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=Cue(t);return _ue({baseUrl:Eue(t),token:e,clientVersion:n})}function Cue(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.17.1"}function Eue(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Og(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 Mue(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function jg(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 Due(i)}`);return i.json().catch(()=>null)}async function Due(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function wc(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function $ue(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 Nue(t){if(!wc(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=$H(t.sourceTier),n=NH(t.trustStage),r=Lg(t.resourceRiskTier),o=Lg(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:KA(t.title,80),summary:KA(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=>KA(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function KA(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function Oue(t){return!wc(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 jue(t){if(!wc(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 Lue=new Set(["R0","R1","R2","R3"]),Uue=new Set(["official","community"]),Fue=new Set(["quarantine","trial","trusted"]),Hue=new Set(["pending","approved","rejected"]);function Lg(t){return typeof t=="string"&&Lue.has(t)?t:null}function $H(t){return typeof t=="string"&&Uue.has(t)?t:null}function NH(t){return typeof t=="string"&&Fue.has(t)?t:null}function zue(t){return typeof t=="string"&&Hue.has(t)?t:null}function OH(t){if(!wc(t))return null;let e=$H(t.sourceTier),n=NH(t.trustStage),r=zue(t.reviewStatus),o=Lg(t.resourceRiskTier),i=Lg(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(OH);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}}de();var VA={enabled:!0},Bue=new Set(["R2","R3"]);function jH(t,e=VA){return Bue.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 que,verify as Wue}from"node:crypto";function Gue(t){return`id=${t.id}
721
721
  version=${t.version}
722
722
  checksum=${t.checksum}
723
723
  sizeBytes=${t.sizeBytes}`}function Kue(t){return t.includes("\\n")?t.replace(/\\n/g,`