qlogicagent 2.17.7 → 2.17.8

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
@@ -683,7 +683,7 @@ ${e}
683
683
  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 xi(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:nc(e,"input",t.processors),output:nc(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Yt(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Yt(r.element,n);if(r.type==="set")return Yt(r.valueType,n);if(r.type==="lazy")return Yt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Yt(r.innerType,n);if(r.type==="intersection")return Yt(r.left,n)||Yt(r.right,n);if(r.type==="record"||r.type==="map")return Yt(r.keyType,n)||Yt(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Yt(r.in,n)||Yt(r.out,n);if(r.type==="object"){for(let o in r.shape)if(Yt(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(Yt(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(Yt(o,n))return!0;return!!(r.rest&&Yt(r.rest,n))}return!1}var hT=(t,e={})=>n=>{let r=wi({...n,processors:e});return Pe(t,r),Si(r,t),xi(r,t)},nc=(t,e,n={})=>r=>{let{libraryOptions:o,target:i}=r??{},s=wi({...o??{},target:i,io:e,processors:n});return Pe(t,s),Si(s,t),xi(s,t)};var use={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yT=(t,e,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:l}=t._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=use[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}))])}},vT=(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)},bT=(t,e,n,r)=>{n.type="boolean"},kT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},wT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},ST=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},xT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},RT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},TT=(t,e,n,r)=>{n.not={}},AT=(t,e,n,r)=>{},PT=(t,e,n,r)=>{},IT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},_T=(t,e,n,r)=>{let o=t._zod.def,i=id(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},CT=(t,e,n,r)=>{let o=t._zod.def,i=[];for(let s of o.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];n.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},ET=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},MT=(t,e,n,r)=>{let o=n,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},DT=(t,e,n,r)=>{let o=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=t._zod.bag;s!==void 0&&(i.minLength=s),a!==void 0&&(i.maxLength=a),c?c.length===1?(i.contentMediaType=c[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(o,i)},$T=(t,e,n,r)=>{n.type="boolean"},NT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},OT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},jT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},LT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},UT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},FT=(t,e,n,r)=>{let o=n,i=t._zod.def,{minimum:s,maximum:a}=t._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=Pe(i.element,e,{...r,path:[...r.path,"items"]})},HT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="object",o.properties={};let s=i.shape;for(let l in s)o.properties[l]=Pe(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=Pe(i.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Uf=(t,e,n,r)=>{let o=t._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>Pe(a,e,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=s:n.anyOf=s},zT=(t,e,n,r)=>{let o=t._zod.def,i=Pe(o.left,e,{...r,path:[...r.path,"allOf",0]}),s=Pe(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=l=>"allOf"in l&&Object.keys(l).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c},BT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,f)=>Pe(m,e,{...r,path:[...r.path,s,f]})),l=i.rest?Pe(i.rest,e,{...r,path:[...r.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null;e.target==="draft-2020-12"?(o.prefixItems=c,l&&(o.items=l)):e.target==="openapi-3.0"?(o.items={anyOf:c},l&&o.items.anyOf.push(l),o.minItems=c.length,l||(o.maxItems=c.length)):(o.items=c,l&&(o.additionalItems=l));let{minimum:d,maximum:p}=t._zod.bag;typeof d=="number"&&(o.minItems=d),typeof p=="number"&&(o.maxItems=p)},qT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=Pe(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=Pe(i.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Pe(i.valueType,e,{...r,path:[...r.path,"additionalProperties"]});let l=s._zod.values;if(l){let d=[...l].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(o.required=d)}},WT=(t,e,n,r)=>{let o=t._zod.def,i=Pe(o.innerType,e,r),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},GT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},KT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},VT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},JT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},ZT=(t,e,n,r)=>{let o=t._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?o.out:o.in:o.out;Pe(s,e,r);let a=e.seen.get(t);a.ref=s},XT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,n.readOnly=!0},YT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},Ff=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},QT=(t,e,n,r)=>{let o=t._zod.innerType;Pe(o,e,r);let i=e.seen.get(t);i.ref=o},Lf={string:yT,number:vT,boolean:bT,bigint:kT,symbol:wT,null:ST,undefined:xT,void:RT,never:TT,any:AT,unknown:PT,date:IT,enum:_T,literal:CT,nan:ET,template_literal:MT,file:DT,success:$T,custom:NT,function:OT,transform:jT,map:LT,set:UT,array:FT,object:HT,union:Uf,intersection:zT,tuple:BT,record:qT,nullable:WT,nonoptional:GT,default:KT,prefault:VT,catch:JT,pipe:ZT,readonly:XT,promise:YT,optional:Ff,lazy:QT};function Hf(t,e){if("_idmap"in t){let r=t,o=wi({...e,processors:Lf}),i={};for(let c of r._idmap.entries()){let[l,d]=c;Pe(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;Si(o,d),s[l]=xi(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=wi({...e,processors:Lf});return Pe(t,n),Si(n,t),xi(n,t)}var zf=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=wi({processors:Lf,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 Pe(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)),Si(this.ctx,e);let r=xi(this.ctx,e),{"~standard":o,...i}=r;return i}};var Bj={};var xd={};sn(xd,{ZodAny:()=>xA,ZodArray:()=>PA,ZodBase64:()=>lg,ZodBase64URL:()=>dg,ZodBigInt:()=>dc,ZodBigIntFormat:()=>mg,ZodBoolean:()=>lc,ZodCIDRv4:()=>ag,ZodCIDRv6:()=>cg,ZodCUID:()=>eg,ZodCUID2:()=>tg,ZodCatch:()=>JA,ZodCodec:()=>Nd,ZodCustom:()=>Od,ZodCustomStringFormat:()=>ac,ZodDate:()=>Cd,ZodDefault:()=>BA,ZodDiscriminatedUnion:()=>_A,ZodE164:()=>ug,ZodEmail:()=>Xf,ZodEmoji:()=>Yf,ZodEnum:()=>ic,ZodExactOptional:()=>FA,ZodFile:()=>LA,ZodFunction:()=>iP,ZodGUID:()=>Td,ZodIPv4:()=>ig,ZodIPv6:()=>sg,ZodIntersection:()=>CA,ZodJWT:()=>pg,ZodKSUID:()=>og,ZodLazy:()=>nP,ZodLiteral:()=>jA,ZodMAC:()=>hA,ZodMap:()=>NA,ZodNaN:()=>XA,ZodNanoID:()=>Qf,ZodNever:()=>TA,ZodNonOptional:()=>bg,ZodNull:()=>wA,ZodNullable:()=>zA,ZodNumber:()=>cc,ZodNumberFormat:()=>Fs,ZodObject:()=>Md,ZodOptional:()=>vg,ZodPipe:()=>$d,ZodPrefault:()=>WA,ZodPreprocess:()=>YA,ZodPromise:()=>oP,ZodReadonly:()=>QA,ZodRecord:()=>oc,ZodSet:()=>OA,ZodString:()=>sc,ZodStringFormat:()=>$e,ZodSuccess:()=>VA,ZodSymbol:()=>bA,ZodTemplateLiteral:()=>tP,ZodTransform:()=>UA,ZodTuple:()=>MA,ZodType:()=>ue,ZodULID:()=>ng,ZodURL:()=>_d,ZodUUID:()=>Kr,ZodUndefined:()=>kA,ZodUnion:()=>Dd,ZodUnknown:()=>RA,ZodVoid:()=>AA,ZodXID:()=>rg,ZodXor:()=>IA,_ZodString:()=>Zf,_default:()=>qA,_function:()=>YL,any:()=>_L,array:()=>Ed,base64:()=>pL,base64url:()=>mL,bigint:()=>RL,boolean:()=>vA,catch:()=>ZA,check:()=>QL,cidrv4:()=>dL,cidrv6:()=>uL,codec:()=>VL,cuid:()=>nL,cuid2:()=>rL,custom:()=>eU,date:()=>EL,describe:()=>tU,discriminatedUnion:()=>jL,e164:()=>fL,email:()=>Gj,emoji:()=>eL,enum:()=>hg,exactOptional:()=>HA,file:()=>qL,float32:()=>kL,float64:()=>wL,function:()=>YL,guid:()=>Kj,hash:()=>bL,hex:()=>vL,hostname:()=>yL,httpUrl:()=>Qj,instanceof:()=>rU,int:()=>Vf,int32:()=>SL,int64:()=>TL,intersection:()=>EA,invertCodec:()=>JL,ipv4:()=>aL,ipv6:()=>lL,json:()=>iU,jwt:()=>gL,keyof:()=>ML,ksuid:()=>sL,lazy:()=>rP,literal:()=>BL,looseObject:()=>NL,looseRecord:()=>UL,mac:()=>cL,map:()=>FL,meta:()=>nU,nan:()=>KL,nanoid:()=>tL,nativeEnum:()=>zL,never:()=>fg,nonoptional:()=>KA,null:()=>SA,nullable:()=>Pd,nullish:()=>WL,number:()=>yA,object:()=>DL,optional:()=>Ad,partialRecord:()=>LL,pipe:()=>Jf,prefault:()=>GA,preprocess:()=>sU,promise:()=>XL,readonly:()=>eP,record:()=>$A,refine:()=>sP,set:()=>HL,strictObject:()=>$L,string:()=>Rd,stringFormat:()=>hL,stringbool:()=>oU,success:()=>GL,superRefine:()=>aP,symbol:()=>PL,templateLiteral:()=>ZL,transform:()=>yg,tuple:()=>DA,uint32:()=>xL,uint64:()=>AL,ulid:()=>oL,undefined:()=>IL,union:()=>gg,unknown:()=>Us,url:()=>Yj,uuid:()=>Vj,uuidv4:()=>Jj,uuidv6:()=>Zj,uuidv7:()=>Xj,void:()=>CL,xid:()=>iL,xor:()=>OL});var Bf={};sn(Bf,{endsWith:()=>Va,gt:()=>Wr,gte:()=>Xt,includes:()=>Ga,length:()=>Ls,lowercase:()=>qa,lt:()=>qr,lte:()=>jn,maxLength:()=>js,maxSize:()=>ki,mime:()=>Ja,minLength:()=>_o,minSize:()=>Gr,multipleOf:()=>bi,negative:()=>$f,nonnegative:()=>Of,nonpositive:()=>Nf,normalize:()=>Za,overwrite:()=>br,positive:()=>Df,property:()=>jf,regex:()=>Ba,size:()=>Os,slugify:()=>ec,startsWith:()=>Ka,toLowerCase:()=>Ya,toUpperCase:()=>Qa,trim:()=>Xa,uppercase:()=>Wa});var rc={};sn(rc,{ZodISODate:()=>Wf,ZodISODateTime:()=>qf,ZodISODuration:()=>Kf,ZodISOTime:()=>Gf,date:()=>tA,datetime:()=>eA,duration:()=>rA,time:()=>nA});var qf=I("ZodISODateTime",(t,e)=>{Ex.init(t,e),$e.init(t,e)});function eA(t){return NR(qf,t)}var Wf=I("ZodISODate",(t,e)=>{Mx.init(t,e),$e.init(t,e)});function tA(t){return OR(Wf,t)}var Gf=I("ZodISOTime",(t,e)=>{Dx.init(t,e),$e.init(t,e)});function nA(t){return jR(Gf,t)}var Kf=I("ZodISODuration",(t,e)=>{$x.init(t,e),$e.init(t,e)});function rA(t){return LR(Kf,t)}var qj=(t,e)=>{dd.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>pd(t,n)},flatten:{value:n=>ud(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,$a,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,$a,2)}},isEmpty:{get(){return t.issues.length===0}}})},mse=I("ZodError",qj),mn=I("ZodError",qj,{Parent:Error});var oA=ja(mn),iA=La(mn),sA=Ua(mn),aA=Fa(mn),cA=Fm(mn),lA=Hm(mn),dA=zm(mn),uA=Bm(mn),pA=qm(mn),mA=Wm(mn),fA=Gm(mn),gA=Km(mn);var Wj=new WeakMap;function Id(t,e,n){let r=Object.getPrototypeOf(t),o=Wj.get(r);if(o||(o=new Set,Wj.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=I("ZodType",(t,e)=>(ie.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:nc(t,"input"),output:nc(t,"output")}}),t.toJSONSchema=hT(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>oA(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>sA(t,n,r),t.parseAsync=async(n,r)=>iA(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>aA(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>cA(t,n,r),t.decode=(n,r)=>lA(t,n,r),t.encodeAsync=async(n,r)=>dA(t,n,r),t.decodeAsync=async(n,r)=>uA(t,n,r),t.safeEncode=(n,r)=>pA(t,n,r),t.safeDecode=(n,r)=>mA(t,n,r),t.safeEncodeAsync=async(n,r)=>fA(t,n,r),t.safeDecodeAsync=async(n,r)=>gA(t,n,r),Id(t,"ZodType",{check(...n){let r=this.def;return this.clone(F.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(sP(n,r))},superRefine(n,r){return this.check(aP(n,r))},overwrite(n){return this.check(br(n))},optional(){return Ad(this)},exactOptional(){return HA(this)},nullable(){return Pd(this)},nullish(){return Ad(Pd(this))},nonoptional(n){return KA(this,n)},array(){return Ed(this)},or(n){return gg([this,n])},and(n){return EA(this,n)},transform(n){return Jf(this,yg(n))},default(n){return qA(this,n)},prefault(n){return GA(this,n)},catch(n){return ZA(this,n)},pipe(n){return Jf(this,n)},readonly(){return eP(this)},describe(n){let r=this.clone();return It.add(r,{description:n}),r},meta(...n){if(n.length===0)return It.get(this);let r=this.clone();return It.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 It.get(t)?.description},configurable:!0}),t)),Zf=I("_ZodString",(t,e)=>{Ns.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>yT(t,r,o,i);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,Id(t,"_ZodString",{regex(...r){return this.check(Ba(...r))},includes(...r){return this.check(Ga(...r))},startsWith(...r){return this.check(Ka(...r))},endsWith(...r){return this.check(Va(...r))},min(...r){return this.check(_o(...r))},max(...r){return this.check(js(...r))},length(...r){return this.check(Ls(...r))},nonempty(...r){return this.check(_o(1,...r))},lowercase(r){return this.check(qa(r))},uppercase(r){return this.check(Wa(r))},trim(){return this.check(Xa())},normalize(...r){return this.check(Za(...r))},toLowerCase(){return this.check(Ya())},toUpperCase(){return this.check(Qa())},slugify(){return this.check(ec())}})}),sc=I("ZodString",(t,e)=>{Ns.init(t,e),Zf.init(t,e),t.email=n=>t.check(mf(Xf,n)),t.url=n=>t.check(Sd(_d,n)),t.jwt=n=>t.check(Mf(pg,n)),t.emoji=n=>t.check(vf(Yf,n)),t.guid=n=>t.check(wd(Td,n)),t.uuid=n=>t.check(ff(Kr,n)),t.uuidv4=n=>t.check(gf(Kr,n)),t.uuidv6=n=>t.check(hf(Kr,n)),t.uuidv7=n=>t.check(yf(Kr,n)),t.nanoid=n=>t.check(bf(Qf,n)),t.guid=n=>t.check(wd(Td,n)),t.cuid=n=>t.check(kf(eg,n)),t.cuid2=n=>t.check(wf(tg,n)),t.ulid=n=>t.check(Sf(ng,n)),t.base64=n=>t.check(_f(lg,n)),t.base64url=n=>t.check(Cf(dg,n)),t.xid=n=>t.check(xf(rg,n)),t.ksuid=n=>t.check(Rf(og,n)),t.ipv4=n=>t.check(Tf(ig,n)),t.ipv6=n=>t.check(Af(sg,n)),t.cidrv4=n=>t.check(Pf(ag,n)),t.cidrv6=n=>t.check(If(cg,n)),t.e164=n=>t.check(Ef(ug,n)),t.datetime=n=>t.check(eA(n)),t.date=n=>t.check(tA(n)),t.time=n=>t.check(nA(n)),t.duration=n=>t.check(rA(n))});function Rd(t){return ER(sc,t)}var $e=I("ZodStringFormat",(t,e)=>{De.init(t,e),Zf.init(t,e)}),Xf=I("ZodEmail",(t,e)=>{Sx.init(t,e),$e.init(t,e)});function Gj(t){return mf(Xf,t)}var Td=I("ZodGUID",(t,e)=>{kx.init(t,e),$e.init(t,e)});function Kj(t){return wd(Td,t)}var Kr=I("ZodUUID",(t,e)=>{wx.init(t,e),$e.init(t,e)});function Vj(t){return ff(Kr,t)}function Jj(t){return gf(Kr,t)}function Zj(t){return hf(Kr,t)}function Xj(t){return yf(Kr,t)}var _d=I("ZodURL",(t,e)=>{xx.init(t,e),$e.init(t,e)});function Yj(t){return Sd(_d,t)}function Qj(t){return Sd(_d,{protocol:On.httpProtocol,hostname:On.domain,...F.normalizeParams(t)})}var Yf=I("ZodEmoji",(t,e)=>{Rx.init(t,e),$e.init(t,e)});function eL(t){return vf(Yf,t)}var Qf=I("ZodNanoID",(t,e)=>{Tx.init(t,e),$e.init(t,e)});function tL(t){return bf(Qf,t)}var eg=I("ZodCUID",(t,e)=>{Ax.init(t,e),$e.init(t,e)});function nL(t){return kf(eg,t)}var tg=I("ZodCUID2",(t,e)=>{Px.init(t,e),$e.init(t,e)});function rL(t){return wf(tg,t)}var ng=I("ZodULID",(t,e)=>{Ix.init(t,e),$e.init(t,e)});function oL(t){return Sf(ng,t)}var rg=I("ZodXID",(t,e)=>{_x.init(t,e),$e.init(t,e)});function iL(t){return xf(rg,t)}var og=I("ZodKSUID",(t,e)=>{Cx.init(t,e),$e.init(t,e)});function sL(t){return Rf(og,t)}var ig=I("ZodIPv4",(t,e)=>{Nx.init(t,e),$e.init(t,e)});function aL(t){return Tf(ig,t)}var hA=I("ZodMAC",(t,e)=>{jx.init(t,e),$e.init(t,e)});function cL(t){return DR(hA,t)}var sg=I("ZodIPv6",(t,e)=>{Ox.init(t,e),$e.init(t,e)});function lL(t){return Af(sg,t)}var ag=I("ZodCIDRv4",(t,e)=>{Lx.init(t,e),$e.init(t,e)});function dL(t){return Pf(ag,t)}var cg=I("ZodCIDRv6",(t,e)=>{Ux.init(t,e),$e.init(t,e)});function uL(t){return If(cg,t)}var lg=I("ZodBase64",(t,e)=>{Hx.init(t,e),$e.init(t,e)});function pL(t){return _f(lg,t)}var dg=I("ZodBase64URL",(t,e)=>{zx.init(t,e),$e.init(t,e)});function mL(t){return Cf(dg,t)}var ug=I("ZodE164",(t,e)=>{Bx.init(t,e),$e.init(t,e)});function fL(t){return Ef(ug,t)}var pg=I("ZodJWT",(t,e)=>{qx.init(t,e),$e.init(t,e)});function gL(t){return Mf(pg,t)}var ac=I("ZodCustomStringFormat",(t,e)=>{Wx.init(t,e),$e.init(t,e)});function hL(t,e,n={}){return tc(ac,t,e,n)}function yL(t){return tc(ac,"hostname",On.hostname,t)}function vL(t){return tc(ac,"hex",On.hex,t)}function bL(t,e){let n=e?.enc??"hex",r=`${t}_${n}`,o=On[r];if(!o)throw new Error(`Unrecognized hash format: ${r}`);return tc(ac,r,o,e)}var cc=I("ZodNumber",(t,e)=>{nf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>vT(t,r,o,i),Id(t,"ZodNumber",{gt(r,o){return this.check(Wr(r,o))},gte(r,o){return this.check(Xt(r,o))},min(r,o){return this.check(Xt(r,o))},lt(r,o){return this.check(qr(r,o))},lte(r,o){return this.check(jn(r,o))},max(r,o){return this.check(jn(r,o))},int(r){return this.check(Vf(r))},safe(r){return this.check(Vf(r))},positive(r){return this.check(Wr(0,r))},nonnegative(r){return this.check(Xt(0,r))},negative(r){return this.check(qr(0,r))},nonpositive(r){return this.check(jn(0,r))},multipleOf(r,o){return this.check(bi(r,o))},step(r,o){return this.check(bi(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 yA(t){return UR(cc,t)}var Fs=I("ZodNumberFormat",(t,e)=>{Gx.init(t,e),cc.init(t,e)});function Vf(t){return HR(Fs,t)}function kL(t){return zR(Fs,t)}function wL(t){return BR(Fs,t)}function SL(t){return qR(Fs,t)}function xL(t){return WR(Fs,t)}var lc=I("ZodBoolean",(t,e)=>{hd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>bT(t,n,r,o)});function vA(t){return GR(lc,t)}var dc=I("ZodBigInt",(t,e)=>{rf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>kT(t,r,o,i),t.gte=(r,o)=>t.check(Xt(r,o)),t.min=(r,o)=>t.check(Xt(r,o)),t.gt=(r,o)=>t.check(Wr(r,o)),t.gte=(r,o)=>t.check(Xt(r,o)),t.min=(r,o)=>t.check(Xt(r,o)),t.lt=(r,o)=>t.check(qr(r,o)),t.lte=(r,o)=>t.check(jn(r,o)),t.max=(r,o)=>t.check(jn(r,o)),t.positive=r=>t.check(Wr(BigInt(0),r)),t.negative=r=>t.check(qr(BigInt(0),r)),t.nonpositive=r=>t.check(jn(BigInt(0),r)),t.nonnegative=r=>t.check(Xt(BigInt(0),r)),t.multipleOf=(r,o)=>t.check(bi(r,o));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});function RL(t){return VR(dc,t)}var mg=I("ZodBigIntFormat",(t,e)=>{Kx.init(t,e),dc.init(t,e)});function TL(t){return ZR(mg,t)}function AL(t){return XR(mg,t)}var bA=I("ZodSymbol",(t,e)=>{Vx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wT(t,n,r,o)});function PL(t){return YR(bA,t)}var kA=I("ZodUndefined",(t,e)=>{Jx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>xT(t,n,r,o)});function IL(t){return QR(kA,t)}var wA=I("ZodNull",(t,e)=>{Zx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ST(t,n,r,o)});function SA(t){return eT(wA,t)}var xA=I("ZodAny",(t,e)=>{Xx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>AT(t,n,r,o)});function _L(){return tT(xA)}var RA=I("ZodUnknown",(t,e)=>{Yx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>PT(t,n,r,o)});function Us(){return nT(RA)}var TA=I("ZodNever",(t,e)=>{Qx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>TT(t,n,r,o)});function fg(t){return rT(TA,t)}var AA=I("ZodVoid",(t,e)=>{eR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>RT(t,n,r,o)});function CL(t){return oT(AA,t)}var Cd=I("ZodDate",(t,e)=>{tR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>IT(t,r,o,i),t.min=(r,o)=>t.check(Xt(r,o)),t.max=(r,o)=>t.check(jn(r,o));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});function EL(t){return iT(Cd,t)}var PA=I("ZodArray",(t,e)=>{nR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>FT(t,n,r,o),t.element=e.element,Id(t,"ZodArray",{min(n,r){return this.check(_o(n,r))},nonempty(n){return this.check(_o(1,n))},max(n,r){return this.check(js(n,r))},length(n,r){return this.check(Ls(n,r))},unwrap(){return this.element}})});function Ed(t,e){return cT(PA,t,e)}function ML(t){let e=t._zod.def.shape;return hg(Object.keys(e))}var Md=I("ZodObject",(t,e)=>{rR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>HT(t,n,r,o),F.defineLazy(t,"shape",()=>e.shape),Id(t,"ZodObject",{keyof(){return hg(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Us()})},loose(){return this.clone({...this._zod.def,catchall:Us()})},strict(){return this.clone({...this._zod.def,catchall:fg()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return F.extend(this,n)},safeExtend(n){return F.safeExtend(this,n)},merge(n){return F.merge(this,n)},pick(n){return F.pick(this,n)},omit(n){return F.omit(this,n)},partial(...n){return F.partial(vg,this,n[0])},required(...n){return F.required(bg,this,n[0])}})});function DL(t,e){let n={type:"object",shape:t??{},...F.normalizeParams(e)};return new Md(n)}function $L(t,e){return new Md({type:"object",shape:t,catchall:fg(),...F.normalizeParams(e)})}function NL(t,e){return new Md({type:"object",shape:t,catchall:Us(),...F.normalizeParams(e)})}var Dd=I("ZodUnion",(t,e)=>{yd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Uf(t,n,r,o),t.options=e.options});function gg(t,e){return new Dd({type:"union",options:t,...F.normalizeParams(e)})}var IA=I("ZodXor",(t,e)=>{Dd.init(t,e),oR.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Uf(t,n,r,o),t.options=e.options});function OL(t,e){return new IA({type:"union",options:t,inclusive:!1,...F.normalizeParams(e)})}var _A=I("ZodDiscriminatedUnion",(t,e)=>{Dd.init(t,e),iR.init(t,e)});function jL(t,e,n){return new _A({type:"union",options:e,discriminator:t,...F.normalizeParams(n)})}var CA=I("ZodIntersection",(t,e)=>{sR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>zT(t,n,r,o)});function EA(t,e){return new CA({type:"intersection",left:t,right:e})}var MA=I("ZodTuple",(t,e)=>{of.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>BT(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function DA(t,e,n){let r=e instanceof ie,o=r?n:e,i=r?e:null;return new MA({type:"tuple",items:t,rest:i,...F.normalizeParams(o)})}var oc=I("ZodRecord",(t,e)=>{aR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function $A(t,e,n){return!e||!e._zod?new oc({type:"record",keyType:Rd(),valueType:t,...F.normalizeParams(e)}):new oc({type:"record",keyType:t,valueType:e,...F.normalizeParams(n)})}function LL(t,e,n){let r=Jt(t);return r._zod.values=void 0,new oc({type:"record",keyType:r,valueType:e,...F.normalizeParams(n)})}function UL(t,e,n){return new oc({type:"record",keyType:t,valueType:e,mode:"loose",...F.normalizeParams(n)})}var NA=I("ZodMap",(t,e)=>{cR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>LT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...n)=>t.check(Gr(...n)),t.nonempty=n=>t.check(Gr(1,n)),t.max=(...n)=>t.check(ki(...n)),t.size=(...n)=>t.check(Os(...n))});function FL(t,e,n){return new NA({type:"map",keyType:t,valueType:e,...F.normalizeParams(n)})}var OA=I("ZodSet",(t,e)=>{lR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>UT(t,n,r,o),t.min=(...n)=>t.check(Gr(...n)),t.nonempty=n=>t.check(Gr(1,n)),t.max=(...n)=>t.check(ki(...n)),t.size=(...n)=>t.check(Os(...n))});function HL(t,e){return new OA({type:"set",valueType:t,...F.normalizeParams(e)})}var ic=I("ZodEnum",(t,e)=>{dR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>_T(t,r,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let i={};for(let s of r)if(n.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ic({...e,checks:[],...F.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 ic({...e,checks:[],...F.normalizeParams(o),entries:i})}});function hg(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new ic({type:"enum",entries:n,...F.normalizeParams(e)})}function zL(t,e){return new ic({type:"enum",entries:t,...F.normalizeParams(e)})}var jA=I("ZodLiteral",(t,e)=>{uR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>CT(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function BL(t,e){return new jA({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var LA=I("ZodFile",(t,e)=>{pR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>DT(t,n,r,o),t.min=(n,r)=>t.check(Gr(n,r)),t.max=(n,r)=>t.check(ki(n,r)),t.mime=(n,r)=>t.check(Ja(Array.isArray(n)?n:[n],r))});function qL(t){return lT(LA,t)}var UA=I("ZodTransform",(t,e)=>{mR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>jT(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new fi(t.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(F.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(F.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 yg(t){return new UA({type:"transform",transform:t})}var vg=I("ZodOptional",(t,e)=>{sf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ff(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Ad(t){return new vg({type:"optional",innerType:t})}var FA=I("ZodExactOptional",(t,e)=>{fR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ff(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function HA(t){return new FA({type:"optional",innerType:t})}var zA=I("ZodNullable",(t,e)=>{gR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>WT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Pd(t){return new zA({type:"nullable",innerType:t})}function WL(t){return Ad(Pd(t))}var BA=I("ZodDefault",(t,e)=>{hR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>KT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function qA(t,e){return new BA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var WA=I("ZodPrefault",(t,e)=>{yR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>VT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function GA(t,e){return new WA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var bg=I("ZodNonOptional",(t,e)=>{vR.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 KA(t,e){return new bg({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var VA=I("ZodSuccess",(t,e)=>{bR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>$T(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function GL(t){return new VA({type:"success",innerType:t})}var JA=I("ZodCatch",(t,e)=>{kR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>JT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function ZA(t,e){return new JA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var XA=I("ZodNaN",(t,e)=>{wR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ET(t,n,r,o)});function KL(t){return aT(XA,t)}var $d=I("ZodPipe",(t,e)=>{af.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ZT(t,n,r,o),t.in=e.in,t.out=e.out});function Jf(t,e){return new $d({type:"pipe",in:t,out:e})}var Nd=I("ZodCodec",(t,e)=>{$d.init(t,e),vd.init(t,e)});function VL(t,e,n){return new Nd({type:"pipe",in:t,out:e,transform:n.decode,reverseTransform:n.encode})}function JL(t){let e=t._zod.def;return new Nd({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var YA=I("ZodPreprocess",(t,e)=>{$d.init(t,e),SR.init(t,e)}),QA=I("ZodReadonly",(t,e)=>{xR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>XT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function eP(t){return new QA({type:"readonly",innerType:t})}var tP=I("ZodTemplateLiteral",(t,e)=>{RR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>MT(t,n,r,o)});function ZL(t,e){return new tP({type:"template_literal",parts:t,...F.normalizeParams(e)})}var nP=I("ZodLazy",(t,e)=>{PR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>QT(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function rP(t){return new nP({type:"lazy",getter:t})}var oP=I("ZodPromise",(t,e)=>{AR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>YT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function XL(t){return new oP({type:"promise",innerType:t})}var iP=I("ZodFunction",(t,e)=>{TR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>OT(t,n,r,o)});function YL(t){return new iP({type:"function",input:Array.isArray(t?.input)?DA(t?.input):t?.input??Ed(Us()),output:t?.output??Us()})}var Od=I("ZodCustom",(t,e)=>{IR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>NT(t,n,r,o)});function QL(t){let e=new Le({check:"custom"});return e._zod.check=t,e}function eU(t,e){return dT(Od,t??(()=>!0),e)}function sP(t,e={}){return uT(Od,t,e)}function aP(t,e){return pT(t,e)}var tU=mT,nU=fT;function rU(t,e={}){let n=new Od({type:"custom",check:"custom",fn:r=>r instanceof t,abort:!0,...F.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 oU=(...t)=>gT({Codec:Nd,Boolean:lc,String:sc},...t);function iU(t){let e=rP(()=>gg([Rd(t),yA(),vA(),SA(),Ed(e),$A(Rd(),e)]));return e}function sU(t,e){return new YA({type:"pipe",in:yg(t),out:e})}var gse={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 hse(t){Ye({customError:t})}function yse(){return Ye().customError}var cP;cP||(cP={});var G={...xd,...Bf,iso:rc},vse=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 bse(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 kse(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 aU(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=kse(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 aU(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=aU(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))vse.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 cU(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=bse(n,e?.defaultTarget),o=n.$defs||n.definitions||{},i={version:r,defs:o,refs:new Map,processing:new Set,rootSchema:n,registry:e?.registry??It};return Ft(n,i)}var lP={};sn(lP,{bigint:()=>Rse,boolean:()=>xse,date:()=>Tse,number:()=>Sse,string:()=>wse});function wse(t){return MR(sc,t)}function Sse(t){return FR(cc,t)}function xse(t){return KR(lc,t)}function Rse(t){return JR(dc,t)}function Tse(t){return sT(Cd,t)}Ye(cf());var Ne={authenticate:"authenticate",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_focus:"document/didFocus",document_did_open:"document/didOpen",document_did_save:"document/didSave",initialize:"initialize",logout:"logout",mcp_message:"mcp/message",nes_accept:"nes/accept",nes_close:"nes/close",nes_reject:"nes/reject",nes_start:"nes/start",nes_suggest:"nes/suggest",providers_disable:"providers/disable",providers_list:"providers/list",providers_set:"providers/set",session_cancel:"session/cancel",session_close:"session/close",session_delete:"session/delete",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode"},ar={elicitation_complete:"elicitation/complete",elicitation_create:"elicitation/create",fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",mcp_connect:"mcp/connect",mcp_disconnect:"mcp/disconnect",mcp_message:"mcp/message",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"};var lU=Symbol("skippedItem");function W(t,e){return t.catch(e)}function kr(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(lU)).transform(e=>e.filter(n=>n!==lU))}var Pse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminal:u.boolean().optional().default(!1)}),Ise=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)}),_se=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),name:u.string()}),Cse=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(Ise)}),Ese=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()}),Mse=u.union([Cse.and(u.object({type:u.literal("env_var")})),Ese.and(u.object({type:u.literal("terminal")})),_se]),dU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),methodId:u.string()}),Dse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),$se=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),blob:u.string(),mimeType:u.string().nullish(),uri:u.string()}),Nse=u.object({default:u.boolean().nullish(),description:u.string().nullish(),title:u.string().nullish()}),Ose=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),jse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Lse=u.object({amount:u.number(),currency:u.string()}),Use=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),Fse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Hse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),newText:u.string(),oldText:u.string().nullish(),path:u.string()}),uU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string()}),zse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Bse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),qse=u.union([u.string(),u.number(),u.number(),u.boolean(),u.array(u.string())]),Wse=u.object({content:u.record(u.string(),qse).nullish()}),Gse=u.intersection(u.union([Wse.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()})),Kse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),pU=u.string(),uP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),elicitationId:pU}),Vse=u.literal("object"),Jse=u.literal("string"),Zse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Xse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),form:W(Kse.nullish(),()=>{}),url:W(Zse.nullish(),()=>{})}),mU=u.object({const:u.string(),title:u.string()}),fU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),Yse=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"})]),gU=u.object({code:Yse,data:u.unknown().optional(),message:u.string()}),hU=u.unknown(),yU=u.unknown(),vU=u.unknown(),Qse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),readTextFile:u.boolean().optional().default(!1),writeTextFile:u.boolean().optional().default(!1)}),bU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),kU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),title:u.string().nullish(),version:u.string()}),eae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),tae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),wU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),SU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cursor:u.string().nullish(),cwd:u.string().nullish()}),pP=u.union([u.literal("anthropic"),u.literal("openai"),u.literal("azure"),u.literal("vertex"),u.literal("bedrock"),u.string()]),nae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),rae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),logout:W(nae.nullish(),()=>{})}),xU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),oae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),iae=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)}),kg=u.string(),sae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:kg}),aae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:kg}),RU=u.string(),cae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acpId:RU}),lae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:RU,name:u.string()}),dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(bU),name:u.string(),url:u.string()}),uae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(bU),name:u.string(),url:u.string()}),pae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()),command:u.string(),env:u.array(fU),name:u.string()}),wg=u.union([dae.and(u.object({type:u.literal("http")})),uae.and(u.object({type:u.literal("sse")})),lae.and(u.object({type:u.literal("acp")})),pae]),mae=u.string(),TU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:kg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),AU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:kg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),PU=u.unknown(),fae=u.union([u.literal("error"),u.literal("warning"),u.literal("information"),u.literal("hint")]),gae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),hae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),yae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),vae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),bae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),kae=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()}),wae=u.object({diff:u.string(),uri:u.string()}),Sae=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()}),xae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Rae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Tae=u.object({languageId:u.string(),text:u.string(),uri:u.string()}),Aae=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()}),Pae=u.union([u.literal("rejected"),u.literal("ignored"),u.literal("replaced"),u.literal("cancelled")]),Iae=u.object({excerpts:u.array(Sae),uri:u.string()}),_ae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Cae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Eae=u.object({name:u.string(),owner:u.string(),remoteUrl:u.string()}),Mae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),jump:W(xae.nullish(),()=>{}),rename:W(Cae.nullish(),()=>{}),searchAndReplace:W(Mae.nullish(),()=>{})}),$ae=u.object({id:u.string(),isRegex:u.boolean().nullish(),replace:u.string(),search:u.string(),uri:u.string()}),Nae=u.union([u.literal("automatic"),u.literal("diagnostic"),u.literal("manual")]),Oae=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()}),jae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(gae.nullish(),()=>{}),editHistory:W(kae.nullish(),()=>{}),openFiles:W(Rae.nullish(),()=>{}),recentFiles:W(Aae.nullish(),()=>{}),relatedSnippets:W(_ae.nullish(),()=>{}),userActions:W(Oae.nullish(),()=>{})}),IU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(wg)}),Lae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),_U=u.string(),Uae=u.union([u.literal("allow_once"),u.literal("allow_always"),u.literal("reject_once"),u.literal("reject_always")]),Fae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),kind:Uae,name:u.string(),optionId:_U}),Hae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),zae=u.union([u.literal("high"),u.literal("medium"),u.literal("low")]),Bae=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed")]),CU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),priority:zae,status:Bae}),qae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:kr(Ce(CU),()=>[])}),Sg=u.string(),Wae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:Sg,uri:u.string()}),Gae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:kr(Ce(CU),()=>[]),id:Sg}),Kae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),id:Sg}),Vae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:Sg}),Jae=u.union([Gae.and(u.object({type:u.literal("items")})),Wae.and(u.object({type:u.literal("file")})),Kae.and(u.object({type:u.literal("markdown")}))]),Zae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),plan:Jae}),Ri=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"})}),Xae=u.object({id:u.string(),position:Ri,uri:u.string()}),Yae=u.object({id:u.string(),newName:u.string(),position:Ri,uri:u.string()}),Qae=u.object({action:u.string(),position:Ri,timestampMs:u.number(),uri:u.string()}),EU=u.union([u.literal("utf-16"),u.literal("utf-32"),u.literal("utf-8")]),ece=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:Pse.optional().default({terminal:!1}),elicitation:W(Xse.nullish(),()=>{}),fs:Qse.optional().default({readTextFile:!1,writeTextFile:!1}),nes:W(Dae.nullish(),()=>{}),plan:W(Hae.nullish(),()=>{}),positionEncodings:W(Ce(EU).optional(),()=>[]),terminal:u.boolean().optional().default(!1)}),tce=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)}),MU=u.number().int().gte(0).lte(65535),DU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),clientCapabilities:ece.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:W(kU.nullish(),()=>{}),protocolVersion:MU}),nce=u.object({apiType:pP,baseUrl:u.string()}),rce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),current:nce.nullish(),id:u.string(),required:u.boolean(),supported:kr(Ce(pP),()=>[])}),oce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),providers:kr(Ce(rce),()=>[])}),ice=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),uc=u.object({end:Ri,start:Ri}),sce=u.object({message:u.string(),range:uc,severity:fae,uri:u.string()}),ace=u.object({languageId:u.string(),lastFocusedMs:W(u.number().nullish(),()=>{}),uri:u.string(),visibleRange:W(uc.nullish(),()=>{})}),cce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(Ce(sce).nullish(),()=>{}),editHistory:W(Ce(wae).nullish(),()=>{}),openFiles:W(Ce(ace).nullish(),()=>{}),recentFiles:W(Ce(Tae).nullish(),()=>{}),relatedSnippets:W(Ce(Iae).nullish(),()=>{}),userActions:W(Ce(Qae).nullish(),()=>{})}),lce=u.object({newText:u.string(),range:uc}),dce=u.object({cursorPosition:W(Ri.nullish(),()=>{}),edits:u.array(lce),id:u.string(),uri:u.string()}),uce=u.union([dce.and(u.object({kind:u.literal("edit")})),Xae.and(u.object({kind:u.literal("jump")})),Yae.and(u.object({kind:u.literal("rename")})),$ae.and(u.object({kind:u.literal("searchAndReplace")}))]),pce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string()}),mce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ti=u.union([u.number(),u.string()]).nullable(),Pze=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),requestId:Ti}),$U=u.object({requestId:Ti}),fce=u.enum(["assistant","user"]),jd=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audience:W(Ce(fce).nullish(),()=>{}),lastModified:u.string().nullish(),priority:u.number().nullish()}),gce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),data:u.string(),mimeType:u.string()}),hce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),data:u.string(),mimeType:u.string(),uri:u.string().nullish()}),yce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),description:u.string().nullish(),mimeType:u.string().nullish(),name:u.string(),size:u.number().nullish(),title:u.string().nullish(),uri:u.string()}),vce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),optionId:_U}),bce=u.union([u.object({outcome:u.literal("cancelled")}),vce.and(u.object({outcome:u.literal("selected")}))]),kce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),outcome:bce}),wce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Sce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xce=u.object({currentValue:u.boolean()}),Rce=u.string(),NU=u.string(),Tce=u.union([u.literal("mode"),u.literal("model"),u.literal("thought_level"),u.string()]),mP=u.string(),OU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),name:u.string(),value:mP}),Ace=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),group:Rce,name:u.string(),options:u.array(OU)}),Pce=u.union([u.array(OU),u.array(Ace)]),Ice=u.object({currentValue:mP,options:Pce}),pc=u.intersection(u.union([Ice.and(u.object({type:u.literal("select")})),xce.and(u.object({type:u.literal("boolean")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),category:W(Tce.nullish(),()=>{}),description:u.string().nullish(),id:NU,name:u.string()})),_ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:kr(Ce(pc),()=>[])}),Cce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ece=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xe=u.string(),jU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),sessionId:xe}),LU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),UU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),FU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),fP=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(fU).optional(),outputByteLimit:u.number().nullish(),sessionId:xe}),HU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),zU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,uri:u.string()}),BU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),position:Ri,sessionId:xe,uri:u.string(),version:u.number(),visibleRange:uc}),qU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),languageId:u.string(),sessionId:xe,text:u.string(),uri:u.string(),version:u.number()}),WU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,uri:u.string()}),GU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(wg).optional(),sessionId:xe}),gP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),KU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(wg),sessionId:xe}),hP=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:xe}),VU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),reason:W(Pae.nullish(),()=>{}),sessionId:xe}),yP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),JU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(wg).optional(),sessionId:xe}),Mce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),sessionId:xe,title:W(u.string().nullish(),()=>{}),updatedAt:W(u.string().nullish(),()=>{})}),Dce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),nextCursor:u.string().nullish(),sessions:kr(Ce(Mce),()=>[])}),$ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),title:u.string().nullish(),updatedAt:u.string().nullish()}),Nce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xg=u.string(),Oce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),currentModeId:xg}),jce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:xg,name:u.string()}),Rg=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableModes:kr(Ce(jce),()=>[]),currentModeId:xg}),Lce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(pc).nullish(),()=>{}),modes:W(Rg.nullish(),()=>{}),sessionId:xe}),Uce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(pc).nullish(),()=>{}),modes:W(Rg.nullish(),()=>{})}),Fce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(pc).nullish(),()=>{}),modes:W(Rg.nullish(),()=>{}),sessionId:xe}),Hce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(pc).nullish(),()=>{}),modes:W(Rg.nullish(),()=>{})}),zce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Bce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:W(wce.nullish(),()=>{}),close:W(Sce.nullish(),()=>{}),delete:W(Cce.nullish(),()=>{}),fork:W(Ece.nullish(),()=>{}),list:W(Nce.nullish(),()=>{}),resume:W(zce.nullish(),()=>{})}),ZU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),apiType:pP,baseUrl:u.string(),headers:u.record(u.string(),u.string()).optional(),id:u.string()}),qce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),XU=u.intersection(u.union([u.object({type:u.literal("boolean"),value:u.boolean()}),u.object({value:mP})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configId:NU,sessionId:xe})),Wce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:kr(Ce(pc),()=>[])}),YU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),modeId:xg,sessionId:xe}),Gce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Kce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),Vce=u.union([u.literal("end_turn"),u.literal("max_tokens"),u.literal("max_turn_requests"),u.literal("refusal"),u.literal("cancelled")]),Jce=u.union([u.literal("email"),u.literal("uri"),u.literal("date"),u.literal("date-time")]),Zce=u.object({default:u.string().nullish(),description:u.string().nullish(),enum:u.array(u.string()).nullish(),format:Jce.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(mU).nullish(),pattern:u.string().nullish(),title:u.string().nullish()}),QU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(cce.nullish(),()=>{}),position:Ri,selection:W(uc.nullish(),()=>{}),sessionId:xe,triggerKind:Nae,uri:u.string(),version:u.number()}),Xce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),suggestions:kr(Ce(uce),()=>[])}),Yce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),Qce=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()}),vP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),ele=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitStatus:Qce.nullish(),output:u.string(),truncated:u.boolean()}),tle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),text:u.string()}),nle=u.object({range:uc.nullish(),text:u.string()}),eF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),contentChanges:u.array(nle),sessionId:xe,uri:u.string(),version:u.number()}),Ize=u.object({method:u.string(),params:u.union([LU,qU,eF,zU,WU,BU,jU,VU,TU,hU]).nullish()}),rle=u.union([u.literal("full"),u.literal("incremental")]),ole=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),syncKind:rle}),ile=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),didChange:W(ole.nullish(),()=>{}),didClose:W(hae.nullish(),()=>{}),didFocus:W(yae.nullish(),()=>{}),didOpen:W(vae.nullish(),()=>{}),didSave:W(bae.nullish(),()=>{})}),sle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),document:W(ile.nullish(),()=>{})}),ale=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(jae.nullish(),()=>{}),events:W(sle.nullish(),()=>{})}),cle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:rae.optional().default({}),loadSession:u.boolean().optional().default(!1),mcpCapabilities:iae.optional().default({acp:!1,http:!1,sse:!1}),nes:W(ale.nullish(),()=>{}),positionEncoding:W(EU.nullish(),()=>{}),promptCapabilities:tce.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:W(ice.nullish(),()=>{}),sessionCapabilities:Bce.optional().default({})}),lle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),agentCapabilities:cle.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:W(kU.nullish(),()=>{}),authMethods:W(Ce(Mse).optional().default([]),()=>[]),protocolVersion:MU}),dle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),mimeType:u.string().nullish(),text:u.string(),uri:u.string()}),ule=u.union([dle,$se]),ple=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),resource:ule}),bP=u.union([tle.and(u.object({type:u.literal("text")})),hce.and(u.object({type:u.literal("image")})),gce.and(u.object({type:u.literal("audio")})),yce.and(u.object({type:u.literal("resource_link")})),ple.and(u.object({type:u.literal("resource")}))]),mle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:bP}),dP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:bP,messageId:mae.nullish()}),tF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),prompt:u.array(bP),sessionId:xe}),fle=u.object({anyOf:u.array(mU)}),nF=u.union([mle.and(u.object({type:u.literal("content")})),Hse.and(u.object({type:u.literal("diff")})),Yce.and(u.object({type:u.literal("terminal")}))]),kP=u.string(),rF=u.object({sessionId:xe,toolCallId:kP.nullish()}),gle=u.intersection(u.union([rF,$U]),u.object({elicitationId:pU,url:u.string().url()})),oF=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()}),iF=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed"),u.literal("failed")]),sF=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")]),hle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(nF).optional(),()=>[]),kind:sF.optional(),locations:W(Ce(oF).optional(),()=>[]),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:iF.optional(),title:u.string(),toolCallId:kP}),aF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(nF).nullish(),()=>{}),kind:W(sF.nullish(),()=>{}),locations:W(Ce(oF).nullish(),()=>{}),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:W(iF.nullish(),()=>{}),title:u.string().nullish(),toolCallId:kP}),wP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),options:u.array(Fae),sessionId:xe,toolCall:aF}),yle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),hint:u.string()}),vle=yle,ble=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string(),input:W(vle.nullish(),()=>{}),name:u.string()}),kle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableCommands:kr(Ce(ble),()=>[])}),wle=u.object({enum:u.array(u.string()),type:Jse}),Sle=u.union([wle,fle]),xle=u.object({default:u.array(u.string()).nullish(),description:u.string().nullish(),items:Sle,maxItems:u.number().nullish(),minItems:u.number().nullish(),title:u.string().nullish()}),Rle=u.union([Zce.and(u.object({type:u.literal("string")})),Lae.and(u.object({type:u.literal("number")})),eae.and(u.object({type:u.literal("integer")})),Nse.and(u.object({type:u.literal("boolean")})),xle.and(u.object({type:u.literal("array")}))]),Tle=u.object({description:u.string().nullish(),properties:u.record(u.string(),Rle).optional().default({}),required:u.array(u.string()).nullish(),title:u.string().nullish(),type:Vse.optional().default("object")}),Ale=u.intersection(u.union([rF,$U]),u.object({requestedSchema:Tle})),SP=u.intersection(u.union([Ale.and(u.object({mode:u.literal("form")})),gle.and(u.object({mode:u.literal("url")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),message:u.string()})),Ple=u.object({cachedReadTokens:u.number().nullish(),cachedWriteTokens:u.number().nullish(),inputTokens:u.number(),outputTokens:u.number(),thoughtTokens:u.number().nullish(),totalTokens:u.number()}),Ile=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),stopReason:Vce,usage:W(Ple.nullish(),()=>{})}),_ze=u.union([u.object({id:Ti,result:u.union([lle,Dse,oce,qce,zse,oae,Fce,Uce,Dce,Fse,Lce,Hce,jse,Gce,Wce,Ile,Kce,Xce,Ose,vU,PU])}),u.object({error:gU,id:Ti})]),_le=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cost:W(Lse.nullish(),()=>{}),size:u.number(),used:u.number()}),Cle=u.union([dP.and(u.object({sessionUpdate:u.literal("user_message_chunk")})),dP.and(u.object({sessionUpdate:u.literal("agent_message_chunk")})),dP.and(u.object({sessionUpdate:u.literal("agent_thought_chunk")})),hle.and(u.object({sessionUpdate:u.literal("tool_call")})),aF.and(u.object({sessionUpdate:u.literal("tool_call_update")})),qae.and(u.object({sessionUpdate:u.literal("plan")})),Zae.and(u.object({sessionUpdate:u.literal("plan_update")})),Vae.and(u.object({sessionUpdate:u.literal("plan_removed")})),kle.and(u.object({sessionUpdate:u.literal("available_commands_update")})),Oce.and(u.object({sessionUpdate:u.literal("current_mode_update")})),_ce.and(u.object({sessionUpdate:u.literal("config_option_update")})),$ce.and(u.object({sessionUpdate:u.literal("session_info_update")})),_le.and(u.object({sessionUpdate:u.literal("usage_update")}))]),xP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,update:Cle}),Cze=u.object({method:u.string(),params:u.union([xP,uP,TU,hU]).nullish()}),RP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),Ele=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()}),Mle=u.object({name:u.string(),uri:u.string()}),cF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),repository:W(Eae.nullish(),()=>{}),workspaceFolders:W(Ce(Mle).nullish(),()=>{}),workspaceUri:u.string().nullish()}),Eze=u.object({id:Ti,method:u.string(),params:u.union([DU,dU,wU,ZU,uU,xU,IU,KU,SU,HU,GU,JU,FU,YU,XU,tF,cF,QU,UU,AU,yU]).nullish()}),TP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),path:u.string(),sessionId:xe}),Mze=u.object({id:Ti,method:u.string(),params:u.union([TP,hP,wP,fP,vP,yP,RP,gP,SP,cae,AU,aae,yU]).nullish()}),Dle=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Dze=u.union([u.object({id:Ti,result:u.union([Dle,pce,kce,Use,ele,mce,Ele,tae,Gse,sae,Bse,vU,PU])}),u.object({error:gU,id:Ti})]);function lF(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(`
684
684
  `);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)+`
685
685
  `,c=t.getWriter();try{await c.write(n.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Ai(t){return t??{}}function dF(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var Tg=class{connection;constructor(e,n){let r=e(this),o=async(s,a)=>{switch(s){case ar.fs_write_text_file:{let c=TP.parse(a);return await r.writeTextFile?.(c)??{}}case ar.fs_read_text_file:{let c=hP.parse(a);return r.readTextFile?.(c)}case ar.session_request_permission:{let c=wP.parse(a);return r.requestPermission(c)}case ar.terminal_create:{let c=fP.parse(a);return r.createTerminal?.(c)}case ar.terminal_output:{let c=vP.parse(a);return r.terminalOutput?.(c)}case ar.terminal_release:{let c=yP.parse(a);return await r.releaseTerminal?.(c)??{}}case ar.terminal_wait_for_exit:{let c=RP.parse(a);return r.waitForTerminalExit?.(c)}case ar.terminal_kill:{let c=gP.parse(a);return await r.killTerminal?.(c)??{}}case ar.elicitation_create:{if(!r.unstable_createElicitation)throw fn.methodNotFound(s);let c=SP.parse(a);return r.unstable_createElicitation(c)}default:if(r.extMethod)return r.extMethod(s,a);throw fn.methodNotFound(s)}},i=async(s,a)=>{switch(s){case ar.session_update:{let c=xP.parse(a);return r.sessionUpdate(c)}case ar.elicitation_complete:{if(!r.unstable_completeElicitation)return;let c=uP.parse(a);return r.unstable_completeElicitation(c)}default:if(r.extNotification)return r.extNotification(s,a);throw fn.methodNotFound(s)}};this.connection=new AP(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,Ai)}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,Ai)}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,Ai)}setSessionConfigOption(e){return this.connection.sendRequest(Ne.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Ne.authenticate,e,Ai)}unstable_listProviders(e){return this.connection.sendRequest(Ne.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Ne.providers_set,e,Ai)}unstable_disableProvider(e){return this.connection.sendRequest(Ne.providers_disable,e,Ai)}logout(e){return this.connection.sendRequest(Ne.logout,e,Ai)}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,Ai)}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}},AP=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 dF(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?dF(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 jle=1,Lle=2e4,uF=3e4,Ule=3e5,wr={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",USAGE_UPDATE:"usage_update"};var Ld=class extends Error{retryable=!1;authMethods;constructor(e,n){super(e),this.name="AcpAuthRequiredError",this.authMethods=n}};function Ud(t,e){if(t instanceof Ld)return t;let n=t,r=Array.isArray(n?.data?.authMethods)?n.data.authMethods:[];if(n?.code===-32e3||r.length>0||/auth(?:entication|orization)?\s+required/i.test(n?.message??"")){let i=r[0],s=i?.description||(i?.name?`Use "${i.name}".`:"");return new Ld(`Authentication required.${s?` ${s}`:""}`,r)}if(e&&e.length>0&&Fle(n)){let i=e[0],s=n?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:n?.message||"Authentication required.");return new Ld(s,e)}return null}function Fle(t){let e=`${t?.message??""}
686
- ${t?.data?.details??""}`;return/\b(auth(?:entication|orization)?|login|log in|api key|apikey|token|credential|provider|configured|configuration|setup|sign in)\b/i.test(e)}function Hle(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 Pi=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=lF(Ole.toWeb(e.stdin),Nle.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new Tg(()=>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:jle,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),Lle,"initialize").catch(i=>{throw Ud(i)??i}),o=r?.agentCapabilities??{};return{protocolVersion:typeof r?.protocolVersion=="number"?r.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:r?.agentInfo,authMethods:r?.authMethods}}async createSession(e,n){let r={cwd:n.cwd,mcpServers:n.mcpServers??[]};n.additionalDirectories?.length&&(r.additionalDirectories=n.additionalDirectories),n.systemPrompt&&(r._meta={qlogicagent:{systemPrompt:n.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(r),uF,"session/new").catch(i=>{throw Ud(i)??i});if(typeof o?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:o.sessionId}}async sendPrompt(e,n,r,o=Ule){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:n,prompt:[{type:"text",text:r}]}),o,"session/prompt",()=>{i.cancel({sessionId:n}).catch(()=>{})}).catch(a=>{throw Ud(a)??Hle(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),uF,"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 wr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case wr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case wr.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 wr.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 wr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case wr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case wr.AVAILABLE_COMMANDS_UPDATE:case wr.CURRENT_MODE_UPDATE:case wr.CONFIG_OPTION_UPDATE:case wr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case wr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as zle}from"node:child_process";import{readFile as Ble,writeFile as qle}from"node:fs/promises";import{isAbsolute as pF,normalize as Wle,relative as Gle,resolve as Kle,sep as Vle}from"node:path";function Jle(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 PP(t){let e=new Map,n=0,r=i=>{let s=pF(i)?Wle(i):Kle(t.cwd,i),a=Gle(t.cwd,s);if(a===".."||a.startsWith(`..${Vle}`)||pF(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:Jle(i)}},async readTextFile(i){return{content:await Ble(r(i.path),"utf8")}},async writeTextFile(i){return await qle(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=zle(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"],windowsHide:!0}),g=`term-${++n}`,h={child:f,output:"",exitStatus:null,exit:new Promise(y=>{f.on("exit",(b,v)=>{let k={exitCode:b,signal:v};h.exitStatus=k,y(k)}),f.on("error",()=>{let b={exitCode:null,signal:null};h.exitStatus=b,y(b)})})};return f.stdout?.on("data",y=>{h.output+=y.toString()}),f.stderr?.on("data",y=>{h.output+=y.toString()}),e.set(g,h),{terminalId:g}},async terminalOutput(i){let s=e.get(o(i));return s?{output:s.output,truncated:!1,exitStatus:s.exitStatus}:{output:"",truncated:!1,exitStatus:null}},async waitForTerminalExit(i){let s=e.get(o(i));return s?s.exit:{exitCode:null,signal:null}},async releaseTerminal(i){let s=o(i),a=e.get(s);if(a&&a.child.exitCode===null&&a.child.signalCode===null)try{a.child.kill()}catch{}return e.delete(s),{}},async killTerminal(i){let s=e.get(o(i));if(s)try{s.child.kill("SIGKILL")}catch{}return{}},disposeAll(){for(let i of e.values())try{i.child.kill("SIGKILL")}catch{}e.clear()}}}var Fd=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{exec as Xle,execFile as Yle,execFileSync as mF,execSync as AF}from"node:child_process";import{existsSync as Ei,mkdirSync as PF,readFileSync as gc,readdirSync as IF,writeFileSync as _F}from"node:fs";import{homedir as NP,platform as Qle,tmpdir as ede}from"node:os";import{dirname as Hd,join as bt}from"node:path";import{promisify as CF}from"node:util";function Ii(){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 _i(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function IP(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 _P(t){return Zle.test(t.trim())}function CP(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var fF=CF(Yle),EF=CF(Xle),Hs={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"}},tde=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],gF={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 Eo(t){let e=Hs[t];if(e)return gF[t]?{...e,...gF[t]}:e}function zd(){return tde.map(t=>{let e=Eo(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Mo=Qle()==="win32",MF=5*6e4,nde=2e4,Ci,mc=new Map,EP=bt(process.env.QLOGICAGENT_HOME||bt(NP(),".qlogicagent"),"agent-update-cache.json"),hF=!1;function DF(){if(!hF){hF=!0;try{let t=JSON.parse(gc(EP,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!mc.has(e)&&mc.set(e,n)}catch{}}}var Ag=null;function rde(){Ag||(Ag=setTimeout(()=>{Ag=null;try{let t={};for(let[e,n]of mc)t[e]=n;PF(Hd(EP),{recursive:!0}),_F(EP,JSON.stringify(t),"utf8")}catch{}},1e3),Ag.unref?.())}function MP(t){try{let e=Mo?`where ${t}`:`which ${t}`;return AF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function DP(t){try{let e=Mo?`where ${t}`:`which ${t}`,{stdout:n}=await EF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function $F(t,e){let n=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r[i]!==o[i])return o[i]-r[i];return e.localeCompare(t)}function ode(){if(!Mo)return null;let t=[process.env.COPILOT_CACHE_HOME?bt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?bt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?bt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,bt(NP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=IF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort($F);for(let r of n){let o=bt(e,r,"npm-loader.js");if(Ei(o)&&FF(o))return o}}catch{}return null}function ide(t){return t.id==="copilot"?ode()??MP(t.cliCommand):MP(t.cliCommand)}async function sde(){if(!Mo)return null;let t=[process.env.COPILOT_CACHE_HOME?bt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?bt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?bt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,bt(NP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=IF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort($F);for(let r of n){let o=bt(e,r,"npm-loader.js");if(Ei(o)&&await HF(o))return o}}catch{}return null}async function ade(t){return t.id==="copilot"?await sde()??await DP(t.cliCommand):DP(t.cliCommand)}function cde(t,e){let n=Ii();return n?mF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:_i(n),windowsHide:!0}).trim():mF(Mo?"cmd.exe":"npm",Mo?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()}async function NF(t,e){let n=Ii();if(n){let{stdout:o}=await fF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:_i(n)});return o.trim()}let{stdout:r}=await fF(Mo?"cmd.exe":"npm",Mo?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function lde(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 Eg(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 lde(o)}}return null}function Bd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function dde(t,e){let n=i=>{let s=Bd(i)??i,[a,c=""]=s.replace(/^v/,"").split("-",2),l=a.split(".").map(d=>Number.parseInt(d,10)||0);for(;l.length<3;)l.push(0);return{nums:l,pre:c}},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r.nums[i]!==o.nums[i])return r.nums[i]-o.nums[i];return r.pre===o.pre?0:r.pre?o.pre?r.pre.localeCompare(o.pre):-1:1}function OF(t,e){return!t||!e?!1:dde(t,e)>0}function ude(){if(Ci!==void 0)return Ci;try{Ci=cde(["root","-g"],3e3)||null}catch{Ci=null}return Ci}async function pde(){if(Ci===void 0)try{Ci=await NF(["root","-g"],3e3)||null}catch{Ci=null}}function Mg(t){if(!t)return null;let e=ude();if(!e)return null;let n=bt(e,...t.split("/"),"package.json");try{let r=JSON.parse(gc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function yF(t){let e=Eg(t?.npm);return Mg(e)}function jF(t,e){return Mg(Eg(t.install?.npm))??Bd(e)??e??void 0}async function mde(t,e){if(!t)return null;DF();let n=e?`${t}\0${e}`:t,r=mc.get(n);if(r){let i=r.version?MF:nde;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 NF(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Bd(s)}catch{o=null}return mc.set(n,{timestamp:Date.now(),version:o}),rde(),o}async function LF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=Eg(i.install?.npm),c=Mg(a)??Bd(s)??s??void 0;if(!a||!c)return null;let l=await mde(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:OF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function UF(t,e){DF();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=Eg(i.install?.npm),c=Mg(a)??Bd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=mc.get(l);d?.version&&Date.now()-d.timestamp<MF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:OF(d.version,c)})}return{updates:n,stale:r}}function FF(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=AF(r,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}async function HF(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 EF(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 fde(t,e){if(!Mo)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=zF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=gde(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function zF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ei(r))continue;let o;try{o=gc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=bt(Hd(e),s);if(Ei(a))return a}return null}function gde(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ei(r))continue;let o;try{o=gc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=bt(Hd(e),s);if(Ei(a))return a}return null}function vF(t){let e=zF(t);if(!e)return null;let n=Hd(e);for(let r=0;r<6;r+=1){let o=bt(n,"package.json");try{if(Ei(o)){let s=JSON.parse(gc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=Hd(n);if(i===n)break;n=i}return null}var bF=6e4;function hde(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 BF=new Set(["codex","qwen","opencode"]),Ig=new Set(["qwen","opencode"]),_g=new Set(["gemini"]),$P=new Set(["glm"]),kF={claude:"anthropic",codex:"openai"};function yde(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function vde(t){let e=bt(ede(),"qlogicagent-codex-model-catalog");PF(e,{recursive:!0});let n=bt(e,`${yde(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(!Ei(n)||gc(n,"utf8")!==r)&&_F(n,r,"utf8"),n}function OP(t){return t.id!=="claude"}function Cg(t,e){return e==="account"&&!OP(t)?"auto":e}function qF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&OP(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||Ig.has(t.id)||_g.has(t.id)||$P.has(t.id))&&e.push("managed"),e}function jP(t,e,n){let r=Cg(t,e);return!!(r==="account"||r==="auto"&&OP(t)&&n?.hasSubscription?.(t.id)===!0)}var WF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},bde={glm:"ACP_GLM_AVAILABLE_MODELS"};function Pg(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=WF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=bde[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function wF(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 SF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function xF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...SF]:SF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function RF(t){return!!t.apiKeyEnvVar||Ig.has(t.id)||_g.has(t.id)}function TF(t,e,n="auto"){let r={};if(!t)return r;let o=Cg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=kF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||_g.has(t.id)||$P.has(t.id)?Pg(t,e,r):Ig.has(t.id)&&wF(t,e,r),r;if(jP(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=kF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:Pg(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:Ig.has(t.id)?wF(t,e,r):(_g.has(t.id)||$P.has(t.id))&&Pg(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&BF.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 kde(t,e,n){if(!t||!jP(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),BF.has(t.id)&&r.push("OPENAI_MODEL"),r}function wde(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==="gemini"){let a=r.llmrouterModel;return!n.GEMINI_API_KEY||!a||e.some(c=>c==="-m"||c==="--model"||c.startsWith("--model="))?e:[...e,"--model",a]}if(t.id!=="codex")return e;if(jP(t,o,r))return e.some(a=>a.includes("preferred_auth_method"))?e:[...e,"-c","preferred_auth_method=chatgpt"];if(t.keySource!=="llmrouter"||!n.OPENAI_API_KEY||e.some(a=>a.includes("model_provider")||a.includes("model_providers.")))return e;let i=n.OPENAI_BASE_URL,s=r.llmrouterModel||n.OPENAI_MODEL||"deepseek-v4-flash";return i?[...e,"-c","model_providers.llmrouter.name=llmrouter","-c",`model_providers.llmrouter.base_url=${i}`,"-c","model_providers.llmrouter.wire_api=responses","-c","model_providers.llmrouter.env_key=OPENAI_API_KEY","-c","model_provider=llmrouter","-c",`model=${s}`,"-c",`model_catalog_json=${vde(s)}`]:e}var fc=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<bF)return this.cache.agents;let n=[];for(let r of Object.values(Hs))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<bF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await pde();let n=[...await Promise.all(Object.values(Hs).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=ide(e),r=n?FF(n)??vF(n)??yF(Eo(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await ade(e),r=n?await HF(n)??vF(n)??yF(Eo(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,MP(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await DP(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=Eo(e)??Hs[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}:fde(n.cliPath,s),c=o?.authPreference??"auto",l=TF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:wde(r,a.acpArgs,l,this.keySources,c),p=r?kde(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:hde(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=Eo(e)??Hs[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Cg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&RF(r)?xF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Eo(e)??Hs[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Cg(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(!RF(n)||xF(TF(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 GF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=WF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var qd="https://registry.npmmirror.com",hc="https://pypi.tuna.tsinghua.edu.cn/simple",LP="https://registry.npmmirror.com/-/binary";function KF(){return{npm_config_registry:qd,PIP_INDEX_URL:hc,UV_DEFAULT_INDEX:hc,UV_INDEX_URL:hc,UV_PYTHON_INSTALL_MIRROR:`${LP}/python-build-standalone`,NODEJS_ORG_MIRROR:`${LP}/node`,npm_config_disturl:`${LP}/node`}}var UP=Object.keys(KF());import{readFileSync as Ede}from"node:fs";import{randomUUID as Mde}from"node:crypto";de();Pa();import{readdirSync as Sde,readFileSync as xde,statSync as FP,writeFileSync as Rde}from"node:fs";import{join as Wd}from"node:path";var Tde=["auto-skill-","test-skill-"],Ade=".skills_prompt_snapshot.json";function Pde(t){return Tde.some(e=>t.startsWith(e))}function Ide(t){let e=t.replace(/\r\n/g,`
686
+ ${t?.data?.details??""}`;return/\b(auth(?:entication|orization)?|login|log in|api key|apikey|token|credential|provider|configured|configuration|setup|sign in)\b/i.test(e)}function Hle(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 Pi=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=lF(Ole.toWeb(e.stdin),Nle.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new Tg(()=>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:jle,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),Lle,"initialize").catch(i=>{throw Ud(i)??i}),o=r?.agentCapabilities??{};return{protocolVersion:typeof r?.protocolVersion=="number"?r.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:r?.agentInfo,authMethods:r?.authMethods}}async createSession(e,n){let r={cwd:n.cwd,mcpServers:n.mcpServers??[]};n.additionalDirectories?.length&&(r.additionalDirectories=n.additionalDirectories),n.systemPrompt&&(r._meta={qlogicagent:{systemPrompt:n.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(r),uF,"session/new").catch(i=>{throw Ud(i)??i});if(typeof o?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:o.sessionId}}async sendPrompt(e,n,r,o=Ule){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:n,prompt:[{type:"text",text:r}]}),o,"session/prompt",()=>{i.cancel({sessionId:n}).catch(()=>{})}).catch(a=>{throw Ud(a)??Hle(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),uF,"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 wr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case wr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case wr.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 wr.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 wr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case wr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case wr.AVAILABLE_COMMANDS_UPDATE:case wr.CURRENT_MODE_UPDATE:case wr.CONFIG_OPTION_UPDATE:case wr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case wr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as zle}from"node:child_process";import{readFile as Ble,writeFile as qle}from"node:fs/promises";import{isAbsolute as pF,normalize as Wle,relative as Gle,resolve as Kle,sep as Vle}from"node:path";function Jle(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 PP(t){let e=new Map,n=0,r=i=>{let s=pF(i)?Wle(i):Kle(t.cwd,i),a=Gle(t.cwd,s);if(a===".."||a.startsWith(`..${Vle}`)||pF(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:Jle(i)}},async readTextFile(i){return{content:await Ble(r(i.path),"utf8")}},async writeTextFile(i){return await qle(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=zle(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"],windowsHide:!0}),g=`term-${++n}`,h={child:f,output:"",exitStatus:null,exit:new Promise(y=>{f.on("exit",(b,v)=>{let k={exitCode:b,signal:v};h.exitStatus=k,y(k)}),f.on("error",()=>{let b={exitCode:null,signal:null};h.exitStatus=b,y(b)})})};return f.stdout?.on("data",y=>{h.output+=y.toString()}),f.stderr?.on("data",y=>{h.output+=y.toString()}),e.set(g,h),{terminalId:g}},async terminalOutput(i){let s=e.get(o(i));return s?{output:s.output,truncated:!1,exitStatus:s.exitStatus}:{output:"",truncated:!1,exitStatus:null}},async waitForTerminalExit(i){let s=e.get(o(i));return s?s.exit:{exitCode:null,signal:null}},async releaseTerminal(i){let s=o(i),a=e.get(s);if(a&&a.child.exitCode===null&&a.child.signalCode===null)try{a.child.kill()}catch{}return e.delete(s),{}},async killTerminal(i){let s=e.get(o(i));if(s)try{s.child.kill("SIGKILL")}catch{}return{}},disposeAll(){for(let i of e.values())try{i.child.kill("SIGKILL")}catch{}e.clear()}}}var Fd=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{exec as Xle,execFile as Yle,execFileSync as mF,execSync as AF}from"node:child_process";import{existsSync as Ei,mkdirSync as PF,readFileSync as gc,readdirSync as IF,writeFileSync as _F}from"node:fs";import{homedir as NP,platform as Qle,tmpdir as ede}from"node:os";import{dirname as Hd,join as bt}from"node:path";import{promisify as CF}from"node:util";function Ii(){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 _i(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function IP(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 _P(t){return Zle.test(t.trim())}function CP(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var fF=CF(Yle),EF=CF(Xle),Hs={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"}},tde=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],gF={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 Eo(t){let e=Hs[t];if(e)return gF[t]?{...e,...gF[t]}:e}function zd(){return tde.map(t=>{let e=Eo(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Mo=Qle()==="win32",MF=5*6e4,nde=2e4,Ci,mc=new Map,EP=bt(process.env.QLOGICAGENT_HOME||bt(NP(),".qlogicagent"),"agent-update-cache.json"),hF=!1;function DF(){if(!hF){hF=!0;try{let t=JSON.parse(gc(EP,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!mc.has(e)&&mc.set(e,n)}catch{}}}var Ag=null;function rde(){Ag||(Ag=setTimeout(()=>{Ag=null;try{let t={};for(let[e,n]of mc)t[e]=n;PF(Hd(EP),{recursive:!0}),_F(EP,JSON.stringify(t),"utf8")}catch{}},1e3),Ag.unref?.())}function MP(t){try{let e=Mo?`where ${t}`:`which ${t}`;return AF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function DP(t){try{let e=Mo?`where ${t}`:`which ${t}`,{stdout:n}=await EF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function $F(t,e){let n=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r[i]!==o[i])return o[i]-r[i];return e.localeCompare(t)}function ode(){if(!Mo)return null;let t=[process.env.COPILOT_CACHE_HOME?bt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?bt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?bt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,bt(NP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=IF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort($F);for(let r of n){let o=bt(e,r,"npm-loader.js");if(Ei(o)&&FF(o))return o}}catch{}return null}function ide(t){return t.id==="copilot"?ode()??MP(t.cliCommand):MP(t.cliCommand)}async function sde(){if(!Mo)return null;let t=[process.env.COPILOT_CACHE_HOME?bt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?bt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?bt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,bt(NP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=IF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort($F);for(let r of n){let o=bt(e,r,"npm-loader.js");if(Ei(o)&&await HF(o))return o}}catch{}return null}async function ade(t){return t.id==="copilot"?await sde()??await DP(t.cliCommand):DP(t.cliCommand)}function cde(t,e){let n=Ii();return n?mF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:_i(n),windowsHide:!0}).trim():mF(Mo?"cmd.exe":"npm",Mo?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()}async function NF(t,e){let n=Ii();if(n){let{stdout:o}=await fF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:_i(n),windowsHide:!0});return o.trim()}let{stdout:r}=await fF(Mo?"cmd.exe":"npm",Mo?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,windowsHide:!0});return r.trim()}function lde(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 Eg(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 lde(o)}}return null}function Bd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function dde(t,e){let n=i=>{let s=Bd(i)??i,[a,c=""]=s.replace(/^v/,"").split("-",2),l=a.split(".").map(d=>Number.parseInt(d,10)||0);for(;l.length<3;)l.push(0);return{nums:l,pre:c}},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r.nums[i]!==o.nums[i])return r.nums[i]-o.nums[i];return r.pre===o.pre?0:r.pre?o.pre?r.pre.localeCompare(o.pre):-1:1}function OF(t,e){return!t||!e?!1:dde(t,e)>0}function ude(){if(Ci!==void 0)return Ci;try{Ci=cde(["root","-g"],3e3)||null}catch{Ci=null}return Ci}async function pde(){if(Ci===void 0)try{Ci=await NF(["root","-g"],3e3)||null}catch{Ci=null}}function Mg(t){if(!t)return null;let e=ude();if(!e)return null;let n=bt(e,...t.split("/"),"package.json");try{let r=JSON.parse(gc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function yF(t){let e=Eg(t?.npm);return Mg(e)}function jF(t,e){return Mg(Eg(t.install?.npm))??Bd(e)??e??void 0}async function mde(t,e){if(!t)return null;DF();let n=e?`${t}\0${e}`:t,r=mc.get(n);if(r){let i=r.version?MF:nde;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 NF(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Bd(s)}catch{o=null}return mc.set(n,{timestamp:Date.now(),version:o}),rde(),o}async function LF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=Eg(i.install?.npm),c=Mg(a)??Bd(s)??s??void 0;if(!a||!c)return null;let l=await mde(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:OF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function UF(t,e){DF();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=Eg(i.install?.npm),c=Mg(a)??Bd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=mc.get(l);d?.version&&Date.now()-d.timestamp<MF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:OF(d.version,c)})}return{updates:n,stale:r}}function FF(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=AF(r,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}async function HF(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 EF(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 fde(t,e){if(!Mo)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=zF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=gde(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function zF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ei(r))continue;let o;try{o=gc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=bt(Hd(e),s);if(Ei(a))return a}return null}function gde(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ei(r))continue;let o;try{o=gc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=bt(Hd(e),s);if(Ei(a))return a}return null}function vF(t){let e=zF(t);if(!e)return null;let n=Hd(e);for(let r=0;r<6;r+=1){let o=bt(n,"package.json");try{if(Ei(o)){let s=JSON.parse(gc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=Hd(n);if(i===n)break;n=i}return null}var bF=6e4;function hde(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 BF=new Set(["codex","qwen","opencode"]),Ig=new Set(["qwen","opencode"]),_g=new Set(["gemini"]),$P=new Set(["glm"]),kF={claude:"anthropic",codex:"openai"};function yde(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function vde(t){let e=bt(ede(),"qlogicagent-codex-model-catalog");PF(e,{recursive:!0});let n=bt(e,`${yde(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(!Ei(n)||gc(n,"utf8")!==r)&&_F(n,r,"utf8"),n}function OP(t){return t.id!=="claude"}function Cg(t,e){return e==="account"&&!OP(t)?"auto":e}function qF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&OP(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||Ig.has(t.id)||_g.has(t.id)||$P.has(t.id))&&e.push("managed"),e}function jP(t,e,n){let r=Cg(t,e);return!!(r==="account"||r==="auto"&&OP(t)&&n?.hasSubscription?.(t.id)===!0)}var WF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},bde={glm:"ACP_GLM_AVAILABLE_MODELS"};function Pg(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=WF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=bde[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function wF(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 SF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function xF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...SF]:SF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function RF(t){return!!t.apiKeyEnvVar||Ig.has(t.id)||_g.has(t.id)}function TF(t,e,n="auto"){let r={};if(!t)return r;let o=Cg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=kF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||_g.has(t.id)||$P.has(t.id)?Pg(t,e,r):Ig.has(t.id)&&wF(t,e,r),r;if(jP(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=kF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:Pg(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:Ig.has(t.id)?wF(t,e,r):(_g.has(t.id)||$P.has(t.id))&&Pg(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&BF.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 kde(t,e,n){if(!t||!jP(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),BF.has(t.id)&&r.push("OPENAI_MODEL"),r}function wde(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==="gemini"){let a=r.llmrouterModel;return!n.GEMINI_API_KEY||!a||e.some(c=>c==="-m"||c==="--model"||c.startsWith("--model="))?e:[...e,"--model",a]}if(t.id!=="codex")return e;if(jP(t,o,r))return e.some(a=>a.includes("preferred_auth_method"))?e:[...e,"-c","preferred_auth_method=chatgpt"];if(t.keySource!=="llmrouter"||!n.OPENAI_API_KEY||e.some(a=>a.includes("model_provider")||a.includes("model_providers.")))return e;let i=n.OPENAI_BASE_URL,s=r.llmrouterModel||n.OPENAI_MODEL||"deepseek-v4-flash";return i?[...e,"-c","model_providers.llmrouter.name=llmrouter","-c",`model_providers.llmrouter.base_url=${i}`,"-c","model_providers.llmrouter.wire_api=responses","-c","model_providers.llmrouter.env_key=OPENAI_API_KEY","-c","model_provider=llmrouter","-c",`model=${s}`,"-c",`model_catalog_json=${vde(s)}`]:e}var fc=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<bF)return this.cache.agents;let n=[];for(let r of Object.values(Hs))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<bF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await pde();let n=[...await Promise.all(Object.values(Hs).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=ide(e),r=n?FF(n)??vF(n)??yF(Eo(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await ade(e),r=n?await HF(n)??vF(n)??yF(Eo(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,MP(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await DP(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=Eo(e)??Hs[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}:fde(n.cliPath,s),c=o?.authPreference??"auto",l=TF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:wde(r,a.acpArgs,l,this.keySources,c),p=r?kde(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:hde(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=Eo(e)??Hs[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Cg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&RF(r)?xF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Eo(e)??Hs[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Cg(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(!RF(n)||xF(TF(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 GF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=WF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var qd="https://registry.npmmirror.com",hc="https://pypi.tuna.tsinghua.edu.cn/simple",LP="https://registry.npmmirror.com/-/binary";function KF(){return{npm_config_registry:qd,PIP_INDEX_URL:hc,UV_DEFAULT_INDEX:hc,UV_INDEX_URL:hc,UV_PYTHON_INSTALL_MIRROR:`${LP}/python-build-standalone`,NODEJS_ORG_MIRROR:`${LP}/node`,npm_config_disturl:`${LP}/node`}}var UP=Object.keys(KF());import{readFileSync as Ede}from"node:fs";import{randomUUID as Mde}from"node:crypto";de();Pa();import{readdirSync as Sde,readFileSync as xde,statSync as FP,writeFileSync as Rde}from"node:fs";import{join as Wd}from"node:path";var Tde=["auto-skill-","test-skill-"],Ade=".skills_prompt_snapshot.json";function Pde(t){return Tde.some(e=>t.startsWith(e))}function Ide(t){let e=t.replace(/\r\n/g,`
687
687
  `),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:VF(s?.[1]),environments:VF(a?.[1])}}function Gd(t,e){let n=_n(),r=Y0(),o=t?Q0(t):new Set,i=[],s;try{s=Sde(n,{withFileTypes:!0})}catch{s=[]}for(let a of s){if(!a.isDirectory()||a.name.startsWith("."))continue;let c=Wd(n,a.name),l=Wd(c,"SKILL.md"),d;try{if(!FP(l).isFile())continue;d=xde(l,"utf8")}catch{continue}let p=r.has(a.name),m=o.has(a.name),f=Ide(d),g=!_de(f,e);i.push({name:a.name,filePath:l,baseDir:c,globallyDisabled:p,projectDisabled:m,active:!p&&!m&&!g,systemGenerated:Pde(a.name),description:f.description,version:f.version,category:f.category,author:f.author,requiredTools:f.requiredTools,environments:f.environments})}return Cde(n,i),i}function Do(t,e){return Gd(t,e).filter(n=>n.active)}function Ln(t){let e=_n(),n=Wd(e,t),r=Wd(n,"SKILL.md");try{if(FP(r).isFile())return{baseDir:n,filePath:r}}catch{}return null}function VF(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 _de(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 Cde(t,e){try{let r={version:1,entries:e.map(o=>{let i=FP(o.filePath);return{name:o.name,size:i.size,mtimeMs:i.mtimeMs,description:o.description,version:o.version,requiredTools:o.requiredTools,environments:o.environments}})};Rde(Wd(t,Ade),JSON.stringify(r,null,2),"utf8")}catch{}}var Dde="astraclaw_capabilities",Sr=[Dde,"astraclaw"];function Dg(t){let e=Do(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 session did not accept direct AstraClaw MCP injection. If this agent exposes AstraClaw through its native MCP config, prefer those live tools (`skills_list`, `skill_view`, `mcp_connectors_list`, `mcp_tool_call`); otherwise 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(`
688
688
  `)}function JF(t){let e=Dg(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(`
689
689
  `)}async function $g(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:Do(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform}).map($de)}};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:Ede(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:Ode(n.function.name),name:jde(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=Nde(t.args.args),o=`astraclaw_mcp_${Mde().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 $de(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function Nde(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Ode(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function jde(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import{existsSync as Kd,mkdirSync as Vd,readFileSync as zs,writeFileSync as Jd}from"node:fs";import{homedir as Lde}from"node:os";import{dirname as Zd,join as cr}from"node:path";de();var Ude={qwen:[".qwen","settings.json"],gemini:[".gemini","settings.json"]},Ng="# BEGIN ASTRACLAW MANAGED MCP",BP="# END ASTRACLAW MANAGED MCP",ZF=" # BEGIN ASTRACLAW MANAGED MCP",XF=" # END ASTRACLAW MANAGED MCP";function YF(t){let e=t.agentId.trim().toLowerCase(),n=t.homeDir||Lde(),r=Fde(t),o=Ude[e];if(o){let i=cr(n,...o);return qde({agentId:e,configPath:i,server:r})}if(e==="codex"){let i=cr(t.codexHome||process.env.CODEX_HOME?.trim()||cr(n,".codex"),"config.toml");return Vde({agentId:e,configPath:i,server:r})}if(e==="kimi"){let i=cr(n,".kimi","mcp.json");return Wde({agentId:e,configPath:i,server:r})}if(e==="hermes"){let i=cr(Hde(n),"config.yaml");return Jde({agentId:e,configPath:i,server:r})}if(e==="opencode"){let i=cr(zde(n,t.homeDir!==void 0),"opencode.jsonc");return Zde({agentId:e,configPath:i,server:r})}return{agentId:e,status:"unsupported",reason:`No native MCP config adapter for agent "${e}"`}}function Fde(t){return{command:t.nodePath||process.execPath,args:[t.serverScriptPath],env:Bde({ASTRACLAW_PROJECT_ROOT:t.projectRoot,ASTRACLAW_MANAGED:"1",ASTRACLAW_MCP_CONFIG_PATH:Nl(),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 Hde(t){let e=process.env.HERMES_HOME?.trim();if(e)return e;let n=process.env.LOCALAPPDATA?.trim();return process.platform==="win32"&&n?cr(n,"hermes"):cr(t,".hermes")}function zde(t,e=!1){if(e)return cr(t,"opencode");let n=process.env.XDG_CONFIG_HOME?.trim();if(n)return cr(n,"opencode");let r=process.env.APPDATA?.trim();return process.platform==="win32"&&r?cr(r,"opencode"):cr(t,".config","opencode")}function Bde(t){return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"&&e[1].length>0))}function qde(t){let e=QF(t.configPath),n={...e,mcpServers:{...Xd(e.mcpServers)?e.mcpServers:{}}},r=n.mcpServers;for(let s of Sr)r[s]=t.server;let o=`${JSON.stringify(n,null,2)}
@@ -724,7 +724,7 @@ ${n}
724
724
  `);A&&(C.systemPrompt=A);let _=await h.createSession(f,C);l.sessionId=_.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,C=>{this.slog("warn",C,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(C,"agents.error",{agentId:C,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(C)})}catch(l){let d=this.processes.get(e.memberId);d&&(d.handle.state="failed",d.handle.error=`Runtime restart failed: ${l instanceof Error?l.message:String(l)}`,d.handle.endedAt=Date.now()),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Restart failed after ${r} attempts: ${l instanceof Error?l.message:String(l)}`,retriesLeft:0})}}getMcpIpcPath(e){return this.processes.get(e)?.ipcPath}heartbeatTimers=new Map;missedBeats=new Map;static HEARTBEAT_INTERVAL=3e4;static MAX_MISSED_BEATS=3;startHeartbeat(e,n){this.stopHeartbeat(e),this.missedBeats.set(e,0);let r=setInterval(async()=>{let o=this.processes.get(e);if(!o||o.handle.state==="completed"||o.handle.state==="failed"||o.handle.state==="killed"){this.stopHeartbeat(e);return}if(await this.ping(e,1e4)){this.missedBeats.set(e,0);return}let s=(this.missedBeats.get(e)??0)+1;this.missedBeats.set(e,s),this.slog("warn",e,"heartbeat",`missed (${s}/${t.MAX_MISSED_BEATS})`),s>=t.MAX_MISSED_BEATS&&(this.slog("warn",e,"heartbeat","hang detected, force-killing"),this.stopHeartbeat(e),o.handle.error=`Hang detected: ${s} consecutive heartbeat failures`,this.kill(e),n?.(e))},t.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,r)}stopHeartbeat(e){let n=this.heartbeatTimers.get(e);n&&(clearInterval(n),this.heartbeatTimers.delete(e)),this.missedBeats.delete(e)}getMissedBeats(e){return this.missedBeats.get(e)??0}activeCount(){return[...this.processes.values()].filter(e=>e.handle.state==="starting"||e.handle.state==="ready"||e.handle.state==="running").length}remove(e){let n=this.processes.get(e);n&&(this.stopHeartbeat(e),(n.handle.state==="running"||n.handle.state==="starting"||n.handle.state==="ready")&&this.kill(e),this.processes.delete(e))}dispose(){for(let e of this.heartbeatTimers.keys())this.stopHeartbeat(e);for(let e of this.processes.values()){try{e.ipcServer?.close()}catch{}try{e.stderrStream?.end()}catch{}}this.killAll(),this.processes.clear()}};import{spawn as Mi}from"node:child_process";var aH=/[|&;><$`(){}]/;function cH(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=aH.test(i);if(!(s&&n)&&!(i.startsWith("brew ")&&!r))return{command:i,shell:s}}return null}function lH(t,e){if(e!=="cn")return t;let n=t.trim();return/^npm\b/.test(n)&&!/(?:^|\s)--registry(?:\s|=)/.test(n)?`${n} --registry ${qd}`:/^uv\b/.test(n)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(n)?`${n} --default-index ${hc}`:/^(?:pipx|pip3?|python -m pip)\b/.test(n)&&!/(?:^|\s)--index-url(?:\s|=)/.test(n)?`${n} --index-url ${hc}`:n}function sH(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 Iue=(t,e)=>{let n=Ii();if(n&&IP(t)){let i=t.trim().split(/\s+/).slice(1);return Mi(n.nodeExe,[n.npmCli,...i],{env:_i(n),stdio:["ignore","pipe","pipe"],windowsHide:!0})}let r=_P(t)?CP():void 0;if(e||process.platform==="win32")return Mi(t,{shell:!0,...r?{env:r}:{},stdio:["ignore","pipe","pipe"],windowsHide:!0});let o=t.split(/\s+/).filter(Boolean);return Mi(o[0],o.slice(1),{...r?{env:r}:{},stdio:["ignore","pipe","pipe"]})};async function dH(t,e,n={}){let r=n.platform??process.platform,o=n.spawnImpl??Iue,i=cH(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=lH(i.command,n.mirror);e({type:"state",state:"installing"});let a=await sH(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 sH(c,aH.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 uH(t,e=process.platform){try{return e==="win32"?Mi("cmd.exe",["/c","start","","cmd","/k",t],{detached:!0,stdio:"ignore",windowsHide:!1}).unref():e==="darwin"?Mi("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(t)}`,"-e",'tell application "Terminal" to activate'],{detached:!0,stdio:"ignore"}).unref():Mi("x-terminal-emulator",["-e","bash","-lc",`${t}; exec bash`],{detached:!0,stdio:"ignore"}).unref(),{ok:!0}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}function pH(t,e={}){let n=e.platform??process.platform,r=cH(t,n);if(!r)return{ok:!1,error:`No install command available for ${n}`};let o=lH(r.command,e.mirror);try{let i=Ii(),s;if(i&&IP(o)){let a=o.trim().split(/\s+/).slice(1);s=Mi(i.nodeExe,[i.npmCli,...a],{env:_i(i),detached:!0,stdio:"ignore",windowsHide:!0})}else{let a=_P(o)?CP():void 0;s=Mi(o,{shell:!0,...a?{env:a}:{},detached:!0,stdio:"ignore",windowsHide:!0})}return s.unref(),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}}var kt=new Map,_ue=10*6e4,Cue=6e4,Eue=6,jg=null;function Lg(t,e,n){return`${t}\0${e}\0${n??"default"}`}function Yd(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function mH(t){let e=kt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){kt.delete(t),Yd(e);return}return e}}function fH(t,e){let n=kt.get(t);n&&n!==e&&(kt.delete(t),Yd(n)),kt.set(t,e),Mue(),$ue()}function gH(t,e){let n=kt.get(t);if(!n)return;if(!n.manager.isAlive(n.memberId)){kt.delete(t),Yd(n);return}kt.delete(t);let r=kt.get(e);return r&&r!==n&&(kt.delete(e),Yd(r)),kt.set(e,n),n.lastUsed=Date.now(),n}var Ug="__warm__";function bc(t){let e=kt.get(t);e&&(kt.delete(t),Yd(e))}function Qd(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):(bc(o),n+=1));return{evicted:n,deferred:r}}function hH(t){kt.get(t)?.pendingRecredential&&bc(t)}function Mue(){for(;kt.size>Eue;){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;bc(t)}}function Due(t){for(let[e,n]of[...kt.entries()])n.holder.current||t-n.lastUsed>_ue&&bc(e)}function $ue(){jg||(jg=setInterval(()=>Due(Date.now()),Cue),typeof jg.unref=="function"&&jg.unref())}import{randomUUID as Nue}from"node:crypto";var kc=new Map;function Oue(t,e){let n=kc.get(t);return n&&(clearTimeout(n.timer),n.resolve(null),kc.delete(t)),new Promise(r=>{let o=setTimeout(()=>{kc.delete(t),r(null)},e);typeof o.unref=="function"&&o.unref(),kc.set(t,{resolve:r,timer:o})})}function yH(t,e){let n=kc.get(t);return n?(clearTimeout(n.timer),kc.delete(t),n.resolve(e),!0):!1}function jue(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}function Lue(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 GP(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)GP(n,e);return e}for(let n of Object.values(t))GP(n,e);return e}function Uue(t){let e=GP(t).join(`
725
725
  `);return/astraclaw/i.test(e)&&/\b(?:skills_list|skill_view|mcp_connectors_list|mcp_tool_call)\b/.test(e)}async function vH(t,e){let n=e.turnContext(),r=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:Nue(),i=Array.isArray(t.options)?t.options:[];if(Uue(t))return{optionId:Lue(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:jue(r.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await Oue(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 Hue(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function zue(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 Bue(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:Hue(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:zue(s)}})}function kH(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function wH(t){return t instanceof Error?t.message:String(t)}async function que(t){let e=kH(t.error);if(!t.sessionId||!e)return;let n=wH(t.error);await hr(t.sessionId,{role:"user",content:t.prompt},t.projectRoot,t.turnId),await hr(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 _a(t.sessionId,t.projectRoot);await yt(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...r?.title?{}:{title:Bl(t.prompt,"External agent login required")},...t.lockSessionOwner===!1||r?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function SH(t){let e=t.params,n=typeof e?.approvalId=="string"?e.approvalId:"",r=typeof e?.optionId=="string"?e.optionId:"",o=n&&r?yH(n,r):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function xH(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 RH(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 TH(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let n=new Map(this.acpDetector.list().map(o=>[o.id,o])),r=zd().map(o=>{let i=n.get(o.id);return{id:o.id,name:o.name,brandId:o.brandId??o.id,category:o.category??"code",integration:o.integration??"acp",authMode:o.authMode??"key",keySource:o.keySource??"none",note:o.note,availableModes:qF(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:jF(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 KP=new Set;async function AH(t){try{let e=t.params,r=(typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR)==="cn"?qd:void 0,o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData());let i=new Map(this.acpDetector.list().map(l=>[l.id,l])),s=zd().map(l=>({id:l.id,entry:l,detectedVersion:i.get(l.id)?.version})),{updates:a,stale:c}=UF(s,r);if(t.id!==void 0&&this.sendResponse(t.id,{updates:a,refreshing:c}),c){let l=r??"";KP.has(l)||(KP.add(l),LF(s,r).catch(()=>{}).finally(()=>KP.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 PH(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=Eo(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=pH(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 dH(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 IH(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=Eo(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=uH(o);t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error,command:o})}async function _H(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 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(),{agentId:r,...o}=e;await n.setAgentConfig(r,o),this.acpDetector.setConfigStore(n.getData());let{deferred:i}=Qd(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 EH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let 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 MH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();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 Wue(t){let e=bH.homedir();if(t==="codex"){let n=process.env.CODEX_HOME?.trim()||wc.join(e,".codex");return[wc.join(n,"auth.json")]}return[]}async function DH(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 Wue(n))try{Sc.existsSync(o)&&(Sc.rmSync(o,{force:!0}),r=!0)}catch{}Qd(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 $H(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 NH(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 OH(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 jH(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 LH(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 UH(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=wc.join(_e(),"agent-logs"),r=wc.join(n,`${e.agentId}.stderr.log`),o="";try{o=Sc.readFileSync(r,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
726
726
  `).slice(-e.tail).join(`
727
- `)),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 FH(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 HH(t,e,n,r,o,i){let s=Lg(e,r,o),a=mH(s);if(a)return a;if(o!==Ug){let f=gH(Lg(e,r,Ug),s);if(f)return f}let c=`chat-${e}-${Fue().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Vr({onNotification:(f,g,h)=>{Bue({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 $g({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>vH(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:wc.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 fH(s,m),m}async function zH(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 HH(this,n,o,i,Ug),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 BH(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=Lg(n,a,l),h=await HH(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 b;try{b=await h.manager.sendTask(h.memberId,r,{timeout:c})}catch(S){throw await que({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),bc(g),S}finally{h.holder.current=null,hH(g)}let v=y.deltas.join("")||(typeof b?.content=="string"?b.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){hr(l,{role:"user",content:r},a,d),v&&hr(l,{role:"assistant",content:v},a,d);let S=Vt(l,a);yt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:Bl(r,"External agent session")},...f&&!S?.agentId?{agentId:n}:{}},a)}t.id!==void 0&&this.sendResponse(t.id,{ok:!0,agentId:n,content:v,streamed:y.streamedAny,stopReason:b?.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=kH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:wH(e),...n?{data:{authMethods:n}}:{}})}}}Rm();function Gue(t){let e=Jue(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=Xue(r.topK),s=await Hg(e,Fg(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(xc(s)&&Array.isArray(s.matches)?s.matches:[]).map(Yue).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 Hg(e,Fg(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=GH(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 Hg(e,Fg(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(xc(i)&&Array.isArray(i.versions)?i.versions:[]).map(Que).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 Hg(e,Fg(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=epe(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Rc(t=li()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=Kue(t);return Gue({baseUrl:Vue(t),token:e,clientVersion:n})}function Kue(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.17.7"}function Vue(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Fg(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 Jue(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function Hg(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 Zue(i)}`);return i.json().catch(()=>null)}async function Zue(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function xc(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Xue(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 Yue(t){if(!xc(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=qH(t.sourceTier),n=WH(t.trustStage),r=zg(t.resourceRiskTier),o=zg(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:VP(t.title,80),summary:VP(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=>VP(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function VP(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function Que(t){return!xc(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 epe(t){if(!xc(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 tpe=new Set(["R0","R1","R2","R3"]),npe=new Set(["official","community"]),rpe=new Set(["quarantine","trial","trusted"]),ope=new Set(["pending","approved","rejected"]);function zg(t){return typeof t=="string"&&tpe.has(t)?t:null}function qH(t){return typeof t=="string"&&npe.has(t)?t:null}function WH(t){return typeof t=="string"&&rpe.has(t)?t:null}function ipe(t){return typeof t=="string"&&ope.has(t)?t:null}function GH(t){if(!xc(t))return null;let e=qH(t.sourceTier),n=WH(t.trustStage),r=ipe(t.reviewStatus),o=zg(t.resourceRiskTier),i=zg(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(GH);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 JP={enabled:!0},spe=new Set(["R2","R3"]);function KH(t,e=JP){return spe.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 ape,verify as cpe}from"node:crypto";function lpe(t){return`id=${t.id}
727
+ `)),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 FH(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 HH(t,e,n,r,o,i){let s=Lg(e,r,o),a=mH(s);if(a)return a;if(o!==Ug){let f=gH(Lg(e,r,Ug),s);if(f)return f}let c=`chat-${e}-${Fue().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Vr({onNotification:(f,g,h)=>{Bue({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 $g({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>vH(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:wc.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 fH(s,m),m}async function zH(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 HH(this,n,o,i,Ug),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 BH(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=Lg(n,a,l),h=await HH(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 b;try{b=await h.manager.sendTask(h.memberId,r,{timeout:c})}catch(S){throw await que({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),bc(g),S}finally{h.holder.current=null,hH(g)}let v=y.deltas.join("")||(typeof b?.content=="string"?b.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){hr(l,{role:"user",content:r},a,d),v&&hr(l,{role:"assistant",content:v},a,d);let S=Vt(l,a);yt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:Bl(r,"External agent session")},...f&&!S?.agentId?{agentId:n}:{}},a)}t.id!==void 0&&this.sendResponse(t.id,{ok:!0,agentId:n,content:v,streamed:y.streamedAny,stopReason:b?.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=kH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:wH(e),...n?{data:{authMethods:n}}:{}})}}}Rm();function Gue(t){let e=Jue(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=Xue(r.topK),s=await Hg(e,Fg(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(xc(s)&&Array.isArray(s.matches)?s.matches:[]).map(Yue).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 Hg(e,Fg(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=GH(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 Hg(e,Fg(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(xc(i)&&Array.isArray(i.versions)?i.versions:[]).map(Que).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 Hg(e,Fg(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=epe(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Rc(t=li()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=Kue(t);return Gue({baseUrl:Vue(t),token:e,clientVersion:n})}function Kue(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.17.8"}function Vue(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Fg(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 Jue(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function Hg(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 Zue(i)}`);return i.json().catch(()=>null)}async function Zue(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function xc(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Xue(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 Yue(t){if(!xc(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=qH(t.sourceTier),n=WH(t.trustStage),r=zg(t.resourceRiskTier),o=zg(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:VP(t.title,80),summary:VP(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=>VP(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function VP(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function Que(t){return!xc(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 epe(t){if(!xc(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 tpe=new Set(["R0","R1","R2","R3"]),npe=new Set(["official","community"]),rpe=new Set(["quarantine","trial","trusted"]),ope=new Set(["pending","approved","rejected"]);function zg(t){return typeof t=="string"&&tpe.has(t)?t:null}function qH(t){return typeof t=="string"&&npe.has(t)?t:null}function WH(t){return typeof t=="string"&&rpe.has(t)?t:null}function ipe(t){return typeof t=="string"&&ope.has(t)?t:null}function GH(t){if(!xc(t))return null;let e=qH(t.sourceTier),n=WH(t.trustStage),r=ipe(t.reviewStatus),o=zg(t.resourceRiskTier),i=zg(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(GH);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 JP={enabled:!0},spe=new Set(["R2","R3"]);function KH(t,e=JP){return spe.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 ape,verify as cpe}from"node:crypto";function lpe(t){return`id=${t.id}
728
728
  version=${t.version}
729
729
  checksum=${t.checksum}
730
730
  sizeBytes=${t.sizeBytes}`}function dpe(t){return t.includes("\\n")?t.replace(/\\n/g,`
@@ -1535,8 +1535,8 @@ ${s.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.
1535
1535
  `)}case"codeActions":{if(e.actions.length===0)return"No code actions available.";let n=[`Available code actions (${e.actions.length}):`,""];for(let r of e.actions)n.push(` ${r.isPreferred?"\u2605":"-"} ${r.title}${r.kind?` [${r.kind}]`:""}`);return n.join(`
1536
1536
  `)}default:return"Unknown result type."}}import*as Xv from"node:path";function _Z(t){let e=t.workdir;return{executeOperation:async n=>{switch(n.operation){case"goToDefinition":case"findReferences":return{type:"locations",locations:[]};case"hover":return{type:"hover",hover:null};case"documentSymbol":return{type:"symbols",symbols:[]};case"diagnostics":return{type:"diagnostics",diagnostics:[]};case"completion":return{type:"completions",completions:[]};case"signatureHelp":return{type:"signatureHelp",signatures:[]};case"rename":return{type:"rename",edits:[]};case"codeAction":return{type:"codeActions",actions:[]};default:return{type:"locations",locations:[]}}},resolvePath:n=>Xv.isAbsolute(n)?n:Xv.resolve(e,n)}}function CZ(t){return[IZ(_Z({workdir:t.workdir}))]}function EZ(t){for(let e of CZ({workdir:t.workdir}))t.toolCatalog.addTool(e)}var cEe={id:"dev-tools",kind:"dev",register:lEe};function MZ(t){cEe.register(t)}function lEe(t){let e=typeof t.config.workdir=="string"?t.config.workdir:t.pathService?.getActiveProjectRoot();if(!e)throw new Error("Dev tool bootstrap requires a workdir or PathService active project root.");EZ({workdir:e,toolCatalog:t.toolCatalog})}import*as Qv from"node:fs";import ip from"node:path";import{fileURLToPath as mEe}from"node:url";import{createRuntime as fEe}from"mcporter";var dEe=new Set(["describe","fetch","find","get","inspect","list","query","read","search","stat"]),uEe=new Set(["append","copy","create","delete","edit","move","patch","remove","rename","set","update","upload","write"]);function DZ(t){let e=t.annotations,n=pEe(t.name),r=n.some(c=>uEe.has(c)),o=n.some(c=>dEe.has(c)),i=e?.destructiveHint===!0||r,s=e?.readOnlyHint===!0||!i&&o,a=s||e?.idempotentHint===!0&&!i;return{isReadOnly:s,isConcurrencySafe:a,isDestructive:i}}function pEe(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}var gEe=12e4,BE=3,hEe=1e3;async function yEe(t,e){let n=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),r=Math.max(1,e.attempts),o;for(let i=1;i<=r;i++)try{return await t()}catch(s){o=s,i<r&&(e.onRetry?.(i,s),await n(e.baseDelayMs*i))}throw o}var Yv=class{runtime=null;definitions=[];toolsByServer=new Map;injectedNames=new Set;log;workspaceRoot;toolCatalog;serverToolFilters=new Map;serverOAuth=new Map;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}},this.workspaceRoot=e.workspaceRoot?ip.resolve(e.workspaceRoot):void 0,this.toolCatalog=e.toolCatalog,this.definitions=e.servers.filter(n=>!n.disabled).filter(n=>{let r=EEe(n);for(let o of r)this.log.warn(`[mcp] rejected server "${n.name}": ${o.message}`);return n.tools&&this.serverToolFilters.set(n.name,n.tools),n.oauth===!0&&this.serverOAuth.set(n.name,!0),r.length===0}).map(n=>this.toServerDefinition(n)).filter(n=>n!==null)}toServerDefinition(e){if((e.type??(e.url?"http":"stdio"))==="http"){if(!e.url)return this.log.warn(`[mcp] server "${e.name}" is type "http" but has no url, skipping`),null;let r;try{r=new URL(e.url)}catch{return this.log.warn(`[mcp] server "${e.name}" has an invalid url "${e.url}", skipping`),null}return{name:e.name,command:{kind:"http",url:r,headers:e.headers}}}return e.command?{name:e.name,command:{kind:"stdio",command:e.command,args:e.args??[],cwd:e.cwd??this.workspaceRoot??process.cwd()},env:e.env}:(this.log.warn(`[mcp] server "${e.name}" is type "stdio" but has no command, skipping`),null)}async connectAll(){this.definitions.length!==0&&(this.runtime=await fEe({servers:this.definitions,clientInfo:{name:"qlogicagent",version:"1.0.0"},logger:{info:e=>this.log.info(`[mcp] ${e}`),warn:e=>this.log.warn(`[mcp] ${e}`),error:(e,n)=>this.log.warn(`[mcp] ${e}${n?` (${n instanceof Error?n.message:String(n)})`:""}`),debug:()=>{}}}),await Promise.allSettled(this.definitions.map(async e=>{try{let n=await yEe(()=>this.runtime.listTools(e.name,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e.name)!==!0}),{attempts:BE,baseDelayMs:hEe,onRetry:(o,i)=>this.log.warn(`[mcp] connect attempt ${o}/${BE} for ${e.name} failed, retrying: ${i instanceof Error?i.message:i}`)}),r=OZ(n,this.serverToolFilters.get(e.name));this.toolsByServer.set(e.name,r),this.log.info(`[mcp] connected to ${e.name} (${r.length}/${n.length} tools)`)}catch(n){this.log.warn(`[mcp] failed to connect to ${e.name} after ${BE} attempts: ${n instanceof Error?n.message:n}`)}})))}injectTools(){for(let[e,n]of this.toolsByServer){let r=this.injectPortableTools(e,n);this.log.info(`[mcp] injected ${r.length} tools from ${e}`)}}async refreshServerTools(e){if(!this.runtime)throw new Error("MCP runtime is not connected");let n=await this.runtime.listTools(e,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e)!==!0}),r=OZ(n,this.serverToolFilters.get(e));return this.toolsByServer.set(e,r),this.retractServerTools(e),this.injectPortableTools(e,r),r.length}getConnectedServers(){return Array.from(this.toolsByServer.keys())}getToolCount(){let e=0;for(let n of this.toolsByServer.values())e+=n.length;return e}async disconnectAll(){for(let n of this.injectedNames)this.removeRegisteredTool(n);this.injectedNames.clear(),this.toolsByServer.clear();let e=this.runtime;if(this.runtime=null,e)try{await e.close()}catch{}}toPortableTool(e,n){let r=DZ({name:n.name,description:n.description});return{name:`mcp__${$Z(e)}__${n.name}`,label:`[${e}] ${n.name}`,category:"mcp",description:n.description??`MCP tool from ${e}`,parameters:n.inputSchema??{type:"object",properties:{}},isConcurrencySafe:r.isConcurrencySafe,isReadOnly:r.isReadOnly,isDestructive:r.isDestructive,searchHint:`mcp ${e} ${n.name.replace(/[_-]+/g," ")}`,execute:async(o,i)=>{let s=this.runtime;if(!s)return{content:[{type:"text",text:`MCP server "${e}" is not connected.`}],details:{error:"mcp_not_connected"}};try{let a=await s.callTool(e,n.name,{args:i,timeoutMs:gEe});return vEe(a)}catch(a){let c=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${c}`}],details:{error:c}}}}}}wrapToolsForWorkspaceBoundary(e){return this.workspaceRoot?e.map(n=>{if(!n.execute)return n;let r=n.execute;return{...n,execute:async(o,i,s)=>{let a=kEe(n.name,i,this.workspaceRoot);return a?{content:[{type:"text",text:a}],details:{type:"mcp",error:"workspace_boundary"}}:r(o,i,s)}}}):e}injectPortableTools(e,n){let r=this.wrapToolsForWorkspaceBoundary(n.map(o=>this.toPortableTool(e,o)));this.registerTools(r);for(let o of r)this.injectedNames.add(o.name);return r}retractServerTools(e){let n=`mcp__${$Z(e)}__`;for(let r of[...this.injectedNames])r.startsWith(n)&&(this.removeRegisteredTool(r),this.injectedNames.delete(r))}registerTools(e){this.toolCatalog?this.toolCatalog.addTools(e):XB(e)}removeRegisteredTool(e){return this.toolCatalog?.removeTool(e)??vh(e)}};function vEe(t){let e=t&&typeof t=="object"?t:{};return{content:[{type:"text",text:(Array.isArray(e.content)?e.content:[]).filter(i=>!!i&&typeof i=="object").filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
1537
1537
  `)||"(no text output)"}],...e.isError?{details:{error:"mcp_tool_error"}}:{}}}function $Z(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var bEe=/(?:^|_)(path|paths|file|files|filename|filenames|dir|dirs|directory|directories|folder|folders|cwd|root|uri)(?:$|_)/i;function kEe(t,e,n){if(!n)return null;for(let r of WE(e)){let o=xEe(r.value,n);if(o&&!REe(o.candidate,o.root,o.pathApi))return`Blocked: MCP tool "${t}" path "${r.value}" is outside the workspace boundary "${o.root}"`}return null}function WE(t,e="",n=0){if(n>8)return[];if(typeof t=="string")return wEe(e,t)?[{key:e,value:t}]:[];if(Array.isArray(t))return t.flatMap(o=>WE(o,e,n+1));if(!t||typeof t!="object")return[];let r=[];for(let[o,i]of Object.entries(t))r.push(...WE(i,o,n+1));return r}function wEe(t,e){if(!bEe.test(t))return!1;let n=e.trim();return!n||/^https?:\/\//i.test(n)?!1:SEe(n)}function SEe(t){return ip.isAbsolute(t)||/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)||/^file:\/\//i.test(t)||t.includes("../")||t.includes("..\\")||t.startsWith(".\\")||t.startsWith("./")||t.includes("/")||t.includes("\\")}function xEe(t,e){let n=t.trim();if(/^file:\/\//i.test(n))try{n=mEe(n)}catch{return null}let r=NZ(n)||NZ(e)?ip.win32:ip,o=r.resolve(e);return{candidate:r.isAbsolute(n)?r.resolve(n):r.resolve(o,n),root:o,pathApi:r}}function REe(t,e,n){let r=n.relative(e,t);return r===""||!r.startsWith("..")&&!n.isAbsolute(r)}function NZ(t){return/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)}function GE(t){if(!t||typeof t!="object")return[];let e=t,n=[],r=e.mcpServers??e.servers??e;for(let[o,i]of Object.entries(r)){if(!i||typeof i!="object")continue;let s=i;if(typeof s.url=="string"){n.push({name:o,type:"http",url:s.url,headers:s.headers&&typeof s.headers=="object"?s.headers:void 0,disabled:s.disabled===!0,oauth:s.oauth===!0,tools:jZ(s.tools)});continue}typeof s.command=="string"&&n.push({name:o,type:"stdio",command:s.command,args:Array.isArray(s.args)?s.args:void 0,env:s.env&&typeof s.env=="object"?s.env:void 0,cwd:typeof s.cwd=="string"?s.cwd:void 0,disabled:s.disabled===!0,oauth:s.oauth===!0,tools:jZ(s.tools)})}return n}function OZ(t,e){let n=new Set(e?.include??[]),r=new Set(e?.exclude??[]);return t.filter(o=>n.size>0&&!n.has(o.name)?!1:!r.has(o.name))}function jZ(t){if(!t||typeof t!="object")return;let e=t,n=LZ(e.include),r=LZ(e.exclude);if(!(!n&&!r))return{...n?{include:n}:{},...r?{exclude:r}:{}}}function LZ(t){if(!Array.isArray(t))return;let e=t.filter(n=>typeof n=="string"&&n.trim().length>0);return e.length>0?e:void 0}var TEe=new Set(["bash","sh","zsh","fish","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe"]),AEe=new Set(["-c","/c","-command","-encodedcommand","-e"]),PEe=["curl","wget","invokewebrequest","invoke-restmethod","iwr","irm","nc","netcat"],IEe=["env","processenv","apikey","api_key","token","secret","credential","credentials","awsaccesskey","awssecret"],_Ee=["authorizedkeys","sshknownhosts","crontab","launchctl","schtasks","startup","runkey","runonce","bashrc","profile"],CEe=/\bssh-(?:rsa|ed25519|ecdsa-[^\s]+)\s+[A-Za-z0-9+/=]{40,}/i;function EEe(t){let e=[],n=[t.command??"",...t.args??[],...Object.keys(t.env??{}),...Object.values(t.env??{})].join(`
1538
- `);if(CEe.test(n)&&e.push({code:"ioc_public_key",message:"configuration contains an inline SSH public key IOC"}),(t.type??(t.url?"http":"stdio"))!=="stdio"||!MEe(t.command))return e;let r=DEe(t.args??[]);if(!r)return e;let o=$Ee(r);return qE(o,_Ee)&&e.push({code:"persistence",message:"stdio shell command attempts a persistence write"}),qE(o,PEe)&&qE(o,IEe)&&e.push({code:"dangerous_egress",message:"stdio shell command combines network egress with likely secret access"}),e}function MEe(t){if(!t)return!1;let e=ip.basename(t).toLowerCase();return TEe.has(e)}function DEe(t){for(let e=0;e<t.length;e++){let n=t[e]?.toLowerCase();if(n&&AEe.has(n))return t.slice(e+1).join(" ")}return""}function $Ee(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function qE(t,e){return e.some(n=>t.includes(n))}var NEe={id:"mcp-tools",kind:"mcp",register:OEe};function FZ(t){NEe.register(t)}function OEe(t){let e=LEe({turnMcpConfig:t.config.mcpServers??{},userMcpConfig:jEe(t.pathService,t.log),projectRoot:t.projectRoot});if(e.length===0)return;t.currentManager?.disconnectAll().catch(()=>{});let n=new Yv({servers:e,log:t.log,workspaceRoot:t.projectRoot,toolCatalog:t.toolCatalog});t.setManager(n),Ps(async()=>{await n.disconnectAll()}),t.setReady(n.connectAll().then(()=>{n.injectTools(),t.log.info(`[mcp] ${n.getToolCount()} tools from ${n.getConnectedServers().length} servers`)}).catch(r=>{t.log.warn(`[mcp] connection error: ${r instanceof Error?r.message:r}`)}))}function jEe(t,e){let n=t.getUserMcpConfigPath();if(!Qv.existsSync(n))return;let r;try{r=Qv.readFileSync(n,"utf8")}catch(o){e?.warn(`[mcp] cannot read user MCP config at ${n}: ${o instanceof Error?o.message:o}`);return}try{return JSON.parse(r.replace(/^\uFEFF/,""))}catch(o){e?.warn(`[mcp] failed to parse user MCP config at ${n} \u2014 all its servers will be skipped: ${o instanceof Error?o.message:o}`);return}}function LEe(t){let e=UZ(GE(t.turnMcpConfig??{}),t.projectRoot),n=UZ(GE(t.userMcpConfig??{}),t.projectRoot),r=new Set(e.map(o=>o.name));return[...e,...n.filter(o=>!r.has(o.name))]}function UZ(t,e){return t.map(n=>(n.type??"stdio")!=="stdio"||n.cwd?n:{...n,cwd:e})}import*as GZ from"node:fs";import*as uo from"node:fs";import*as sp from"node:path";import{pathToFileURL as UEe}from"node:url";var HZ={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var eb=class{constructor(e){this.config=e;this.log=e.log??{info:()=>{},warn:()=>{}}}config;loaded=[];pluginSkills=[];activations=new Map;log;async loadAll(){for(let e of this.config.pluginDirs){if(!uo.existsSync(e))continue;let n;try{n=uo.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let r of n){if(!r.isDirectory()||r.name.startsWith(".")||r.name.startsWith("_"))continue;let o=sp.join(e,r.name);await this.loadPlugin(r.name,o)}}return this.log.info(`[plugins] loaded ${this.loaded.length} plugin(s): ${this.loaded.map(e=>e.name).join(", ")||"(none)"}`),this.loaded}getPluginSkills(){return this.pluginSkills}getLoaded(){return this.loaded}async discoverNew(){let e=new Set(this.loaded.map(r=>r.name)),n=0;for(let r of this.config.pluginDirs){if(!uo.existsSync(r))continue;let o;try{o=uo.readdirSync(r,{withFileTypes:!0})}catch{continue}for(let i of o){if(!i.isDirectory()||i.name.startsWith(".")||i.name.startsWith("_")||e.has(i.name))continue;let s=sp.join(r,i.name);await this.loadPlugin(i.name,s),n++}}return n>0&&this.log.info(`[plugins] discovered ${n} new plugin(s)`),n}async refreshActivations(){let e=Date.now();for(let[n,r]of this.activations){if(e-r.lastCheckAt<r.ttlMs)continue;let o;try{o=await r.checkFn()}catch(i){this.log.warn(`[plugins] ${n}: check_fn error: ${i instanceof Error?i.message:i}`),o=r.lastResult}if(r.lastCheckAt=e,o!==r.lastResult){if(r.lastResult=o,o&&!r.active){for(let i of r.tools)this.addRegisteredTool(i);r.active=!0,this.log.info(`[plugins] ${n}: reactivated (${r.tools.length} tools)`)}else if(!o&&r.active){for(let i of r.tools)this.removeRegisteredTool(i.name);for(let i of r.hookUnregisterFns)i();r.active=!1,this.log.info(`[plugins] ${n}: deactivated`)}}}}async loadPlugin(e,n){let r=["index.js","index.mjs"],o=null;for(let h of r){let y=sp.join(n,h);if(uo.existsSync(y)){o=y;break}}if(!o){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let i=0,s=0,a=0,c=[],l=[],d=null,p=6e4,m={},f=sp.join(n,"config.json");if(uo.existsSync(f))try{m=JSON.parse(uo.readFileSync(f,"utf8"))}catch{}let g={pluginName:e,registerTool:h=>{this.addRegisteredTool(h),c.push(h),i++},registerHook:(h,y)=>{let b=HZ[h];if(!b){this.log.warn(`[plugins] ${e}: unknown hook phase "${h}"`);return}let v=this.config.hookRegistry.register({point:b,handler:y,label:`plugin:${e}:${h}`,priority:200});l.push(v),s++},registerSkill:h=>{this.pluginSkills.push(h),a++},getConfig:()=>m,setActivationCheck:(h,y)=>{d=h,y!==void 0&&(p=y)}};try{let y=await import(UEe(o).href);if(typeof y.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await y.register(g),d&&this.activations.set(e,{checkFn:d,ttlMs:p,lastCheckAt:Date.now(),lastResult:!0,directory:n,tools:c,hookUnregisterFns:l,active:!0}),this.loaded.push({name:e,directory:n,toolCount:i,hookCount:s,skillCount:a}),this.log.info(`[plugins] ${e}: ${i} tools, ${s} hooks, ${a} skills`)}catch(h){this.log.warn(`[plugins] ${e}: load error: ${h instanceof Error?h.message:h}`)}}addRegisteredTool(e){this.config.toolCatalog?this.config.toolCatalog.addTool(e):ZB(e)}removeRegisteredTool(e){return this.config.toolCatalog?.removeTool(e)??vh(e)}};Ke();import*as At from"node:fs";import*as ap from"node:path";function KE(){return ee().getUserPluginCacheDir()}function BZ(){return ap.join(KE(),"installed_plugins.json")}function qZ(){let t=BZ();if(!At.existsSync(t))return{version:1,plugins:[]};try{return JSON.parse(At.readFileSync(t,"utf-8"))}catch{return{version:1,plugins:[]}}}function FEe(t){let e=KE();At.existsSync(e)||At.mkdirSync(e,{recursive:!0}),At.writeFileSync(BZ(),JSON.stringify(t,null,2),"utf-8")}function HEe(t,e){return!(e.blocklist?.includes(t)||e.allowlist&&!e.allowlist.includes(t))}function zZ(t,e){return t?{file:t.nodeExe,argv:[t.npmCli,...e],env:_i(t)}:{file:"npm",argv:e}}async function zEe(t,e,n){let{execFile:r}=await import("node:child_process"),{promisify:o}=await import("node:util"),i=o(r),s=KE(),a=e?`${t}@${e}`:t,c=Ii();try{let l=zZ(c,["pack",a,"--pack-destination",s]),{stdout:d}=await i(l.file,l.argv,{timeout:6e4,cwd:s,...l.env?{env:l.env}:{}}),p=d.trim().split(`
1539
- `).pop()?.trim();if(!p)return n.warn(`[marketplace] npm pack returned no output for ${a}`),null;let m=ap.join(s,p),g=p.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",h=ap.join(s,`${t}@${g}`);At.existsSync(h)||At.mkdirSync(h,{recursive:!0}),await i("tar",["xzf",m,"-C",h,"--strip-components=1"],{timeout:3e4});try{At.unlinkSync(m)}catch{}let y=ap.join(h,"package.json");if(At.existsSync(y))try{let b=zZ(c,["install","--production","--no-save"]);await i(b.file,b.argv,{cwd:h,timeout:12e4,...b.env?{env:b.env}:{}})}catch(b){n.warn(`[marketplace] npm install for ${t} failed: ${b.message}`)}return n.info(`[marketplace] installed ${t}@${g} from npm`),{name:t,version:g,installPath:h}}catch(l){return n.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function BEe(){return qZ().plugins.filter(e=>At.existsSync(e.installPath)).map(e=>e.installPath)}async function qEe(t,e){let n=qZ(),r=[];for(let o of t.enabledPlugins){let i=o.specifier.split("/").pop()??o.specifier;if(!HEe(i,t)){e.warn(`[marketplace] plugin "${i}" blocked by enterprise policy`);continue}let s=n.plugins.find(c=>c.source.specifier===o.specifier&&c.source.type===o.type);if(s&&At.existsSync(s.installPath)&&(!o.version||s.version===o.version)){r.push(s.installPath);continue}let a=null;switch(o.type){case"npm":a=await zEe(o.specifier,o.version,e);break;case"git":case"url":e.warn(`[marketplace] ${o.type} source not yet implemented for "${o.specifier}"`);break}if(a){let c={name:a.name,version:a.version,source:o,installPath:a.installPath,installedAt:new Date().toISOString()};n.plugins=n.plugins.filter(l=>!(l.source.specifier===o.specifier&&l.source.type===o.type)),n.plugins.push(c),r.push(a.installPath)}}return FEe(n),r}function WEe(){let t=ee().getUserMarketplaceConfigPath();if(!At.existsSync(t))return null;try{return JSON.parse(At.readFileSync(t,"utf-8"))}catch{return null}}async function WZ(t,e){let n=[...t],r=BEe();n.push(...r);let o=WEe();if(o&&o.enabledPlugins.length>0)try{let i=await qEe(o,e),s=new Set(n);for(let a of i)s.has(a)||n.push(a)}catch(i){e.warn(`[marketplace] failed to update plugins: ${i.message}`)}return n}var GEe={id:"plugin-tools",kind:"plugin",register:KEe};function KZ(t){GEe.register(t)}function KEe(t){let e=VEe(t.config,t.pathService);WZ(e,t.log).then(n=>{if(n.length===0)return;let r=new eb({pluginDirs:n,hookRegistry:t.hooks,log:t.log,toolCatalog:t.toolCatalog});t.setPluginLoader(r),r.loadAll().then(o=>{t.log.info(`[plugins] ${o.length} loaded, ${r.getPluginSkills().length} skills`)}).catch(o=>{t.log.warn(`[plugins] load error: ${o instanceof Error?o.message:o}`)}),t.hooks.register({point:"turn.submitted",handler:async()=>(await r.discoverNew(),await r.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(n=>{t.log.warn(`[plugins] marketplace resolve error: ${n instanceof Error?n.message:n}`)})}function VEe(t,e){let n=[],r=s=>{!s||!GZ.existsSync(s)||n.includes(s)||n.push(s)},o=e.getUserPluginsDir();r(o),r(e.getProjectPluginsDir(e.getActiveProjectRoot()));let i=t.pluginPaths;if(Array.isArray(i))for(let s of i)typeof s=="string"&&r(s);return n}async function VZ(t,e){let n=e.getAcpPermissionSession();if(n)try{let r=su(t.category??"destructive").map(i=>({optionId:i.optionId,name:i.name,kind:i.kind})),o=await n.requestPermission({sessionId:n.sessionId,permissionId:t.approvalId,toolCall:{toolCallId:t.callId,title:t.toolName,rawInput:t.arguments??{}},message:t.message,category:t.category,options:r});return JZ(t,o.optionId)}catch{return{approvalId:t.approvalId,decision:"deny"}}if(e.sendNotification("tool.approval.request",{approvalId:t.approvalId,callId:t.callId,toolName:t.toolName,arguments:t.arguments?JSON.stringify(t.arguments):"",message:t.message,category:t.category,reason:t.message,options:su(t.category??"destructive"),rememberScope:t.rememberScope}),e.isPetActive()){let r=JEe(t.toolName);e.sendNotification("pet.confirm",{confirmId:t.approvalId,toolName:t.toolName,description:t.message??`Allow ${t.toolName}`,risk:r,timeoutMs:3e4})}return new Promise(()=>{})}function JEe(t){return t.match(/exec|bash|shell|terminal|run_command|reset|force|drop/i)?"system":t.match(/web|http|fetch|mcp|media|image|video|music|tts/i)?"external_egress":t.match(/write|delete|rm|move|patch|edit|create/i)?"write":"read"}function JZ(t,e){let n=su(t.category??"destructive").find(r=>r.optionId===e);return!n||n.kind.startsWith("reject")?{approvalId:t.approvalId,decision:"deny"}:{approvalId:t.approvalId,decision:"allow",scope:n.scope}}function ZZ(t){let e=Ku(t.config.permissions),n=b8(e);if(mm()){let o=$1();for(let i of o)n.addRule(i);Rh(!0),t.log.info(`[permissions] group security mode active: ${o.length} rules injected`)}else Rh(!1);t.currentUnregister?.();let r=k8({ruleEngine:n,hookRegistry:t.hooks,getWorkspaceRoot:t.getActiveWorkdir,auditLogger:new Yy(t.getActiveProjectRoot()),sessionId:t.sessionId,getTurnId:t.getTurnId,onRequestApproval:o=>VZ(o,t),onDenied:(o,i)=>{t.log.warn(`[permissions] blocked "${o}": ${i}`)}});return r.setToolMeta(t.toolCatalog.getToolManifest()),D2(()=>({mode:n.getMode(),workdir:t.getActiveWorkdir(),allowedDirs:n.getAllowedWriteDirectories()})),{permissionChecker:r,permissionUnregister:r.register(),ruleEngine:n}}function VE(t){let e=new Map;return{register(n){let r=e.get(n.point)??[],o={handler:n.handler,priority:n.priority??100,label:n.label,critical:n.critical};return r.push(o),r.sort((i,s)=>i.priority-s.priority),e.set(n.point,r),()=>{let i=r.indexOf(o);i>=0&&r.splice(i,1)}},async invoke(n,r){let o=e.get(n);if(!o||o.length===0)return{action:"continue",context:r};let i=r;for(let s of o)try{let a=await s.handler(n,i);if(!a||a.action==="continue"){a?.context&&(i=a.context);continue}if(a.action==="abort"||a.action==="skip")return t.info({hook:n,label:s.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){if(s.critical){let c=a instanceof Error?a.message:String(a),d=`critical hook ${s.label??n} failed: ${c}`;return t.warn({hook:n,label:s.label,err:c},"critical hook handler failed (blocking)"),{action:"abort",reason:d}}t.warn({hook:n,label:s.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:i}}}}si();function XZ(t,e){return t.register({point:"memory.before_recall",priority:60,label:"community-discovery",handler:async(n,r)=>{let o=r.query;if(!o)return{action:"continue",context:r};let i=await ZEe(o,e);return i?{action:"continue",context:{...r,recalledMemories:[...r.recalledMemories??[],XEe(i)]}}:{action:"continue",context:r}}})}async function ZEe(t,e){if(!e.communityDiscovery)return null;let n=await e.communityDiscovery.matchForTurn(t);return n.status==="matched"||n.status==="cached"?n:(n.status==="unavailable"&&e.log.debug(`community-discovery: unavailable (${n.error??"unknown"})`),null)}function XEe(t){let e=t.match,n=t.cacheEntry,r=e?.id??n?.resourceId??"",o=e?.title??n?.title??r,i=e?.summary??n?.summary??"",s=e?.sourceTier??n?.sourceTier??"community",a=e?.effectiveRiskTier??n?.effectiveRiskTier??"unknown";return{text:[`[Community skill available] "${o}" (${r})`,`Summary: ${i}`,`Source: ${s}; effective risk: ${a}`,"Use community.resolveInstall before any install. Do not inject or execute package contents from discovery."].join(`
1538
+ `);if(CEe.test(n)&&e.push({code:"ioc_public_key",message:"configuration contains an inline SSH public key IOC"}),(t.type??(t.url?"http":"stdio"))!=="stdio"||!MEe(t.command))return e;let r=DEe(t.args??[]);if(!r)return e;let o=$Ee(r);return qE(o,_Ee)&&e.push({code:"persistence",message:"stdio shell command attempts a persistence write"}),qE(o,PEe)&&qE(o,IEe)&&e.push({code:"dangerous_egress",message:"stdio shell command combines network egress with likely secret access"}),e}function MEe(t){if(!t)return!1;let e=ip.basename(t).toLowerCase();return TEe.has(e)}function DEe(t){for(let e=0;e<t.length;e++){let n=t[e]?.toLowerCase();if(n&&AEe.has(n))return t.slice(e+1).join(" ")}return""}function $Ee(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function qE(t,e){return e.some(n=>t.includes(n))}var NEe={id:"mcp-tools",kind:"mcp",register:OEe};function FZ(t){NEe.register(t)}function OEe(t){let e=LEe({turnMcpConfig:t.config.mcpServers??{},userMcpConfig:jEe(t.pathService,t.log),projectRoot:t.projectRoot});if(e.length===0)return;t.currentManager?.disconnectAll().catch(()=>{});let n=new Yv({servers:e,log:t.log,workspaceRoot:t.projectRoot,toolCatalog:t.toolCatalog});t.setManager(n),Ps(async()=>{await n.disconnectAll()}),t.setReady(n.connectAll().then(()=>{n.injectTools(),t.log.info(`[mcp] ${n.getToolCount()} tools from ${n.getConnectedServers().length} servers`)}).catch(r=>{t.log.warn(`[mcp] connection error: ${r instanceof Error?r.message:r}`)}))}function jEe(t,e){let n=t.getUserMcpConfigPath();if(!Qv.existsSync(n))return;let r;try{r=Qv.readFileSync(n,"utf8")}catch(o){e?.warn(`[mcp] cannot read user MCP config at ${n}: ${o instanceof Error?o.message:o}`);return}try{return JSON.parse(r.replace(/^\uFEFF/,""))}catch(o){e?.warn(`[mcp] failed to parse user MCP config at ${n} \u2014 all its servers will be skipped: ${o instanceof Error?o.message:o}`);return}}function LEe(t){let e=UZ(GE(t.turnMcpConfig??{}),t.projectRoot),n=UZ(GE(t.userMcpConfig??{}),t.projectRoot),r=new Set(e.map(o=>o.name));return[...e,...n.filter(o=>!r.has(o.name))]}function UZ(t,e){return t.map(n=>(n.type??"stdio")!=="stdio"||n.cwd?n:{...n,cwd:e})}import*as GZ from"node:fs";import*as uo from"node:fs";import*as sp from"node:path";import{pathToFileURL as UEe}from"node:url";var HZ={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var eb=class{constructor(e){this.config=e;this.log=e.log??{info:()=>{},warn:()=>{}}}config;loaded=[];pluginSkills=[];activations=new Map;log;async loadAll(){for(let e of this.config.pluginDirs){if(!uo.existsSync(e))continue;let n;try{n=uo.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let r of n){if(!r.isDirectory()||r.name.startsWith(".")||r.name.startsWith("_"))continue;let o=sp.join(e,r.name);await this.loadPlugin(r.name,o)}}return this.log.info(`[plugins] loaded ${this.loaded.length} plugin(s): ${this.loaded.map(e=>e.name).join(", ")||"(none)"}`),this.loaded}getPluginSkills(){return this.pluginSkills}getLoaded(){return this.loaded}async discoverNew(){let e=new Set(this.loaded.map(r=>r.name)),n=0;for(let r of this.config.pluginDirs){if(!uo.existsSync(r))continue;let o;try{o=uo.readdirSync(r,{withFileTypes:!0})}catch{continue}for(let i of o){if(!i.isDirectory()||i.name.startsWith(".")||i.name.startsWith("_")||e.has(i.name))continue;let s=sp.join(r,i.name);await this.loadPlugin(i.name,s),n++}}return n>0&&this.log.info(`[plugins] discovered ${n} new plugin(s)`),n}async refreshActivations(){let e=Date.now();for(let[n,r]of this.activations){if(e-r.lastCheckAt<r.ttlMs)continue;let o;try{o=await r.checkFn()}catch(i){this.log.warn(`[plugins] ${n}: check_fn error: ${i instanceof Error?i.message:i}`),o=r.lastResult}if(r.lastCheckAt=e,o!==r.lastResult){if(r.lastResult=o,o&&!r.active){for(let i of r.tools)this.addRegisteredTool(i);r.active=!0,this.log.info(`[plugins] ${n}: reactivated (${r.tools.length} tools)`)}else if(!o&&r.active){for(let i of r.tools)this.removeRegisteredTool(i.name);for(let i of r.hookUnregisterFns)i();r.active=!1,this.log.info(`[plugins] ${n}: deactivated`)}}}}async loadPlugin(e,n){let r=["index.js","index.mjs"],o=null;for(let h of r){let y=sp.join(n,h);if(uo.existsSync(y)){o=y;break}}if(!o){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let i=0,s=0,a=0,c=[],l=[],d=null,p=6e4,m={},f=sp.join(n,"config.json");if(uo.existsSync(f))try{m=JSON.parse(uo.readFileSync(f,"utf8"))}catch{}let g={pluginName:e,registerTool:h=>{this.addRegisteredTool(h),c.push(h),i++},registerHook:(h,y)=>{let b=HZ[h];if(!b){this.log.warn(`[plugins] ${e}: unknown hook phase "${h}"`);return}let v=this.config.hookRegistry.register({point:b,handler:y,label:`plugin:${e}:${h}`,priority:200});l.push(v),s++},registerSkill:h=>{this.pluginSkills.push(h),a++},getConfig:()=>m,setActivationCheck:(h,y)=>{d=h,y!==void 0&&(p=y)}};try{let y=await import(UEe(o).href);if(typeof y.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await y.register(g),d&&this.activations.set(e,{checkFn:d,ttlMs:p,lastCheckAt:Date.now(),lastResult:!0,directory:n,tools:c,hookUnregisterFns:l,active:!0}),this.loaded.push({name:e,directory:n,toolCount:i,hookCount:s,skillCount:a}),this.log.info(`[plugins] ${e}: ${i} tools, ${s} hooks, ${a} skills`)}catch(h){this.log.warn(`[plugins] ${e}: load error: ${h instanceof Error?h.message:h}`)}}addRegisteredTool(e){this.config.toolCatalog?this.config.toolCatalog.addTool(e):ZB(e)}removeRegisteredTool(e){return this.config.toolCatalog?.removeTool(e)??vh(e)}};Ke();import*as At from"node:fs";import*as ap from"node:path";function KE(){return ee().getUserPluginCacheDir()}function BZ(){return ap.join(KE(),"installed_plugins.json")}function qZ(){let t=BZ();if(!At.existsSync(t))return{version:1,plugins:[]};try{return JSON.parse(At.readFileSync(t,"utf-8"))}catch{return{version:1,plugins:[]}}}function FEe(t){let e=KE();At.existsSync(e)||At.mkdirSync(e,{recursive:!0}),At.writeFileSync(BZ(),JSON.stringify(t,null,2),"utf-8")}function HEe(t,e){return!(e.blocklist?.includes(t)||e.allowlist&&!e.allowlist.includes(t))}function zZ(t,e){return t?{file:t.nodeExe,argv:[t.npmCli,...e],env:_i(t)}:{file:"npm",argv:e}}async function zEe(t,e,n){let{execFile:r}=await import("node:child_process"),{promisify:o}=await import("node:util"),i=o(r),s=KE(),a=e?`${t}@${e}`:t,c=Ii();try{let l=zZ(c,["pack",a,"--pack-destination",s]),{stdout:d}=await i(l.file,l.argv,{timeout:6e4,cwd:s,windowsHide:!0,...l.env?{env:l.env}:{}}),p=d.trim().split(`
1539
+ `).pop()?.trim();if(!p)return n.warn(`[marketplace] npm pack returned no output for ${a}`),null;let m=ap.join(s,p),g=p.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",h=ap.join(s,`${t}@${g}`);At.existsSync(h)||At.mkdirSync(h,{recursive:!0}),await i("tar",["xzf",m,"-C",h,"--strip-components=1"],{timeout:3e4,windowsHide:!0});try{At.unlinkSync(m)}catch{}let y=ap.join(h,"package.json");if(At.existsSync(y))try{let b=zZ(c,["install","--production","--no-save"]);await i(b.file,b.argv,{cwd:h,timeout:12e4,windowsHide:!0,...b.env?{env:b.env}:{}})}catch(b){n.warn(`[marketplace] npm install for ${t} failed: ${b.message}`)}return n.info(`[marketplace] installed ${t}@${g} from npm`),{name:t,version:g,installPath:h}}catch(l){return n.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function BEe(){return qZ().plugins.filter(e=>At.existsSync(e.installPath)).map(e=>e.installPath)}async function qEe(t,e){let n=qZ(),r=[];for(let o of t.enabledPlugins){let i=o.specifier.split("/").pop()??o.specifier;if(!HEe(i,t)){e.warn(`[marketplace] plugin "${i}" blocked by enterprise policy`);continue}let s=n.plugins.find(c=>c.source.specifier===o.specifier&&c.source.type===o.type);if(s&&At.existsSync(s.installPath)&&(!o.version||s.version===o.version)){r.push(s.installPath);continue}let a=null;switch(o.type){case"npm":a=await zEe(o.specifier,o.version,e);break;case"git":case"url":e.warn(`[marketplace] ${o.type} source not yet implemented for "${o.specifier}"`);break}if(a){let c={name:a.name,version:a.version,source:o,installPath:a.installPath,installedAt:new Date().toISOString()};n.plugins=n.plugins.filter(l=>!(l.source.specifier===o.specifier&&l.source.type===o.type)),n.plugins.push(c),r.push(a.installPath)}}return FEe(n),r}function WEe(){let t=ee().getUserMarketplaceConfigPath();if(!At.existsSync(t))return null;try{return JSON.parse(At.readFileSync(t,"utf-8"))}catch{return null}}async function WZ(t,e){let n=[...t],r=BEe();n.push(...r);let o=WEe();if(o&&o.enabledPlugins.length>0)try{let i=await qEe(o,e),s=new Set(n);for(let a of i)s.has(a)||n.push(a)}catch(i){e.warn(`[marketplace] failed to update plugins: ${i.message}`)}return n}var GEe={id:"plugin-tools",kind:"plugin",register:KEe};function KZ(t){GEe.register(t)}function KEe(t){let e=VEe(t.config,t.pathService);WZ(e,t.log).then(n=>{if(n.length===0)return;let r=new eb({pluginDirs:n,hookRegistry:t.hooks,log:t.log,toolCatalog:t.toolCatalog});t.setPluginLoader(r),r.loadAll().then(o=>{t.log.info(`[plugins] ${o.length} loaded, ${r.getPluginSkills().length} skills`)}).catch(o=>{t.log.warn(`[plugins] load error: ${o instanceof Error?o.message:o}`)}),t.hooks.register({point:"turn.submitted",handler:async()=>(await r.discoverNew(),await r.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(n=>{t.log.warn(`[plugins] marketplace resolve error: ${n instanceof Error?n.message:n}`)})}function VEe(t,e){let n=[],r=s=>{!s||!GZ.existsSync(s)||n.includes(s)||n.push(s)},o=e.getUserPluginsDir();r(o),r(e.getProjectPluginsDir(e.getActiveProjectRoot()));let i=t.pluginPaths;if(Array.isArray(i))for(let s of i)typeof s=="string"&&r(s);return n}async function VZ(t,e){let n=e.getAcpPermissionSession();if(n)try{let r=su(t.category??"destructive").map(i=>({optionId:i.optionId,name:i.name,kind:i.kind})),o=await n.requestPermission({sessionId:n.sessionId,permissionId:t.approvalId,toolCall:{toolCallId:t.callId,title:t.toolName,rawInput:t.arguments??{}},message:t.message,category:t.category,options:r});return JZ(t,o.optionId)}catch{return{approvalId:t.approvalId,decision:"deny"}}if(e.sendNotification("tool.approval.request",{approvalId:t.approvalId,callId:t.callId,toolName:t.toolName,arguments:t.arguments?JSON.stringify(t.arguments):"",message:t.message,category:t.category,reason:t.message,options:su(t.category??"destructive"),rememberScope:t.rememberScope}),e.isPetActive()){let r=JEe(t.toolName);e.sendNotification("pet.confirm",{confirmId:t.approvalId,toolName:t.toolName,description:t.message??`Allow ${t.toolName}`,risk:r,timeoutMs:3e4})}return new Promise(()=>{})}function JEe(t){return t.match(/exec|bash|shell|terminal|run_command|reset|force|drop/i)?"system":t.match(/web|http|fetch|mcp|media|image|video|music|tts/i)?"external_egress":t.match(/write|delete|rm|move|patch|edit|create/i)?"write":"read"}function JZ(t,e){let n=su(t.category??"destructive").find(r=>r.optionId===e);return!n||n.kind.startsWith("reject")?{approvalId:t.approvalId,decision:"deny"}:{approvalId:t.approvalId,decision:"allow",scope:n.scope}}function ZZ(t){let e=Ku(t.config.permissions),n=b8(e);if(mm()){let o=$1();for(let i of o)n.addRule(i);Rh(!0),t.log.info(`[permissions] group security mode active: ${o.length} rules injected`)}else Rh(!1);t.currentUnregister?.();let r=k8({ruleEngine:n,hookRegistry:t.hooks,getWorkspaceRoot:t.getActiveWorkdir,auditLogger:new Yy(t.getActiveProjectRoot()),sessionId:t.sessionId,getTurnId:t.getTurnId,onRequestApproval:o=>VZ(o,t),onDenied:(o,i)=>{t.log.warn(`[permissions] blocked "${o}": ${i}`)}});return r.setToolMeta(t.toolCatalog.getToolManifest()),D2(()=>({mode:n.getMode(),workdir:t.getActiveWorkdir(),allowedDirs:n.getAllowedWriteDirectories()})),{permissionChecker:r,permissionUnregister:r.register(),ruleEngine:n}}function VE(t){let e=new Map;return{register(n){let r=e.get(n.point)??[],o={handler:n.handler,priority:n.priority??100,label:n.label,critical:n.critical};return r.push(o),r.sort((i,s)=>i.priority-s.priority),e.set(n.point,r),()=>{let i=r.indexOf(o);i>=0&&r.splice(i,1)}},async invoke(n,r){let o=e.get(n);if(!o||o.length===0)return{action:"continue",context:r};let i=r;for(let s of o)try{let a=await s.handler(n,i);if(!a||a.action==="continue"){a?.context&&(i=a.context);continue}if(a.action==="abort"||a.action==="skip")return t.info({hook:n,label:s.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){if(s.critical){let c=a instanceof Error?a.message:String(a),d=`critical hook ${s.label??n} failed: ${c}`;return t.warn({hook:n,label:s.label,err:c},"critical hook handler failed (blocking)"),{action:"abort",reason:d}}t.warn({hook:n,label:s.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:i}}}}si();function XZ(t,e){return t.register({point:"memory.before_recall",priority:60,label:"community-discovery",handler:async(n,r)=>{let o=r.query;if(!o)return{action:"continue",context:r};let i=await ZEe(o,e);return i?{action:"continue",context:{...r,recalledMemories:[...r.recalledMemories??[],XEe(i)]}}:{action:"continue",context:r}}})}async function ZEe(t,e){if(!e.communityDiscovery)return null;let n=await e.communityDiscovery.matchForTurn(t);return n.status==="matched"||n.status==="cached"?n:(n.status==="unavailable"&&e.log.debug(`community-discovery: unavailable (${n.error??"unknown"})`),null)}function XEe(t){let e=t.match,n=t.cacheEntry,r=e?.id??n?.resourceId??"",o=e?.title??n?.title??r,i=e?.summary??n?.summary??"",s=e?.sourceTier??n?.sourceTier??"community",a=e?.effectiveRiskTier??n?.effectiveRiskTier??"unknown";return{text:[`[Community skill available] "${o}" (${r})`,`Summary: ${i}`,`Source: ${s}; effective risk: ${a}`,"Use community.resolveInstall before any install. Do not inject or execute package contents from discovery."].join(`
1540
1540
  `),source:"community",label:"Community",score:t.status==="matched"?.74:.68}}Kh();function YZ(t){let e=VE(t.log);t.taskStore.setHooks(e,t.sessionId),O2(t.backgroundTasks),N2({onTaskCreated:r=>{e.invoke("task.created",{sessionId:t.sessionId,taskId:String(r.id),taskType:"planning",label:r.title}).catch(()=>{})},onTaskCompleted:r=>{e.invoke("task.completed",{sessionId:t.sessionId,taskId:String(r.id),taskType:"planning",label:r.title}).catch(()=>{})}});let n=__({hooks:e,currentUserId:t.currentUserId,log:t.log,prefetchState:t.prefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient});return XZ(e,{communityDiscovery:new Bc({client:Rc()}),log:{debug:r=>t.log.debug(r),warn:r=>t.log.warn(r)}}),aO(e,t.log,{transport:t.compressionClient.transport,apiKey:t.compressionClient.apiKey}),C_({memdir:t.memdir,getMemdir:()=>t.getMemdir?.()??t.memdir,memoryProvider:n.toolProvider,memoryUserId:n.userId,toolCatalog:t.toolCatalog,sendNotification:t.sendNotification}),q0(e,{getMemorySource:()=>t.getMemdir?.()??t.memdir,log:{debug:r=>t.log.debug(r),warn:r=>t.log.warn(r)}},t.prefetchState),{hooks:e,memoryHandlerProvider:n.handlerProvider,memoryDreamProvider:n.dreamProvider,memoryLearningSink:n.learningSink,memoryUserId:n.userId}}de();import{watch as YEe}from"node:fs";import{stat as QEe}from"node:fs/promises";import{join as QZ,relative as eMe,resolve as tMe}from"node:path";var nMe=[`${ko}/settings.json`,"INSTRUCTIONS.md",`${ko}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${ko}/rules`],rMe=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${ko}/rules`],JE=class{watchers=new Map;deps;debounceTimers=new Map;_cwd;constructor(e){this.deps=e,this._cwd=e.projectRoot}get cwd(){return this._cwd}async start(){for(let e of nMe){let n=QZ(this.deps.projectRoot,e);this.watchPath(n,e)}this.deps.log?.(`file-watcher: watching ${this.watchers.size} paths`)}watchPath(e,n){if(!this.watchers.has(e))try{let r=YEe(e,{persistent:!1,recursive:n.includes("/")?!1:void 0},(o,i)=>{let s=i?QZ(e,i):e;this.handleChange(s,o==="rename"?"created":"modified")});r.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,r)}catch{}}handleChange(e,n){let r=this.debounceTimers.get(e);r&&clearTimeout(r),this.debounceTimers.set(e,setTimeout(async()=>{this.debounceTimers.delete(e);let o=n;try{await QEe(e)}catch{o="deleted"}let i=eMe(this.deps.projectRoot,e);this.deps.log?.(`file-watcher: ${o} ${i}`),this.deps.hooks.invoke("file.changed",{sessionId:this.deps.sessionId,filePath:e,changeType:o}).catch(()=>{}),rMe.some(a=>i.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let n=tMe(e);if(n===this._cwd)return;let r=this._cwd;this._cwd=n,this.deps.hooks.invoke("cwd.changed",{sessionId:this.deps.sessionId,oldCwd:r,newCwd:n}).catch(()=>{}),this.deps.onInstructionCacheReset?.()}stop(){for(let[,e]of this.watchers)e.close();this.watchers.clear();for(let[,e]of this.debounceTimers)clearTimeout(e);this.debounceTimers.clear()}};async function eX(t){let e=new JE(t);return await e.start(),e}Ke();import{watch as oMe}from"node:fs";import{readFile as iMe}from"node:fs/promises";function sMe(t){return ee().getProjectSettingsPath(t)}async function aMe(t){try{let e=await iMe(t,"utf-8");return JSON.parse(e)}catch{return null}}function cMe(t,e,n,r){let o=!1,i=lMe(t);i&&(i.mode!==e.getMode()&&(e.setMode(i.mode),r?.(`settings: permission mode -> ${i.mode}`),o=!0),dMe(i.rules,e.getRules())||(e.replaceRules(i.rules),r?.(`settings: ${i.rules.length} permission rules loaded`),o=!0),o&&n&&n.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:t}).catch(()=>{}))}function tX(t){let e=sMe(t.projectRoot),n=null,r=null,o=async()=>{let i=await aMe(e);i&&cMe(i,t.ruleEngine,t.hooks,t.log)};o().catch(()=>{});try{n=oMe(e,{persistent:!1},()=>{r&&clearTimeout(r),r=setTimeout(()=>{o().catch(()=>{})},200)}),n.on("error",()=>{})}catch{}return()=>{r&&clearTimeout(r),n?.close(),n=null}}function lMe(t){return uMe(t),t.permissions&&typeof t.permissions=="object"?tv(t.permissions):null}function dMe(t,e){return t.length!==e.length?!1:t.every((n,r)=>{let o=e[r];return!!o&&n.pattern===o.pattern&&n.behavior===o.behavior&&n.reason===o.reason&&n.source===o.source})}function uMe(t){let e=t,n={permissionMode:"permissions.mode",permissionRules:"permissions.rules",defaultBehavior:"permissions.defaultBehavior"};for(let[r,o]of Object.entries(n))if(r in e)throw new Error(`Legacy top-level ${r} is not supported; use ${o}`)}function nX(t){let e=typeof t.config.workdir=="string"?t.config.workdir:process.cwd(),n=tX({projectRoot:e,ruleEngine:t.ruleEngine,hooks:t.hooks,log:r=>t.log.info(`[settings] ${r}`)});Ps(async()=>{n()}),t.currentFileWatcher?.stop(),t.setFileWatcher(null),eX({projectRoot:e,sessionId:t.sessionId,hooks:t.hooks,log:r=>t.log.debug(r),onInstructionCacheReset:d5}).then(r=>{t.setFileWatcher(r),Ps(async()=>{r.stop()})}).catch(r=>{t.log.warn(`[file-watcher] init error: ${r instanceof Error?r.message:r}`)})}import*as $t from"node:fs";import*as rn from"node:path";var pMe="skill_view",mMe="skills_list",fMe="skill_manage",gMe={type:"object",properties:{name:{type:"string",description:"The skill to use. For a matching workflow, call skill_view before read/search/exec/MCP. Calling skill_view(name='X') loads that skill and you follow its instructions in THIS turn - that single call is all you need to USE a skill."},args:{type:"string",description:"Optional context/arguments to pass to the skill."},filePath:{type:"string",description:"Optional path of a supporting file inside the skill folder to read instead of running the skill (e.g. a reference doc or script). When omitted, the skill is loaded and run."}},required:["name"]},hMe={type:"object",properties:{category:{type:"string",description:"Optional category filter."}},required:[]},yMe={type:"object",properties:{action:{type:"string",enum:["create","edit","patch","delete","promote"],description:["The authoring operation to perform:","\u2022 'create' \u2014 save a new skill (provide 'name' + 'content', optional supporting 'filePath'+'fileContent').","\u2022 'edit' \u2014 replace a skill's SKILL.md ('content') or a supporting file ('filePath'+'fileContent').","\u2022 'patch' \u2014 find/replace inside SKILL.md ('oldString' + 'newString').","\u2022 'delete' \u2014 remove a skill ('name').","\u2022 'promote' \u2014 enable a skill globally so it's available across all projects ('name')."].join(`
1541
1541
  `)},name:{type:"string",description:"The skill name to author or manage."},category:{type:"string",description:"Classification for create/edit \u2014 pick the ONE best-fitting label from: efficiency, dev, writing, data, search, automation, knowledge, lifestyle. Drives the skill card's color/tag on the plugins page."},content:{type:"string",description:"Full SKILL.md content for create/edit actions."},filePath:{type:"string",description:"Path of a file inside the skill folder to write with fileContent (create/edit). SKILL.md itself always goes through 'content'."},fileContent:{type:"string",description:"Supporting file content. With filePath, writes that file inside the skill folder."},oldString:{type:"string",description:"Text to find for the patch action."},newString:{type:"string",description:"Replacement text for the patch action."}},required:["action","name"]};function rX(t){return{name:pMe,label:"Skill View",category:"system",riskLevel:"read",isReadOnly:!0,description:"Use a skill - a reusable workflow or domain-knowledge package. Call skill_view(name='X') and it loads that skill so you follow its instructions in THIS turn. For a matching workflow, skill_view should be the first tool call; do not inspect the workspace first just to decide whether the skill applies. That single call is all you need - you do NOT have to list skills first. Pass optional 'args' for context. To read a supporting file inside the skill folder without running it, pass 'filePath'.",parameters:gMe,isConcurrencySafe:!1,searchHint:"skill invoke run execute use named slash-command view \u8FD0\u884C\u6280\u80FD \u8C03\u7528\u6280\u80FD \u4F7F\u7528\u6280\u80FD",execute:async(e,n,r)=>{let{name:o,args:i,filePath:s}=n;if(!o)return{content:[{type:"text",text:`Error: 'name' is required. Available skills: ${t.listSkills().map(l=>l.name).join(", ")||"(none)"}`}]};if(s){let c=await t.viewSkill(o,s);return c?{content:[{type:"text",text:`## Skill: ${c.name} \u2014 ${s}
1542
1542