qlogicagent 2.12.4 → 2.12.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -607,7 +607,7 @@ ${R}`})}}ut(this.hooks,"memory.after_recall",{sessionId:e.sessionId,turnId:n,blo
607
607
 
608
608
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let p=d[1];if(e===d[0]){s(d);continue}if(n.external){let g=n.external.registry.get(d[0])?.id;if(e!==d[0]&&g){s(d);continue}}if(this.metadataRegistry.get(d[0])?.id){s(d);continue}if(p.cycle){s(d);continue}if(p.count>1&&n.reused==="ref"){s(d);continue}}let a=(d,p)=>{let m=this.seen.get(d),g=m.def??m.schema,f={...g};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,p);let y=this.seen.get(h).schema;y.$ref&&p.target==="draft-7"?(g.allOf=g.allOf??[],g.allOf.push(y)):(Object.assign(g,y),Object.assign(g,f))}m.isParent||this.override({zodSchema:d,jsonSchema:g,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let p=d[1];p.def&&p.defId&&(u[p.defId]=p.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function vy(t,e){if(t instanceof Vo){let n=new Cs(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let i={},s={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;i[c]=n.emit(u,{...e,external:s})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[a]:o}}return{schemas:i}}let r=new Cs(e);return r.process(t),r.emit(t,e)}function Le(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Le(o.element,r);case"object":{for(let i in o.shape)if(Le(o.shape[i],r))return!0;return!1}case"union":{for(let i of o.options)if(Le(i,r))return!0;return!1}case"intersection":return Le(o.left,r)||Le(o.right,r);case"tuple":{for(let i of o.items)if(Le(i,r))return!0;return!!(o.rest&&Le(o.rest,r))}case"record":return Le(o.keyType,r)||Le(o.valueType,r);case"map":return Le(o.keyType,r)||Le(o.valueType,r);case"set":return Le(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Le(o.innerType,r);case"lazy":return Le(o.getter(),r);case"default":return Le(o.innerType,r);case"prefault":return Le(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Le(o.in,r)||Le(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var qT={};var il={};qt(il,{ZodISODate:()=>rl,ZodISODateTime:()=>tl,ZodISODuration:()=>ol,ZodISOTime:()=>nl,date:()=>ky,datetime:()=>by,duration:()=>Sy,time:()=>wy});var tl=T("ZodISODateTime",(t,e)=>{Lf.init(t,e),ye.init(t,e)});function by(t){return Nh(tl,t)}var rl=T("ZodISODate",(t,e)=>{Uf.init(t,e),ye.init(t,e)});function ky(t){return $h(rl,t)}var nl=T("ZodISOTime",(t,e)=>{Ff.init(t,e),ye.init(t,e)});function wy(t){return Oh(nl,t)}var ol=T("ZodISODuration",(t,e)=>{Hf.init(t,e),ye.init(t,e)});function Sy(t){return jh(ol,t)}var GT=(t,e)=>{ss.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>cs(t,r)},flatten:{value:r=>as(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},KW=T("ZodError",GT),Qo=T("ZodError",GT,{Parent:Error});var xy=yc(Qo),Ry=bc(Qo),Ty=wc(Qo),Py=Sc(Qo);var J=T("ZodType",(t,e)=>(K.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Dt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>xy(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ty(t,r,n),t.parseAsync=async(r,n)=>Ry(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Py(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(DP(r,n)),t.superRefine=r=>t.check(NP(r)),t.overwrite=r=>t.check(Wr(r)),t.optional=()=>cl(t),t.nullable=()=>ll(t),t.nullish=()=>cl(ll(t)),t.nonoptional=r=>wP(t,r),t.array=()=>Vy(t),t.or=r=>gl([t,r]),t.and=r=>aP(t,r),t.transform=r=>ul(t,Yy(r)),t.default=r=>vP(t,r),t.prefault=r=>kP(t,r),t.catch=r=>RP(t,r),t.pipe=r=>ul(t,r),t.readonly=()=>AP(t),t.describe=r=>{let n=t.clone();return Sr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Sr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Sr.get(t);let n=t.clone();return Sr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Cy=T("_ZodString",(t,e)=>{Jn.init(t,e),J.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(ys(...n)),t.includes=(...n)=>t.check(ks(...n)),t.startsWith=(...n)=>t.check(ws(...n)),t.endsWith=(...n)=>t.check(Ss(...n)),t.min=(...n)=>t.check(un(...n)),t.max=(...n)=>t.check(Xo(...n)),t.length=(...n)=>t.check(Yo(...n)),t.nonempty=(...n)=>t.check(un(1,...n)),t.lowercase=n=>t.check(vs(n)),t.uppercase=n=>t.check(bs(n)),t.trim=()=>t.check(Ts()),t.normalize=(...n)=>t.check(Rs(...n)),t.toLowerCase=()=>t.check(Ps()),t.toUpperCase=()=>t.check(As())}),Es=T("ZodString",(t,e)=>{Jn.init(t,e),Cy.init(t,e),t.email=r=>t.check(Dc(_y,r)),t.url=r=>t.check(Lc(Ey,r)),t.jwt=r=>t.check(Qc(Gy,r)),t.emoji=r=>t.check(Uc(My,r)),t.guid=r=>t.check(fs(sl,r)),t.uuid=r=>t.check(Nc(Kr,r)),t.uuidv4=r=>t.check($c(Kr,r)),t.uuidv6=r=>t.check(Oc(Kr,r)),t.uuidv7=r=>t.check(jc(Kr,r)),t.nanoid=r=>t.check(Fc(Dy,r)),t.guid=r=>t.check(fs(sl,r)),t.cuid=r=>t.check(Hc(Ny,r)),t.cuid2=r=>t.check(zc($y,r)),t.ulid=r=>t.check(Bc(Oy,r)),t.base64=r=>t.check(Jc(By,r)),t.base64url=r=>t.check(Xc(qy,r)),t.xid=r=>t.check(qc(jy,r)),t.ksuid=r=>t.check(Wc(Ly,r)),t.ipv4=r=>t.check(Gc(Uy,r)),t.ipv6=r=>t.check(Kc(Fy,r)),t.cidrv4=r=>t.check(Vc(Hy,r)),t.cidrv6=r=>t.check(Zc(zy,r)),t.e164=r=>t.check(Yc(Wy,r)),t.datetime=r=>t.check(by(r)),t.date=r=>t.check(ky(r)),t.time=r=>t.check(wy(r)),t.duration=r=>t.check(Sy(r))});function Ay(t){return Eh(Es,t)}var ye=T("ZodStringFormat",(t,e)=>{fe.init(t,e),Cy.init(t,e)}),_y=T("ZodEmail",(t,e)=>{Cf.init(t,e),ye.init(t,e)});function ZW(t){return Dc(_y,t)}var sl=T("ZodGUID",(t,e)=>{Af.init(t,e),ye.init(t,e)});function JW(t){return fs(sl,t)}var Kr=T("ZodUUID",(t,e)=>{If.init(t,e),ye.init(t,e)});function XW(t){return Nc(Kr,t)}function YW(t){return $c(Kr,t)}function QW(t){return Oc(Kr,t)}function e2(t){return jc(Kr,t)}var Ey=T("ZodURL",(t,e)=>{_f.init(t,e),ye.init(t,e)});function t2(t){return Lc(Ey,t)}var My=T("ZodEmoji",(t,e)=>{Ef.init(t,e),ye.init(t,e)});function r2(t){return Uc(My,t)}var Dy=T("ZodNanoID",(t,e)=>{Mf.init(t,e),ye.init(t,e)});function n2(t){return Fc(Dy,t)}var Ny=T("ZodCUID",(t,e)=>{Df.init(t,e),ye.init(t,e)});function o2(t){return Hc(Ny,t)}var $y=T("ZodCUID2",(t,e)=>{Nf.init(t,e),ye.init(t,e)});function i2(t){return zc($y,t)}var Oy=T("ZodULID",(t,e)=>{$f.init(t,e),ye.init(t,e)});function s2(t){return Bc(Oy,t)}var jy=T("ZodXID",(t,e)=>{Of.init(t,e),ye.init(t,e)});function a2(t){return qc(jy,t)}var Ly=T("ZodKSUID",(t,e)=>{jf.init(t,e),ye.init(t,e)});function c2(t){return Wc(Ly,t)}var Uy=T("ZodIPv4",(t,e)=>{zf.init(t,e),ye.init(t,e)});function l2(t){return Gc(Uy,t)}var Fy=T("ZodIPv6",(t,e)=>{Bf.init(t,e),ye.init(t,e)});function u2(t){return Kc(Fy,t)}var Hy=T("ZodCIDRv4",(t,e)=>{qf.init(t,e),ye.init(t,e)});function d2(t){return Vc(Hy,t)}var zy=T("ZodCIDRv6",(t,e)=>{Wf.init(t,e),ye.init(t,e)});function p2(t){return Zc(zy,t)}var By=T("ZodBase64",(t,e)=>{Kf.init(t,e),ye.init(t,e)});function m2(t){return Jc(By,t)}var qy=T("ZodBase64URL",(t,e)=>{Vf.init(t,e),ye.init(t,e)});function g2(t){return Xc(qy,t)}var Wy=T("ZodE164",(t,e)=>{Zf.init(t,e),ye.init(t,e)});function f2(t){return Yc(Wy,t)}var Gy=T("ZodJWT",(t,e)=>{Jf.init(t,e),ye.init(t,e)});function h2(t){return Qc(Gy,t)}var KT=T("ZodCustomStringFormat",(t,e)=>{Xf.init(t,e),ye.init(t,e)});function y2(t,e,r={}){return hy(KT,t,e,r)}var Ms=T("ZodNumber",(t,e)=>{Ic.init(t,e),J.init(t,e),t.gt=(n,o)=>t.check(qr(n,o)),t.gte=(n,o)=>t.check(vt(n,o)),t.min=(n,o)=>t.check(vt(n,o)),t.lt=(n,o)=>t.check(Br(n,o)),t.lte=(n,o)=>t.check(Kt(n,o)),t.max=(n,o)=>t.check(Kt(n,o)),t.int=n=>t.check(Iy(n)),t.safe=n=>t.check(Iy(n)),t.positive=n=>t.check(qr(0,n)),t.nonnegative=n=>t.check(vt(0,n)),t.negative=n=>t.check(Br(0,n)),t.nonpositive=n=>t.check(Kt(0,n)),t.multipleOf=(n,o)=>t.check(Yn(n,o)),t.step=(n,o)=>t.check(Yn(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function VT(t){return Lh(Ms,t)}var ei=T("ZodNumberFormat",(t,e)=>{Yf.init(t,e),Ms.init(t,e)});function Iy(t){return Fh(ei,t)}function v2(t){return Hh(ei,t)}function b2(t){return zh(ei,t)}function k2(t){return Bh(ei,t)}function w2(t){return qh(ei,t)}var Ds=T("ZodBoolean",(t,e)=>{us.init(t,e),J.init(t,e)});function ZT(t){return Wh(Ds,t)}var Ns=T("ZodBigInt",(t,e)=>{Cc.init(t,e),J.init(t,e),t.gte=(n,o)=>t.check(vt(n,o)),t.min=(n,o)=>t.check(vt(n,o)),t.gt=(n,o)=>t.check(qr(n,o)),t.gte=(n,o)=>t.check(vt(n,o)),t.min=(n,o)=>t.check(vt(n,o)),t.lt=(n,o)=>t.check(Br(n,o)),t.lte=(n,o)=>t.check(Kt(n,o)),t.max=(n,o)=>t.check(Kt(n,o)),t.positive=n=>t.check(qr(BigInt(0),n)),t.negative=n=>t.check(Br(BigInt(0),n)),t.nonpositive=n=>t.check(Kt(BigInt(0),n)),t.nonnegative=n=>t.check(vt(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(Yn(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function S2(t){return Kh(Ns,t)}var Ky=T("ZodBigIntFormat",(t,e)=>{Qf.init(t,e),Ns.init(t,e)});function x2(t){return Zh(Ky,t)}function R2(t){return Jh(Ky,t)}var JT=T("ZodSymbol",(t,e)=>{eh.init(t,e),J.init(t,e)});function T2(t){return Xh(JT,t)}var XT=T("ZodUndefined",(t,e)=>{th.init(t,e),J.init(t,e)});function P2(t){return Yh(XT,t)}var YT=T("ZodNull",(t,e)=>{rh.init(t,e),J.init(t,e)});function QT(t){return Qh(YT,t)}var eP=T("ZodAny",(t,e)=>{nh.init(t,e),J.init(t,e)});function A2(){return ey(eP)}var tP=T("ZodUnknown",(t,e)=>{Ko.init(t,e),J.init(t,e)});function al(){return Zo(tP)}var rP=T("ZodNever",(t,e)=>{oh.init(t,e),J.init(t,e)});function dl(t){return ty(rP,t)}var nP=T("ZodVoid",(t,e)=>{ih.init(t,e),J.init(t,e)});function I2(t){return ry(nP,t)}var pl=T("ZodDate",(t,e)=>{sh.init(t,e),J.init(t,e),t.min=(n,o)=>t.check(vt(n,o)),t.max=(n,o)=>t.check(Kt(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function C2(t){return ny(pl,t)}var oP=T("ZodArray",(t,e)=>{ds.init(t,e),J.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(un(r,n)),t.nonempty=r=>t.check(un(1,r)),t.max=(r,n)=>t.check(Xo(r,n)),t.length=(r,n)=>t.check(Yo(r,n)),t.unwrap=()=>t.element});function Vy(t,e){return Is(oP,t,e)}function _2(t){let e=t._zod.def.shape;return gP(Object.keys(e))}var ml=T("ZodObject",(t,e)=>{ah.init(t,e),J.init(t,e),$.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>pP(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:al()}),t.loose=()=>t.clone({...t._zod.def,catchall:al()}),t.strict=()=>t.clone({...t._zod.def,catchall:dl()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>$.extend(t,r),t.merge=r=>$.merge(t,r),t.pick=r=>$.pick(t,r),t.omit=r=>$.omit(t,r),t.partial=(...r)=>$.partial(Qy,t,r[0]),t.required=(...r)=>$.required(ev,t,r[0])});function E2(t,e){let r={type:"object",get shape(){return $.assignProp(this,"shape",{...t}),this.shape},...$.normalizeParams(e)};return new ml(r)}function M2(t,e){return new ml({type:"object",get shape(){return $.assignProp(this,"shape",{...t}),this.shape},catchall:dl(),...$.normalizeParams(e)})}function D2(t,e){return new ml({type:"object",get shape(){return $.assignProp(this,"shape",{...t}),this.shape},catchall:al(),...$.normalizeParams(e)})}var Zy=T("ZodUnion",(t,e)=>{_c.init(t,e),J.init(t,e),t.options=e.options});function gl(t,e){return new Zy({type:"union",options:t,...$.normalizeParams(e)})}var iP=T("ZodDiscriminatedUnion",(t,e)=>{Zy.init(t,e),ch.init(t,e)});function N2(t,e,r){return new iP({type:"union",options:e,discriminator:t,...$.normalizeParams(r)})}var sP=T("ZodIntersection",(t,e)=>{lh.init(t,e),J.init(t,e)});function aP(t,e){return new sP({type:"intersection",left:t,right:e})}var cP=T("ZodTuple",(t,e)=>{Xn.init(t,e),J.init(t,e),t.rest=r=>t.clone({...t._zod.def,rest:r})});function $2(t,e,r){let n=e instanceof K,o=n?r:e,i=n?e:null;return new cP({type:"tuple",items:t,rest:i,...$.normalizeParams(o)})}var Jy=T("ZodRecord",(t,e)=>{uh.init(t,e),J.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function lP(t,e,r){return new Jy({type:"record",keyType:t,valueType:e,...$.normalizeParams(r)})}function O2(t,e,r){return new Jy({type:"record",keyType:gl([t,dl()]),valueType:e,...$.normalizeParams(r)})}var uP=T("ZodMap",(t,e)=>{dh.init(t,e),J.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function j2(t,e,r){return new uP({type:"map",keyType:t,valueType:e,...$.normalizeParams(r)})}var dP=T("ZodSet",(t,e)=>{ph.init(t,e),J.init(t,e),t.min=(...r)=>t.check(Qn(...r)),t.nonempty=r=>t.check(Qn(1,r)),t.max=(...r)=>t.check(Jo(...r)),t.size=(...r)=>t.check(hs(...r))});function L2(t,e){return new dP({type:"set",valueType:t,...$.normalizeParams(e)})}var _s=T("ZodEnum",(t,e)=>{mh.init(t,e),J.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new _s({...e,checks:[],...$.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new _s({...e,checks:[],...$.normalizeParams(o),entries:i})}});function pP(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new _s({type:"enum",entries:r,...$.normalizeParams(e)})}function U2(t,e){return new _s({type:"enum",entries:t,...$.normalizeParams(e)})}var mP=T("ZodLiteral",(t,e)=>{gh.init(t,e),J.init(t,e),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 gP(t,e){return new mP({type:"literal",values:Array.isArray(t)?t:[t],...$.normalizeParams(e)})}var fP=T("ZodFile",(t,e)=>{fh.init(t,e),J.init(t,e),t.min=(r,n)=>t.check(Qn(r,n)),t.max=(r,n)=>t.check(Jo(r,n)),t.mime=(r,n)=>t.check(xs(Array.isArray(r)?r:[r],n))});function F2(t){return py(fP,t)}var Xy=T("ZodTransform",(t,e)=>{ps.init(t,e),J.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push($.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),s.continue??(s.continue=!0),r.issues.push($.issue(s))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function Yy(t){return new Xy({type:"transform",transform:t})}var Qy=T("ZodOptional",(t,e)=>{hh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function cl(t){return new Qy({type:"optional",innerType:t})}var hP=T("ZodNullable",(t,e)=>{yh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ll(t){return new hP({type:"nullable",innerType:t})}function H2(t){return cl(ll(t))}var yP=T("ZodDefault",(t,e)=>{vh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function vP(t,e){return new yP({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var bP=T("ZodPrefault",(t,e)=>{bh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function kP(t,e){return new bP({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var ev=T("ZodNonOptional",(t,e)=>{kh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function wP(t,e){return new ev({type:"nonoptional",innerType:t,...$.normalizeParams(e)})}var SP=T("ZodSuccess",(t,e)=>{wh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function z2(t){return new SP({type:"success",innerType:t})}var xP=T("ZodCatch",(t,e)=>{Sh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function RP(t,e){return new xP({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var TP=T("ZodNaN",(t,e)=>{xh.init(t,e),J.init(t,e)});function B2(t){return iy(TP,t)}var tv=T("ZodPipe",(t,e)=>{ms.init(t,e),J.init(t,e),t.in=e.in,t.out=e.out});function ul(t,e){return new tv({type:"pipe",in:t,out:e})}var PP=T("ZodReadonly",(t,e)=>{Rh.init(t,e),J.init(t,e)});function AP(t){return new PP({type:"readonly",innerType:t})}var IP=T("ZodTemplateLiteral",(t,e)=>{Th.init(t,e),J.init(t,e)});function q2(t,e){return new IP({type:"template_literal",parts:t,...$.normalizeParams(e)})}var CP=T("ZodLazy",(t,e)=>{Ah.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.getter()});function _P(t){return new CP({type:"lazy",getter:t})}var EP=T("ZodPromise",(t,e)=>{Ph.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function W2(t){return new EP({type:"promise",innerType:t})}var fl=T("ZodCustom",(t,e)=>{Ih.init(t,e),J.init(t,e)});function MP(t){let e=new xe({check:"custom"});return e._zod.check=t,e}function G2(t,e){return my(fl,t??(()=>!0),e)}function DP(t,e={}){return gy(fl,t,e)}function NP(t){let e=MP(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push($.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push($.issue(o))}},t(r.value,r)));return e}function K2(t,e={error:`Input not instance of ${t.name}`}){let r=new fl({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...$.normalizeParams(e)});return r._zod.bag.Class=t,r}var V2=(...t)=>fy({Pipe:tv,Boolean:Ds,String:Es,Transform:Xy},...t);function Z2(t){let e=_P(()=>gl([Ay(t),VT(),ZT(),QT(),Vy(e),lP(Ay(),e)]));return e}function J2(t,e){return ul(Yy(t),e)}var X2={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 Y2(t){De({customError:t})}function Q2(){return De().customError}var rv={};qt(rv,{bigint:()=>nG,boolean:()=>rG,date:()=>oG,number:()=>tG,string:()=>eG});function eG(t){return Mh(Es,t)}function tG(t){return Uh(Ms,t)}function rG(t){return Gh(Ds,t)}function nG(t){return Vh(Ns,t)}function oG(t){return oy(pl,t)}De(Ec());var me={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"},Vt={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 $P=Symbol("skippedItem");function j(t,e){return t.catch(e)}function ir(t,e){let r=t.catch(e);return l.unknown().transform((n,o)=>n!==void 0?r.parse(n):(o.addIssue({code:"custom",message:"Required value is missing"}),l.NEVER))}function de(t){return l.array(t.catch($P)).transform(e=>e.filter(r=>r!==$P))}var sG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),terminal:l.boolean().optional().default(!1)}),aG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),label:l.string().nullish(),name:l.string(),optional:l.boolean().optional().default(!1),secret:l.boolean().optional().default(!0)}),cG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string().nullish(),id:l.string(),name:l.string()}),lG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string().nullish(),id:l.string(),link:l.string().nullish(),name:l.string(),vars:l.array(aG)}),uG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),args:l.array(l.string()).optional(),description:l.string().nullish(),env:l.record(l.string(),l.string()).optional(),id:l.string(),name:l.string()}),dG=l.union([lG.and(l.object({type:l.literal("env_var")})),uG.and(l.object({type:l.literal("terminal")})),cG]),OP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),methodId:l.string()}),pG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),mG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),blob:l.string(),mimeType:l.string().nullish(),uri:l.string()}),gG=l.object({default:l.boolean().nullish(),description:l.string().nullish(),title:l.string().nullish()}),fG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),hG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),yG=l.object({amount:l.number(),currency:l.string()}),vG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),terminalId:l.string()}),bG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),kG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),newText:l.string(),oldText:l.string().nullish(),path:l.string()}),jP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:l.string()}),wG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),SG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),xG=l.union([l.string(),l.number(),l.number(),l.boolean(),l.array(l.string())]),RG=l.object({content:l.record(l.string(),xG).nullish()}),TG=l.intersection(l.union([RG.and(l.object({action:l.literal("accept")})),l.object({action:l.literal("decline")}),l.object({action:l.literal("cancel")})]),l.object({_meta:l.record(l.string(),l.unknown()).nullish()})),PG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),LP=l.string(),ov=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),elicitationId:LP}),AG=l.literal("object"),IG=l.literal("string"),CG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),_G=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),form:j(PG.nullish(),()=>{}),url:j(CG.nullish(),()=>{})}),UP=l.object({const:l.string(),title:l.string()}),FP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),name:l.string(),value:l.string()}),EG=l.union([l.literal(-32700),l.literal(-32600),l.literal(-32601),l.literal(-32602),l.literal(-32603),l.literal(-32800),l.literal(-32e3),l.literal(-32002),l.literal(-32042),l.number().int().min(-2147483648,{message:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{message:"Invalid value: Expected int32 to be <= 2147483647"})]),HP=l.object({code:EG,data:l.unknown().optional(),message:l.string()}),zP=l.unknown(),BP=l.unknown(),qP=l.unknown(),MG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),readTextFile:l.boolean().optional().default(!1),writeTextFile:l.boolean().optional().default(!1)}),WP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),name:l.string(),value:l.string()}),GP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),name:l.string(),title:l.string().nullish(),version:l.string()}),DG=l.object({default:l.number().nullish(),description:l.string().nullish(),maximum:l.number().nullish(),minimum:l.number().nullish(),title:l.string().nullish()}),NG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),KP=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),VP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),cursor:l.string().nullish(),cwd:l.string().nullish()}),iv=l.union([l.literal("anthropic"),l.literal("openai"),l.literal("azure"),l.literal("vertex"),l.literal("bedrock"),l.string()]),$G=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),OG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),logout:j($G.nullish(),()=>{})}),ZP=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),jG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),LG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),acp:l.boolean().optional().default(!1),http:l.boolean().optional().default(!1),sse:l.boolean().optional().default(!1)}),hl=l.string(),UG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),connectionId:hl}),FG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),connectionId:hl}),JP=l.string(),HG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),acpId:JP}),zG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:JP,name:l.string()}),BG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),headers:l.array(WP),name:l.string(),url:l.string()}),qG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),headers:l.array(WP),name:l.string(),url:l.string()}),WG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),args:l.array(l.string()),command:l.string(),env:l.array(FP),name:l.string()}),yl=l.union([BG.and(l.object({type:l.literal("http")})),qG.and(l.object({type:l.literal("sse")})),zG.and(l.object({type:l.literal("acp")})),WG]),GG=l.string(),XP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),connectionId:hl,method:l.string(),params:l.record(l.string(),l.unknown()).nullish()}),YP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),connectionId:hl,method:l.string(),params:l.record(l.string(),l.unknown()).nullish()}),QP=l.unknown(),KG=l.union([l.literal("error"),l.literal("warning"),l.literal("information"),l.literal("hint")]),VG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),ZG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),JG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),XG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),YG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),QG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),maxCount:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),e4=l.object({diff:l.string(),uri:l.string()}),t4=l.object({endLine:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),startLine:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),text:l.string()}),r4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),n4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),o4=l.object({languageId:l.string(),text:l.string(),uri:l.string()}),i4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),maxCount:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),s4=l.union([l.literal("rejected"),l.literal("ignored"),l.literal("replaced"),l.literal("cancelled")]),a4=l.object({excerpts:l.array(t4),uri:l.string()}),c4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),l4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),u4=l.object({name:l.string(),owner:l.string(),remoteUrl:l.string()}),d4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),p4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),jump:j(r4.nullish(),()=>{}),rename:j(l4.nullish(),()=>{}),searchAndReplace:j(d4.nullish(),()=>{})}),m4=l.object({id:l.string(),isRegex:l.boolean().nullish(),replace:l.string(),search:l.string(),uri:l.string()}),g4=l.union([l.literal("automatic"),l.literal("diagnostic"),l.literal("manual")]),f4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),maxCount:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),h4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),diagnostics:j(VG.nullish(),()=>{}),editHistory:j(QG.nullish(),()=>{}),openFiles:j(n4.nullish(),()=>{}),recentFiles:j(i4.nullish(),()=>{}),relatedSnippets:j(c4.nullish(),()=>{}),userActions:j(f4.nullish(),()=>{})}),eA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:l.array(l.string()).optional(),cwd:l.string(),mcpServers:l.array(yl)}),y4=l.object({default:l.number().nullish(),description:l.string().nullish(),maximum:l.number().nullish(),minimum:l.number().nullish(),title:l.string().nullish()}),tA=l.string(),v4=l.union([l.literal("allow_once"),l.literal("allow_always"),l.literal("reject_once"),l.literal("reject_always")]),b4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),kind:v4,name:l.string(),optionId:tA}),k4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),w4=l.union([l.literal("high"),l.literal("medium"),l.literal("low")]),S4=l.union([l.literal("pending"),l.literal("in_progress"),l.literal("completed")]),rA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:l.string(),priority:w4,status:S4}),x4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),entries:ir(de(rA),()=>[])}),vl=l.string(),R4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:vl,uri:l.string()}),T4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),entries:ir(de(rA),()=>[]),id:vl}),P4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:l.string(),id:vl}),A4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:vl}),I4=l.union([T4.and(l.object({type:l.literal("items")})),R4.and(l.object({type:l.literal("file")})),P4.and(l.object({type:l.literal("markdown")}))]),C4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),plan:I4}),dn=l.object({character:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),line:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"})}),_4=l.object({id:l.string(),position:dn,uri:l.string()}),E4=l.object({id:l.string(),newName:l.string(),position:dn,uri:l.string()}),M4=l.object({action:l.string(),position:dn,timestampMs:l.number(),uri:l.string()}),nA=l.union([l.literal("utf-16"),l.literal("utf-32"),l.literal("utf-8")]),D4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),auth:sG.optional().default({terminal:!1}),elicitation:j(_G.nullish(),()=>{}),fs:MG.optional().default({readTextFile:!1,writeTextFile:!1}),nes:j(p4.nullish(),()=>{}),plan:j(k4.nullish(),()=>{}),positionEncodings:j(de(nA).optional(),()=>[]),terminal:l.boolean().optional().default(!1)}),N4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),audio:l.boolean().optional().default(!1),embeddedContext:l.boolean().optional().default(!1),image:l.boolean().optional().default(!1)}),oA=l.number().int().gte(0).lte(65535),iA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),clientCapabilities:D4.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:j(GP.nullish(),()=>{}),protocolVersion:oA}),$4=l.object({apiType:iv,baseUrl:l.string()}),O4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),current:$4.nullish(),id:l.string(),required:l.boolean(),supported:ir(de(iv),()=>[])}),j4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),providers:ir(de(O4),()=>[])}),L4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),ti=l.object({end:dn,start:dn}),U4=l.object({message:l.string(),range:ti,severity:KG,uri:l.string()}),F4=l.object({languageId:l.string(),lastFocusedMs:j(l.number().nullish(),()=>{}),uri:l.string(),visibleRange:j(ti.nullish(),()=>{})}),H4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),diagnostics:j(de(U4).nullish(),()=>{}),editHistory:j(de(e4).nullish(),()=>{}),openFiles:j(de(F4).nullish(),()=>{}),recentFiles:j(de(o4).nullish(),()=>{}),relatedSnippets:j(de(a4).nullish(),()=>{}),userActions:j(de(M4).nullish(),()=>{})}),z4=l.object({newText:l.string(),range:ti}),B4=l.object({cursorPosition:j(dn.nullish(),()=>{}),edits:l.array(z4),id:l.string(),uri:l.string()}),q4=l.union([B4.and(l.object({kind:l.literal("edit")})),_4.and(l.object({kind:l.literal("jump")})),E4.and(l.object({kind:l.literal("rename")})),m4.and(l.object({kind:l.literal("searchAndReplace")}))]),W4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:l.string()}),G4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),pn=l.union([l.number(),l.string()]).nullable(),fme=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),requestId:pn}),sA=l.object({requestId:pn}),K4=l.enum(["assistant","user"]),$s=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),audience:j(de(K4).nullish(),()=>{}),lastModified:l.string().nullish(),priority:l.number().nullish()}),V4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j($s.nullish(),()=>{}),data:l.string(),mimeType:l.string()}),Z4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j($s.nullish(),()=>{}),data:l.string(),mimeType:l.string(),uri:l.string().nullish()}),J4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j($s.nullish(),()=>{}),description:l.string().nullish(),mimeType:l.string().nullish(),name:l.string(),size:l.number().nullish(),title:l.string().nullish(),uri:l.string()}),X4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),optionId:tA}),Y4=l.union([l.object({outcome:l.literal("cancelled")}),X4.and(l.object({outcome:l.literal("selected")}))]),Q4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),outcome:Y4}),eK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),tK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),rK=l.object({currentValue:l.boolean()}),nK=l.string(),aA=l.string(),oK=l.union([l.literal("mode"),l.literal("model"),l.literal("thought_level"),l.string()]),sv=l.string(),cA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string().nullish(),name:l.string(),value:sv}),iK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),group:nK,name:l.string(),options:l.array(cA)}),sK=l.union([l.array(cA),l.array(iK)]),aK=l.object({currentValue:sv,options:sK}),ri=l.intersection(l.union([aK.and(l.object({type:l.literal("select")})),rK.and(l.object({type:l.literal("boolean")}))]),l.object({_meta:l.record(l.string(),l.unknown()).nullish(),category:j(oK.nullish(),()=>{}),description:l.string().nullish(),id:aA,name:l.string()})),cK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:ir(de(ri),()=>[])}),lK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),uK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),ie=l.string(),lA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:l.string(),sessionId:ie}),uA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),dA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),pA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),av=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),args:l.array(l.string()).optional(),command:l.string(),cwd:l.string().nullish(),env:l.array(FP).optional(),outputByteLimit:l.number().nullish(),sessionId:ie}),mA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),gA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,uri:l.string()}),fA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),position:dn,sessionId:ie,uri:l.string(),version:l.number(),visibleRange:ti}),hA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),languageId:l.string(),sessionId:ie,text:l.string(),uri:l.string(),version:l.number()}),yA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,uri:l.string()}),vA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:l.array(l.string()).optional(),cwd:l.string(),mcpServers:l.array(yl).optional(),sessionId:ie}),cv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,terminalId:l.string()}),bA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:l.array(l.string()).optional(),cwd:l.string(),mcpServers:l.array(yl),sessionId:ie}),lv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),limit:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),line:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:l.string(),sessionId:ie}),kA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:l.string(),reason:j(s4.nullish(),()=>{}),sessionId:ie}),uv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,terminalId:l.string()}),wA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:l.array(l.string()).optional(),cwd:l.string(),mcpServers:l.array(yl).optional(),sessionId:ie}),dK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:l.array(l.string()).optional(),cwd:l.string(),sessionId:ie,title:j(l.string().nullish(),()=>{}),updatedAt:j(l.string().nullish(),()=>{})}),pK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),nextCursor:l.string().nullish(),sessions:ir(de(dK),()=>[])}),mK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),title:l.string().nullish(),updatedAt:l.string().nullish()}),gK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),bl=l.string(),fK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),currentModeId:bl}),hK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string().nullish(),id:bl,name:l.string()}),kl=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),availableModes:ir(de(hK),()=>[]),currentModeId:bl}),yK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:j(de(ri).nullish(),()=>{}),modes:j(kl.nullish(),()=>{}),sessionId:ie}),vK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:j(de(ri).nullish(),()=>{}),modes:j(kl.nullish(),()=>{})}),bK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:j(de(ri).nullish(),()=>{}),modes:j(kl.nullish(),()=>{}),sessionId:ie}),kK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:j(de(ri).nullish(),()=>{}),modes:j(kl.nullish(),()=>{})}),wK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),SK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:j(eK.nullish(),()=>{}),close:j(tK.nullish(),()=>{}),delete:j(lK.nullish(),()=>{}),fork:j(uK.nullish(),()=>{}),list:j(gK.nullish(),()=>{}),resume:j(wK.nullish(),()=>{})}),SA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),apiType:iv,baseUrl:l.string(),headers:l.record(l.string(),l.string()).optional(),id:l.string()}),xK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),xA=l.intersection(l.union([l.object({type:l.literal("boolean"),value:l.boolean()}),l.object({value:sv})]),l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configId:aA,sessionId:ie})),RK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:ir(de(ri),()=>[])}),RA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),modeId:bl,sessionId:ie}),TK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),PK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),AK=l.union([l.literal("end_turn"),l.literal("max_tokens"),l.literal("max_turn_requests"),l.literal("refusal"),l.literal("cancelled")]),IK=l.union([l.literal("email"),l.literal("uri"),l.literal("date"),l.literal("date-time")]),CK=l.object({default:l.string().nullish(),description:l.string().nullish(),enum:l.array(l.string()).nullish(),format:IK.nullish(),maxLength:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),minLength:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),oneOf:l.array(UP).nullish(),pattern:l.string().nullish(),title:l.string().nullish()}),TA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),context:j(H4.nullish(),()=>{}),position:dn,selection:j(ti.nullish(),()=>{}),sessionId:ie,triggerKind:g4,uri:l.string(),version:l.number()}),_K=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),suggestions:ir(de(q4),()=>[])}),EK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),terminalId:l.string()}),MK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),exitCode:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:l.string().nullish()}),dv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,terminalId:l.string()}),DK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),exitStatus:MK.nullish(),output:l.string(),truncated:l.boolean()}),NK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j($s.nullish(),()=>{}),text:l.string()}),$K=l.object({range:ti.nullish(),text:l.string()}),PA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),contentChanges:l.array($K),sessionId:ie,uri:l.string(),version:l.number()}),hme=l.object({method:l.string(),params:l.union([uA,hA,PA,gA,yA,fA,lA,kA,XP,zP]).nullish()}),OK=l.union([l.literal("full"),l.literal("incremental")]),jK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),syncKind:OK}),LK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),didChange:j(jK.nullish(),()=>{}),didClose:j(ZG.nullish(),()=>{}),didFocus:j(JG.nullish(),()=>{}),didOpen:j(XG.nullish(),()=>{}),didSave:j(YG.nullish(),()=>{})}),UK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),document:j(LK.nullish(),()=>{})}),FK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),context:j(h4.nullish(),()=>{}),events:j(UK.nullish(),()=>{})}),HK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),auth:OG.optional().default({}),loadSession:l.boolean().optional().default(!1),mcpCapabilities:LG.optional().default({acp:!1,http:!1,sse:!1}),nes:j(FK.nullish(),()=>{}),positionEncoding:j(nA.nullish(),()=>{}),promptCapabilities:N4.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:j(L4.nullish(),()=>{}),sessionCapabilities:SK.optional().default({})}),zK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),agentCapabilities:HK.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:j(GP.nullish(),()=>{}),authMethods:j(de(dG).optional().default([]),()=>[]),protocolVersion:oA}),BK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),mimeType:l.string().nullish(),text:l.string(),uri:l.string()}),qK=l.union([BK,mG]),WK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j($s.nullish(),()=>{}),resource:qK}),pv=l.union([NK.and(l.object({type:l.literal("text")})),Z4.and(l.object({type:l.literal("image")})),V4.and(l.object({type:l.literal("audio")})),J4.and(l.object({type:l.literal("resource_link")})),WK.and(l.object({type:l.literal("resource")}))]),GK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:pv}),nv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:pv,messageId:GG.nullish()}),AA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),prompt:l.array(pv),sessionId:ie}),KK=l.object({anyOf:l.array(UP)}),IA=l.union([GK.and(l.object({type:l.literal("content")})),kG.and(l.object({type:l.literal("diff")})),EK.and(l.object({type:l.literal("terminal")}))]),mv=l.string(),CA=l.object({sessionId:ie,toolCallId:mv.nullish()}),VK=l.intersection(l.union([CA,sA]),l.object({elicitationId:LP,url:l.string().url()})),_A=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),line:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:l.string()}),EA=l.union([l.literal("pending"),l.literal("in_progress"),l.literal("completed"),l.literal("failed")]),MA=l.union([l.literal("read"),l.literal("edit"),l.literal("delete"),l.literal("move"),l.literal("search"),l.literal("execute"),l.literal("think"),l.literal("fetch"),l.literal("switch_mode"),l.literal("other")]),ZK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:j(de(IA).optional(),()=>[]),kind:MA.optional(),locations:j(de(_A).optional(),()=>[]),rawInput:l.unknown().optional(),rawOutput:l.unknown().optional(),status:EA.optional(),title:l.string(),toolCallId:mv}),DA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:j(de(IA).nullish(),()=>{}),kind:j(MA.nullish(),()=>{}),locations:j(de(_A).nullish(),()=>{}),rawInput:l.unknown().optional(),rawOutput:l.unknown().optional(),status:j(EA.nullish(),()=>{}),title:l.string().nullish(),toolCallId:mv}),gv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),options:l.array(b4),sessionId:ie,toolCall:DA}),JK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),hint:l.string()}),XK=JK,YK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string(),input:j(XK.nullish(),()=>{}),name:l.string()}),QK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),availableCommands:ir(de(YK),()=>[])}),e6=l.object({enum:l.array(l.string()),type:IG}),t6=l.union([e6,KK]),r6=l.object({default:l.array(l.string()).nullish(),description:l.string().nullish(),items:t6,maxItems:l.number().nullish(),minItems:l.number().nullish(),title:l.string().nullish()}),n6=l.union([CK.and(l.object({type:l.literal("string")})),y4.and(l.object({type:l.literal("number")})),DG.and(l.object({type:l.literal("integer")})),gG.and(l.object({type:l.literal("boolean")})),r6.and(l.object({type:l.literal("array")}))]),o6=l.object({description:l.string().nullish(),properties:l.record(l.string(),n6).optional().default({}),required:l.array(l.string()).nullish(),title:l.string().nullish(),type:AG.optional().default("object")}),i6=l.intersection(l.union([CA,sA]),l.object({requestedSchema:o6})),fv=l.intersection(l.union([i6.and(l.object({mode:l.literal("form")})),VK.and(l.object({mode:l.literal("url")}))]),l.object({_meta:l.record(l.string(),l.unknown()).nullish(),message:l.string()})),s6=l.object({cachedReadTokens:l.number().nullish(),cachedWriteTokens:l.number().nullish(),inputTokens:l.number(),outputTokens:l.number(),thoughtTokens:l.number().nullish(),totalTokens:l.number()}),a6=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),stopReason:AK,usage:j(s6.nullish(),()=>{})}),yme=l.union([l.object({id:pn,result:l.union([zK,pG,j4,xK,wG,jG,bK,vK,pK,bG,yK,kK,hG,TK,RK,a6,PK,_K,fG,qP,QP])}),l.object({error:HP,id:pn})]),c6=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),cost:j(yG.nullish(),()=>{}),size:l.number(),used:l.number()}),l6=l.union([nv.and(l.object({sessionUpdate:l.literal("user_message_chunk")})),nv.and(l.object({sessionUpdate:l.literal("agent_message_chunk")})),nv.and(l.object({sessionUpdate:l.literal("agent_thought_chunk")})),ZK.and(l.object({sessionUpdate:l.literal("tool_call")})),DA.and(l.object({sessionUpdate:l.literal("tool_call_update")})),x4.and(l.object({sessionUpdate:l.literal("plan")})),C4.and(l.object({sessionUpdate:l.literal("plan_update")})),A4.and(l.object({sessionUpdate:l.literal("plan_removed")})),QK.and(l.object({sessionUpdate:l.literal("available_commands_update")})),fK.and(l.object({sessionUpdate:l.literal("current_mode_update")})),cK.and(l.object({sessionUpdate:l.literal("config_option_update")})),mK.and(l.object({sessionUpdate:l.literal("session_info_update")})),c6.and(l.object({sessionUpdate:l.literal("usage_update")}))]),hv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,update:l6}),vme=l.object({method:l.string(),params:l.union([hv,ov,XP,zP]).nullish()}),yv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,terminalId:l.string()}),u6=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),exitCode:l.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:l.string().nullish()}),d6=l.object({name:l.string(),uri:l.string()}),NA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),repository:j(u4.nullish(),()=>{}),workspaceFolders:j(de(d6).nullish(),()=>{}),workspaceUri:l.string().nullish()}),bme=l.object({id:pn,method:l.string(),params:l.union([iA,OP,KP,SA,jP,ZP,eA,bA,VP,mA,vA,wA,pA,RA,xA,AA,NA,TA,dA,YP,BP]).nullish()}),vv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:l.string(),path:l.string(),sessionId:ie}),kme=l.object({id:pn,method:l.string(),params:l.union([vv,lv,gv,av,dv,uv,yv,cv,fv,HG,YP,FG,BP]).nullish()}),p6=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),wme=l.union([l.object({id:pn,result:l.union([p6,W4,Q4,vG,DK,G4,u6,NG,TG,UG,SG,qP,QP])}),l.object({error:HP,id:pn})]);function $A(t,e){let r=new TextEncoder,n=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+=n.decode();break}if(!d)continue;a+=n.decode(d,{stream:!0});let m=a.split(`
609
609
  `);a=m.pop()||"";for(let g of m){let f=g.trim();if(f)try{let h=JSON.parse(f);s.enqueue(h)}catch(h){console.error("Failed to parse JSON message:",f,h)}}}let u=a.trim();if(u)try{let d=JSON.parse(u);s.enqueue(d)}catch(d){console.error("Failed to parse JSON message:",u,d)}}catch(u){s.error(u);return}finally{c.releaseLock()}s.close()}}),i=new WritableStream({async write(s){let a=JSON.stringify(s)+`
610
- `,c=t.getWriter();try{await c.write(r.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function mn(t){return t??{}}function OA(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var wl=class{connection;constructor(e,r){let n=e(this),o=async(s,a)=>{switch(s){case Vt.fs_write_text_file:{let c=vv.parse(a);return await n.writeTextFile?.(c)??{}}case Vt.fs_read_text_file:{let c=lv.parse(a);return n.readTextFile?.(c)}case Vt.session_request_permission:{let c=gv.parse(a);return n.requestPermission(c)}case Vt.terminal_create:{let c=av.parse(a);return n.createTerminal?.(c)}case Vt.terminal_output:{let c=dv.parse(a);return n.terminalOutput?.(c)}case Vt.terminal_release:{let c=uv.parse(a);return await n.releaseTerminal?.(c)??{}}case Vt.terminal_wait_for_exit:{let c=yv.parse(a);return n.waitForTerminalExit?.(c)}case Vt.terminal_kill:{let c=cv.parse(a);return await n.killTerminal?.(c)??{}}case Vt.elicitation_create:{if(!n.unstable_createElicitation)throw bt.methodNotFound(s);let c=fv.parse(a);return n.unstable_createElicitation(c)}default:if(n.extMethod)return n.extMethod(s,a);throw bt.methodNotFound(s)}},i=async(s,a)=>{switch(s){case Vt.session_update:{let c=hv.parse(a);return n.sessionUpdate(c)}case Vt.elicitation_complete:{if(!n.unstable_completeElicitation)return;let c=ov.parse(a);return n.unstable_completeElicitation(c)}default:if(n.extNotification)return n.extNotification(s,a);throw bt.methodNotFound(s)}};this.connection=new bv(o,i,r)}initialize(e){return this.connection.sendRequest(me.initialize,e)}newSession(e){return this.connection.sendRequest(me.session_new,e)}loadSession(e){return this.connection.sendRequest(me.session_load,e,mn)}unstable_forkSession(e){return this.connection.sendRequest(me.session_fork,e)}listSessions(e){return this.connection.sendRequest(me.session_list,e)}deleteSession(e){return this.connection.sendRequest(me.session_delete,e,mn)}resumeSession(e){return this.connection.sendRequest(me.session_resume,e)}closeSession(e){return this.connection.sendRequest(me.session_close,e)}setSessionMode(e){return this.connection.sendRequest(me.session_set_mode,e,mn)}setSessionConfigOption(e){return this.connection.sendRequest(me.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(me.authenticate,e,mn)}unstable_listProviders(e){return this.connection.sendRequest(me.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(me.providers_set,e,mn)}unstable_disableProvider(e){return this.connection.sendRequest(me.providers_disable,e,mn)}logout(e){return this.connection.sendRequest(me.logout,e,mn)}prompt(e){return this.connection.sendRequest(me.session_prompt,e)}cancel(e){return this.connection.sendNotification(me.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(me.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(me.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(me.nes_close,e,mn)}unstable_didOpenDocument(e){return this.connection.sendNotification(me.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(me.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(me.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(me.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(me.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(me.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(me.nes_reject,e)}extMethod(e,r){return this.connection.sendRequest(e,r)}extNotification(e,r){return this.connection.sendNotification(e,r)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},bv=class{pendingResponses=new Map;nextRequestId=0;requestHandler;notificationHandler;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;constructor(e,r,n){this.requestHandler=e,this.notificationHandler=r,this.stream=n,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 r=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:n,done:o}=await r.read();if(o)break;if(n)try{this.processMessage(n)}catch(i){console.error("Unexpected error during message processing:",n,i),"id"in n&&n.id!==void 0&&this.sendMessage({jsonrpc:"2.0",id:n.id,error:{code:-32700,message:"Parse error"}})}}}finally{r.releaseLock()}}catch(r){e=r}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let r=e??new Error("ACP connection closed");for(let n of this.pendingResponses.values())n.reject(r);this.pendingResponses.clear(),this.abortController.abort(r)}async processMessage(e){if("method"in e&&"id"in e){let r=await this.tryCallRequestHandler(e.method,e.params);"error"in r&&console.error("Error handling request",e,r.error),await this.sendMessage({jsonrpc:"2.0",id:e.id,...r})}else if("method"in e){let r=await this.tryCallNotificationHandler(e.method,e.params);"error"in r&&console.error("Error handling notification",e,r.error)}else"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}async tryCallRequestHandler(e,r){try{return{result:await this.requestHandler(e,r)??null}}catch(n){if(n instanceof bt)return n.toResult();if(n instanceof l.ZodError)return bt.invalidParams(n.format()).toResult();let o;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(o=n.message);try{return bt.internalError(o?JSON.parse(o):{}).toResult()}catch{return bt.internalError({details:o}).toResult()}}}async tryCallNotificationHandler(e,r){try{return await this.notificationHandler(e,r),{result:null}}catch(n){if(n instanceof bt)return n.toResult();if(n instanceof l.ZodError)return bt.invalidParams(n.format()).toResult();let o;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(o=n.message);try{return bt.internalError(o?JSON.parse(o):{}).toResult()}catch{return bt.internalError({details:o}).toResult()}}}handleResponse(e){let r=this.pendingResponses.get(e.id);if(r){if("result"in e)r.resolve(e.result);else if("error"in e){let{code:n,message:o,data:i}=e.error;r.reject(new bt(n,o,i))}this.pendingResponses.delete(e.id)}else console.error("Got response to unknown request",e.id)}sendRequest(e,r,n){if(this.abortController.signal.aborted)return OA(this.closedReason());let o=this.nextRequestId++,i=new Promise((s,a)=>{this.pendingResponses.set(o,{resolve:c=>{try{s(n?n(c):c)}catch(u){a(u)}},reject:a})});return i.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:o,method:e,params:r}),i}sendNotification(e,r){return this.abortController.signal.aborted?OA(this.closedReason()):this.sendMessage({jsonrpc:"2.0",method:e,params:r})}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let r=this.stream.writable.getWriter();try{await r.write(e)}finally{r.releaseLock()}}).catch(r=>{this.close(r)}),this.writeQueue}},bt=class t extends Error{code;data;constructor(e,r,n){super(r),this.code=e,this.name="RequestError",this.data=n}static parseError(e,r){return new t(-32700,`Parse error${r?`: ${r}`:""}`,e)}static invalidRequest(e,r){return new t(-32600,`Invalid request${r?`: ${r}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,r){return new t(-32602,`Invalid params${r?`: ${r}`:""}`,e)}static internalError(e,r){return new t(-32603,`Internal error${r?`: ${r}`:""}`,e)}static authRequired(e,r){return new t(-32e3,`Authentication required${r?`: ${r}`:""}`,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 h6=1,y6=2e4,jA=3e4,v6=3e5,sr={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"},Os=class extends Error{retryable=!1;authMethods;constructor(e,r){super(e),this.name="AcpAuthRequiredError",this.authMethods=r}};function Sl(t,e){if(t instanceof Os)return t;let r=t,n=Array.isArray(r?.data?.authMethods)?r.data.authMethods:[];if(r?.code===-32e3||n.length>0||/auth(?:entication|orization)?\s+required/i.test(r?.message??"")){let i=n[0],s=i?.description||(i?.name?`Use "${i.name}".`:"");return new Os(`Authentication required.${s?` ${s}`:""}`,n)}if(e&&e.length>0){let i=e[0],s=r?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:r?.message||"Authentication required.");return new Os(s,e)}return null}var gn=class{conn=null;child=null;onNotification=null;hostHandler=null;attach(e,r,n){if(this.child=e,this.onNotification=r??null,this.hostHandler=n??null,!e.stdin||!e.stdout)throw new Error("ACP adapter: child process has no stdio");let o=$A(f6.toWeb(e.stdin),g6.toWeb(e.stdout));this.conn=new wl(()=>this.buildClient(),o)}buildClient(){let e=()=>this.hostHandler,r=(n,o)=>this.onNotification?.(n,o);return{async sessionUpdate(n){r("session/update",n)},async requestPermission(n){let o=e(),s=(o?.requestPermission?await o.requestPermission(n):{optionId:"allow"})?.optionId;return s?{outcome:{outcome:"selected",optionId:s}}:{outcome:{outcome:"cancelled"}}},async readTextFile(n){return{content:(await e()?.readTextFile?.(n))?.content??""}},async writeTextFile(n){return await e()?.writeTextFile?.(n),{}},async createTerminal(n){return await e()?.createTerminal?.(n)??{terminalId:""}},async terminalOutput(n){return await e()?.terminalOutput?.(n)??{output:"",truncated:!1}},async releaseTerminal(n){return await e()?.releaseTerminal?.(n),{}},async waitForTerminalExit(n){return await e()?.waitForTerminalExit?.(n)??{}},async killTerminal(n){return await e()?.killTerminal?.(n),{}},async extMethod(n,o){return await e()?.extMethod?.(n,o)??{}},async extNotification(n,o){r(n,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,r,n,o){let i,s=new Promise((a,c)=>{i=setTimeout(()=>{try{o?.()}catch{}c(new Error(`ACP ${n} timeout (${r}ms)`))},r)});try{return await Promise.race([e,s])}finally{i&&clearTimeout(i)}}async initialize(e){let r={protocolVersion:h6,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}},clientInfo:{name:"qlogicagent",version:"1.0.0"}},n=await this.withTimeout(this.requireConn().initialize(r),y6,"initialize").catch(i=>{throw Sl(i)??i}),o=n?.agentCapabilities??{};return{protocolVersion:typeof n?.protocolVersion=="number"?n.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:n?.agentInfo,authMethods:n?.authMethods}}async createSession(e,r){let n={cwd:r.cwd,mcpServers:r.mcpServers??[]};r.additionalDirectories?.length&&(n.additionalDirectories=r.additionalDirectories),r.systemPrompt&&(n._meta={qlogicagent:{systemPrompt:r.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(n),jA,"session/new").catch(i=>{throw Sl(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,r,n,o=v6){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:r,prompt:[{type:"text",text:n}]}),o,"session/prompt",()=>{i.cancel({sessionId:r}).catch(()=>{})});return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:void 0}}async resumeSession(e,r,n){let o={sessionId:r,cwd:n?.cwd??process.cwd(),mcpServers:n?.mcpServers??[]},i=await this.withTimeout(this.requireConn().loadSession(o),jA,"session/load");return{sessionId:typeof i?.sessionId=="string"?i.sessionId:r}}static translateNotification(e,r){let n=r;if(e==="session/update"){if(!n)return null;let o=n.update;if(!o)return null;let i=o.sessionUpdate,s=n.sessionId;switch(i){case sr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case sr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case sr.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 sr.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 sr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case sr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case sr.AVAILABLE_COMMANDS_UPDATE:case sr.CURRENT_MODE_UPDATE:case sr.CONFIG_OPTION_UPDATE:case sr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case sr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as b6}from"node:child_process";import{readFile as k6,writeFile as w6}from"node:fs/promises";import{isAbsolute as LA,normalize as S6,relative as x6,resolve as R6,sep as T6}from"node:path";function kv(t){let e=new Map,r=0,n=i=>{let s=LA(i)?S6(i):R6(t.cwd,i),a=x6(t.cwd,s);if(a===".."||a.startsWith(`..${T6}`)||LA(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:"allow"}},async readTextFile(i){return{content:await k6(n(i.path),"utf8")}},async writeTextFile(i){return await w6(n(i.path),i.content,"utf8"),{}},async createTerminal(i){let s=String(i.command??""),a=i.args,c=Array.isArray(a)?a.map(String):[],u=i.cwd,d=u?n(String(u)):t.cwd,p=i.env,m={...process.env,...p&&typeof p=="object"?p:{}},g=b6(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"]}),f=`term-${++r}`,h={child:g,output:"",exitStatus:null,exit:new Promise(y=>{g.on("exit",(S,w)=>{let v={exitCode:S,signal:w};h.exitStatus=v,y(v)}),g.on("error",()=>{let S={exitCode:null,signal:null};h.exitStatus=S,y(S)})})};return g.stdout?.on("data",y=>{h.output+=y.toString()}),g.stderr?.on("data",y=>{h.output+=y.toString()}),e.set(f,h),{terminalId:f}},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 js=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{execSync as FA}from"node:child_process";import{existsSync as wv,readFileSync as P6,readdirSync as A6}from"node:fs";import{homedir as I6,platform as C6}from"node:os";import{dirname as _6,join as ni}from"node:path";var Ls={claude:{id:"claude",name:"Claude Code",cliCommand:"claude-agent-acp",acpArgs:[],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:["-c","sandbox_mode=danger-full-access","-c","approval_policy=untrusted"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!0,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!1},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--experimental-acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!1,apiKeyEnvVar:"GEMINI_API_KEY"},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"},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"}},E6=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],UA={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"}},codex:{brandId:"codex",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @zed-industries/codex-acp",cliCommand:"codex-acp",docsUrl:"https://github.com/zed-industries/codex-acp"}},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"}},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",docsUrl:"https://docs.github.com/copilot/concepts/agents/about-copilot-cli"}},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",docsUrl:"https://cursor.com/cli"}},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"}},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",docsUrl:"https://github.com/MoonshotAI/kimi-cli"}},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"}},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"}},kiro:{brandId:"kiro",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{cliCommand:"kiro-cli",docsUrl:"https://kiro.dev/docs"}},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"}},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",docsUrl:"https://github.com/openclaw/openclaw"}},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",docsUrl:"https://github.com/NousResearch/hermes-agent"}}};function Us(t){let e=Ls[t];if(e)return UA[t]?{...e,...UA[t]}:e}function HA(){return E6.map(t=>{let e=Us(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var xv=C6()==="win32";function Sv(t){try{let e=xv?`where ${t}`:`which ${t}`;return FA(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function M6(t,e){let r=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},n=r(t),o=r(e);for(let i=0;i<3;i+=1)if(n[i]!==o[i])return o[i]-n[i];return e.localeCompare(t)}function D6(){if(!xv)return null;let t=[process.env.COPILOT_CACHE_HOME?ni(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?ni(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?ni(process.env.COPILOT_HOME,"pkg","win32-x64"):null,ni(I6(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let r=A6(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name).sort(M6);for(let n of r){let o=ni(e,n,"npm-loader.js");if(wv(o)&&zA(o))return o}}catch{}return null}function N6(t){return t.id==="copilot"?D6()??Sv(t.cliCommand):Sv(t.cliCommand)}function zA(t){try{let e=t.endsWith("npm-loader.js")?`"${process.execPath}" "${t}" version`:`"${t}" version`;return FA(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}function $6(t,e){if(!xv)return{cliPath:t,acpArgs:e};if(t.endsWith("npm-loader.js")){let n=e.includes("--no-auto-update");return{cliPath:process.execPath,acpArgs:[t,...e,...n?[]:["--no-auto-update"]]}}let r=O6(t);return r?{cliPath:process.execPath,acpArgs:[r,...e]}:{cliPath:t,acpArgs:e}}function O6(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),r=[`${e}.cmd`,`${e}.ps1`,e];for(let n of r){if(!wv(n))continue;let o;try{o=P6(n,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=ni(_6(e),s);if(wv(a))return a}return null}var j6=6e4;function L6(t,e,r){let n={};return t?.env&&Object.assign(n,t.env),r&&Object.assign(n,r),t?.apiKeyEnvVar&&e?.apiKey&&(n[t.apiKeyEnvVar]=e.apiKey),t?.baseUrlEnvVar&&e?.baseUrl&&(n[t.baseUrlEnvVar]=e.baseUrl),e?.env&&Object.assign(n,e.env),Object.keys(n).length>0?n:void 0}var U6=new Set(["codex","qwen","opencode"]);function F6(t,e){let r={};if(!t||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:n,baseUrlEnvVar:o}=t;if(t.keySource==="llmrouter")n&&e.llmrouterKey&&(r[n]=e.llmrouterKey),o&&e.llmrouterBaseUrl&&(r[o]=e.llmrouterBaseUrl);else if(t.keySource==="direct"){let i=e.getDirectKey?.(t.id);n&&i&&(r[n]=i)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&U6.has(t.id)){let i=e.passthroughModel;r.OPENAI_API_KEY=i.apiKey,i.baseUrl&&(r.OPENAI_BASE_URL=i.baseUrl),i.model&&(r.OPENAI_MODEL=i.model)}return r}var oi=class{cache=null;configStore=null;keySources={};setConfigStore(e){this.configStore=e}setKeySources(e){this.keySources=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<j6)return this.cache.agents;let r=[];for(let n of Object.values(Ls))r.push(this.detectBackend(n));if(this.configStore?.customAgents)for(let n of Object.values(this.configStore.customAgents))r.push(this.detectCustomAgent(n));return this.cache={agents:r,timestamp:Date.now()},r}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let r=N6(e),n=this.hasAgentConfig(e.id);if(!r)return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}};let o=zA(r);return e.id==="copilot"&&!o?{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,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:r,version:o??void 0,authRequired:e.authRequired,hasConfig:n,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}}}detectCustomAgent(e){let r=Sv(e.cliCommand),n=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:r?"available":"not_installed",cliPath:r??void 0,authRequired:e.authRequired??!1,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let r=this.configStore.agents[e];return!!(r?.apiKey||r?.baseUrl||r?.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"],r={};for(let n of e){let o=process.env[n];o&&(r[n]=o)}return{id:"qlogicagent",cliPath:process.execPath,acpArgs:[process.argv[1]??""],env:Object.keys(r).length>0?r:void 0,protocol:"acp"}}buildExternalDescriptor(e){if(e==="qlogicagent")return this.buildSelfDescriptor();let r=this.list().find(a=>a.id===e);if(!r||r.protocol!=="acp"||r.status!=="available"||!r.cliPath)return null;let n=Us(e)??Ls[e],o=this.configStore?.agents[e],i=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:o?.customArgs??n?.acpArgs??[]}:$6(r.cliPath,o?.customArgs??n?.acpArgs??[]),s=F6(n,this.keySources);return{id:e,cliPath:i.cliPath,acpArgs:i.acpArgs,env:L6(n,o,s),protocol:"acp"}}isAgentReady(e){if(e==="qlogicagent")return!0;let r=this.buildExternalDescriptor(e);if(!r)return!1;let n=Us(e)??Ls[e];return n?.apiKeyEnvVar&&n.authMode!=="oauth"?!!r.env?.[n.apiKeyEnvVar]:!0}};var V6=1;function Z6(t,e){return{jsonrpc:"2.0",id:V6++,method:t,params:e,meta:wm(t)}}var J6=["NODE_ENV","HOME","PATH","TERM","OPENAI_API_KEY","OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function X6(t){let e={};for(let r of J6)process.env[r]&&(e[r]=process.env[r]);return t.apiKey&&(e.OPENAI_API_KEY=t.apiKey),t.baseUrl&&(e.OPENAI_BASE_URL=t.baseUrl),e.QLOGICAGENT_MEMBER_ID=t.memberId,e.QLOGICAGENT_MEMBER_NAME=t.name,t.agentType&&(e.QLOGICAGENT_AGENT_TYPE=t.agentType),t.model&&(e.QLOGICAGENT_MODEL=t.model),t.env&&Object.assign(e,t.env),e}function BA(t){if(!t)return;let e={};return t.model&&(e.model=t.model),t.apiKey&&(e.apiKey=t.apiKey),t.baseUrl&&(e.baseUrl=t.baseUrl),Object.keys(e).length?e:void 0}var Tv=Bp,Y6=qp,ii=Wp,qA=Gp;function Q6(t){return new Promise(e=>setTimeout(e,t))}function eV(t,e){if(process.platform==="win32"&&typeof e=="number"&&e>0)try{H6("taskkill",["/PID",String(e),"/T","/F"],()=>{});return}catch{}try{t.kill("SIGTERM"),setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},1e4)}catch{}}var Zt=class t{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let r=z6(Fs(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=Fs(r,"dist","cli.js"),this.mcpBridgeScriptPath=Fs(r,"dist","runtime","infra","mcp-bridge-server.js")}slog(e,r,n,o){let s=`[${new Date().toISOString()}] [${e}] [agent:${r}] [${n}] ${o}`;e==="warn"?this.callbacks.log?.warn(s):this.callbacks.log?.info(s)}async spawn(e){if(this.processes.has(e.memberId))throw new Error(`Agent process "${e.memberId}" already spawned`);let r=this.callbacks.log,n=X6(e),o={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()};if(e.external)return this.spawnAcpAgentWithRetry(e,o,n);let i=[this.cliBinaryPath];e.verbose&&i.push("--verbose"),this.slog("info",e.memberId,"spawn",`spawning ${e.name} in ${e.cwd}`);let s=Rv(process.execPath,i,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});o.pid=s.pid??-1;let a=new Map;this.processes.set(e.memberId,{handle:o,child:s,pendingRpc:a}),xl({input:s.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",u=>{let d=u.trim();if(d)try{let p=JSON.parse(d),m="id"in p,g="method"in p&&typeof p.method=="string";if(m&&g){this.handleChildHostRequest(e.memberId,p);return}if(m){let f=a.get(p.id);if(f){clearTimeout(f.timer),a.delete(p.id);let h=p;h.error?f.reject(new Error(h.error.message)):f.resolve(h.result)}return}if(g){let f=gn.translateNotification(p.method,p.params),h=f?.method??p.method,y=f?.params??p.params;this.captureChildProgress(e.memberId,h,y),this.callbacks.onNotification?.(e.memberId,h,y)}}catch{this.slog("warn",e.memberId,"parse",`invalid JSON: ${d.slice(0,200)}`)}}),s.stderr&&xl({input:s.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",d=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${d}`)}),s.on("exit",(u,d)=>{o.state!=="killed"&&(o.state=u===0?"completed":"failed"),o.endedAt=Date.now(),u!==0&&!o.error&&(o.error=`Process exited with code ${u} (signal: ${d})`);for(let[m,g]of a)clearTimeout(g.timer),g.reject(new Error(`Agent process exited (code=${u})`)),a.delete(m);this.callbacks.onStateChange?.(e.memberId,o.state),this.callbacks.onExit?.(e.memberId,u,d),this.slog("info",e.memberId,"exit",`exited (code=${u}, signal=${d})`)}),s.on("error",u=>{o.state="failed",o.error=u.message,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",u.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{await this.sendRpc(e.memberId,"initialize",{protocolVersion:1,clientInfo:{name:"qlogicagent-team-leader",version:"1.0.0"},clientCapabilities:{qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}}},15e3);let u=B6();await this.sendRpc(e.memberId,"session/new",{sessionId:u,cwd:e.cwd},15e3),o.sessionId=u,o.state="ready",this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`initialized (pid=${o.pid}, session=${u})`)}catch(u){throw o.state="failed",o.error=`Initialize handshake failed: ${u instanceof Error?u.message:String(u)}`,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.kill(e.memberId),new Error(o.error)}return o}async sendTask(e,r,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.resultText="",o.handle.state="running",this.callbacks.onStateChange?.(e,"running");try{let i;if(o.acpAdapter){let s=o.handle.sessionId??"default",a=await o.acpAdapter.sendPrompt(o.child,s,r,n?.timeout??3e5),c=o.handle.resultText??"";a.usage&&o.usageTracker&&o.usageTracker.onPromptResponseUsage(a.usage),i={content:c,stopReason:a.stopReason}}else{let s=n?.sessionId??o.handle.sessionId??"default",a=BA(n),c=await this.sendRpc(e,"session/prompt",{sessionId:s,prompt:[{type:"text",text:r}],...a?{_meta:a}:{}},n?.timeout??3e5),u=o.handle.resultText??"",d=c&&typeof c.stopReason=="string"?c.stopReason:void 0;i={content:u,stopReason:d}}return o.handle.state="completed",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),i}catch(i){throw o.handle.state="failed",o.handle.error=i instanceof Error?i.message:String(i),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),i}}async sendRpc(e,r,n,o=3e4){let i=this.processes.get(e);if(!i)throw new Error(`No agent process: ${e}`);let s=Z6(r,n);return new Promise((a,c)=>{let u=setTimeout(()=>{i.pendingRpc.delete(s.id),c(new Error(`RPC timeout: ${r} (${o}ms)`))},o);i.pendingRpc.set(s.id,{resolve:a,reject:c,timer:u});try{i.child.stdin.write(`${JSON.stringify(s)}
610
+ `,c=t.getWriter();try{await c.write(r.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function mn(t){return t??{}}function OA(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var wl=class{connection;constructor(e,r){let n=e(this),o=async(s,a)=>{switch(s){case Vt.fs_write_text_file:{let c=vv.parse(a);return await n.writeTextFile?.(c)??{}}case Vt.fs_read_text_file:{let c=lv.parse(a);return n.readTextFile?.(c)}case Vt.session_request_permission:{let c=gv.parse(a);return n.requestPermission(c)}case Vt.terminal_create:{let c=av.parse(a);return n.createTerminal?.(c)}case Vt.terminal_output:{let c=dv.parse(a);return n.terminalOutput?.(c)}case Vt.terminal_release:{let c=uv.parse(a);return await n.releaseTerminal?.(c)??{}}case Vt.terminal_wait_for_exit:{let c=yv.parse(a);return n.waitForTerminalExit?.(c)}case Vt.terminal_kill:{let c=cv.parse(a);return await n.killTerminal?.(c)??{}}case Vt.elicitation_create:{if(!n.unstable_createElicitation)throw bt.methodNotFound(s);let c=fv.parse(a);return n.unstable_createElicitation(c)}default:if(n.extMethod)return n.extMethod(s,a);throw bt.methodNotFound(s)}},i=async(s,a)=>{switch(s){case Vt.session_update:{let c=hv.parse(a);return n.sessionUpdate(c)}case Vt.elicitation_complete:{if(!n.unstable_completeElicitation)return;let c=ov.parse(a);return n.unstable_completeElicitation(c)}default:if(n.extNotification)return n.extNotification(s,a);throw bt.methodNotFound(s)}};this.connection=new bv(o,i,r)}initialize(e){return this.connection.sendRequest(me.initialize,e)}newSession(e){return this.connection.sendRequest(me.session_new,e)}loadSession(e){return this.connection.sendRequest(me.session_load,e,mn)}unstable_forkSession(e){return this.connection.sendRequest(me.session_fork,e)}listSessions(e){return this.connection.sendRequest(me.session_list,e)}deleteSession(e){return this.connection.sendRequest(me.session_delete,e,mn)}resumeSession(e){return this.connection.sendRequest(me.session_resume,e)}closeSession(e){return this.connection.sendRequest(me.session_close,e)}setSessionMode(e){return this.connection.sendRequest(me.session_set_mode,e,mn)}setSessionConfigOption(e){return this.connection.sendRequest(me.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(me.authenticate,e,mn)}unstable_listProviders(e){return this.connection.sendRequest(me.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(me.providers_set,e,mn)}unstable_disableProvider(e){return this.connection.sendRequest(me.providers_disable,e,mn)}logout(e){return this.connection.sendRequest(me.logout,e,mn)}prompt(e){return this.connection.sendRequest(me.session_prompt,e)}cancel(e){return this.connection.sendNotification(me.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(me.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(me.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(me.nes_close,e,mn)}unstable_didOpenDocument(e){return this.connection.sendNotification(me.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(me.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(me.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(me.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(me.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(me.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(me.nes_reject,e)}extMethod(e,r){return this.connection.sendRequest(e,r)}extNotification(e,r){return this.connection.sendNotification(e,r)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},bv=class{pendingResponses=new Map;nextRequestId=0;requestHandler;notificationHandler;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;constructor(e,r,n){this.requestHandler=e,this.notificationHandler=r,this.stream=n,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 r=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:n,done:o}=await r.read();if(o)break;if(n)try{this.processMessage(n)}catch(i){console.error("Unexpected error during message processing:",n,i),"id"in n&&n.id!==void 0&&this.sendMessage({jsonrpc:"2.0",id:n.id,error:{code:-32700,message:"Parse error"}})}}}finally{r.releaseLock()}}catch(r){e=r}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let r=e??new Error("ACP connection closed");for(let n of this.pendingResponses.values())n.reject(r);this.pendingResponses.clear(),this.abortController.abort(r)}async processMessage(e){if("method"in e&&"id"in e){let r=await this.tryCallRequestHandler(e.method,e.params);"error"in r&&console.error("Error handling request",e,r.error),await this.sendMessage({jsonrpc:"2.0",id:e.id,...r})}else if("method"in e){let r=await this.tryCallNotificationHandler(e.method,e.params);"error"in r&&console.error("Error handling notification",e,r.error)}else"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}async tryCallRequestHandler(e,r){try{return{result:await this.requestHandler(e,r)??null}}catch(n){if(n instanceof bt)return n.toResult();if(n instanceof l.ZodError)return bt.invalidParams(n.format()).toResult();let o;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(o=n.message);try{return bt.internalError(o?JSON.parse(o):{}).toResult()}catch{return bt.internalError({details:o}).toResult()}}}async tryCallNotificationHandler(e,r){try{return await this.notificationHandler(e,r),{result:null}}catch(n){if(n instanceof bt)return n.toResult();if(n instanceof l.ZodError)return bt.invalidParams(n.format()).toResult();let o;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(o=n.message);try{return bt.internalError(o?JSON.parse(o):{}).toResult()}catch{return bt.internalError({details:o}).toResult()}}}handleResponse(e){let r=this.pendingResponses.get(e.id);if(r){if("result"in e)r.resolve(e.result);else if("error"in e){let{code:n,message:o,data:i}=e.error;r.reject(new bt(n,o,i))}this.pendingResponses.delete(e.id)}else console.error("Got response to unknown request",e.id)}sendRequest(e,r,n){if(this.abortController.signal.aborted)return OA(this.closedReason());let o=this.nextRequestId++,i=new Promise((s,a)=>{this.pendingResponses.set(o,{resolve:c=>{try{s(n?n(c):c)}catch(u){a(u)}},reject:a})});return i.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:o,method:e,params:r}),i}sendNotification(e,r){return this.abortController.signal.aborted?OA(this.closedReason()):this.sendMessage({jsonrpc:"2.0",method:e,params:r})}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let r=this.stream.writable.getWriter();try{await r.write(e)}finally{r.releaseLock()}}).catch(r=>{this.close(r)}),this.writeQueue}},bt=class t extends Error{code;data;constructor(e,r,n){super(r),this.code=e,this.name="RequestError",this.data=n}static parseError(e,r){return new t(-32700,`Parse error${r?`: ${r}`:""}`,e)}static invalidRequest(e,r){return new t(-32600,`Invalid request${r?`: ${r}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,r){return new t(-32602,`Invalid params${r?`: ${r}`:""}`,e)}static internalError(e,r){return new t(-32603,`Internal error${r?`: ${r}`:""}`,e)}static authRequired(e,r){return new t(-32e3,`Authentication required${r?`: ${r}`:""}`,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 h6=1,y6=2e4,jA=3e4,v6=3e5,sr={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"},Os=class extends Error{retryable=!1;authMethods;constructor(e,r){super(e),this.name="AcpAuthRequiredError",this.authMethods=r}};function Sl(t,e){if(t instanceof Os)return t;let r=t,n=Array.isArray(r?.data?.authMethods)?r.data.authMethods:[];if(r?.code===-32e3||n.length>0||/auth(?:entication|orization)?\s+required/i.test(r?.message??"")){let i=n[0],s=i?.description||(i?.name?`Use "${i.name}".`:"");return new Os(`Authentication required.${s?` ${s}`:""}`,n)}if(e&&e.length>0){let i=e[0],s=r?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:r?.message||"Authentication required.");return new Os(s,e)}return null}var gn=class{conn=null;child=null;onNotification=null;hostHandler=null;attach(e,r,n){if(this.child=e,this.onNotification=r??null,this.hostHandler=n??null,!e.stdin||!e.stdout)throw new Error("ACP adapter: child process has no stdio");let o=$A(f6.toWeb(e.stdin),g6.toWeb(e.stdout));this.conn=new wl(()=>this.buildClient(),o)}buildClient(){let e=()=>this.hostHandler,r=(n,o)=>this.onNotification?.(n,o);return{async sessionUpdate(n){r("session/update",n)},async requestPermission(n){let o=e(),s=(o?.requestPermission?await o.requestPermission(n):{optionId:"allow"})?.optionId;return s?{outcome:{outcome:"selected",optionId:s}}:{outcome:{outcome:"cancelled"}}},async readTextFile(n){return{content:(await e()?.readTextFile?.(n))?.content??""}},async writeTextFile(n){return await e()?.writeTextFile?.(n),{}},async createTerminal(n){return await e()?.createTerminal?.(n)??{terminalId:""}},async terminalOutput(n){return await e()?.terminalOutput?.(n)??{output:"",truncated:!1}},async releaseTerminal(n){return await e()?.releaseTerminal?.(n),{}},async waitForTerminalExit(n){return await e()?.waitForTerminalExit?.(n)??{}},async killTerminal(n){return await e()?.killTerminal?.(n),{}},async extMethod(n,o){return await e()?.extMethod?.(n,o)??{}},async extNotification(n,o){r(n,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,r,n,o){let i,s=new Promise((a,c)=>{i=setTimeout(()=>{try{o?.()}catch{}c(new Error(`ACP ${n} timeout (${r}ms)`))},r)});try{return await Promise.race([e,s])}finally{i&&clearTimeout(i)}}async initialize(e){let r={protocolVersion:h6,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}},clientInfo:{name:"qlogicagent",version:"1.0.0"}},n=await this.withTimeout(this.requireConn().initialize(r),y6,"initialize").catch(i=>{throw Sl(i)??i}),o=n?.agentCapabilities??{};return{protocolVersion:typeof n?.protocolVersion=="number"?n.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:n?.agentInfo,authMethods:n?.authMethods}}async createSession(e,r){let n={cwd:r.cwd,mcpServers:r.mcpServers??[]};r.additionalDirectories?.length&&(n.additionalDirectories=r.additionalDirectories),r.systemPrompt&&(n._meta={qlogicagent:{systemPrompt:r.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(n),jA,"session/new").catch(i=>{throw Sl(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,r,n,o=v6){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:r,prompt:[{type:"text",text:n}]}),o,"session/prompt",()=>{i.cancel({sessionId:r}).catch(()=>{})});return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:void 0}}async resumeSession(e,r,n){let o={sessionId:r,cwd:n?.cwd??process.cwd(),mcpServers:n?.mcpServers??[]},i=await this.withTimeout(this.requireConn().loadSession(o),jA,"session/load");return{sessionId:typeof i?.sessionId=="string"?i.sessionId:r}}static translateNotification(e,r){let n=r;if(e==="session/update"){if(!n)return null;let o=n.update;if(!o)return null;let i=o.sessionUpdate,s=n.sessionId;switch(i){case sr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case sr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case sr.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 sr.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 sr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case sr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case sr.AVAILABLE_COMMANDS_UPDATE:case sr.CURRENT_MODE_UPDATE:case sr.CONFIG_OPTION_UPDATE:case sr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case sr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as b6}from"node:child_process";import{readFile as k6,writeFile as w6}from"node:fs/promises";import{isAbsolute as LA,normalize as S6,relative as x6,resolve as R6,sep as T6}from"node:path";function kv(t){let e=new Map,r=0,n=i=>{let s=LA(i)?S6(i):R6(t.cwd,i),a=x6(t.cwd,s);if(a===".."||a.startsWith(`..${T6}`)||LA(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:"allow"}},async readTextFile(i){return{content:await k6(n(i.path),"utf8")}},async writeTextFile(i){return await w6(n(i.path),i.content,"utf8"),{}},async createTerminal(i){let s=String(i.command??""),a=i.args,c=Array.isArray(a)?a.map(String):[],u=i.cwd,d=u?n(String(u)):t.cwd,p=i.env,m={...process.env,...p&&typeof p=="object"?p:{}},g=b6(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"]}),f=`term-${++r}`,h={child:g,output:"",exitStatus:null,exit:new Promise(y=>{g.on("exit",(S,w)=>{let v={exitCode:S,signal:w};h.exitStatus=v,y(v)}),g.on("error",()=>{let S={exitCode:null,signal:null};h.exitStatus=S,y(S)})})};return g.stdout?.on("data",y=>{h.output+=y.toString()}),g.stderr?.on("data",y=>{h.output+=y.toString()}),e.set(f,h),{terminalId:f}},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 js=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{execSync as FA}from"node:child_process";import{existsSync as wv,readFileSync as P6,readdirSync as A6}from"node:fs";import{homedir as I6,platform as C6}from"node:os";import{dirname as _6,join as ni}from"node:path";var Ls={claude:{id:"claude",name:"Claude Code",cliCommand:"claude-agent-acp",acpArgs:[],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:["-c","sandbox_mode=danger-full-access","-c","approval_policy=untrusted"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!0,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!1},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--experimental-acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!1,apiKeyEnvVar:"GEMINI_API_KEY"},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"},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"}},E6=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],UA={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"}},codex:{brandId:"codex",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @zed-industries/codex-acp",cliCommand:"codex-acp",docsUrl:"https://github.com/zed-industries/codex-acp"}},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"}},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",docsUrl:"https://docs.github.com/copilot/concepts/agents/about-copilot-cli"}},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",docsUrl:"https://cursor.com/cli"}},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"}},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",docsUrl:"https://github.com/MoonshotAI/kimi-cli"}},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"}},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"}},kiro:{brandId:"kiro",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{cliCommand:"kiro-cli",docsUrl:"https://kiro.dev/docs"}},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"}},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",docsUrl:"https://github.com/openclaw/openclaw"}},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",docsUrl:"https://github.com/NousResearch/hermes-agent"}}};function Us(t){let e=Ls[t];if(e)return UA[t]?{...e,...UA[t]}:e}function HA(){return E6.map(t=>{let e=Us(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var xv=C6()==="win32";function Sv(t){try{let e=xv?`where ${t}`:`which ${t}`;return FA(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function M6(t,e){let r=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},n=r(t),o=r(e);for(let i=0;i<3;i+=1)if(n[i]!==o[i])return o[i]-n[i];return e.localeCompare(t)}function D6(){if(!xv)return null;let t=[process.env.COPILOT_CACHE_HOME?ni(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?ni(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?ni(process.env.COPILOT_HOME,"pkg","win32-x64"):null,ni(I6(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let r=A6(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name).sort(M6);for(let n of r){let o=ni(e,n,"npm-loader.js");if(wv(o)&&zA(o))return o}}catch{}return null}function N6(t){return t.id==="copilot"?D6()??Sv(t.cliCommand):Sv(t.cliCommand)}function zA(t){try{let e=t.endsWith("npm-loader.js")?`"${process.execPath}" "${t}" version`:`"${t}" version`;return FA(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}function $6(t,e){if(!xv)return{cliPath:t,acpArgs:e};if(t.endsWith("npm-loader.js")){let n=e.includes("--no-auto-update");return{cliPath:process.execPath,acpArgs:[t,...e,...n?[]:["--no-auto-update"]]}}let r=O6(t);return r?{cliPath:process.execPath,acpArgs:[r,...e]}:{cliPath:t,acpArgs:e}}function O6(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),r=[`${e}.cmd`,`${e}.ps1`,e];for(let n of r){if(!wv(n))continue;let o;try{o=P6(n,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=ni(_6(e),s);if(wv(a))return a}return null}var j6=6e4;function L6(t,e,r){let n={};return t?.env&&Object.assign(n,t.env),r&&Object.assign(n,r),t?.apiKeyEnvVar&&e?.apiKey&&(n[t.apiKeyEnvVar]=e.apiKey),t?.baseUrlEnvVar&&e?.baseUrl&&(n[t.baseUrlEnvVar]=e.baseUrl),e?.env&&Object.assign(n,e.env),Object.keys(n).length>0?n:void 0}var U6=new Set(["codex","qwen","opencode"]);function F6(t,e){let r={};if(!t||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:n,baseUrlEnvVar:o}=t;if(t.keySource==="llmrouter")n&&e.llmrouterKey&&(r[n]=e.llmrouterKey),o&&e.llmrouterBaseUrl&&(r[o]=e.llmrouterBaseUrl);else if(t.keySource==="direct"){let i=e.getDirectKey?.(t.id);n&&i&&(r[n]=i)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&U6.has(t.id)){let i=e.passthroughModel;r.OPENAI_API_KEY=i.apiKey,i.baseUrl&&(r.OPENAI_BASE_URL=i.baseUrl),i.model&&(r.OPENAI_MODEL=i.model)}return r}var oi=class{cache=null;configStore=null;keySources={};setConfigStore(e){this.configStore=e}setKeySources(e){this.keySources=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<j6)return this.cache.agents;let r=[];for(let n of Object.values(Ls))r.push(this.detectBackend(n));if(this.configStore?.customAgents)for(let n of Object.values(this.configStore.customAgents))r.push(this.detectCustomAgent(n));return this.cache={agents:r,timestamp:Date.now()},r}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let r=N6(e),n=this.hasAgentConfig(e.id);if(!r)return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}};let o=zA(r);return e.id==="copilot"&&!o?{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,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:r,version:o??void 0,authRequired:e.authRequired,hasConfig:n,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}}}detectCustomAgent(e){let r=Sv(e.cliCommand),n=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:r?"available":"not_installed",cliPath:r??void 0,authRequired:e.authRequired??!1,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let r=this.configStore.agents[e];return!!(r?.apiKey||r?.baseUrl||r?.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"],r={};for(let n of e){let o=process.env[n];o&&(r[n]=o)}return{id:"qlogicagent",cliPath:process.execPath,acpArgs:[process.argv[1]??""],env:Object.keys(r).length>0?r:void 0,protocol:"acp"}}buildExternalDescriptor(e){if(e==="qlogicagent")return this.buildSelfDescriptor();let r=this.list().find(a=>a.id===e);if(!r||r.protocol!=="acp"||r.status!=="available"||!r.cliPath)return null;let n=Us(e)??Ls[e],o=this.configStore?.agents[e],i=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:o?.customArgs??n?.acpArgs??[]}:$6(r.cliPath,o?.customArgs??n?.acpArgs??[]),s=F6(n,this.keySources);return{id:e,cliPath:i.cliPath,acpArgs:i.acpArgs,env:L6(n,o,s),protocol:"acp"}}isAgentReady(e){if(e==="qlogicagent")return!0;let r=this.buildExternalDescriptor(e);if(!r)return!1;let n=Us(e)??Ls[e];return n?.apiKeyEnvVar&&n.authMode!=="oauth"?!!r.env?.[n.apiKeyEnvVar]:!0}};var V6=1;function Z6(t,e){return{jsonrpc:"2.0",id:V6++,method:t,params:e,meta:wm(t)}}var J6=["NODE_ENV","HOME","PATH","TERM","OPENAI_API_KEY","OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","QLOGIC_LLMROUTER_BASE_URL","QLOGIC_LLMROUTER_ACCESS_TOKEN","QLOGIC_LLMROUTER_USER_ID","QLOGIC_LLMROUTER_EMBEDDING_MODEL","QLOGIC_LLMROUTER_EMBEDDING_DIMENSIONS","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function X6(t){let e={};for(let r of J6)process.env[r]&&(e[r]=process.env[r]);return t.apiKey&&(e.OPENAI_API_KEY=t.apiKey),t.baseUrl&&(e.OPENAI_BASE_URL=t.baseUrl),e.QLOGICAGENT_MEMBER_ID=t.memberId,e.QLOGICAGENT_MEMBER_NAME=t.name,t.agentType&&(e.QLOGICAGENT_AGENT_TYPE=t.agentType),t.model&&(e.QLOGICAGENT_MODEL=t.model),t.env&&Object.assign(e,t.env),e}function BA(t){if(!t)return;let e={};return t.model&&(e.model=t.model),t.apiKey&&(e.apiKey=t.apiKey),t.baseUrl&&(e.baseUrl=t.baseUrl),Object.keys(e).length?e:void 0}var Tv=Bp,Y6=qp,ii=Wp,qA=Gp;function Q6(t){return new Promise(e=>setTimeout(e,t))}function eV(t,e){if(process.platform==="win32"&&typeof e=="number"&&e>0)try{H6("taskkill",["/PID",String(e),"/T","/F"],()=>{});return}catch{}try{t.kill("SIGTERM"),setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},1e4)}catch{}}var Zt=class t{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let r=z6(Fs(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=Fs(r,"dist","cli.js"),this.mcpBridgeScriptPath=Fs(r,"dist","runtime","infra","mcp-bridge-server.js")}slog(e,r,n,o){let s=`[${new Date().toISOString()}] [${e}] [agent:${r}] [${n}] ${o}`;e==="warn"?this.callbacks.log?.warn(s):this.callbacks.log?.info(s)}async spawn(e){if(this.processes.has(e.memberId))throw new Error(`Agent process "${e.memberId}" already spawned`);let r=this.callbacks.log,n=X6(e),o={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()};if(e.external)return this.spawnAcpAgentWithRetry(e,o,n);let i=[this.cliBinaryPath];e.verbose&&i.push("--verbose"),this.slog("info",e.memberId,"spawn",`spawning ${e.name} in ${e.cwd}`);let s=Rv(process.execPath,i,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});o.pid=s.pid??-1;let a=new Map;this.processes.set(e.memberId,{handle:o,child:s,pendingRpc:a}),xl({input:s.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",u=>{let d=u.trim();if(d)try{let p=JSON.parse(d),m="id"in p,g="method"in p&&typeof p.method=="string";if(m&&g){this.handleChildHostRequest(e.memberId,p);return}if(m){let f=a.get(p.id);if(f){clearTimeout(f.timer),a.delete(p.id);let h=p;h.error?f.reject(new Error(h.error.message)):f.resolve(h.result)}return}if(g){let f=gn.translateNotification(p.method,p.params),h=f?.method??p.method,y=f?.params??p.params;this.captureChildProgress(e.memberId,h,y),this.callbacks.onNotification?.(e.memberId,h,y)}}catch{this.slog("warn",e.memberId,"parse",`invalid JSON: ${d.slice(0,200)}`)}}),s.stderr&&xl({input:s.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",d=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${d}`)}),s.on("exit",(u,d)=>{o.state!=="killed"&&(o.state=u===0?"completed":"failed"),o.endedAt=Date.now(),u!==0&&!o.error&&(o.error=`Process exited with code ${u} (signal: ${d})`);for(let[m,g]of a)clearTimeout(g.timer),g.reject(new Error(`Agent process exited (code=${u})`)),a.delete(m);this.callbacks.onStateChange?.(e.memberId,o.state),this.callbacks.onExit?.(e.memberId,u,d),this.slog("info",e.memberId,"exit",`exited (code=${u}, signal=${d})`)}),s.on("error",u=>{o.state="failed",o.error=u.message,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",u.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{await this.sendRpc(e.memberId,"initialize",{protocolVersion:1,clientInfo:{name:"qlogicagent-team-leader",version:"1.0.0"},clientCapabilities:{qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}}},15e3);let u=B6();await this.sendRpc(e.memberId,"session/new",{sessionId:u,cwd:e.cwd},15e3),o.sessionId=u,o.state="ready",this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`initialized (pid=${o.pid}, session=${u})`)}catch(u){throw o.state="failed",o.error=`Initialize handshake failed: ${u instanceof Error?u.message:String(u)}`,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.kill(e.memberId),new Error(o.error)}return o}async sendTask(e,r,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.resultText="",o.handle.state="running",this.callbacks.onStateChange?.(e,"running");try{let i;if(o.acpAdapter){let s=o.handle.sessionId??"default",a=await o.acpAdapter.sendPrompt(o.child,s,r,n?.timeout??3e5),c=o.handle.resultText??"";a.usage&&o.usageTracker&&o.usageTracker.onPromptResponseUsage(a.usage),i={content:c,stopReason:a.stopReason}}else{let s=n?.sessionId??o.handle.sessionId??"default",a=BA(n),c=await this.sendRpc(e,"session/prompt",{sessionId:s,prompt:[{type:"text",text:r}],...a?{_meta:a}:{}},n?.timeout??3e5),u=o.handle.resultText??"",d=c&&typeof c.stopReason=="string"?c.stopReason:void 0;i={content:u,stopReason:d}}return o.handle.state="completed",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),i}catch(i){throw o.handle.state="failed",o.handle.error=i instanceof Error?i.message:String(i),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),i}}async sendRpc(e,r,n,o=3e4){let i=this.processes.get(e);if(!i)throw new Error(`No agent process: ${e}`);let s=Z6(r,n);return new Promise((a,c)=>{let u=setTimeout(()=>{i.pendingRpc.delete(s.id),c(new Error(`RPC timeout: ${r} (${o}ms)`))},o);i.pendingRpc.set(s.id,{resolve:a,reject:c,timer:u});try{i.child.stdin.write(`${JSON.stringify(s)}
611
611
  `)}catch(d){clearTimeout(u),i.pendingRpc.delete(s.id),c(d instanceof Error?d:new Error(String(d)))}})}async sendTaskAsync(e,r,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.state="running",this.callbacks.onStateChange?.(e,"running");let i=n?.sessionId??o.handle.sessionId??"default",s=BA(n),a={sessionId:i,prompt:[{type:"text",text:r}],...s?{_meta:s}:{}},c=n?.pingInterval??6e4,u=n?.pingTimeout??1e4,d=n?.timeout??0,p=Date.now(),m=d>0?d:1440*60*1e3,g=this.sendRpc(e,"session/prompt",a,m),f=setInterval(async()=>{if(d>0&&Date.now()-p>d){clearInterval(f),o.handle.state="failed",o.handle.error="Task timed out",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed");return}try{await this.sendRpc(e,"ping",void 0,u)}catch{this.slog("warn",o.handle.memberId,"heartbeat","ping failed")}},c);try{let h=await g;return clearInterval(f),o.handle.state="completed",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),h}catch(h){throw clearInterval(f),o.handle.state="failed",o.handle.error=h instanceof Error?h.message:String(h),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),h}}async ping(e,r=5e3){let n=this.processes.get(e);if(!n)return!1;if(n.acpAdapter){try{let s=JSON.stringify({jsonrpc:"2.0",method:"notifications/ping",params:{timestamp:Date.now()}})+`
612
612
  `;n.child.stdin?.write(s)}catch{return!1}let o=n.handle.lastActivityAt??0,i=Date.now()+r;for(;Date.now()<i;)if(await new Promise(s=>setTimeout(s,500)),(n.handle.lastActivityAt??0)>o)return!0;try{return await this.sendRpc(e,"ping",void 0,Math.min(r,3e3)),!0}catch{return!1}}try{return await this.sendRpc(e,"ping",void 0,r),!0}catch{return!1}}getStatus(e){let r=this.processes.get(e);if(!r)return null;let{handle:n}=r,o=n.state==="starting"||n.state==="ready"||n.state==="running",i=o?Date.now()-n.startedAt:void 0,s=n.lastActivityAt&&o?Math.round((Date.now()-n.lastActivityAt)/1e3):void 0;return{alive:o,state:n.state,runningFor:i,resultText:n.resultText,error:n.error,mediaProgress:n.mediaProgress,lastToolCall:n.lastToolCall,idleFor:s}}handleChildHostRequest(e,r){let o=this.processes.get(e)?.child.stdin;if(!o?.writable)return;let i=s=>{try{o.write(`${JSON.stringify({jsonrpc:"2.0",id:r.id,...s})}
613
613
  `)}catch{}};if(r.method==="session/request_permission"){i({result:{optionId:"allow"}});return}i({error:{code:-32601,message:`Method not found: ${r.method}`}})}captureChildProgress(e,r,n){let o=this.processes.get(e);if(!o)return;let{handle:i}=o;switch(i.lastActivityAt=Date.now(),r){case"turn.media_progress":{let s=n;s&&typeof s.taskId=="string"&&(i.mediaProgress={taskId:s.taskId,mediaType:s.mediaType??"unknown",percent:typeof s.percent=="number"?s.percent:0,status:s.status??"unknown",provider:s.provider,updatedAt:Date.now()});break}case"turn.tool_call":{let s=n;s&&typeof s.name=="string"&&(i.lastToolCall=s.name);break}case"turn.delta":{let s=n;if(s&&typeof s.text=="string"){let a=s.text;i.resultText=`${i.resultText??""}${a}`,i.lastDelta=a.slice(-200)}break}case"turn.tool_result":{n&&i.mediaProgress&&i.mediaProgress.percent>=100&&(i.mediaProgress=void 0);break}}}async spawnAcpAgentWithRetry(e,r,n){let o=null;for(let i=0;i<=Tv;i++)try{if(i>0){this.processes.delete(e.memberId),r.state="starting",r.error=void 0,r.endedAt=void 0;let s=Y6*i;this.slog("info",e.memberId,"spawn",`retry ${i}/${Tv} after ${s}ms`),await Q6(s)}return await this.spawnAcpAgent(e,r,n)}catch(s){if(o=s instanceof Error?s:new Error(String(s)),o.retryable===!1)throw r.state="failed",r.error=o.message,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),o;this.slog("warn",e.memberId,"spawn",`attempt ${i+1} failed: ${o.message}`)}throw r.state="failed",r.error=`ACP spawn failed after ${Tv+1} attempts: ${o?.message}`,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),new Error(r.error)}async spawnAcpAgent(e,r,n){let o=this.callbacks.log,i=e.external;i.env&&Object.assign(n,i.env);let s=[...i.acpArgs];this.slog("info",e.memberId,"spawn",`spawning ACP ${e.name} via ${i.cliPath} ${s.join(" ")}`);let a=Rv(i.cliPath,s,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});r.pid=a.pid??-1;let c=new Map,u=new gn,d=new js,{server:p,pipePath:m}=this.createMcpIpcServer(e.memberId);n.QLOGICAGENT_PARENT_RPC=m;let g;if(this.callbacks.sessionDir)try{G6(this.callbacks.sessionDir,{recursive:!0}),g=W6(Fs(this.callbacks.sessionDir,`${e.memberId}.stderr.log`),{flags:"a"})}catch{}let f=kv({cwd:e.cwd,requestPermission:this.callbacks.onPermissionRequest?h=>this.callbacks.onPermissionRequest(e.memberId,h):void 0});this.processes.set(e.memberId,{handle:r,child:a,pendingRpc:c,acpAdapter:u,usageTracker:d,ipcServer:p,ipcPath:m,stderrStream:g,hostHandler:f}),u.attach(a,(h,y)=>{h==="usage_update"&&d.onUsageUpdate(y);let S=gn.translateNotification(h,y);S?(this.captureChildProgress(e.memberId,S.method,S.params),this.callbacks.onNotification?.(e.memberId,S.method,S.params)):(this.captureChildProgress(e.memberId,h,y),this.callbacks.onNotification?.(e.memberId,h,y))},f),a.stderr&&xl({input:a.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",y=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${y}`),g?.write(`${new Date().toISOString()} ${y}
@@ -1039,7 +1039,7 @@ Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;as
1039
1039
  `)})}function kj(){return Sd("tool_guidance",()=>["# Tool Usage Guidance","","You have access to specialized tools. Use them appropriately:","","## Agent Delegation","Use the `agent` tool to delegate complex, multi-step tasks to sub-agents:","- Research/exploration tasks that benefit from focused attention","- File analysis across multiple files that need independent reasoning","- Any task the user explicitly asks you to delegate","- **When the user says 'delegate', 'sub-agent', 'fork', or 'hand off', you MUST use the `agent` tool \u2014 never handle it yourself**","Do NOT use `agent` for simple file reads or single-step operations.","","### Background execution & parallel fan-out","- `agent(background=true)` returns a task id immediately and keeps working \u2014 use it for independent subtasks so you can continue in parallel. Launch several in one message for parallel work.","- `exec(background=true)` does the same for long-running commands (dev servers, builds, watchers).",'- Track background work with the `task` tool: action "output" reads status/output by taskId, action "cancel" stops it; `list` shows active background tasks.',"- Completed background tasks are announced automatically at the start of your next turn \u2014 you do not need to busy-poll.","- For multi-step plans, create checklist tasks first, then fan out unblocked independent steps to background agents and set each checklist task's owner to the returned task id.","","## Skill System","Use the `skill` tool (unified meta-tool) for all skill operations:","- action 'invoke' \u2014 run a skill by name","- action 'list' \u2014 discover available skills (shows scope: project/global)","- action 'create' \u2014 save a new skill to current project","- action 'promote' \u2014 copy a project skill to global (user-level)","When recalled memories show '[Cross-project skill available]', proactively offer to use or save the skill.","","## Checkpoint","Use the `checkpoint` tool (not raw git commands) to:","- Save workspace state before making changes","- Restore to a previous state if changes go wrong","The checkpoint tool manages git shadow history automatically.","","## Ask User","Use `ask_user` to clarify genuinely ambiguous requests before proceeding.","For ordinary creative media requests, infer sensible defaults and use the appropriate media tool directly.","Ask before media generation only when a missing detail is critical to the result or the user is choosing among materially different outputs.","","## Project Rules Management","You can create, edit, and delete project rule files at `.qlogicagent/rules/*.md`.","These files are loaded into your system prompt every turn \u2014 changes take effect immediately.","Use this to help users establish coding conventions, workflow guidelines, or project-specific instructions.","When the user asks to 'add a rule', 'set up conventions', or 'configure instructions', write to `.qlogicagent/rules/<descriptive-name>.md`.","You may also create or edit `.qlogicagent/INSTRUCTIONS.md` for a single top-level instruction file.","","## File Operations \u2014 Use Dedicated Tools","File operations (creating, modifying, or deleting files) should use the dedicated `write` / `edit` / `read` tools, which take structured file-path arguments.","Do NOT use shell redirection (`echo >`, `cat >`, `>>`, `tee`) to create or modify files.","Use `exec` only for real commands (build, test, git, package managers).","This keeps file paths explicit and permission checks accurate.","","### Choosing among the edit tools","- `write` \u2014 create a new file or fully replace one. Overwrites.","- `edit` \u2014 single-file, exact-string replacement for precise surgical edits. Call it repeatedly for multiple edits in one file.","- `patch` / `apply_patch` \u2014 multi-file changes in one shot via the V4A diff format (`*** Begin Patch` \u2026 `*** End Patch`), incl. Add/Update/Delete/Move. Prefer for cross-file refactors.","Do NOT reach for `patch` to change one line in one file \u2014 use `edit`.","","### Searching \u2014 prefer `search` over `exec grep`","Use the `search` tool for finding files/content: it excludes VCS and dependency dirs (`.git`, `node_modules`, `dist`, \u2026) and returns structured matches. `exec grep -r` scans those too, so the two can disagree \u2014 `search` is the consistent, intended path.","","## Deliverable Discipline \u2014 Long Output Goes to Files","The chat window is a conversation surface, not a document dump. Users see deliverables in the workspace file tree and the side panel.","- Long documents/plans/designs/reports/tutorials (anything beyond ~40 lines) MUST be written to a workspace file (e.g. `docs/` or an appropriate project directory) using the file tools. In chat, reply with a 3-5 sentence summary and reference the file \u2014 do NOT paste the full document into the conversation.","- Code longer than ~30 lines belongs in a workspace file; in chat, reference the file path and quote only the key fragment.","- Generated media is already persisted to the workspace `assets/` directory automatically \u2014 do not repeat raw URL lists in your reply."].join(`
1040
1040
  `))}function kw(t){return Sd("language",()=>t?["# Language","",`Always respond in ${t}.`,`Use ${t} for all text output, explanations, and descriptions.`,"Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
1041
1041
  `):["# Language","","Respond in the same language as the user's message.","If the user writes in English, respond in English. If in Chinese, respond in Chinese.","Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
1042
- `))}var wj={requiresFreshTool:!1,allowedToolNames:[]},bte=["txt","json","jsonl","ts","tsx","js","jsx","mjs","cjs","md","mdx","yaml","yml","toml","ini","xml","csv","tsv","env","py","go","rs","java","kt","kts","cs","cpp","c","h","hpp","html","css","scss","sass","less","sql","lock","log","sh","ps1","bat","cmd"],ww=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${bte.join("|")})\\b`,"i"),kte=/write|create|edit|replace|change|update|modify|overwrite|fix|implement|\u5199|\u65b0\u5efa|\u521b\u5efa|\u7f16\u8f91|\u66ff\u6362|\u6539\u6210|\u4fee\u6539|\u4fee\u590d|\u5b9e\u73b0|\u8986\u76d6/i,wte=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,Ste=/(?:memory|\u8bb0\u5fc6).*(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b|\u5220\u9664|\u79fb\u9664|\u66ff\u6362|\u521b\u5efa|\u8bfb\u53d6|\u641c\u7d22)|(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b).*(?:memory|\u8bb0\u5fc6)/i,xte=/(?:current\s+directory|directory\s+(?:contains|listing|files)|list\s+(?:the\s+)?files|what\s+files|\u5f53\u524d\u76ee\u5f55|\u76ee\u5f55\u4e0b|\u54ea\u4e9b\u6587\u4ef6|\u5217\u51fa.*\u6587\u4ef6)/i,Rte=/(?:which\s+file.*contains|contains.*which\s+file|\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6.*\u5305\u542b|\u5305\u542b.*\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6)/i,Tte=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,Pte=/https?:\/\/\S+/i,Ate=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,Ite=/(?:\bimage_generate\b|\bgenerate\s+(?:an?\s+)?image\b|\bmake\s+(?:an?\s+)?image\b|\bdraw\s+(?:an?\s+)?(?:image|picture|illustration)\b|\bcreate\s+(?:an?\s+)?(?:image|picture|illustration)\b|\u751f\u56fe|\u751f\u6210(?:一张|个|幅)?(?:图片|图像|插画|海报|头像)?|\u753b(?:一张|一个|一幅|一只|一群|个|张|幅|一下)?.+|\u753b(?:一张|个|幅|一幅)?.*(?:图|图片|图像|插画|画面)|(?:图片|图像|插画|海报|头像).*\u751f\u6210)/i,Cte=/(?:\btts\b|\btext[-\s]?to[-\s]?speech\b|\bread\s+(?:this\s+)?(?:aloud|out)\b|\bgenerate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bcreate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bmake\s+(?:a\s+)?(?:voice\s+message|spoken\s+audio)\b|\u6587\u5b57\u8f6c\u8bed\u97f3|\u8bed\u97f3\u5408\u6210|\u8f6c\u6210\u8bed\u97f3|\u8f6c\u8bed\u97f3|\u751f\u6210.*(?:\u8bed\u97f3|\u97f3\u9891|\u58f0\u97f3|\u5f55\u97f3|\u6709\u58f0)|(?:\u8bfb|\u6717\u8bfb|\u64ad\u62a5|\u914d\u97f3|\u65c1\u767d).*(?:\u4e00\u6bb5|\u8fd9\u6bb5|\u8fd9\u4e9b|\u6587\u5b57|\u5185\u5bb9|\u8bed\u97f3|\u97f3\u9891)?)/i,_te=/(?:\bmusic_generate\b|\bgenerate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bcreate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bmake\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\u751f\u6210.*(?:\u6b4c\u66f2|\u97f3\u4e50|\u65cb\u5f8b|\u914d\u4e50|\u80cc\u666f\u97f3\u4e50|\u7eaf\u97f3\u4e50|\u54fc\u5531)|(?:\u4f5c\u66f2|\u7f16\u66f2|\u5199\u4e00\u9996\u6b4c))/i,Ete=/^(?:hi|hello|hey|ping|test|yo|在吗|在不在|你在吗|你好|您好|早上好|中午好|晚上好|哈喽|嗨|有人吗|能听到吗|你是谁|你还在吗)[?!!?.。~\s]*$/i;function xj(t){let e=typeof t=="string"?t:Aj(t);return e.trim()?_te.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"music",allowedToolNames:["music_generate"]}:Cte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"tts",allowedToolNames:["tts"]}:Ite.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"image",allowedToolNames:["image_generate"]}:Pte.test(e)&&Ate.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:wte.test(e)&&ww.test(e)||Ste.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:kte.test(e)&&ww.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:ww.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:xte.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:Rte.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:Tte.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:wj:wj}function Rj(t){let r=(typeof t=="string"?t:Aj(t)).trim();return!r||r.length>24?!1:Ete.test(r)}var Mte=new Set(["think","task","agent","ask_user"]);function Tj(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(i=>{let s=Sj(i);return r.has(s)||Mte.has(s)});return n.some(i=>r.has(Sj(i)))?n:[...t]}function Pj(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");if(t.reason==="file-mutation")return Er("fresh_workspace_evidence",()=>["# Workspace File Action Required","","The latest user request asks you to create, edit, fix, or implement files in the workspace.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use write/edit/patch/apply_patch to make the requested on-disk change. Reading or searching can locate context, but does not satisfy the requested action.","Do not merely describe code, print snippets, or claim completion without a successful file-changing tool result.","If a file-changing tool fails, make at most two focused attempts, then report the exact failure."].join(`
1042
+ `))}var wj={requiresFreshTool:!1,allowedToolNames:[]},bte=["txt","json","jsonl","ts","tsx","js","jsx","mjs","cjs","md","mdx","yaml","yml","toml","ini","xml","csv","tsv","env","py","go","rs","java","kt","kts","cs","cpp","c","h","hpp","html","css","scss","sass","less","sql","lock","log","sh","ps1","bat","cmd"],ww=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${bte.join("|")})\\b`,"i"),kte=/write|create|edit|replace|change|update|modify|overwrite|fix|implement|\u5199|\u65b0\u5efa|\u521b\u5efa|\u7f16\u8f91|\u66ff\u6362|\u6539\u6210|\u4fee\u6539|\u4fee\u590d|\u5b9e\u73b0|\u8986\u76d6/i,wte=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,Ste=/(?:memory|\u8bb0\u5fc6).*(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b|\u5220\u9664|\u79fb\u9664|\u66ff\u6362|\u521b\u5efa|\u8bfb\u53d6|\u641c\u7d22)|(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b).*(?:memory|\u8bb0\u5fc6)/i,xte=/(?:current\s+directory|directory\s+(?:contains|listing|files)|list\s+(?:the\s+)?files|what\s+files|\u5f53\u524d\u76ee\u5f55|\u76ee\u5f55\u4e0b|\u54ea\u4e9b\u6587\u4ef6|\u5217\u51fa.*\u6587\u4ef6)/i,Rte=/(?:which\s+file.*contains|contains.*which\s+file|\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6.*\u5305\u542b|\u5305\u542b.*\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6)/i,Tte=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,Pte=/https?:\/\/\S+/i,Ate=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,Ite=/(?:\bimage_generate\b|\bgenerate\s+(?:an?\s+)?image\b|\bmake\s+(?:an?\s+)?image\b|\bdraw\s+(?:an?\s+)?(?:image|picture|illustration)\b|\bcreate\s+(?:an?\s+)?(?:image|picture|illustration)\b|\u751f\u56fe|\u751f\u6210(?:一张|个|幅)?(?:图片|图像|插画|海报|头像)?|\u753b(?:一张|一个|一幅|一只|一群|个|张|幅|一下)?.+|\u753b(?:一张|个|幅|一幅)?.*(?:图|图片|图像|插画|画面)|(?:图片|图像|插画|海报|头像).*\u751f\u6210)/i,Cte=/(?:\btts\b|\btext[-\s]?to[-\s]?speech\b|\bread\s+(?:this\s+)?(?:aloud|out)\b|\bgenerate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bcreate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bmake\s+(?:a\s+)?(?:voice\s+message|spoken\s+audio)\b|\u6587\u5b57\u8f6c\u8bed\u97f3|\u8bed\u97f3\u5408\u6210|\u8f6c\u6210\u8bed\u97f3|\u8f6c\u8bed\u97f3|\u751f\u6210.*(?:\u8bed\u97f3|\u97f3\u9891|\u58f0\u97f3|\u5f55\u97f3|\u6709\u58f0)|(?:\u8bfb|\u6717\u8bfb|\u64ad\u62a5|\u914d\u97f3|\u65c1\u767d).*(?:\u4e00\u6bb5|\u8fd9\u6bb5|\u8fd9\u4e9b|\u6587\u5b57|\u5185\u5bb9|\u8bed\u97f3|\u97f3\u9891)?)/i,_te=/(?:\bmusic_generate\b|\bgenerate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bcreate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bmake\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\u751f\u6210.*(?:\u6b4c\u66f2|\u97f3\u4e50|\u65cb\u5f8b|\u914d\u4e50|\u80cc\u666f\u97f3\u4e50|\u7eaf\u97f3\u4e50|\u54fc\u5531)|(?:\u4f5c\u66f2|\u7f16\u66f2|\u5199\u4e00\u9996\u6b4c))/i,Ete=/^(?:hi|hello|hey|ping|test|yo|在吗|在不在|你在吗|你好|您好|早上好|中午好|晚上好|哈喽|嗨|有人吗|能听到吗|你是谁|你还在吗)[?!!?.。~\s]*$/i;function xj(t){let e=typeof t=="string"?t:Aj(t);return e.trim()?_te.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"music",allowedToolNames:["music_generate"]}:Cte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"tts",allowedToolNames:["tts"]}:Ite.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"image",allowedToolNames:["image_generate"]}:Pte.test(e)&&Ate.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:wte.test(e)&&ww.test(e)||Ste.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:kte.test(e)&&ww.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:ww.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:xte.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:Rte.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:Tte.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:wj:wj}function Rj(t){let r=(typeof t=="string"?t:Aj(t)).trim();return!r||r.length>24?!1:Ete.test(r)}var Mte=new Set(["think","task","agent","ask_user","team","send_message"]);function Tj(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(i=>{let s=Sj(i);return r.has(s)||Mte.has(s)});return n.some(i=>r.has(Sj(i)))?n:[...t]}function Pj(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");if(t.reason==="file-mutation")return Er("fresh_workspace_evidence",()=>["# Workspace File Action Required","","The latest user request asks you to create, edit, fix, or implement files in the workspace.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use write/edit/patch/apply_patch to make the requested on-disk change. Reading or searching can locate context, but does not satisfy the requested action.","Do not merely describe code, print snippets, or claim completion without a successful file-changing tool result.","If a file-changing tool fails, make at most two focused attempts, then report the exact failure."].join(`
1043
1043
  `));if(t.reason==="memory-mutation")return Er("fresh_workspace_evidence",()=>["# Memory File Action Required","","The latest user request explicitly asks to use the memory tool for a memory file action.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use the requested memory action and target filename instead of workspace file write/edit tools.","For removal requests, call memory with action='remove' and set old_text to the exact INDEX.md line or labeled marker line the user asked to remove.","Do not call action='add', action='remember', or action='create_file' for a removal request.","Do not merely describe the memory content or create a regular workspace file."].join(`
1044
1044
  `));if(t.reason==="media-generation"){let r=t.mediaKind==="tts"?"spoken audio / text-to-speech":t.mediaKind==="music"?"music or song":"image",n=t.mediaKind==="tts"?"Do not answer by saying you cannot generate audio when the TTS tool is available, and do not invent a placeholder audio URL.":t.mediaKind==="music"?"Do not answer by describing music in text or inventing a placeholder audio URL.":"Do not answer by inventing a Markdown image URL or placeholder attachment path.",o=t.mediaKind==="tts"?"Use TTS for spoken-word output, narration, reading text aloud, or voice messages. STT is only for transcribing incoming speech.":t.mediaKind==="music"?"Use music generation for songs, melodies, BGM, or sung/musical output; use TTS only for spoken words.":"Use image generation for pictures, illustrations, posters, avatars, or visual output.";return Er("fresh_workspace_evidence",()=>["# Media Generation Required","",`The latest user request asks you to create ${r}.`,`Before answering, call the appropriate media tool for this turn: ${e}.`,n,o,"For ordinary creative requests, infer reasonable defaults for purpose, style, and size instead of asking follow-up questions.","Ask the user only when a missing detail is critical to the result or the request is genuinely ambiguous."].join(`
1045
1045
  `))}return Er("fresh_workspace_evidence",()=>["# Fresh Workspace Evidence","","The latest user request asks for current workspace, shell, or URL state.",`Before answering, call one of these tools for this turn: ${e}.`,"Do not answer this request from conversation history, memory, or prior tool results.","For an explicit filename, inspect that exact file first and report the observed value.","If the filename is not found at the given path, use search to locate it, then read the located file before answering.","A filename search alone is not enough to answer content or code-symbol questions."].join(`
@@ -1190,12 +1190,12 @@ ${s.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.
1190
1190
  `)}],details:{type:"team",action:"create",teamName:n.team.name}}}case"delete":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for delete."}],details:{type:"team",error:"missing_name"}};let n=await t.deleteTeam(r.teamName);return n.success?{content:[{type:"text",text:`Team "${r.teamName}" disbanded.`}],details:{type:"team",action:"delete",teamName:r.teamName}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}}}case"list":{let n=await t.listTeams();if(!n.teams||n.teams.length===0)return{content:[{type:"text",text:"No active teams."}],details:{type:"team",action:"list",count:0}};let o=[`Active teams (${n.teams.length}):`,""];for(let i of n.teams)o.push(`- **${i.name}**: ${i.description||"(no description)"} \u2014 ${i.members.length} members`);return{content:[{type:"text",text:o.join(`
1191
1191
  `)}],details:{type:"team",action:"list",count:n.teams.length}}}case"status":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for status."}],details:{type:"team",error:"missing_name"}};let n=await t.getTeamStatus(r.teamName);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let o=n.team,i=n.memberProgress??{},s=[`Team: ${o.name}`,`Description: ${o.description||"\u2014"}`,`Lead: ${o.leadId}`,`Created: ${o.createdAt}`,"",`Members (${o.members.length}):`];for(let a of o.members){let c=a.tools?` [tools: ${a.tools.join(", ")}]`:"",u=a.worktreePath?` [worktree: ${a.worktreePath}]`:a.cwd?` [cwd: ${a.cwd}]`:"",d=i[a.name],p=a.isActive===!1?" (idle)":" (active)";if(d){let m=[];if(d.runningFor&&m.push(`running ${Math.round(d.runningFor/1e3)}s`),d.lastToolCall&&m.push(`tool: ${d.lastToolCall}`),d.idleFor!==void 0&&d.idleFor>5&&m.push(`idle ${d.idleFor}s`),d.mediaProgress){let g=d.mediaProgress;m.push(`${g.mediaType} ${g.percent}% [${g.status}] taskId=${g.taskId}${g.provider?` provider=${g.provider}`:""}`)}m.length&&(p=` (${m.join(", ")})`)}s.push(` - ${a.name} (${a.role})${c}${u}${p}`)}return{content:[{type:"text",text:s.join(`
1192
1192
  `)}],details:{type:"team",action:"status",teamName:o.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}import*as RU from"node:path";ve();function One(t){if(t&&typeof t=="object"&&"content"in t){let e=t.content;if(typeof e=="string")return e}return""}function jne(t,e){return`[message from ${e}]
1193
- ${t}`}function TU(t,e,r){let n=new Map,o={info:s=>e.info(s),warn:s=>e.warn(s)},i=new Zt({onNotification:(s,a,c)=>{t.sendNotification("team.member.notification",{memberId:s,method:a,params:c})},onStateChange:(s,a)=>{t.sendNotification("team.member.state",{memberId:s,state:a});let c=i.getHandle(s),d=i.getUsageTracker(s)?.getUsage();t.emitAgentStatus(s,a,{missedBeats:i.getMissedBeats(s),lastActivityAt:c?.lastActivityAt,usage:d&&d.totalTokens>0?{inputTokens:d.inputTokens,outputTokens:d.outputTokens,totalTokens:d.totalTokens}:void 0})},onExit:(s,a,c)=>{for(let u of n.values()){let d=u.members.find(p=>p.cwd&&Aa(u.name,p.name)===s);d&&(d.isActive=!1)}r.unregister(s),e.info(`[team] member ${s} exited (code=${a}, signal=${c})`)},onMcpToolCall:(s,a,c)=>t.handleMcpToolCall(s,a,c),log:{info:s=>e.info(s),warn:s=>e.warn(s),debug:s=>e.debug(s)},sessionDir:RU.join(H().getUserAgentHome(),"agent-logs")});return{async createTeam(s){if(n.has(s.teamName))return{success:!1,error:`Team "${s.teamName}" already exists.`};let a=await na(),c=[];for(let m of s.members??[]){let g={...m,isActive:!0};if(a){let f=`team-${s.teamName}-${m.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),h=await mE(a,f,o);h?(g.worktreePath=h.worktreePath,g.worktreeBranch=h.branch,g.cwd=h.worktreePath,e.info(`[team] provisioned worktree for ${m.name}: ${h.worktreePath}`)):(g.cwd=process.cwd(),e.warn(`[team] worktree provision failed for ${m.name}, using shared cwd`))}else g.cwd=process.cwd();c.push(g)}let u={name:s.teamName,description:s.description,leadId:t.currentSessionId??"default",members:c,createdAt:new Date().toISOString()};n.set(s.teamName,u);let d=[];for(let m of c){if(!m.cwd)continue;let g=Aa(s.teamName,m.name);try{await i.spawn({memberId:g,name:m.name,cwd:m.cwd,prompt:`You are the "${m.name}" team member. Role: ${m.role}.`,agentType:m.role,verbose:t.verbose}),r.register({memberId:g,name:m.name,teamName:s.teamName,role:m.role,deliver:async(f,h)=>One(await i.sendTask(g,jne(f,h))),isAlive:()=>i.isAlive(g)}),e.info(`[team] spawned child process for ${m.name} in ${m.cwd}`)}catch(f){let h=f instanceof Error?f.message:String(f);e.warn(`[team] failed to spawn child process for ${m.name}: ${h}`),m.isActive=!1,d.push({name:m.name,error:h})}}let p=c.filter(m=>m.cwd).length;return p>0&&d.length===p?(n.delete(s.teamName),{success:!1,error:`All ${p} team member(s) failed to spawn: `+d.map(m=>`${m.name} (${m.error})`).join("; ")}):(t.sendNotification("team.updated",{teamName:s.teamName,action:"created",members:u.members.map(m=>({agentName:m.name,role:m.role,worktreePath:m.worktreePath,pid:i.getHandle(Aa(s.teamName,m.name))?.pid}))}),d.length>0?{success:!0,team:u,partialFailures:d}:{success:!0,team:u})},async deleteTeam(s){let a=n.get(s);if(!a)return{success:!1,error:`Team "${s}" not found.`};for(let u of a.members){let d=Aa(s,u.name);r.unregister(d),i.kill(d),i.remove(d)}let c=await na();if(c)for(let u of a.members)u.worktreePath&&u.worktreeBranch&&(await gE(c,u.worktreePath,u.worktreeBranch,o),e.info(`[team] cleaned up worktree for ${u.name}: ${u.worktreePath}`));return n.delete(s),t.sendNotification("team.updated",{teamName:s,action:"destroyed",members:[]}),{success:!0}},async listTeams(){return{success:!0,teams:[...n.values()]}},async getTeamStatus(s){let a=n.get(s);if(!a)return{success:!1,error:`Team "${s}" not found.`};let c={};for(let u of a.members){let d=Aa(s,u.name),p=i.getStatus(d);p&&(u.isActive=p.alive,c[u.name]={mediaProgress:p.mediaProgress,lastToolCall:p.lastToolCall,idleFor:p.idleFor,runningFor:p.runningFor})}return{success:!0,team:a,memberProgress:c}},dispose(){i.dispose()}}}function Aa(t,e){return`team-${t}-${e}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()}function PU({host:t,log:e,toolCatalog:r,teamRegistry:n}){let o=TU(t,e,n);Fr(async()=>o.dispose()),r.addTool(xU(o))}var Lne="send_message",Une={type:"object",properties:{to:{type:"string",description:"Target agent name or '*' for broadcast to all team members. Must be a valid agent name within the current team."},message:{type:"string",description:"Message content to send to the target agent."},summary:{type:"string",description:"Optional short summary (for logging/routing)."}},required:["to","message"]};function AU(t){return{name:Lne,label:"Send Message",isEgress:!0,egressCarriesData:!0,description:"Send a message to another agent in your team. Use '*' to broadcast to all teammates. Messages are delivered asynchronously. Use for coordination, delegation, and status updates.",parameters:Une,execute:async(e,r)=>{if(!r.to||r.to.trim().length===0)return{content:[{type:"text",text:"Error: 'to' is required (agent name or '*')."}],details:{type:"send_message",error:"missing_target"}};if(!r.message||r.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"send_message",error:"empty_message"}};if(r.to!=="*"&&t.listTeammates){let s=t.listTeammates();if(!s.includes(r.to))return{content:[{type:"text",text:`Error: agent "${r.to}" not found in team. Available: ${s.join(", ")}`}],details:{type:"send_message",error:"target_not_found",available:s}}}let n=await t.sendMessage({to:r.to.trim(),message:r.message.trim(),summary:r.summary,senderId:t.getSenderId()});if(!n.success)return{content:[{type:"text",text:`Message delivery failed: ${n.error||"unknown error"}`}],details:{type:"send_message",success:!1,error:n.error}};let o=r.to==="*"?`broadcast (${n.recipients?.length||0} recipients)`:r.to,i=n.replies?.length?`
1193
+ ${t}`}function TU(t,e,r){let n=new Map,o={info:s=>e.info(s),warn:s=>e.warn(s)},i=new Zt({onNotification:(s,a,c)=>{t.sendNotification("team.member.notification",{memberId:s,method:a,params:c})},onStateChange:(s,a)=>{t.sendNotification("team.member.state",{memberId:s,state:a});let c=i.getHandle(s),d=i.getUsageTracker(s)?.getUsage();t.emitAgentStatus(s,a,{missedBeats:i.getMissedBeats(s),lastActivityAt:c?.lastActivityAt,usage:d&&d.totalTokens>0?{inputTokens:d.inputTokens,outputTokens:d.outputTokens,totalTokens:d.totalTokens}:void 0})},onExit:(s,a,c)=>{for(let u of n.values()){let d=u.members.find(p=>p.cwd&&Aa(u.name,p.name)===s);d&&(d.isActive=!1)}r.unregister(s),e.info(`[team] member ${s} exited (code=${a}, signal=${c})`)},onMcpToolCall:(s,a,c)=>t.handleMcpToolCall(s,a,c),log:{info:s=>e.info(s),warn:s=>e.warn(s),debug:s=>e.debug(s)},sessionDir:RU.join(H().getUserAgentHome(),"agent-logs")});return{async createTeam(s){if(n.has(s.teamName))return{success:!1,error:`Team "${s.teamName}" already exists.`};let a=await na(),c=[];for(let m of s.members??[]){let g={...m,isActive:!0};if(a){let f=`team-${s.teamName}-${m.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),h=await mE(a,f,o);h?(g.worktreePath=h.worktreePath,g.worktreeBranch=h.branch,g.cwd=h.worktreePath,e.info(`[team] provisioned worktree for ${m.name}: ${h.worktreePath}`)):(g.cwd=process.cwd(),e.warn(`[team] worktree provision failed for ${m.name}, using shared cwd`))}else g.cwd=process.cwd();c.push(g)}let u={name:s.teamName,description:s.description,leadId:t.currentSessionId??"default",members:c,createdAt:new Date().toISOString()};n.set(s.teamName,u);let d=[];for(let m of c){if(!m.cwd)continue;let g=Aa(s.teamName,m.name);try{let f=t.getLlmConfig();await i.spawn({memberId:g,name:m.name,cwd:m.cwd,prompt:`You are the "${m.name}" team member. Role: ${m.role}.`,agentType:m.role,verbose:t.verbose,...f?{model:f.model,apiKey:f.apiKey,baseUrl:f.baseUrl}:{}}),r.register({memberId:g,name:m.name,teamName:s.teamName,role:m.role,deliver:async(h,y)=>One(await i.sendTask(g,jne(h,y))),isAlive:()=>i.isAlive(g)}),e.info(`[team] spawned child process for ${m.name} in ${m.cwd}`)}catch(f){let h=f instanceof Error?f.message:String(f);e.warn(`[team] failed to spawn child process for ${m.name}: ${h}`),m.isActive=!1,d.push({name:m.name,error:h})}}let p=c.filter(m=>m.cwd).length;return p>0&&d.length===p?(n.delete(s.teamName),{success:!1,error:`All ${p} team member(s) failed to spawn: `+d.map(m=>`${m.name} (${m.error})`).join("; ")}):(t.sendNotification("team.updated",{teamName:s.teamName,action:"created",members:u.members.map(m=>({agentName:m.name,role:m.role,worktreePath:m.worktreePath,pid:i.getHandle(Aa(s.teamName,m.name))?.pid}))}),d.length>0?{success:!0,team:u,partialFailures:d}:{success:!0,team:u})},async deleteTeam(s){let a=n.get(s);if(!a)return{success:!1,error:`Team "${s}" not found.`};for(let u of a.members){let d=Aa(s,u.name);r.unregister(d),i.kill(d),i.remove(d)}let c=await na();if(c)for(let u of a.members)u.worktreePath&&u.worktreeBranch&&(await gE(c,u.worktreePath,u.worktreeBranch,o),e.info(`[team] cleaned up worktree for ${u.name}: ${u.worktreePath}`));return n.delete(s),t.sendNotification("team.updated",{teamName:s,action:"destroyed",members:[]}),{success:!0}},async listTeams(){return{success:!0,teams:[...n.values()]}},async getTeamStatus(s){let a=n.get(s);if(!a)return{success:!1,error:`Team "${s}" not found.`};let c={};for(let u of a.members){let d=Aa(s,u.name),p=i.getStatus(d);p&&(u.isActive=p.alive,c[u.name]={mediaProgress:p.mediaProgress,lastToolCall:p.lastToolCall,idleFor:p.idleFor,runningFor:p.runningFor})}return{success:!0,team:a,memberProgress:c}},dispose(){i.dispose()}}}function Aa(t,e){return`team-${t}-${e}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()}function PU({host:t,log:e,toolCatalog:r,teamRegistry:n}){let o=TU(t,e,n);Fr(async()=>o.dispose()),r.addTool(xU(o))}var Lne="send_message",Une={type:"object",properties:{to:{type:"string",description:"Target agent name or '*' for broadcast to all team members. Must be a valid agent name within the current team."},message:{type:"string",description:"Message content to send to the target agent."},summary:{type:"string",description:"Optional short summary (for logging/routing)."}},required:["to","message"]};function AU(t){return{name:Lne,label:"Send Message",isEgress:!0,egressCarriesData:!0,description:"Send a message to another agent in your team. Use '*' to broadcast to all teammates. Messages are delivered asynchronously. Use for coordination, delegation, and status updates.",parameters:Une,execute:async(e,r)=>{if(!r.to||r.to.trim().length===0)return{content:[{type:"text",text:"Error: 'to' is required (agent name or '*')."}],details:{type:"send_message",error:"missing_target"}};if(!r.message||r.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"send_message",error:"empty_message"}};if(r.to!=="*"&&t.listTeammates){let s=t.listTeammates();if(!s.includes(r.to))return{content:[{type:"text",text:`Error: agent "${r.to}" not found in team. Available: ${s.join(", ")}`}],details:{type:"send_message",error:"target_not_found",available:s}}}let n=await t.sendMessage({to:r.to.trim(),message:r.message.trim(),summary:r.summary,senderId:t.getSenderId()});if(!n.success)return{content:[{type:"text",text:`Message delivery failed: ${n.error||"unknown error"}`}],details:{type:"send_message",success:!1,error:n.error}};let o=r.to==="*"?`broadcast (${n.recipients?.length||0} recipients)`:r.to,i=n.replies?.length?`
1194
1194
 
1195
1195
  `+n.replies.map(s=>`${s.name} replied:
1196
1196
  ${s.reply}`).join(`
1197
1197
 
1198
- `):"";return{content:[{type:"text",text:`Message sent to ${o}.${i}`}],details:{type:"send_message",success:!0,to:r.to,recipients:n.recipients,replies:n.replies}}}}}function IU({host:t,log:e,toolCatalog:r,teamRegistry:n}){r.addTool(AU({sendMessage:async o=>{e.info(`[send_message] ${o.senderId} -> ${o.to}: ${o.message}`);let i=await n.deliver(o.to,o.message,o.senderId);return i.ok?{success:!0,recipients:i.replies?.map(s=>s.name)??[],replies:i.replies}:{success:!1,error:i.error}},getSenderId:()=>t.currentSessionId??"default",listTeammates:()=>n.list().filter(o=>o.alive).map(o=>o.name)}))}function CU(t){let e=new qd;nU({host:{get agent(){return t.host.agent},get currentTransport(){return t.host.currentTransport},get currentApiKey(){return t.host.currentApiKey},get currentModel(){return t.host.currentModel},sendNotification:t.host.sendNotification.bind(t.host),getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext()},hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),pU({toolCatalog:t.toolCatalog,host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),vU({toolCatalog:t.toolCatalog,host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),SU({log:t.log,toolCatalog:t.toolCatalog}),cU({config:t.config,toolCatalog:t.toolCatalog,host:{currentSessionId:t.host.currentSessionId}}),PU({host:{get currentSessionId(){return t.host.currentSessionId},get verbose(){return t.host.verbose},sendNotification:t.host.sendNotification.bind(t.host),emitAgentStatus:t.host.emitAgentStatus.bind(t.host),handleMcpToolCall:t.host.handleMcpToolCall.bind(t.host)},log:t.log,toolCatalog:t.toolCatalog,teamRegistry:e}),IU({toolCatalog:t.toolCatalog,host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log,teamRegistry:e})}var Fne={id:"cli-core-tools",kind:"core",register:Hne};function _U(t){Fne.register(t)}function Hne(t){let e={get agent(){return t.host.getAgent()},get currentTransport(){return t.host.getCurrentTransport()},get currentApiKey(){return t.host.getCurrentApiKey()},get currentModel(){return t.host.getCurrentModel()},get currentSessionId(){return t.host.getCurrentSessionId()},getActiveProjectRoot:()=>t.host.getActiveProjectRoot(),get verbose(){return t.host.getVerbose()},getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext(),sendNotification(n,o){t.host.sendNotification(n,o)},emitAgentStatus(n,o,i){t.host.emitAgentStatus(n,o,i)},handleMcpToolCall(n,o,i){return t.host.handleMcpToolCall(n,o,i)}},r={config:t.config,host:e,hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker};CU(r)}var zne={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
1198
+ `):"";return{content:[{type:"text",text:`Message sent to ${o}.${i}`}],details:{type:"send_message",success:!0,to:r.to,recipients:n.recipients,replies:n.replies}}}}}function IU({host:t,log:e,toolCatalog:r,teamRegistry:n}){r.addTool(AU({sendMessage:async o=>{e.info(`[send_message] ${o.senderId} -> ${o.to}: ${o.message}`);let i=await n.deliver(o.to,o.message,o.senderId);return i.ok?{success:!0,recipients:i.replies?.map(s=>s.name)??[],replies:i.replies}:{success:!1,error:i.error}},getSenderId:()=>t.currentSessionId??"default",listTeammates:()=>n.list().filter(o=>o.alive).map(o=>o.name)}))}function CU(t){let e=new qd;nU({host:{get agent(){return t.host.agent},get currentTransport(){return t.host.currentTransport},get currentApiKey(){return t.host.currentApiKey},get currentModel(){return t.host.currentModel},sendNotification:t.host.sendNotification.bind(t.host),getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext()},hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),pU({toolCatalog:t.toolCatalog,host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),vU({toolCatalog:t.toolCatalog,host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),SU({log:t.log,toolCatalog:t.toolCatalog}),cU({config:t.config,toolCatalog:t.toolCatalog,host:{currentSessionId:t.host.currentSessionId}}),PU({host:{get currentSessionId(){return t.host.currentSessionId},get verbose(){return t.host.verbose},getLlmConfig:()=>t.host.getLlmConfig(),sendNotification:t.host.sendNotification.bind(t.host),emitAgentStatus:t.host.emitAgentStatus.bind(t.host),handleMcpToolCall:t.host.handleMcpToolCall.bind(t.host)},log:t.log,toolCatalog:t.toolCatalog,teamRegistry:e}),IU({toolCatalog:t.toolCatalog,host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log,teamRegistry:e})}var Fne={id:"cli-core-tools",kind:"core",register:Hne};function _U(t){Fne.register(t)}function Hne(t){let e={get agent(){return t.host.getAgent()},get currentTransport(){return t.host.getCurrentTransport()},get currentApiKey(){return t.host.getCurrentApiKey()},get currentModel(){return t.host.getCurrentModel()},get currentBaseUrl(){return t.host.getCurrentBaseUrl()},get currentSessionId(){return t.host.getCurrentSessionId()},getActiveProjectRoot:()=>t.host.getActiveProjectRoot(),get verbose(){return t.host.getVerbose()},getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext(),getLlmConfig:()=>{let n=t.host.getCurrentModel(),o=t.host.getCurrentApiKey();return!n||!o?null:{model:n,apiKey:o,baseUrl:t.host.getCurrentBaseUrl()||void 0}},sendNotification(n,o){t.host.sendNotification(n,o)},emitAgentStatus(n,o,i){t.host.emitAgentStatus(n,o,i)},handleMcpToolCall(n,o,i){return t.host.handleMcpToolCall(n,o,i)}},r={config:t.config,host:e,hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker};CU(r)}var zne={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
1199
1199
  - goToDefinition: jump to symbol definition
1200
1200
  - findReferences: find all usages of a symbol
1201
1201
  - hover: get type/docs for symbol at position
@@ -1252,6 +1252,6 @@ CROSS-PROJECT RECALL: When you see '[Cross-project skill available]' in recalled
1252
1252
  Available skills:
1253
1253
  ${n}`}ve();import{randomUUID as tie}from"node:crypto";var Zoe=10080*60*1e3;function Joe(t){return{async record(e){if(!t)return"disabled";try{let r=await t.getConsent();return!r.enabled||!r.signalsEnabled?"disabled":(await t.recordSignal(e),"recorded")}catch{return"failed"}},async recordSkillUsage(e,r){let n=Uw(e);return n?this.record({resourceId:n,event:r,attribution:"skill-subturn",metadata:{skillName:e?.name,version:e?.registryVersion,effectiveRiskTier:e?.registryEffectiveRiskTier}}):"skipped"},async recordSkillLifecycle(e,r){let n=Uw(e);return n?this.record({resourceId:n,event:r,attribution:"skill-lifecycle",metadata:{skillName:e?.name,version:e?.registryVersion}}):"skipped"},async recordKeptSignals(e,r={}){let n=r.now??new Date,o=r.retentionMs??Zoe,i=[];for(let s of Object.values(e.records)){if(!Xoe(s,n,o))continue;let a=await this.recordSkillLifecycle(s,"kept");a==="recorded"&&(s.registryKeptSignalAt=n.toISOString()),i.push({skillName:s.name,status:a})}return i}}}function lF(){let t=xr();return t?Joe(t):null}function Uw(t){return t?.source!=="installed"||t.registrySourceTier==="official"?null:t.registryResourceId??t.name}function Xoe(t,e,r){if(!Uw(t)||t.registryKeptSignalAt)return!1;let n=Date.parse(t.lastUsedAt??t.createdAt);return Number.isFinite(n)?e.getTime()-n>=r:!1}import{spawn as IMe}from"node:child_process";function uF(t={}){let e=t.platform??process.platform;if(e!=="win32")return{level:"L0",available:!1,backend:"unsupported-platform",platform:e,reason:"unsupported-platform"};let r=t.processTreeLauncherAvailable===!0||t.jobObjectAvailable===!0;return{level:"L0",available:r,backend:r?"windows-process-tree-launcher":"unavailable",platform:e,reason:r?void 0:"windows-l0-not-provisioned"}}function dF(){return{envelope:"l0-launcher-audit-v1",backend:"windows-process-tree-launcher",defaultHostAccess:!0,noFsNetworkRestriction:!0,processTree:{killOnClose:!0,trackChildren:!0},jobObject:{implemented:!1,ready:!0}}}function Yoe(t={}){let e=t.availability??uF({platform:t.platform,appContainerAvailable:t.appContainerAvailable,jobObjectAvailable:t.jobObjectAvailable,processTreeLauncherAvailable:t.processTreeLauncherAvailable});return{getAvailability(){return e},decide(r){if(r.origin==="first-party"||r.origin==="official"||r.official===!0)return{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"first-party-action",backend:"first-party",l0:e};if(r.origin==="community"&&r.executable===!0){let o=e.available?"launcher-required":"launcher-unavailable";return{allowed:e.available,spawnAllowed:e.available,launcherRequired:!0,reason:o,backend:"community-l0-launcher",l0:e,launcher:eie(r,e.available?"allowed":"blocked",o)}}let n=r.riskTier??"unknown";return!Qoe(n)||!r.executable?{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"community-low-risk",backend:"community-l1-l2",l0:e}:r.autoRun===!1?{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"manual-run",backend:"community-l1-l2",l0:e}:{allowed:e.available,spawnAllowed:e.available,launcherRequired:!0,reason:e.available?"l0-available":"l0-unavailable",backend:"community-l0",l0:e}}}}function pF(){return Yoe()}function Qoe(t){return t==="R2"||t==="R3"}function eie(t,e,r){return{level:"L0",mode:"os-native-launcher",defaultHostAccess:!0,noFsNetworkRestriction:!0,audit:{envelope:"l0-launcher-audit-v1",subject:{origin:t.origin,official:t.official===!0,executable:t.executable===!0,autoRun:t.autoRun===!0},decision:e,reason:r},windows:dF()}}async function fF(t){let{host:e,toolCatalog:r,skillName:n,skillContent:o,userArgs:i,signal:s}=t,a=`skill_${n}_${tie().slice(0,8)}`,c=e.getAgent();if(!c)return"[skill] Cannot execute: no LLM provider configured";let u=H().getOwnerProfileDir(),d=e.getCurrentSessionId()||"skill",p=Ae(u).records[n],m=t.communitySignalReporter??lF(),g=(t.skillSandbox??pF()).decide({origin:yF(p)?"community":"first-party",riskTier:p?.registryEffectiveRiskTier??p?.registryRiskTier??"unknown",executable:!0,autoRun:!0});if(!g.allowed)return await m?.recordSkillUsage(p,"fail"),`[skill "${n}"] blocked: community ${g.reason} (${g.l0.reason??g.l0.backend})`;let f=hF(n,p);e.getCurrentHooks()?.invoke("subagent.started",{sessionId:d,turnId:a,subagentId:a,agentType:f}).catch(()=>{});let h=new Set(["skill","agent"]),y=r.getToolManifest().filter(b=>!h.has(b.function.name)),S=i??`Execute skill "${n}" instructions.`,w=[],v;for await(let b of c.run({turnId:a,sessionId:d,messages:[{role:"user",content:S}],tools:y,systemPrompt:o,config:{parentDepth:1,maxRounds:5}},s)){if(b.type==="end"&&b.content)return mF(e,d,a,f,"normal"),gF(u,n,!0),await m?.recordSkillUsage(p,"success"),b.content;if(b.type==="delta"&&b.text&&w.push(b.text),b.type==="error"){v=b.error;break}}return mF(e,d,a,f,v?"error":"normal",v),v?(aw(u,n,!1),await m?.recordSkillUsage(p,"error"),`[skill "${n}"] error: ${v}`):(gF(u,n,!0),await m?.recordSkillUsage(p,"success"),w.join("")||`[skill "${n}"] completed (no output)`)}function hF(t,e){return rie(e)?`community-skill:${t}`:`skill:${t}`}function rie(t){return yF(t)}function yF(t){return t?.source!=="installed"?!1:t.registrySourceTier!=="official"}function mF(t,e,r,n,o,i){t.getCurrentHooks()?.invoke("subagent.stopped",{sessionId:e,turnId:r,subagentId:r,agentType:n,reason:o,error:i}).catch(()=>{})}function gF(t,e,r){aw(t,e,r);let n=Ae(t);cC(n,e),Ue(t,n)}var nie={id:"skill-meta-tool",kind:"skill",register:({host:t,...e})=>oie(t,e)};function vF(t,e){nie.register({...e,host:t})}function oie(t,e){let r=e.pathService;e.toolCatalog.addTool(cF({listSkills:()=>{let n=eC(t.getActiveProjectRoot()).map(o=>({name:o.name,description:o.description,source:o.enabledScope,filePath:o.filePath,baseDir:o.baseDir}));return n.push(...t.getPluginSkills()),n},listSkillsFull:async n=>{let o=[],i=new Set;for(let s of so(t.getActiveProjectRoot())){let a=s.enabledScope;n&&a!==n||(i.add(a),o.push({name:s.name,description:s.description??`Skill (${a})`,category:a,scope:s.enabledScope,version:s.version}))}for(let s of t.getPluginSkills())n&&s.source!==n||(i.add(s.source??"plugin"),o.push({name:s.name,description:`Plugin skill (${s.source})`,category:s.source,scope:"plugin"}));return{skills:o,categories:[...i]}},readSkillContent:async n=>{let o=ao(n);if(!o)return null;try{return await rr.promises.readFile(o.filePath,"utf8")}catch{return null}},viewSkill:async(n,o)=>{let i=ao(n);if(!i)return null;let s=o?_i.join(i.baseDir,o):i.filePath;try{let a=await rr.promises.readFile(s,"utf8");return{name:n,content:a}}catch{return null}},executeSkillSubturn:async(n,o,i,s)=>fF({host:t,toolCatalog:e.toolCatalog,skillName:n,skillContent:o,userArgs:i,signal:s}),manageSkill:async n=>{let o=t.getActiveProjectRoot(),i=r.getUserSkillsDir(),s=_i.join(i,n.name),a=_i.join(s,"SKILL.md"),c=r.getOwnerProfileDir();switch(n.action){case"create":{let u=n.content??"",p=ob(u,n.name,`Skill: ${n.name}`)??u,m=Wl(p,n.name);if(!m.valid)return{success:!1,message:`Skill validation failed: ${m.errors.join("; ")}`};let g=Ae(c);if(g.records[n.name]?.pinned&&rr.existsSync(a))return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};await rr.promises.mkdir(s,{recursive:!0}),await rr.promises.writeFile(a,p,"utf8"),t.sendNotification("turn.skill_instruction",{turnId:`skill-create-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:p,scope:"project"}}),dt(),Ot(g,n.name,"created"),Ue(c,g),$n(n.name),o&&Ur(o,n.name);let f=t.getMemoryLearningSink(),h=t.getMemoryUserId();if(f&&h){let S=p.split(`
1254
1254
  `).slice(0,3).join(" ").slice(0,200),w=o?_i.basename(o):"unknown";f.ingestExtracted([{text:`Learned skill "${n.name}" in project "${w}": ${S}`,category:"skill-learning"}],h).catch(()=>{})}let y=o?` (project-scoped). To make it available across all projects, use: skill promote name:"${n.name}"`:"";return{success:!0,message:`Skill "${n.name}" created${y}`,path:s}}case"edit":{let u=Ae(c);if(u.records[n.name]?.pinned)return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};let d=n.content??"",m=ob(d,n.name)??d;return await rr.promises.writeFile(a,m,"utf8"),tb(u,n.name),Ue(c,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:m,scope:"project"}}),{success:!0,message:`Skill "${n.name}" updated`,path:a}}case"patch":{let u=Ae(c);if(u.records[n.name]?.pinned)return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};let d=await rr.promises.readFile(a,"utf8");if(!n.oldString||!d.includes(n.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let p=d.replace(n.oldString,n.newString??"");return await rr.promises.writeFile(a,p,"utf8"),tb(u,n.name),Ue(c,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:p,scope:"project"}}),{success:!0,message:`Skill "${n.name}" patched`,path:a}}case"delete":{let u=Ae(c);return u.records[n.name]?.pinned?{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`}:(await rr.promises.rm(s,{recursive:!0,force:!0}),Hl(u,n.name),Ue(c,u),No(n.name),o&&Nn(o,n.name),t.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",action:"delete",scope:"project"}}),dt(),{success:!0,message:`Skill "${n.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${n.action}`}}},promoteSkill:async n=>{let o=ao(n);if(!o)return{success:!1,message:`Skill "${n}" not found in skill store. Cannot promote.`};let i=r.getOwnerProfileDir(),s=Ae(i),a=Ot(s,n);a.source="promoted",Ue(i,s),No(n);let c=t.getActiveProjectRoot();c&&Nn(c,n);let u="";try{u=await rr.promises.readFile(o.filePath,"utf8")}catch{}return t.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:n,category:"promoted",content:u,scope:"global"}}),dt(),{success:!0,message:`Skill "${n}" promoted to global. It is now available across all projects.`,path:o.baseDir}}}))}function bF(t){let e=nF({log:t.log,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,projectRoot:t.projectRoot,memdir:t.memdir,toolCatalog:t.toolCatalog,currentUserId:t.currentUserId,prefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,compressionClient:{transport:t.agentClient.transport,apiKey:t.agentClient.apiKey},sendNotification:(o,i)=>t.sendNotification(o,i)}),r=e.hooks;qU({config:t.config,projectRoot:t.projectRoot,pathService:t.pathService,log:t.log,toolCatalog:t.toolCatalog,currentManager:t.currentMcpManager,setManager:t.setMcpManager,setReady:t.setMcpReady}),JU({config:t.config,hooks:r,log:t.log,pathService:t.pathService,toolCatalog:t.toolCatalog,setPluginLoader:t.setPluginLoader});let n=QU({config:t.config,toolCatalog:t.toolCatalog,hooks:r,log:t.log,sessionId:t.sessionId,getTurnId:t.getTurnId,getActiveProjectRoot:()=>t.projectRoot,getActiveWorkdir:()=>t.pathService.getActiveWorkdir(),getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentUnregister:t.currentPermissionUnregister});return vF({getActiveProjectRoot:()=>t.projectRoot,getPluginSkills:t.getPluginSkills,getAgent:t.getAgent,getCurrentSessionId:()=>t.sessionId,getCurrentHooks:()=>r,sendNotification:t.sendNotification,getMemoryLearningSink:()=>e.memoryLearningSink,getMemoryUserId:()=>e.memoryUserId},{config:t.config,pathService:t.pathService,toolCatalog:t.toolCatalog}),_U({config:t.config,host:t.coreToolHost,hooks:r,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),UU({config:t.config,pathService:t.pathService,toolCatalog:t.toolCatalog}),t.sessionId&&r.invoke("session.created",{sessionId:t.sessionId}).catch(()=>{}),aF({config:t.config,hooks:r,ruleEngine:n.ruleEngine,sessionId:t.sessionId,currentFileWatcher:t.currentFileWatcher,log:t.log,setFileWatcher:t.setFileWatcher}),{hooks:r,memoryHandlerProvider:e.memoryHandlerProvider,memoryDreamProvider:e.memoryDreamProvider,memoryUserId:e.memoryUserId,permissionChecker:n.permissionChecker,permissionUnregister:n.permissionUnregister,ruleEngine:n.ruleEngine}}function kF(t){let{provider:e,model:r,apiKey:n,baseUrl:o}=t.resolvedConfig,i=hu({provider:e,model:r,apiKey:n,baseUrl:o},t.providerRegistry);return i.transport=pM(i.transport,t.sessionId||"default"),{transport:i.transport,apiKey:n,model:r,provider:e,baseUrl:o??""}}function wF(t){return{agent:new Fo({llmTransport:t.client.transport,apiKey:t.client.apiKey,toolInvoker:t.toolInvoker,log:t.log,hooks:t.hooks,maxRounds:t.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot,runtimePorts:fc()}),...t.client}}import{randomUUID as iie}from"node:crypto";async function SF(t){let e=[],r=t.result.content.map(d=>{if(d.type==="image"&&d.data){let p=d.mimeType||"image/png";return e.push(`data:${p};base64,${d.data}`),"[Image]"}return d.text??""}).join(`
1255
- `),n=e.length>0?[...e,...t.result.imageUrls??[]]:t.result.imageUrls,o=t.result.details?.error,i=o?r:void 0,s=t.result.details?.type,a=t.result.details?{...t.result.details}:void 0,c=s?.split("_")[0];if(s==="three_d_generate"&&(c="3d"),c&&["image","tts","video","music","3d"].includes(c)){let d=t.result.details?.mediaUrls??[];if(d.length>0)try{let p=await t.mediaPersistence.downloadAll(d,{type:c,sessionId:t.sessionId||void 0},{warn:m=>t.log(m)});if(p.length>0){let m=new Map(p.map(g=>[g.remoteUrl,GL(g.localPath)]));for(let g of p)r=r.replaceAll(g.remoteUrl,g.localPath);d=d.map(g=>m.get(g)??g),t.sendNotification("turn.media_persisted",{turnId:t.turnId,files:p.map(g=>({remoteUrl:g.remoteUrl,localPath:g.localPath,bytes:g.bytes,mimeType:g.mimeType}))})}}catch{}a&&(a.mediaUrls=d)}if(s==="task"&&!o&&t.result.details?.taskList)try{let d=t.result.details;d?.taskList&&t.sendNotification("turn.todos_updated",{turnId:t.turnId,items:d.taskList,summary:{total:d.total??d.taskList.length,completed:d.completed??0,inProgress:d.inProgress??0,notStarted:d.notStarted??0}})}catch{}let u=Array.isArray(t.result.details?.matches)?t.result.details.matches:void 0;return{result:r,error:i,toolReferences:u,imageUrls:n,details:a}}function xF(t){return{invoke:async(e,r,n,o)=>{if(r.startsWith("$"))return{result:n};let i=t.toolCatalog.findTool(r);if(!i)return{result:"",error:`Unknown tool: ${r}`};if(typeof i.execute!="function")return{result:"",error:`Tool is not executable: ${r}`};let s=i.execute,a=`tc_${iie().slice(0,8)}`;try{let c=JSON.parse(n),u=t.getSessionId(),d;try{d=t.mediaPersistence.getMediaDir()}catch{d=void 0}let p=await IM(d,()=>s(a,c,o));return await SF({turnId:e,sessionId:u,result:p,mediaPersistence:t.mediaPersistence,log:t.log,sendNotification:(m,g)=>t.sendNotification(m,g)})}catch(c){return{result:"",error:c instanceof Error?c.message:String(c)}}}}}function RF(t){let e={info:s=>t.log(s),warn:s=>t.log(`[warn] ${s}`),error:s=>t.log(`[error] ${s}`),debug:s=>{t.verbose&&t.log(`[debug] ${s}`)}},r=xF({mediaPersistence:t.mediaPersistence,toolCatalog:t.toolCatalog,getSessionId:()=>t.sessionId,log:s=>t.log(s),sendNotification:t.sendNotification}),n=kF({resolvedConfig:t.resolvedTextConfig,providerRegistry:t.providerRegistry,sessionId:t.sessionId}),o=bF({config:t.config,log:e,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,getTurnId:t.getTurnId,projectRoot:t.projectRoot,pathService:t.pathService,memdir:t.memdir,currentUserId:t.currentUserId,memoryPrefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,agentClient:n,toolCatalog:t.toolCatalog,currentMcpManager:t.runtimeSession.mcpManager,setMcpManager:t.setMcpManager,setMcpReady:t.setMcpReady,setPluginLoader:t.setPluginLoader,getPluginSkills:()=>t.runtimeSession.getPluginSkills(),getAgent:t.getAgent,getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentPermissionUnregister:t.runtimeSession.permissionUnregister,coreToolHost:t.coreToolHost,toolInvoker:r,currentFileWatcher:t.runtimeSession.fileWatcher,setFileWatcher:t.setFileWatcher});return t.runtimeSession.applyBootstrap(o),{agent:wF({client:n,toolInvoker:r,log:e,hooks:o.hooks,maxRounds:t.config.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot}).agent,agentClient:n,toolInvoker:r,hooks:o.hooks}}var aie=sie(import.meta.url);function cie(){for(let t of["../package.json","../../package.json"])try{return aie(t).version}catch{}return"0.0.0"}var TF=cie();var lie=new Set(["thread.user_response"]);var np=class{running=!1;startedAt=Date.now();packageVersion=TF;rpcContract=new Ui;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;runtimeServices;runtimeSession=new Nd;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Ua;backgroundTasks=new Fa(this.taskStore);pendingTaskNotifications=[];memoryPrefetchState=nr();lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=Dd();pendingAskUser=new Map;sessionTaskDomain;acpSessionMeta=null;multiAgentHandlerHost;acpServer=null;sessionHistory=new Ld;idleDreamCoordinator;petConfirmCoordinator;modelRegistryHydration=null;get registry(){return this.runtimeServices.providerRegistry}get mediaClient(){return this.runtimeServices.mediaClient}get mediaPersistence(){return this.runtimeServices.mediaPersistence}get pathService(){return this.runtimeServices.pathService}get toolCatalog(){return this.runtimeServices.toolCatalog}get petRuntime(){return this.runtimeServices.petRuntime}get currentHooks(){return this.runtimeSession.currentHooks}get permissionChecker(){return this.runtimeSession.permissionChecker}set permissionChecker(e){this.runtimeSession.permissionChecker=e}set mcpManager(e){this.runtimeSession.mcpManager=e}get memoryProvider(){return this.runtimeSession.memoryProvider}set memoryProvider(e){this.runtimeSession.memoryProvider=e}get memoryDreamProvider(){return this.runtimeSession.memoryDreamProvider}set memoryDreamProvider(e){this.runtimeSession.memoryDreamProvider=e}get memoryUserId(){return this.runtimeSession.memoryUserId}set memoryUserId(e){this.runtimeSession.memoryUserId=e}constructor(e){this.verbose=e.verbose,this.runtimeServices=JL({verbose:e.verbose,getActiveProjectRoot:()=>this.getActiveProjectRoot(),resolveClientForPurpose:r=>this.resolveClientForPurpose(r),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n)}),this.petConfirmCoordinator=new Fd({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=NL({getActiveProjectRoot:()=>this.getActiveProjectRoot(),emitAgentStatus:(r,n,o)=>this.emitAgentStatus(r,n,o),handleMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),sendResponse:(r,n,o)=>this.sendResponse(r,n,o)}),this.idleDreamCoordinator=new Ud({log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),getCurrentSessionId:()=>this.currentSessionId,getCurrentTurnCount:()=>this.sessionState?.turnCount??0,getActiveTurn:()=>this.activeTurn,resolveDreamClient:()=>this.resolveClientForPurpose("textGeneration"),resolveMemoryRoot:()=>Fw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),listRecentSessions:()=>Gt(20,this.getActiveProjectRoot()),runDream:r=>zo.call(this.createDreamHandlerHost(),r)}),W().onChange(()=>{this.invalidateResolvedLlmCache()}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ao({verbose:e.verbose}),this.taskStore.onTaskChange((r,n)=>{n&&this.sendNotification("task.updated",{taskId:r,type:n.type,lifecycle:n.lifecycle,label:n.label})}),this.backgroundTasks.onTaskSettled(r=>{this.pendingTaskNotifications.push(SS(r,r.output??r.error??""))})}getActiveProjectRoot(){return this.pathService.getActiveProjectRoot()}drainPendingTaskNotifications(){if(this.pendingTaskNotifications.length===0)return[];let e=this.pendingTaskNotifications;return this.pendingTaskNotifications=[],e}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=W();e.load(),await jn(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let r=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${r}`),e})),this.modelRegistryHydration}syncToolListMediaConfig(){this.configureTurnMedia(void 0,this.currentTurnId||"tools-list")}configureTurnMedia(e,r){let n=this;this.runtimeServices.configureTurnMedia({host:{get currentMediaApiKeys(){return n.currentMediaApiKeys},set currentMediaApiKeys(o){n.currentMediaApiKeys=o},get sessionState(){return n.sessionState},sendNotification:(o,i)=>this.sendNotification(o,i)},config:e,turnId:r})}setActiveWorkdir(e){this.pathService.setActiveWorkdir(e)}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(Sm(e)||Hi(e)){this.acpServer.dispatchMessage(e);return}if(Fi(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!km(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}async stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer();for(let e of this.rpcDeadlineTimers.values())clearTimeout(e);this.rpcDeadlineTimers.clear(),this.rpcIds.clear(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{await ZS(),this.runtimeSession.stopFileWatcher(),await this.runtimeSession.disconnectMcp(),this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}methodHandlers=jj(this);handleMessage(e){if(e.id!==void 0&&!lie.has(e.method)){let n=Qa(e);if(!n.ok){this.sendContractError(e.id,n.error);return}let o=this.rpcContract.begin(e.method,n.meta);if(o.status==="rejected"){this.sendContractError(e.id,o.error);return}if(o.status==="deduped"){this.sendContractErrorOrResult(e.id,o.result,o.error);return}this.rpcIds.set(e.id,n.meta),this.scheduleRpcDeadline(e.id,e.method,n.meta)}let r=this.methodHandlers.get(e.method);if(r){let n=o=>{e.id!==void 0&&this.rpcIds.has(e.id)&&this.sendResponse(e.id,void 0,{code:k.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})};try{Promise.resolve(r(e)).catch(n)}catch(o){n(o)}}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:k.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}ensureDefaultProject(){this.memdir=HL({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return OL({purpose:e,providerRegistry:this.registry,currentProvider:this.currentProvider,currentTransport:this.currentTransport})}ensureMemoryProvider(){if(this.memoryProvider)return;let e=this.runtimeServices.ensureMemoryProvider(this.memoryUserId);this.runtimeSession.memoryProvider=e.handlerProvider,this.runtimeSession.memoryDreamProvider=e.dreamProvider,this.runtimeSession.memoryUserId=e.userId}resolveAgent(e){let r=$L(e,u=>this.log(u));if(!r)return null;let{provider:n,model:o,apiKey:i,baseUrl:s,configKey:a}=r;if(this.agent&&this.lastLlmConfigKey===a)return e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s),this.agent;e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s);let c=RF({config:e,taskStore:this.taskStore,backgroundTasks:this.backgroundTasks,sessionId:this.currentSessionId??"",getTurnId:()=>this.currentTurnId,projectRoot:this.getActiveProjectRoot(),pathService:this.pathService,memdir:this.memdir,currentUserId:this.memoryUserId,memoryPrefetchState:this.memoryPrefetchState,getLastUserMessage:()=>this.lastUserMessageForAutoExtract,getLastAssistantMessage:()=>this.lastAssistantMessageForExtract,resolveSmallModelClient:()=>this.resolveClientForPurpose("smallModel"),resolvedTextConfig:r,verbose:this.verbose,providerRegistry:this.registry,mediaPersistence:this.mediaPersistence,toolCatalog:this.toolCatalog,runtimeSession:this.runtimeSession,setMcpManager:u=>{this.runtimeSession.mcpManager=u},setMcpReady:u=>{this.runtimeSession.mcpReady=u},setPluginLoader:u=>{this.runtimeSession.pluginLoader=u},getAgent:()=>this.agent,getAcpPermissionSession:()=>this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)?{sessionId:this.currentSessionId,requestPermission:u=>this.acpServer.requestPermission(u)}:void 0,sendNotification:(u,d)=>this.sendNotification(u,d),isPetActive:()=>this.petRuntime.isActive(),coreToolHost:{getAgent:()=>this.agent,getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),getVerbose:()=>this.verbose,getBackgroundTasks:()=>this.backgroundTasks,getConversationHistory:()=>this.currentSessionId?this.sessionHistory.getResumedHistory(this.currentSessionId):null,isGroupContext:()=>Ga(),sendNotification:(u,d)=>this.sendNotification(u,d),emitAgentStatus:(u,d,p)=>this.emitAgentStatus(u,d,p),handleMcpToolCall:(u,d,p)=>this.handleMcpToolCall(u,d,p)},setFileWatcher:u=>{this.runtimeSession.fileWatcher=u},log:u=>this.log(u)});return this.agent=c.agent,this.lastLlmConfigKey=a,this.currentTransport=c.agentClient.transport,this.currentApiKey=c.agentClient.apiKey,this.currentModel=c.agentClient.model,this.currentProvider=c.agentClient.provider,this.currentBaseUrl=c.agentClient.baseUrl,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}invalidateResolvedLlmCache(){this.agent=null,this.lastLlmConfigKey="",this.currentTransport=null,this.currentApiKey="",this.currentModel="",this.currentProvider="",this.currentBaseUrl="",this.currentMediaApiKeys=null}emitAgentStatus(e,r,n){this.sendNotification("agents.status",LL(e,r,n))}createDreamHandlerHost(){return UL({getActiveTurn:()=>this.activeTurn,setActiveTurn:e=>{this.activeTurn=e},getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentHooks:()=>this.currentHooks,getMemoryProvider:()=>this.memoryDreamProvider,getMemoryUserId:()=>this.memoryUserId,getToolCatalog:()=>this.runtimeServices.toolCatalog,getTaskStore:()=>this.taskStore,getVerbose:()=>this.verbose,log:e=>this.log(e),resolveMemoryRoot:()=>Fw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n)})}createAcpExtendedHandlerHost(){return zL({dreamHost:this.createDreamHandlerHost(),multiAgentHost:this.multiAgentHandlerHost,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n),emitAgentStatus:(e,r,n)=>this.emitAgentStatus(e,r,n),handleMcpToolCall:(e,r,n)=>this.handleMcpToolCall(e,r,n),resolveClientForPurpose:e=>this.resolveClientForPurpose(e),pendingAskUser:this.pendingAskUser})}async handleMcpToolCall(e,r,n){return jL({toolCatalog:this.toolCatalog,memberId:e,toolName:r,args:n})}sendResponse(e,r,n){let o=this.rpcIds.get(e);if(o){let s=this.rpcContract.settle(o.requestId,r,n);if(this.clearRpcLifecycle(e),!s.accepted){this.log(`[rpc] dropped late response id=${String(e)} requestId=${o.requestId} reason=${s.reason}`);return}}let i={jsonrpc:"2.0",id:e};n?i.error=n:i.result=r,this.writeStdout(i)}sendContractError(e,r){let n={jsonrpc:"2.0",id:e,error:r};this.writeStdout(n)}sendContractErrorOrResult(e,r,n){if(n){this.sendContractError(e,n);return}let o={jsonrpc:"2.0",id:e,result:r};this.writeStdout(o)}scheduleRpcDeadline(e,r,n){let o=Math.max(0,n.deadlineAt-Date.now()),i=setTimeout(()=>{if(!this.rpcIds.has(e))return;let s=this.rpcContract.expire(n.requestId);this.clearRpcLifecycle(e),s&&(this.log(`[rpc] deadline exceeded method=${r} id=${String(e)} requestId=${n.requestId}`),this.writeStdout({jsonrpc:"2.0",id:e,error:{code:k.REQUEST_DEADLINE_EXCEEDED,message:`RPC request deadline exceeded: ${r}.`}}))},o);i.unref?.(),this.rpcDeadlineTimers.set(e,i)}clearRpcLifecycle(e){let r=this.rpcDeadlineTimers.get(e);r&&clearTimeout(r),this.rpcDeadlineTimers.delete(e),this.rpcIds.delete(e)}sendNotification(e,r){if(!(this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)&&ux(this.acpServer,this.currentSessionId,e,r))){let n={jsonrpc:"2.0",method:e,params:r};this.writeStdout(n)}this.idleDreamCoordinator.handleTurnNotification(e)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`${JSON.stringify({ts:new Date().toISOString(),level:"info",service:"qlogicagent",message:e})}
1255
+ `),n=e.length>0?[...e,...t.result.imageUrls??[]]:t.result.imageUrls,o=t.result.details?.error,i=o?r:void 0,s=t.result.details?.type,a=t.result.details?{...t.result.details}:void 0,c=s?.split("_")[0];if(s==="three_d_generate"&&(c="3d"),c&&["image","tts","video","music","3d"].includes(c)){let d=t.result.details?.mediaUrls??[];if(d.length>0)try{let p=await t.mediaPersistence.downloadAll(d,{type:c,sessionId:t.sessionId||void 0},{warn:m=>t.log(m)});if(p.length>0){let m=new Map(p.map(g=>[g.remoteUrl,GL(g.localPath)]));for(let g of p)r=r.replaceAll(g.remoteUrl,g.localPath);d=d.map(g=>m.get(g)??g),t.sendNotification("turn.media_persisted",{turnId:t.turnId,files:p.map(g=>({remoteUrl:g.remoteUrl,localPath:g.localPath,bytes:g.bytes,mimeType:g.mimeType}))})}}catch{}a&&(a.mediaUrls=d)}if(s==="task"&&!o&&t.result.details?.taskList)try{let d=t.result.details;d?.taskList&&t.sendNotification("turn.todos_updated",{turnId:t.turnId,items:d.taskList,summary:{total:d.total??d.taskList.length,completed:d.completed??0,inProgress:d.inProgress??0,notStarted:d.notStarted??0}})}catch{}let u=Array.isArray(t.result.details?.matches)?t.result.details.matches:void 0;return{result:r,error:i,toolReferences:u,imageUrls:n,details:a}}function xF(t){return{invoke:async(e,r,n,o)=>{if(r.startsWith("$"))return{result:n};let i=t.toolCatalog.findTool(r);if(!i)return{result:"",error:`Unknown tool: ${r}`};if(typeof i.execute!="function")return{result:"",error:`Tool is not executable: ${r}`};let s=i.execute,a=`tc_${iie().slice(0,8)}`;try{let c=JSON.parse(n),u=t.getSessionId(),d;try{d=t.mediaPersistence.getMediaDir()}catch{d=void 0}let p=await IM(d,()=>s(a,c,o));return await SF({turnId:e,sessionId:u,result:p,mediaPersistence:t.mediaPersistence,log:t.log,sendNotification:(m,g)=>t.sendNotification(m,g)})}catch(c){return{result:"",error:c instanceof Error?c.message:String(c)}}}}}function RF(t){let e={info:s=>t.log(s),warn:s=>t.log(`[warn] ${s}`),error:s=>t.log(`[error] ${s}`),debug:s=>{t.verbose&&t.log(`[debug] ${s}`)}},r=xF({mediaPersistence:t.mediaPersistence,toolCatalog:t.toolCatalog,getSessionId:()=>t.sessionId,log:s=>t.log(s),sendNotification:t.sendNotification}),n=kF({resolvedConfig:t.resolvedTextConfig,providerRegistry:t.providerRegistry,sessionId:t.sessionId}),o=bF({config:t.config,log:e,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,getTurnId:t.getTurnId,projectRoot:t.projectRoot,pathService:t.pathService,memdir:t.memdir,currentUserId:t.currentUserId,memoryPrefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,agentClient:n,toolCatalog:t.toolCatalog,currentMcpManager:t.runtimeSession.mcpManager,setMcpManager:t.setMcpManager,setMcpReady:t.setMcpReady,setPluginLoader:t.setPluginLoader,getPluginSkills:()=>t.runtimeSession.getPluginSkills(),getAgent:t.getAgent,getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentPermissionUnregister:t.runtimeSession.permissionUnregister,coreToolHost:t.coreToolHost,toolInvoker:r,currentFileWatcher:t.runtimeSession.fileWatcher,setFileWatcher:t.setFileWatcher});return t.runtimeSession.applyBootstrap(o),{agent:wF({client:n,toolInvoker:r,log:e,hooks:o.hooks,maxRounds:t.config.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot}).agent,agentClient:n,toolInvoker:r,hooks:o.hooks}}var aie=sie(import.meta.url);function cie(){for(let t of["../package.json","../../package.json"])try{return aie(t).version}catch{}return"0.0.0"}var TF=cie();var lie=new Set(["thread.user_response"]);var np=class{running=!1;startedAt=Date.now();packageVersion=TF;rpcContract=new Ui;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;runtimeServices;runtimeSession=new Nd;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Ua;backgroundTasks=new Fa(this.taskStore);pendingTaskNotifications=[];memoryPrefetchState=nr();lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=Dd();pendingAskUser=new Map;sessionTaskDomain;acpSessionMeta=null;multiAgentHandlerHost;acpServer=null;sessionHistory=new Ld;idleDreamCoordinator;petConfirmCoordinator;modelRegistryHydration=null;get registry(){return this.runtimeServices.providerRegistry}get mediaClient(){return this.runtimeServices.mediaClient}get mediaPersistence(){return this.runtimeServices.mediaPersistence}get pathService(){return this.runtimeServices.pathService}get toolCatalog(){return this.runtimeServices.toolCatalog}get petRuntime(){return this.runtimeServices.petRuntime}get currentHooks(){return this.runtimeSession.currentHooks}get permissionChecker(){return this.runtimeSession.permissionChecker}set permissionChecker(e){this.runtimeSession.permissionChecker=e}set mcpManager(e){this.runtimeSession.mcpManager=e}get memoryProvider(){return this.runtimeSession.memoryProvider}set memoryProvider(e){this.runtimeSession.memoryProvider=e}get memoryDreamProvider(){return this.runtimeSession.memoryDreamProvider}set memoryDreamProvider(e){this.runtimeSession.memoryDreamProvider=e}get memoryUserId(){return this.runtimeSession.memoryUserId}set memoryUserId(e){this.runtimeSession.memoryUserId=e}constructor(e){this.verbose=e.verbose,this.runtimeServices=JL({verbose:e.verbose,getActiveProjectRoot:()=>this.getActiveProjectRoot(),resolveClientForPurpose:r=>this.resolveClientForPurpose(r),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n)}),this.petConfirmCoordinator=new Fd({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=NL({getActiveProjectRoot:()=>this.getActiveProjectRoot(),emitAgentStatus:(r,n,o)=>this.emitAgentStatus(r,n,o),handleMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),sendResponse:(r,n,o)=>this.sendResponse(r,n,o)}),this.idleDreamCoordinator=new Ud({log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),getCurrentSessionId:()=>this.currentSessionId,getCurrentTurnCount:()=>this.sessionState?.turnCount??0,getActiveTurn:()=>this.activeTurn,resolveDreamClient:()=>this.resolveClientForPurpose("textGeneration"),resolveMemoryRoot:()=>Fw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),listRecentSessions:()=>Gt(20,this.getActiveProjectRoot()),runDream:r=>zo.call(this.createDreamHandlerHost(),r)}),W().onChange(()=>{this.invalidateResolvedLlmCache()}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ao({verbose:e.verbose}),this.taskStore.onTaskChange((r,n)=>{n&&this.sendNotification("task.updated",{taskId:r,type:n.type,lifecycle:n.lifecycle,label:n.label})}),this.backgroundTasks.onTaskSettled(r=>{this.pendingTaskNotifications.push(SS(r,r.output??r.error??""))})}getActiveProjectRoot(){return this.pathService.getActiveProjectRoot()}drainPendingTaskNotifications(){if(this.pendingTaskNotifications.length===0)return[];let e=this.pendingTaskNotifications;return this.pendingTaskNotifications=[],e}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=W();e.load(),await jn(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let r=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${r}`),e})),this.modelRegistryHydration}syncToolListMediaConfig(){this.configureTurnMedia(void 0,this.currentTurnId||"tools-list")}configureTurnMedia(e,r){let n=this;this.runtimeServices.configureTurnMedia({host:{get currentMediaApiKeys(){return n.currentMediaApiKeys},set currentMediaApiKeys(o){n.currentMediaApiKeys=o},get sessionState(){return n.sessionState},sendNotification:(o,i)=>this.sendNotification(o,i)},config:e,turnId:r})}setActiveWorkdir(e){this.pathService.setActiveWorkdir(e)}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(Sm(e)||Hi(e)){this.acpServer.dispatchMessage(e);return}if(Fi(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!km(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}async stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer();for(let e of this.rpcDeadlineTimers.values())clearTimeout(e);this.rpcDeadlineTimers.clear(),this.rpcIds.clear(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{await ZS(),this.runtimeSession.stopFileWatcher(),await this.runtimeSession.disconnectMcp(),this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}methodHandlers=jj(this);handleMessage(e){if(e.id!==void 0&&!lie.has(e.method)){let n=Qa(e);if(!n.ok){this.sendContractError(e.id,n.error);return}let o=this.rpcContract.begin(e.method,n.meta);if(o.status==="rejected"){this.sendContractError(e.id,o.error);return}if(o.status==="deduped"){this.sendContractErrorOrResult(e.id,o.result,o.error);return}this.rpcIds.set(e.id,n.meta),this.scheduleRpcDeadline(e.id,e.method,n.meta)}let r=this.methodHandlers.get(e.method);if(r){let n=o=>{e.id!==void 0&&this.rpcIds.has(e.id)&&this.sendResponse(e.id,void 0,{code:k.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})};try{Promise.resolve(r(e)).catch(n)}catch(o){n(o)}}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:k.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}ensureDefaultProject(){this.memdir=HL({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return OL({purpose:e,providerRegistry:this.registry,currentProvider:this.currentProvider,currentTransport:this.currentTransport})}ensureMemoryProvider(){if(this.memoryProvider)return;let e=this.runtimeServices.ensureMemoryProvider(this.memoryUserId);this.runtimeSession.memoryProvider=e.handlerProvider,this.runtimeSession.memoryDreamProvider=e.dreamProvider,this.runtimeSession.memoryUserId=e.userId}resolveAgent(e){let r=$L(e,u=>this.log(u));if(!r)return null;let{provider:n,model:o,apiKey:i,baseUrl:s,configKey:a}=r;if(this.agent&&this.lastLlmConfigKey===a)return e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s),this.agent;e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s);let c=RF({config:e,taskStore:this.taskStore,backgroundTasks:this.backgroundTasks,sessionId:this.currentSessionId??"",getTurnId:()=>this.currentTurnId,projectRoot:this.getActiveProjectRoot(),pathService:this.pathService,memdir:this.memdir,currentUserId:this.memoryUserId,memoryPrefetchState:this.memoryPrefetchState,getLastUserMessage:()=>this.lastUserMessageForAutoExtract,getLastAssistantMessage:()=>this.lastAssistantMessageForExtract,resolveSmallModelClient:()=>this.resolveClientForPurpose("smallModel"),resolvedTextConfig:r,verbose:this.verbose,providerRegistry:this.registry,mediaPersistence:this.mediaPersistence,toolCatalog:this.toolCatalog,runtimeSession:this.runtimeSession,setMcpManager:u=>{this.runtimeSession.mcpManager=u},setMcpReady:u=>{this.runtimeSession.mcpReady=u},setPluginLoader:u=>{this.runtimeSession.pluginLoader=u},getAgent:()=>this.agent,getAcpPermissionSession:()=>this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)?{sessionId:this.currentSessionId,requestPermission:u=>this.acpServer.requestPermission(u)}:void 0,sendNotification:(u,d)=>this.sendNotification(u,d),isPetActive:()=>this.petRuntime.isActive(),coreToolHost:{getAgent:()=>this.agent,getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentBaseUrl:()=>this.currentBaseUrl,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),getVerbose:()=>this.verbose,getBackgroundTasks:()=>this.backgroundTasks,getConversationHistory:()=>this.currentSessionId?this.sessionHistory.getResumedHistory(this.currentSessionId):null,isGroupContext:()=>Ga(),sendNotification:(u,d)=>this.sendNotification(u,d),emitAgentStatus:(u,d,p)=>this.emitAgentStatus(u,d,p),handleMcpToolCall:(u,d,p)=>this.handleMcpToolCall(u,d,p)},setFileWatcher:u=>{this.runtimeSession.fileWatcher=u},log:u=>this.log(u)});return this.agent=c.agent,this.lastLlmConfigKey=a,this.currentTransport=c.agentClient.transport,this.currentApiKey=c.agentClient.apiKey,this.currentModel=c.agentClient.model,this.currentProvider=c.agentClient.provider,this.currentBaseUrl=c.agentClient.baseUrl,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}invalidateResolvedLlmCache(){this.agent=null,this.lastLlmConfigKey="",this.currentTransport=null,this.currentApiKey="",this.currentModel="",this.currentProvider="",this.currentBaseUrl="",this.currentMediaApiKeys=null}emitAgentStatus(e,r,n){this.sendNotification("agents.status",LL(e,r,n))}createDreamHandlerHost(){return UL({getActiveTurn:()=>this.activeTurn,setActiveTurn:e=>{this.activeTurn=e},getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentHooks:()=>this.currentHooks,getMemoryProvider:()=>this.memoryDreamProvider,getMemoryUserId:()=>this.memoryUserId,getToolCatalog:()=>this.runtimeServices.toolCatalog,getTaskStore:()=>this.taskStore,getVerbose:()=>this.verbose,log:e=>this.log(e),resolveMemoryRoot:()=>Fw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n)})}createAcpExtendedHandlerHost(){return zL({dreamHost:this.createDreamHandlerHost(),multiAgentHost:this.multiAgentHandlerHost,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n),emitAgentStatus:(e,r,n)=>this.emitAgentStatus(e,r,n),handleMcpToolCall:(e,r,n)=>this.handleMcpToolCall(e,r,n),resolveClientForPurpose:e=>this.resolveClientForPurpose(e),pendingAskUser:this.pendingAskUser})}async handleMcpToolCall(e,r,n){return jL({toolCatalog:this.toolCatalog,memberId:e,toolName:r,args:n})}sendResponse(e,r,n){let o=this.rpcIds.get(e);if(o){let s=this.rpcContract.settle(o.requestId,r,n);if(this.clearRpcLifecycle(e),!s.accepted){this.log(`[rpc] dropped late response id=${String(e)} requestId=${o.requestId} reason=${s.reason}`);return}}let i={jsonrpc:"2.0",id:e};n?i.error=n:i.result=r,this.writeStdout(i)}sendContractError(e,r){let n={jsonrpc:"2.0",id:e,error:r};this.writeStdout(n)}sendContractErrorOrResult(e,r,n){if(n){this.sendContractError(e,n);return}let o={jsonrpc:"2.0",id:e,result:r};this.writeStdout(o)}scheduleRpcDeadline(e,r,n){let o=Math.max(0,n.deadlineAt-Date.now()),i=setTimeout(()=>{if(!this.rpcIds.has(e))return;let s=this.rpcContract.expire(n.requestId);this.clearRpcLifecycle(e),s&&(this.log(`[rpc] deadline exceeded method=${r} id=${String(e)} requestId=${n.requestId}`),this.writeStdout({jsonrpc:"2.0",id:e,error:{code:k.REQUEST_DEADLINE_EXCEEDED,message:`RPC request deadline exceeded: ${r}.`}}))},o);i.unref?.(),this.rpcDeadlineTimers.set(e,i)}clearRpcLifecycle(e){let r=this.rpcDeadlineTimers.get(e);r&&clearTimeout(r),this.rpcDeadlineTimers.delete(e),this.rpcIds.delete(e)}sendNotification(e,r){if(!(this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)&&ux(this.acpServer,this.currentSessionId,e,r))){let n={jsonrpc:"2.0",method:e,params:r};this.writeStdout(n)}this.idleDreamCoordinator.handleTurnNotification(e)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`${JSON.stringify({ts:new Date().toISOString(),level:"info",service:"qlogicagent",message:e})}
1256
1256
  `)}enableIdleDream(e){this.idleDreamCoordinator.enable(e)}cancelIdleDreamTimer(){this.idleDreamCoordinator.cancelTimer()}disposeSessionRuntime(){this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.agent=null,this.lastLlmConfigKey="",this.memoryPrefetchState=nr(),this.runtimeSession.resetAfterSessionDispose()}closeMemoryProviders(){this.runtimeServices.closeMemoryProviders({memoryProvider:this.memoryProvider,memoryDreamProvider:this.memoryDreamProvider}),this.runtimeSession.resetMemoryProviders()}initAcpServer(){let e=CL(this,TF,this.createAcpExtendedHandlerHost());this.acpServer=new ec(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}};function PF(t){let e={verbose:!1};for(let r of t.slice(2))(r==="--verbose"||r==="-v")&&(e.verbose=!0);return e}import{writeFileSync as uie,appendFileSync as IF,mkdirSync as die}from"node:fs";import{join as Hw}from"node:path";import{homedir as pie}from"node:os";var CF=Hw(process.env.QLOGICAGENT_HOME||Hw(pie(),".qlogicagent"),"debug-logs");try{die(CF,{recursive:!0})}catch{}var zw=Hw(CF,"acp-session.log");try{uie(zw,"")}catch{}function Ht(t){let e=`[${new Date().toISOString()}] ${t}
1257
1257
  `;_F.call(process.stderr,e);try{IF(zw,e)}catch{}}var _F=process.stderr.write.bind(process.stderr);process.stderr.write=((t,...e)=>{let r=typeof t=="string"?t:Buffer.from(t).toString();try{IF(zw,r)}catch{}return _F(t,...e)});Ht(`PID=${process.pid} argv=${JSON.stringify(process.argv.slice(1))} cwd=${process.cwd()} HOME=${process.env.QLOGICAGENT_HOME??"(unset)"} NODE=${process.version}`);var EF=PF(process.argv),mie=!process.argv.includes("--no-acp"),gie=new Ao({verbose:EF.verbose}),Bw=new np({verbose:EF.verbose,transport:gie});mie&&(Bw.initAcpServer(),Ht("ACP server initialized, waiting for messages"));process.on("unhandledRejection",t=>{Ht(`unhandledRejection: ${t instanceof Error?t.stack??t.message:String(t)}`)});process.on("uncaughtException",t=>{Ht(`uncaughtException: ${t.stack??t.message}`)});process.stdin.on("end",()=>{Ht("stdin END received")});process.stdin.on("close",()=>{Ht("stdin CLOSE received")});process.stdout.on("error",t=>{Ht(`stdout ERROR: ${t.message}`)});process.stdout.on("close",()=>{Ht("stdout CLOSE")});process.on("exit",t=>{Ht(`process.exit code=${t}`)});var AF=!1;async function MF(t){if(!AF){AF=!0,Ht(`${t} received`);try{YA(),await Bw.stop()}finally{process.exit(0)}}}process.on("SIGTERM",()=>{MF("SIGTERM")});process.on("SIGINT",()=>{MF("SIGINT")});process.on("SIGHUP",()=>{Ht("SIGHUP received")});Ht("calling server.start()");Bw.start();Ht("server.start() returned, event loop active");