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/index.js
CHANGED
|
@@ -606,7 +606,7 @@ Return a brief summary of what you consolidated, updated, or pruned. If nothing
|
|
|
606
606
|
|
|
607
607
|
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 hy(t,e){if(t instanceof Wo){let n=new Is(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 Is(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 HT={};var rl={};Bt(rl,{ZodISODate:()=>Qc,ZodISODateTime:()=>Yc,ZodISODuration:()=>tl,ZodISOTime:()=>el,date:()=>vy,datetime:()=>yy,duration:()=>ky,time:()=>by});var Yc=T("ZodISODateTime",(t,e)=>{Of.init(t,e),ye.init(t,e)});function yy(t){return Mh(Yc,t)}var Qc=T("ZodISODate",(t,e)=>{jf.init(t,e),ye.init(t,e)});function vy(t){return Dh(Qc,t)}var el=T("ZodISOTime",(t,e)=>{Lf.init(t,e),ye.init(t,e)});function by(t){return Nh(el,t)}var tl=T("ZodISODuration",(t,e)=>{Uf.init(t,e),ye.init(t,e)});function ky(t){return $h(tl,t)}var BT=(t,e)=>{is.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>as(t,r)},flatten:{value:r=>ss(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},OW=T("ZodError",BT),Jo=T("ZodError",BT,{Parent:Error});var wy=gc(Jo),Sy=hc(Jo),xy=vc(Jo),Ry=bc(Jo);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)=>wy(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>xy(t,r,n),t.parseAsync=async(r,n)=>Sy(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ry(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(_P(r,n)),t.superRefine=r=>t.check(EP(r)),t.overwrite=r=>t.check(qr(r)),t.optional=()=>il(t),t.nullable=()=>sl(t),t.nullish=()=>il(sl(t)),t.nonoptional=r=>vP(t,r),t.array=()=>Gy(t),t.or=r=>dl([t,r]),t.and=r=>oP(t,r),t.transform=r=>al(t,Jy(r)),t.default=r=>fP(t,r),t.prefault=r=>yP(t,r),t.catch=r=>wP(t,r),t.pipe=r=>al(t,r),t.readonly=()=>RP(t),t.describe=r=>{let n=t.clone();return wr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return wr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return wr.get(t);let n=t.clone();return wr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Ay=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(hs(...n)),t.includes=(...n)=>t.check(bs(...n)),t.startsWith=(...n)=>t.check(ks(...n)),t.endsWith=(...n)=>t.check(ws(...n)),t.min=(...n)=>t.check(ln(...n)),t.max=(...n)=>t.check(Vo(...n)),t.length=(...n)=>t.check(Zo(...n)),t.nonempty=(...n)=>t.check(ln(1,...n)),t.lowercase=n=>t.check(ys(n)),t.uppercase=n=>t.check(vs(n)),t.trim=()=>t.check(Rs()),t.normalize=(...n)=>t.check(xs(...n)),t.toLowerCase=()=>t.check(Ts()),t.toUpperCase=()=>t.check(Ps())}),_s=T("ZodString",(t,e)=>{Jn.init(t,e),Ay.init(t,e),t.email=r=>t.check(_c(Iy,r)),t.url=r=>t.check($c(Cy,r)),t.jwt=r=>t.check(Jc(qy,r)),t.emoji=r=>t.check(Oc(_y,r)),t.guid=r=>t.check(gs(nl,r)),t.uuid=r=>t.check(Ec(Gr,r)),t.uuidv4=r=>t.check(Mc(Gr,r)),t.uuidv6=r=>t.check(Dc(Gr,r)),t.uuidv7=r=>t.check(Nc(Gr,r)),t.nanoid=r=>t.check(jc(Ey,r)),t.guid=r=>t.check(gs(nl,r)),t.cuid=r=>t.check(Lc(My,r)),t.cuid2=r=>t.check(Uc(Dy,r)),t.ulid=r=>t.check(Fc(Ny,r)),t.base64=r=>t.check(Kc(Hy,r)),t.base64url=r=>t.check(Vc(zy,r)),t.xid=r=>t.check(Hc($y,r)),t.ksuid=r=>t.check(zc(Oy,r)),t.ipv4=r=>t.check(Bc(jy,r)),t.ipv6=r=>t.check(qc(Ly,r)),t.cidrv4=r=>t.check(Wc(Uy,r)),t.cidrv6=r=>t.check(Gc(Fy,r)),t.e164=r=>t.check(Zc(By,r)),t.datetime=r=>t.check(yy(r)),t.date=r=>t.check(vy(r)),t.time=r=>t.check(by(r)),t.duration=r=>t.check(ky(r))});function Ty(t){return Ch(_s,t)}var ye=T("ZodStringFormat",(t,e)=>{fe.init(t,e),Ay.init(t,e)}),Iy=T("ZodEmail",(t,e)=>{Af.init(t,e),ye.init(t,e)});function LW(t){return _c(Iy,t)}var nl=T("ZodGUID",(t,e)=>{Tf.init(t,e),ye.init(t,e)});function UW(t){return gs(nl,t)}var Gr=T("ZodUUID",(t,e)=>{Pf.init(t,e),ye.init(t,e)});function FW(t){return Ec(Gr,t)}function HW(t){return Mc(Gr,t)}function zW(t){return Dc(Gr,t)}function BW(t){return Nc(Gr,t)}var Cy=T("ZodURL",(t,e)=>{If.init(t,e),ye.init(t,e)});function qW(t){return $c(Cy,t)}var _y=T("ZodEmoji",(t,e)=>{Cf.init(t,e),ye.init(t,e)});function WW(t){return Oc(_y,t)}var Ey=T("ZodNanoID",(t,e)=>{_f.init(t,e),ye.init(t,e)});function GW(t){return jc(Ey,t)}var My=T("ZodCUID",(t,e)=>{Ef.init(t,e),ye.init(t,e)});function KW(t){return Lc(My,t)}var Dy=T("ZodCUID2",(t,e)=>{Mf.init(t,e),ye.init(t,e)});function VW(t){return Uc(Dy,t)}var Ny=T("ZodULID",(t,e)=>{Df.init(t,e),ye.init(t,e)});function ZW(t){return Fc(Ny,t)}var $y=T("ZodXID",(t,e)=>{Nf.init(t,e),ye.init(t,e)});function JW(t){return Hc($y,t)}var Oy=T("ZodKSUID",(t,e)=>{$f.init(t,e),ye.init(t,e)});function XW(t){return zc(Oy,t)}var jy=T("ZodIPv4",(t,e)=>{Ff.init(t,e),ye.init(t,e)});function YW(t){return Bc(jy,t)}var Ly=T("ZodIPv6",(t,e)=>{Hf.init(t,e),ye.init(t,e)});function QW(t){return qc(Ly,t)}var Uy=T("ZodCIDRv4",(t,e)=>{zf.init(t,e),ye.init(t,e)});function e2(t){return Wc(Uy,t)}var Fy=T("ZodCIDRv6",(t,e)=>{Bf.init(t,e),ye.init(t,e)});function t2(t){return Gc(Fy,t)}var Hy=T("ZodBase64",(t,e)=>{Wf.init(t,e),ye.init(t,e)});function r2(t){return Kc(Hy,t)}var zy=T("ZodBase64URL",(t,e)=>{Gf.init(t,e),ye.init(t,e)});function n2(t){return Vc(zy,t)}var By=T("ZodE164",(t,e)=>{Kf.init(t,e),ye.init(t,e)});function o2(t){return Zc(By,t)}var qy=T("ZodJWT",(t,e)=>{Vf.init(t,e),ye.init(t,e)});function i2(t){return Jc(qy,t)}var qT=T("ZodCustomStringFormat",(t,e)=>{Zf.init(t,e),ye.init(t,e)});function s2(t,e,r={}){return gy(qT,t,e,r)}var Es=T("ZodNumber",(t,e)=>{Tc.init(t,e),J.init(t,e),t.gt=(n,o)=>t.check(Br(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(zr(n,o)),t.lte=(n,o)=>t.check(Gt(n,o)),t.max=(n,o)=>t.check(Gt(n,o)),t.int=n=>t.check(Py(n)),t.safe=n=>t.check(Py(n)),t.positive=n=>t.check(Br(0,n)),t.nonnegative=n=>t.check(vt(0,n)),t.negative=n=>t.check(zr(0,n)),t.nonpositive=n=>t.check(Gt(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 WT(t){return Oh(Es,t)}var Xo=T("ZodNumberFormat",(t,e)=>{Jf.init(t,e),Es.init(t,e)});function Py(t){return Lh(Xo,t)}function a2(t){return Uh(Xo,t)}function c2(t){return Fh(Xo,t)}function l2(t){return Hh(Xo,t)}function u2(t){return zh(Xo,t)}var Ms=T("ZodBoolean",(t,e)=>{ls.init(t,e),J.init(t,e)});function GT(t){return Bh(Ms,t)}var Ds=T("ZodBigInt",(t,e)=>{Pc.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(Br(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(zr(n,o)),t.lte=(n,o)=>t.check(Gt(n,o)),t.max=(n,o)=>t.check(Gt(n,o)),t.positive=n=>t.check(Br(BigInt(0),n)),t.negative=n=>t.check(zr(BigInt(0),n)),t.nonpositive=n=>t.check(Gt(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 d2(t){return Wh(Ds,t)}var Wy=T("ZodBigIntFormat",(t,e)=>{Xf.init(t,e),Ds.init(t,e)});function p2(t){return Kh(Wy,t)}function m2(t){return Vh(Wy,t)}var KT=T("ZodSymbol",(t,e)=>{Yf.init(t,e),J.init(t,e)});function g2(t){return Zh(KT,t)}var VT=T("ZodUndefined",(t,e)=>{Qf.init(t,e),J.init(t,e)});function f2(t){return Jh(VT,t)}var ZT=T("ZodNull",(t,e)=>{eh.init(t,e),J.init(t,e)});function JT(t){return Xh(ZT,t)}var XT=T("ZodAny",(t,e)=>{th.init(t,e),J.init(t,e)});function h2(){return Yh(XT)}var YT=T("ZodUnknown",(t,e)=>{qo.init(t,e),J.init(t,e)});function ol(){return Go(YT)}var QT=T("ZodNever",(t,e)=>{rh.init(t,e),J.init(t,e)});function cl(t){return Qh(QT,t)}var eP=T("ZodVoid",(t,e)=>{nh.init(t,e),J.init(t,e)});function y2(t){return ey(eP,t)}var ll=T("ZodDate",(t,e)=>{oh.init(t,e),J.init(t,e),t.min=(n,o)=>t.check(vt(n,o)),t.max=(n,o)=>t.check(Gt(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 v2(t){return ty(ll,t)}var tP=T("ZodArray",(t,e)=>{us.init(t,e),J.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(ln(r,n)),t.nonempty=r=>t.check(ln(1,r)),t.max=(r,n)=>t.check(Vo(r,n)),t.length=(r,n)=>t.check(Zo(r,n)),t.unwrap=()=>t.element});function Gy(t,e){return As(tP,t,e)}function b2(t){let e=t._zod.def.shape;return dP(Object.keys(e))}var ul=T("ZodObject",(t,e)=>{ih.init(t,e),J.init(t,e),$.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>lP(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ol()}),t.loose=()=>t.clone({...t._zod.def,catchall:ol()}),t.strict=()=>t.clone({...t._zod.def,catchall:cl()}),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(Xy,t,r[0]),t.required=(...r)=>$.required(Yy,t,r[0])});function k2(t,e){let r={type:"object",get shape(){return $.assignProp(this,"shape",{...t}),this.shape},...$.normalizeParams(e)};return new ul(r)}function w2(t,e){return new ul({type:"object",get shape(){return $.assignProp(this,"shape",{...t}),this.shape},catchall:cl(),...$.normalizeParams(e)})}function S2(t,e){return new ul({type:"object",get shape(){return $.assignProp(this,"shape",{...t}),this.shape},catchall:ol(),...$.normalizeParams(e)})}var Ky=T("ZodUnion",(t,e)=>{Ac.init(t,e),J.init(t,e),t.options=e.options});function dl(t,e){return new Ky({type:"union",options:t,...$.normalizeParams(e)})}var rP=T("ZodDiscriminatedUnion",(t,e)=>{Ky.init(t,e),sh.init(t,e)});function x2(t,e,r){return new rP({type:"union",options:e,discriminator:t,...$.normalizeParams(r)})}var nP=T("ZodIntersection",(t,e)=>{ah.init(t,e),J.init(t,e)});function oP(t,e){return new nP({type:"intersection",left:t,right:e})}var iP=T("ZodTuple",(t,e)=>{Xn.init(t,e),J.init(t,e),t.rest=r=>t.clone({...t._zod.def,rest:r})});function R2(t,e,r){let n=e instanceof K,o=n?r:e,i=n?e:null;return new iP({type:"tuple",items:t,rest:i,...$.normalizeParams(o)})}var Vy=T("ZodRecord",(t,e)=>{ch.init(t,e),J.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function sP(t,e,r){return new Vy({type:"record",keyType:t,valueType:e,...$.normalizeParams(r)})}function T2(t,e,r){return new Vy({type:"record",keyType:dl([t,cl()]),valueType:e,...$.normalizeParams(r)})}var aP=T("ZodMap",(t,e)=>{lh.init(t,e),J.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function P2(t,e,r){return new aP({type:"map",keyType:t,valueType:e,...$.normalizeParams(r)})}var cP=T("ZodSet",(t,e)=>{uh.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(Ko(...r)),t.size=(...r)=>t.check(fs(...r))});function A2(t,e){return new cP({type:"set",valueType:t,...$.normalizeParams(e)})}var Cs=T("ZodEnum",(t,e)=>{dh.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 Cs({...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 Cs({...e,checks:[],...$.normalizeParams(o),entries:i})}});function lP(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Cs({type:"enum",entries:r,...$.normalizeParams(e)})}function I2(t,e){return new Cs({type:"enum",entries:t,...$.normalizeParams(e)})}var uP=T("ZodLiteral",(t,e)=>{ph.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 dP(t,e){return new uP({type:"literal",values:Array.isArray(t)?t:[t],...$.normalizeParams(e)})}var pP=T("ZodFile",(t,e)=>{mh.init(t,e),J.init(t,e),t.min=(r,n)=>t.check(Qn(r,n)),t.max=(r,n)=>t.check(Ko(r,n)),t.mime=(r,n)=>t.check(Ss(Array.isArray(r)?r:[r],n))});function C2(t){return uy(pP,t)}var Zy=T("ZodTransform",(t,e)=>{ds.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 Jy(t){return new Zy({type:"transform",transform:t})}var Xy=T("ZodOptional",(t,e)=>{gh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function il(t){return new Xy({type:"optional",innerType:t})}var mP=T("ZodNullable",(t,e)=>{fh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function sl(t){return new mP({type:"nullable",innerType:t})}function _2(t){return il(sl(t))}var gP=T("ZodDefault",(t,e)=>{hh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function fP(t,e){return new gP({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var hP=T("ZodPrefault",(t,e)=>{yh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function yP(t,e){return new hP({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Yy=T("ZodNonOptional",(t,e)=>{vh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function vP(t,e){return new Yy({type:"nonoptional",innerType:t,...$.normalizeParams(e)})}var bP=T("ZodSuccess",(t,e)=>{bh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function E2(t){return new bP({type:"success",innerType:t})}var kP=T("ZodCatch",(t,e)=>{kh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function wP(t,e){return new kP({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var SP=T("ZodNaN",(t,e)=>{wh.init(t,e),J.init(t,e)});function M2(t){return ny(SP,t)}var Qy=T("ZodPipe",(t,e)=>{ps.init(t,e),J.init(t,e),t.in=e.in,t.out=e.out});function al(t,e){return new Qy({type:"pipe",in:t,out:e})}var xP=T("ZodReadonly",(t,e)=>{Sh.init(t,e),J.init(t,e)});function RP(t){return new xP({type:"readonly",innerType:t})}var TP=T("ZodTemplateLiteral",(t,e)=>{xh.init(t,e),J.init(t,e)});function D2(t,e){return new TP({type:"template_literal",parts:t,...$.normalizeParams(e)})}var PP=T("ZodLazy",(t,e)=>{Th.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.getter()});function AP(t){return new PP({type:"lazy",getter:t})}var IP=T("ZodPromise",(t,e)=>{Rh.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function N2(t){return new IP({type:"promise",innerType:t})}var pl=T("ZodCustom",(t,e)=>{Ph.init(t,e),J.init(t,e)});function CP(t){let e=new xe({check:"custom"});return e._zod.check=t,e}function $2(t,e){return dy(pl,t??(()=>!0),e)}function _P(t,e={}){return py(pl,t,e)}function EP(t){let e=CP(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 O2(t,e={error:`Input not instance of ${t.name}`}){let r=new pl({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...$.normalizeParams(e)});return r._zod.bag.Class=t,r}var j2=(...t)=>my({Pipe:Qy,Boolean:Ms,String:_s,Transform:Zy},...t);function L2(t){let e=AP(()=>dl([Ty(t),WT(),GT(),JT(),Gy(e),sP(Ty(),e)]));return e}function U2(t,e){return al(Jy(t),e)}var F2={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 H2(t){De({customError:t})}function z2(){return De().customError}var ev={};Bt(ev,{bigint:()=>G2,boolean:()=>W2,date:()=>K2,number:()=>q2,string:()=>B2});function B2(t){return _h(_s,t)}function q2(t){return jh(Es,t)}function W2(t){return qh(Ms,t)}function G2(t){return Gh(Ds,t)}function K2(t){return ry(ll,t)}De(Ic());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"},Kt={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 MP=Symbol("skippedItem");function j(t,e){return t.catch(e)}function or(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(MP)).transform(e=>e.filter(r=>r!==MP))}var Z2=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),terminal:l.boolean().optional().default(!1)}),J2=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)}),X2=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string().nullish(),id:l.string(),name:l.string()}),Y2=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(J2)}),Q2=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()}),eG=l.union([Y2.and(l.object({type:l.literal("env_var")})),Q2.and(l.object({type:l.literal("terminal")})),X2]),DP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),methodId:l.string()}),tG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),rG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),blob:l.string(),mimeType:l.string().nullish(),uri:l.string()}),nG=l.object({default:l.boolean().nullish(),description:l.string().nullish(),title:l.string().nullish()}),oG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),iG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),sG=l.object({amount:l.number(),currency:l.string()}),aG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),terminalId:l.string()}),cG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),lG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),newText:l.string(),oldText:l.string().nullish(),path:l.string()}),NP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:l.string()}),uG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),dG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),pG=l.union([l.string(),l.number(),l.number(),l.boolean(),l.array(l.string())]),mG=l.object({content:l.record(l.string(),pG).nullish()}),gG=l.intersection(l.union([mG.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()})),fG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),$P=l.string(),rv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),elicitationId:$P}),hG=l.literal("object"),yG=l.literal("string"),vG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),bG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),form:j(fG.nullish(),()=>{}),url:j(vG.nullish(),()=>{})}),OP=l.object({const:l.string(),title:l.string()}),jP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),name:l.string(),value:l.string()}),kG=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"})]),LP=l.object({code:kG,data:l.unknown().optional(),message:l.string()}),UP=l.unknown(),FP=l.unknown(),HP=l.unknown(),wG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),readTextFile:l.boolean().optional().default(!1),writeTextFile:l.boolean().optional().default(!1)}),zP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),name:l.string(),value:l.string()}),BP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),name:l.string(),title:l.string().nullish(),version:l.string()}),SG=l.object({default:l.number().nullish(),description:l.string().nullish(),maximum:l.number().nullish(),minimum:l.number().nullish(),title:l.string().nullish()}),xG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),qP=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),WP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),cursor:l.string().nullish(),cwd:l.string().nullish()}),nv=l.union([l.literal("anthropic"),l.literal("openai"),l.literal("azure"),l.literal("vertex"),l.literal("bedrock"),l.string()]),RG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),TG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),logout:j(RG.nullish(),()=>{})}),GP=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),PG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),AG=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)}),ml=l.string(),IG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),connectionId:ml}),CG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),connectionId:ml}),KP=l.string(),_G=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),acpId:KP}),EG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:KP,name:l.string()}),MG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),headers:l.array(zP),name:l.string(),url:l.string()}),DG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),headers:l.array(zP),name:l.string(),url:l.string()}),NG=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),args:l.array(l.string()),command:l.string(),env:l.array(jP),name:l.string()}),gl=l.union([MG.and(l.object({type:l.literal("http")})),DG.and(l.object({type:l.literal("sse")})),EG.and(l.object({type:l.literal("acp")})),NG]),$G=l.string(),VP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),connectionId:ml,method:l.string(),params:l.record(l.string(),l.unknown()).nullish()}),ZP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),connectionId:ml,method:l.string(),params:l.record(l.string(),l.unknown()).nullish()}),JP=l.unknown(),OG=l.union([l.literal("error"),l.literal("warning"),l.literal("information"),l.literal("hint")]),jG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),LG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),UG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),FG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),HG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),zG=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()}),BG=l.object({diff:l.string(),uri:l.string()}),qG=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()}),WG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),GG=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),KG=l.object({languageId:l.string(),text:l.string(),uri:l.string()}),VG=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()}),ZG=l.union([l.literal("rejected"),l.literal("ignored"),l.literal("replaced"),l.literal("cancelled")]),JG=l.object({excerpts:l.array(qG),uri:l.string()}),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({name:l.string(),owner:l.string(),remoteUrl:l.string()}),e4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),t4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),jump:j(WG.nullish(),()=>{}),rename:j(YG.nullish(),()=>{}),searchAndReplace:j(e4.nullish(),()=>{})}),r4=l.object({id:l.string(),isRegex:l.boolean().nullish(),replace:l.string(),search:l.string(),uri:l.string()}),n4=l.union([l.literal("automatic"),l.literal("diagnostic"),l.literal("manual")]),o4=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()}),i4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),diagnostics:j(jG.nullish(),()=>{}),editHistory:j(zG.nullish(),()=>{}),openFiles:j(GG.nullish(),()=>{}),recentFiles:j(VG.nullish(),()=>{}),relatedSnippets:j(XG.nullish(),()=>{}),userActions:j(o4.nullish(),()=>{})}),XP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:l.array(l.string()).optional(),cwd:l.string(),mcpServers:l.array(gl)}),s4=l.object({default:l.number().nullish(),description:l.string().nullish(),maximum:l.number().nullish(),minimum:l.number().nullish(),title:l.string().nullish()}),YP=l.string(),a4=l.union([l.literal("allow_once"),l.literal("allow_always"),l.literal("reject_once"),l.literal("reject_always")]),c4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),kind:a4,name:l.string(),optionId:YP}),l4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),u4=l.union([l.literal("high"),l.literal("medium"),l.literal("low")]),d4=l.union([l.literal("pending"),l.literal("in_progress"),l.literal("completed")]),QP=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:l.string(),priority:u4,status:d4}),p4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),entries:or(de(QP),()=>[])}),fl=l.string(),m4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:fl,uri:l.string()}),g4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),entries:or(de(QP),()=>[]),id:fl}),f4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:l.string(),id:fl}),h4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:fl}),y4=l.union([g4.and(l.object({type:l.literal("items")})),m4.and(l.object({type:l.literal("file")})),f4.and(l.object({type:l.literal("markdown")}))]),v4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),plan:y4}),un=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"})}),b4=l.object({id:l.string(),position:un,uri:l.string()}),k4=l.object({id:l.string(),newName:l.string(),position:un,uri:l.string()}),w4=l.object({action:l.string(),position:un,timestampMs:l.number(),uri:l.string()}),eA=l.union([l.literal("utf-16"),l.literal("utf-32"),l.literal("utf-8")]),S4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),auth:Z2.optional().default({terminal:!1}),elicitation:j(bG.nullish(),()=>{}),fs:wG.optional().default({readTextFile:!1,writeTextFile:!1}),nes:j(t4.nullish(),()=>{}),plan:j(l4.nullish(),()=>{}),positionEncodings:j(de(eA).optional(),()=>[]),terminal:l.boolean().optional().default(!1)}),x4=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)}),tA=l.number().int().gte(0).lte(65535),rA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),clientCapabilities:S4.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:j(BP.nullish(),()=>{}),protocolVersion:tA}),R4=l.object({apiType:nv,baseUrl:l.string()}),T4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),current:R4.nullish(),id:l.string(),required:l.boolean(),supported:or(de(nv),()=>[])}),P4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),providers:or(de(T4),()=>[])}),A4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),Yo=l.object({end:un,start:un}),I4=l.object({message:l.string(),range:Yo,severity:OG,uri:l.string()}),C4=l.object({languageId:l.string(),lastFocusedMs:j(l.number().nullish(),()=>{}),uri:l.string(),visibleRange:j(Yo.nullish(),()=>{})}),_4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),diagnostics:j(de(I4).nullish(),()=>{}),editHistory:j(de(BG).nullish(),()=>{}),openFiles:j(de(C4).nullish(),()=>{}),recentFiles:j(de(KG).nullish(),()=>{}),relatedSnippets:j(de(JG).nullish(),()=>{}),userActions:j(de(w4).nullish(),()=>{})}),E4=l.object({newText:l.string(),range:Yo}),M4=l.object({cursorPosition:j(un.nullish(),()=>{}),edits:l.array(E4),id:l.string(),uri:l.string()}),D4=l.union([M4.and(l.object({kind:l.literal("edit")})),b4.and(l.object({kind:l.literal("jump")})),k4.and(l.object({kind:l.literal("rename")})),r4.and(l.object({kind:l.literal("searchAndReplace")}))]),N4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:l.string()}),$4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),dn=l.union([l.number(),l.string()]).nullable(),eme=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),requestId:dn}),nA=l.object({requestId:dn}),O4=l.enum(["assistant","user"]),Ns=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),audience:j(de(O4).nullish(),()=>{}),lastModified:l.string().nullish(),priority:l.number().nullish()}),j4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j(Ns.nullish(),()=>{}),data:l.string(),mimeType:l.string()}),L4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j(Ns.nullish(),()=>{}),data:l.string(),mimeType:l.string(),uri:l.string().nullish()}),U4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j(Ns.nullish(),()=>{}),description:l.string().nullish(),mimeType:l.string().nullish(),name:l.string(),size:l.number().nullish(),title:l.string().nullish(),uri:l.string()}),F4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),optionId:YP}),H4=l.union([l.object({outcome:l.literal("cancelled")}),F4.and(l.object({outcome:l.literal("selected")}))]),z4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),outcome:H4}),B4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),q4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),W4=l.object({currentValue:l.boolean()}),G4=l.string(),oA=l.string(),K4=l.union([l.literal("mode"),l.literal("model"),l.literal("thought_level"),l.string()]),ov=l.string(),iA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string().nullish(),name:l.string(),value:ov}),V4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),group:G4,name:l.string(),options:l.array(iA)}),Z4=l.union([l.array(iA),l.array(V4)]),J4=l.object({currentValue:ov,options:Z4}),Qo=l.intersection(l.union([J4.and(l.object({type:l.literal("select")})),W4.and(l.object({type:l.literal("boolean")}))]),l.object({_meta:l.record(l.string(),l.unknown()).nullish(),category:j(K4.nullish(),()=>{}),description:l.string().nullish(),id:oA,name:l.string()})),X4=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:or(de(Qo),()=>[])}),Y4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),Q4=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),ie=l.string(),sA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:l.string(),sessionId:ie}),aA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),cA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),lA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),iv=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(jP).optional(),outputByteLimit:l.number().nullish(),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,uri:l.string()}),pA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),position:un,sessionId:ie,uri:l.string(),version:l.number(),visibleRange:Yo}),mA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),languageId:l.string(),sessionId:ie,text:l.string(),uri:l.string(),version:l.number()}),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(),additionalDirectories:l.array(l.string()).optional(),cwd:l.string(),mcpServers:l.array(gl).optional(),sessionId:ie}),sv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,terminalId:l.string()}),hA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:l.array(l.string()).optional(),cwd:l.string(),mcpServers:l.array(gl),sessionId:ie}),av=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}),yA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),id:l.string(),reason:j(ZG.nullish(),()=>{}),sessionId:ie}),cv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,terminalId: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(gl).optional(),sessionId:ie}),eK=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(),()=>{})}),tK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),nextCursor:l.string().nullish(),sessions:or(de(eK),()=>[])}),rK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),title:l.string().nullish(),updatedAt:l.string().nullish()}),nK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),hl=l.string(),oK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),currentModeId:hl}),iK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string().nullish(),id:hl,name:l.string()}),yl=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),availableModes:or(de(iK),()=>[]),currentModeId:hl}),sK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:j(de(Qo).nullish(),()=>{}),modes:j(yl.nullish(),()=>{}),sessionId:ie}),aK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:j(de(Qo).nullish(),()=>{}),modes:j(yl.nullish(),()=>{})}),cK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:j(de(Qo).nullish(),()=>{}),modes:j(yl.nullish(),()=>{}),sessionId:ie}),lK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:j(de(Qo).nullish(),()=>{}),modes:j(yl.nullish(),()=>{})}),uK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),dK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),additionalDirectories:j(B4.nullish(),()=>{}),close:j(q4.nullish(),()=>{}),delete:j(Y4.nullish(),()=>{}),fork:j(Q4.nullish(),()=>{}),list:j(nK.nullish(),()=>{}),resume:j(uK.nullish(),()=>{})}),bA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),apiType:nv,baseUrl:l.string(),headers:l.record(l.string(),l.string()).optional(),id:l.string()}),pK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),kA=l.intersection(l.union([l.object({type:l.literal("boolean"),value:l.boolean()}),l.object({value:ov})]),l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configId:oA,sessionId:ie})),mK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),configOptions:or(de(Qo),()=>[])}),wA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),modeId:hl,sessionId:ie}),gK=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),fK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie}),hK=l.union([l.literal("end_turn"),l.literal("max_tokens"),l.literal("max_turn_requests"),l.literal("refusal"),l.literal("cancelled")]),yK=l.union([l.literal("email"),l.literal("uri"),l.literal("date"),l.literal("date-time")]),vK=l.object({default:l.string().nullish(),description:l.string().nullish(),enum:l.array(l.string()).nullish(),format:yK.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(OP).nullish(),pattern:l.string().nullish(),title:l.string().nullish()}),SA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),context:j(_4.nullish(),()=>{}),position:un,selection:j(Yo.nullish(),()=>{}),sessionId:ie,triggerKind:n4,uri:l.string(),version:l.number()}),bK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),suggestions:or(de(D4),()=>[])}),kK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),terminalId:l.string()}),wK=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()}),lv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,terminalId:l.string()}),SK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),exitStatus:wK.nullish(),output:l.string(),truncated:l.boolean()}),xK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j(Ns.nullish(),()=>{}),text:l.string()}),RK=l.object({range:Yo.nullish(),text:l.string()}),xA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),contentChanges:l.array(RK),sessionId:ie,uri:l.string(),version:l.number()}),tme=l.object({method:l.string(),params:l.union([aA,mA,xA,dA,gA,pA,sA,yA,VP,UP]).nullish()}),TK=l.union([l.literal("full"),l.literal("incremental")]),PK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),syncKind:TK}),AK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),didChange:j(PK.nullish(),()=>{}),didClose:j(LG.nullish(),()=>{}),didFocus:j(UG.nullish(),()=>{}),didOpen:j(FG.nullish(),()=>{}),didSave:j(HG.nullish(),()=>{})}),IK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),document:j(AK.nullish(),()=>{})}),CK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),context:j(i4.nullish(),()=>{}),events:j(IK.nullish(),()=>{})}),_K=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),auth:TG.optional().default({}),loadSession:l.boolean().optional().default(!1),mcpCapabilities:AG.optional().default({acp:!1,http:!1,sse:!1}),nes:j(CK.nullish(),()=>{}),positionEncoding:j(eA.nullish(),()=>{}),promptCapabilities:x4.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:j(A4.nullish(),()=>{}),sessionCapabilities:dK.optional().default({})}),EK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),agentCapabilities:_K.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:j(BP.nullish(),()=>{}),authMethods:j(de(eG).optional().default([]),()=>[]),protocolVersion:tA}),MK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),mimeType:l.string().nullish(),text:l.string(),uri:l.string()}),DK=l.union([MK,rG]),NK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),annotations:j(Ns.nullish(),()=>{}),resource:DK}),uv=l.union([xK.and(l.object({type:l.literal("text")})),L4.and(l.object({type:l.literal("image")})),j4.and(l.object({type:l.literal("audio")})),U4.and(l.object({type:l.literal("resource_link")})),NK.and(l.object({type:l.literal("resource")}))]),$K=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:uv}),tv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:uv,messageId:$G.nullish()}),RA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),prompt:l.array(uv),sessionId:ie}),OK=l.object({anyOf:l.array(OP)}),TA=l.union([$K.and(l.object({type:l.literal("content")})),lG.and(l.object({type:l.literal("diff")})),kK.and(l.object({type:l.literal("terminal")}))]),dv=l.string(),PA=l.object({sessionId:ie,toolCallId:dv.nullish()}),jK=l.intersection(l.union([PA,nA]),l.object({elicitationId:$P,url:l.string().url()})),AA=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()}),IA=l.union([l.literal("pending"),l.literal("in_progress"),l.literal("completed"),l.literal("failed")]),CA=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")]),LK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:j(de(TA).optional(),()=>[]),kind:CA.optional(),locations:j(de(AA).optional(),()=>[]),rawInput:l.unknown().optional(),rawOutput:l.unknown().optional(),status:IA.optional(),title:l.string(),toolCallId:dv}),_A=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:j(de(TA).nullish(),()=>{}),kind:j(CA.nullish(),()=>{}),locations:j(de(AA).nullish(),()=>{}),rawInput:l.unknown().optional(),rawOutput:l.unknown().optional(),status:j(IA.nullish(),()=>{}),title:l.string().nullish(),toolCallId:dv}),pv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),options:l.array(c4),sessionId:ie,toolCall:_A}),UK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),hint:l.string()}),FK=UK,HK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),description:l.string(),input:j(FK.nullish(),()=>{}),name:l.string()}),zK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),availableCommands:or(de(HK),()=>[])}),BK=l.object({enum:l.array(l.string()),type:yG}),qK=l.union([BK,OK]),WK=l.object({default:l.array(l.string()).nullish(),description:l.string().nullish(),items:qK,maxItems:l.number().nullish(),minItems:l.number().nullish(),title:l.string().nullish()}),GK=l.union([vK.and(l.object({type:l.literal("string")})),s4.and(l.object({type:l.literal("number")})),SG.and(l.object({type:l.literal("integer")})),nG.and(l.object({type:l.literal("boolean")})),WK.and(l.object({type:l.literal("array")}))]),KK=l.object({description:l.string().nullish(),properties:l.record(l.string(),GK).optional().default({}),required:l.array(l.string()).nullish(),title:l.string().nullish(),type:hG.optional().default("object")}),VK=l.intersection(l.union([PA,nA]),l.object({requestedSchema:KK})),mv=l.intersection(l.union([VK.and(l.object({mode:l.literal("form")})),jK.and(l.object({mode:l.literal("url")}))]),l.object({_meta:l.record(l.string(),l.unknown()).nullish(),message:l.string()})),ZK=l.object({cachedReadTokens:l.number().nullish(),cachedWriteTokens:l.number().nullish(),inputTokens:l.number(),outputTokens:l.number(),thoughtTokens:l.number().nullish(),totalTokens:l.number()}),JK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),stopReason:hK,usage:j(ZK.nullish(),()=>{})}),rme=l.union([l.object({id:dn,result:l.union([EK,tG,P4,pK,uG,PG,cK,aK,tK,cG,sK,lK,iG,gK,mK,JK,fK,bK,oG,HP,JP])}),l.object({error:LP,id:dn})]),XK=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),cost:j(sG.nullish(),()=>{}),size:l.number(),used:l.number()}),YK=l.union([tv.and(l.object({sessionUpdate:l.literal("user_message_chunk")})),tv.and(l.object({sessionUpdate:l.literal("agent_message_chunk")})),tv.and(l.object({sessionUpdate:l.literal("agent_thought_chunk")})),LK.and(l.object({sessionUpdate:l.literal("tool_call")})),_A.and(l.object({sessionUpdate:l.literal("tool_call_update")})),p4.and(l.object({sessionUpdate:l.literal("plan")})),v4.and(l.object({sessionUpdate:l.literal("plan_update")})),h4.and(l.object({sessionUpdate:l.literal("plan_removed")})),zK.and(l.object({sessionUpdate:l.literal("available_commands_update")})),oK.and(l.object({sessionUpdate:l.literal("current_mode_update")})),X4.and(l.object({sessionUpdate:l.literal("config_option_update")})),rK.and(l.object({sessionUpdate:l.literal("session_info_update")})),XK.and(l.object({sessionUpdate:l.literal("usage_update")}))]),gv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,update:YK}),nme=l.object({method:l.string(),params:l.union([gv,rv,VP,UP]).nullish()}),fv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),sessionId:ie,terminalId:l.string()}),QK=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()}),e6=l.object({name:l.string(),uri:l.string()}),EA=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),repository:j(QG.nullish(),()=>{}),workspaceFolders:j(de(e6).nullish(),()=>{}),workspaceUri:l.string().nullish()}),ome=l.object({id:dn,method:l.string(),params:l.union([rA,DP,qP,bA,NP,GP,XP,hA,WP,uA,fA,vA,lA,wA,kA,RA,EA,SA,cA,ZP,FP]).nullish()}),hv=l.object({_meta:l.record(l.string(),l.unknown()).nullish(),content:l.string(),path:l.string(),sessionId:ie}),ime=l.object({id:dn,method:l.string(),params:l.union([hv,av,pv,iv,lv,cv,fv,sv,mv,_G,ZP,CG,FP]).nullish()}),t6=l.object({_meta:l.record(l.string(),l.unknown()).nullish()}),sme=l.union([l.object({id:dn,result:l.union([t6,N4,z4,aG,SK,$4,QK,xG,gG,IG,dG,HP,JP])}),l.object({error:LP,id:dn})]);function MA(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(`
|
|
608
608
|
`);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)+`
|
|
609
|
-
`,c=t.getWriter();try{await c.write(r.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function pn(t){return t??{}}function DA(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var vl=class{connection;constructor(e,r){let n=e(this),o=async(s,a)=>{switch(s){case Kt.fs_write_text_file:{let c=hv.parse(a);return await n.writeTextFile?.(c)??{}}case Kt.fs_read_text_file:{let c=av.parse(a);return n.readTextFile?.(c)}case Kt.session_request_permission:{let c=pv.parse(a);return n.requestPermission(c)}case Kt.terminal_create:{let c=iv.parse(a);return n.createTerminal?.(c)}case Kt.terminal_output:{let c=lv.parse(a);return n.terminalOutput?.(c)}case Kt.terminal_release:{let c=cv.parse(a);return await n.releaseTerminal?.(c)??{}}case Kt.terminal_wait_for_exit:{let c=fv.parse(a);return n.waitForTerminalExit?.(c)}case Kt.terminal_kill:{let c=sv.parse(a);return await n.killTerminal?.(c)??{}}case Kt.elicitation_create:{if(!n.unstable_createElicitation)throw bt.methodNotFound(s);let c=mv.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 Kt.session_update:{let c=gv.parse(a);return n.sessionUpdate(c)}case Kt.elicitation_complete:{if(!n.unstable_completeElicitation)return;let c=rv.parse(a);return n.unstable_completeElicitation(c)}default:if(n.extNotification)return n.extNotification(s,a);throw bt.methodNotFound(s)}};this.connection=new yv(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,pn)}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,pn)}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,pn)}setSessionConfigOption(e){return this.connection.sendRequest(me.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(me.authenticate,e,pn)}unstable_listProviders(e){return this.connection.sendRequest(me.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(me.providers_set,e,pn)}unstable_disableProvider(e){return this.connection.sendRequest(me.providers_disable,e,pn)}logout(e){return this.connection.sendRequest(me.logout,e,pn)}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,pn)}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}},yv=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 DA(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?DA(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 i6=1,s6=2e4,NA=3e4,a6=3e5,ir={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"},$s=class extends Error{retryable=!1;authMethods;constructor(e,r){super(e),this.name="AcpAuthRequiredError",this.authMethods=r}};function bl(t,e){if(t instanceof $s)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 $s(`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 $s(s,e)}return null}var mn=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=MA(o6.toWeb(e.stdin),n6.toWeb(e.stdout));this.conn=new vl(()=>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:i6,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),s6,"initialize").catch(i=>{throw bl(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),NA,"session/new").catch(i=>{throw bl(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=a6){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),NA,"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 ir.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case ir.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case ir.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 ir.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 ir.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case ir.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case ir.AVAILABLE_COMMANDS_UPDATE:case ir.CURRENT_MODE_UPDATE:case ir.CONFIG_OPTION_UPDATE:case ir.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case ir.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as c6}from"node:child_process";import{readFile as l6,writeFile as u6}from"node:fs/promises";import{isAbsolute as $A,normalize as d6,relative as p6,resolve as m6,sep as g6}from"node:path";function vv(t){let e=new Map,r=0,n=i=>{let s=$A(i)?d6(i):m6(t.cwd,i),a=p6(t.cwd,s);if(a===".."||a.startsWith(`..${g6}`)||$A(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 l6(n(i.path),"utf8")}},async writeTextFile(i){return await u6(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=c6(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 Os=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 jA}from"node:child_process";import{existsSync as bv,readFileSync as f6,readdirSync as h6}from"node:fs";import{homedir as y6,platform as v6}from"node:os";import{dirname as b6,join as ei}from"node:path";var js={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"}},k6=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],OA={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 Ls(t){let e=js[t];if(e)return OA[t]?{...e,...OA[t]}:e}function LA(){return k6.map(t=>{let e=Ls(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var wv=v6()==="win32";function kv(t){try{let e=wv?`where ${t}`:`which ${t}`;return jA(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function w6(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 S6(){if(!wv)return null;let t=[process.env.COPILOT_CACHE_HOME?ei(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?ei(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?ei(process.env.COPILOT_HOME,"pkg","win32-x64"):null,ei(y6(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let r=h6(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name).sort(w6);for(let n of r){let o=ei(e,n,"npm-loader.js");if(bv(o)&&UA(o))return o}}catch{}return null}function x6(t){return t.id==="copilot"?S6()??kv(t.cliCommand):kv(t.cliCommand)}function UA(t){try{let e=t.endsWith("npm-loader.js")?`"${process.execPath}" "${t}" version`:`"${t}" version`;return jA(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}function R6(t,e){if(!wv)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=T6(t);return r?{cliPath:process.execPath,acpArgs:[r,...e]}:{cliPath:t,acpArgs:e}}function T6(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),r=[`${e}.cmd`,`${e}.ps1`,e];for(let n of r){if(!bv(n))continue;let o;try{o=f6(n,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=ei(b6(e),s);if(bv(a))return a}return null}var P6=6e4;function A6(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 I6=new Set(["codex","qwen","opencode"]);function C6(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&&I6.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 ti=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<P6)return this.cache.agents;let r=[];for(let n of Object.values(js))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=x6(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=UA(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=kv(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=Ls(e)??js[e],o=this.configStore?.agents[e],i=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:o?.customArgs??n?.acpArgs??[]}:R6(r.cliPath,o?.customArgs??n?.acpArgs??[]),s=C6(n,this.keySources);return{id:e,cliPath:i.cliPath,acpArgs:i.acpArgs,env:A6(n,o,s),protocol:"acp"}}isAgentReady(e){if(e==="qlogicagent")return!0;let r=this.buildExternalDescriptor(e);if(!r)return!1;let n=Ls(e)??js[e];return n?.apiKeyEnvVar&&n.authMode!=="oauth"?!!r.env?.[n.apiKeyEnvVar]:!0}};var j6=1;function L6(t,e){return{jsonrpc:"2.0",id:j6++,method:t,params:e,meta:Qm(t)}}var U6=["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 F6(t){let e={};for(let r of U6)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 FA(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 xv=Vp,H6=Zp,ri=Jp,HA=Xp;function z6(t){return new Promise(e=>setTimeout(e,t))}function B6(t,e){if(process.platform==="win32"&&typeof e=="number"&&e>0)try{_6("taskkill",["/PID",String(e),"/T","/F"],()=>{});return}catch{}try{t.kill("SIGTERM"),setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},1e4)}catch{}}var Vt=class t{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let r=E6(Us(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=Us(r,"dist","cli.js"),this.mcpBridgeScriptPath=Us(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=F6(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=Sv(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}),kl({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=mn.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&&kl({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=M6();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=FA(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=L6(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)}
|
|
609
|
+
`,c=t.getWriter();try{await c.write(r.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function pn(t){return t??{}}function DA(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var vl=class{connection;constructor(e,r){let n=e(this),o=async(s,a)=>{switch(s){case Kt.fs_write_text_file:{let c=hv.parse(a);return await n.writeTextFile?.(c)??{}}case Kt.fs_read_text_file:{let c=av.parse(a);return n.readTextFile?.(c)}case Kt.session_request_permission:{let c=pv.parse(a);return n.requestPermission(c)}case Kt.terminal_create:{let c=iv.parse(a);return n.createTerminal?.(c)}case Kt.terminal_output:{let c=lv.parse(a);return n.terminalOutput?.(c)}case Kt.terminal_release:{let c=cv.parse(a);return await n.releaseTerminal?.(c)??{}}case Kt.terminal_wait_for_exit:{let c=fv.parse(a);return n.waitForTerminalExit?.(c)}case Kt.terminal_kill:{let c=sv.parse(a);return await n.killTerminal?.(c)??{}}case Kt.elicitation_create:{if(!n.unstable_createElicitation)throw bt.methodNotFound(s);let c=mv.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 Kt.session_update:{let c=gv.parse(a);return n.sessionUpdate(c)}case Kt.elicitation_complete:{if(!n.unstable_completeElicitation)return;let c=rv.parse(a);return n.unstable_completeElicitation(c)}default:if(n.extNotification)return n.extNotification(s,a);throw bt.methodNotFound(s)}};this.connection=new yv(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,pn)}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,pn)}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,pn)}setSessionConfigOption(e){return this.connection.sendRequest(me.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(me.authenticate,e,pn)}unstable_listProviders(e){return this.connection.sendRequest(me.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(me.providers_set,e,pn)}unstable_disableProvider(e){return this.connection.sendRequest(me.providers_disable,e,pn)}logout(e){return this.connection.sendRequest(me.logout,e,pn)}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,pn)}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}},yv=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 DA(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?DA(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 i6=1,s6=2e4,NA=3e4,a6=3e5,ir={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"},$s=class extends Error{retryable=!1;authMethods;constructor(e,r){super(e),this.name="AcpAuthRequiredError",this.authMethods=r}};function bl(t,e){if(t instanceof $s)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 $s(`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 $s(s,e)}return null}var mn=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=MA(o6.toWeb(e.stdin),n6.toWeb(e.stdout));this.conn=new vl(()=>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:i6,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),s6,"initialize").catch(i=>{throw bl(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),NA,"session/new").catch(i=>{throw bl(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=a6){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),NA,"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 ir.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case ir.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case ir.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 ir.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 ir.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case ir.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case ir.AVAILABLE_COMMANDS_UPDATE:case ir.CURRENT_MODE_UPDATE:case ir.CONFIG_OPTION_UPDATE:case ir.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case ir.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as c6}from"node:child_process";import{readFile as l6,writeFile as u6}from"node:fs/promises";import{isAbsolute as $A,normalize as d6,relative as p6,resolve as m6,sep as g6}from"node:path";function vv(t){let e=new Map,r=0,n=i=>{let s=$A(i)?d6(i):m6(t.cwd,i),a=p6(t.cwd,s);if(a===".."||a.startsWith(`..${g6}`)||$A(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 l6(n(i.path),"utf8")}},async writeTextFile(i){return await u6(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=c6(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 Os=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 jA}from"node:child_process";import{existsSync as bv,readFileSync as f6,readdirSync as h6}from"node:fs";import{homedir as y6,platform as v6}from"node:os";import{dirname as b6,join as ei}from"node:path";var js={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"}},k6=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],OA={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 Ls(t){let e=js[t];if(e)return OA[t]?{...e,...OA[t]}:e}function LA(){return k6.map(t=>{let e=Ls(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var wv=v6()==="win32";function kv(t){try{let e=wv?`where ${t}`:`which ${t}`;return jA(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function w6(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 S6(){if(!wv)return null;let t=[process.env.COPILOT_CACHE_HOME?ei(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?ei(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?ei(process.env.COPILOT_HOME,"pkg","win32-x64"):null,ei(y6(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let r=h6(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name).sort(w6);for(let n of r){let o=ei(e,n,"npm-loader.js");if(bv(o)&&UA(o))return o}}catch{}return null}function x6(t){return t.id==="copilot"?S6()??kv(t.cliCommand):kv(t.cliCommand)}function UA(t){try{let e=t.endsWith("npm-loader.js")?`"${process.execPath}" "${t}" version`:`"${t}" version`;return jA(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}function R6(t,e){if(!wv)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=T6(t);return r?{cliPath:process.execPath,acpArgs:[r,...e]}:{cliPath:t,acpArgs:e}}function T6(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),r=[`${e}.cmd`,`${e}.ps1`,e];for(let n of r){if(!bv(n))continue;let o;try{o=f6(n,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=ei(b6(e),s);if(bv(a))return a}return null}var P6=6e4;function A6(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 I6=new Set(["codex","qwen","opencode"]);function C6(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&&I6.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 ti=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<P6)return this.cache.agents;let r=[];for(let n of Object.values(js))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=x6(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=UA(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=kv(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=Ls(e)??js[e],o=this.configStore?.agents[e],i=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:o?.customArgs??n?.acpArgs??[]}:R6(r.cliPath,o?.customArgs??n?.acpArgs??[]),s=C6(n,this.keySources);return{id:e,cliPath:i.cliPath,acpArgs:i.acpArgs,env:A6(n,o,s),protocol:"acp"}}isAgentReady(e){if(e==="qlogicagent")return!0;let r=this.buildExternalDescriptor(e);if(!r)return!1;let n=Ls(e)??js[e];return n?.apiKeyEnvVar&&n.authMode!=="oauth"?!!r.env?.[n.apiKeyEnvVar]:!0}};var j6=1;function L6(t,e){return{jsonrpc:"2.0",id:j6++,method:t,params:e,meta:Qm(t)}}var U6=["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 F6(t){let e={};for(let r of U6)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 FA(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 xv=Vp,H6=Zp,ri=Jp,HA=Xp;function z6(t){return new Promise(e=>setTimeout(e,t))}function B6(t,e){if(process.platform==="win32"&&typeof e=="number"&&e>0)try{_6("taskkill",["/PID",String(e),"/T","/F"],()=>{});return}catch{}try{t.kill("SIGTERM"),setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},1e4)}catch{}}var Vt=class t{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let r=E6(Us(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=Us(r,"dist","cli.js"),this.mcpBridgeScriptPath=Us(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=F6(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=Sv(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}),kl({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=mn.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&&kl({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=M6();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=FA(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=L6(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
610
|
`)}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=FA(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()}})+`
|
|
611
611
|
`;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})}
|
|
612
612
|
`)}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<=xv;i++)try{if(i>0){this.processes.delete(e.memberId),r.state="starting",r.error=void 0,r.endedAt=void 0;let s=H6*i;this.slog("info",e.memberId,"spawn",`retry ${i}/${xv} after ${s}ms`),await z6(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 ${xv+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=Sv(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 mn,d=new Os,{server:p,pipePath:m}=this.createMcpIpcServer(e.memberId);n.QLOGICAGENT_PARENT_RPC=m;let g;if(this.callbacks.sessionDir)try{$6(this.callbacks.sessionDir,{recursive:!0}),g=N6(Us(this.callbacks.sessionDir,`${e.memberId}.stderr.log`),{flags:"a"})}catch{}let f=vv({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=mn.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&&kl({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}
|
|
@@ -1038,7 +1038,7 @@ Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;as
|
|
|
1038
1038
|
`)})}function hj(){return wd("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(`
|
|
1039
1039
|
`))}function vw(t){return wd("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(`
|
|
1040
1040
|
`):["# 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(`
|
|
1041
|
-
`))}var yj={requiresFreshTool:!1,allowedToolNames:[]},cte=["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"],bw=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${cte.join("|")})\\b`,"i"),lte=/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,ute=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,dte=/(?: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,pte=/(?: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,mte=/(?: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,gte=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,fte=/https?:\/\/\S+/i,hte=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,yte=/(?:\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,vte=/(?:\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,bte=/(?:\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,kte=/^(?:hi|hello|hey|ping|test|yo|在吗|在不在|你在吗|你好|您好|早上好|中午好|晚上好|哈喽|嗨|有人吗|能听到吗|你是谁|你还在吗)[?!!?.。~\s]*$/i;function bj(t){let e=typeof t=="string"?t:xj(t);return e.trim()?bte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"music",allowedToolNames:["music_generate"]}:vte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"tts",allowedToolNames:["tts"]}:yte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"image",allowedToolNames:["image_generate"]}:fte.test(e)&&hte.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:ute.test(e)&&bw.test(e)||dte.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:lte.test(e)&&bw.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:bw.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:pte.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:mte.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:gte.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:yj:yj}function kj(t){let r=(typeof t=="string"?t:xj(t)).trim();return!r||r.length>24?!1:kte.test(r)}var wte=new Set(["think","task","agent","ask_user"]);function wj(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(i=>{let s=vj(i);return r.has(s)||wte.has(s)});return n.some(i=>r.has(vj(i)))?n:[...t]}function Sj(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");if(t.reason==="file-mutation")return _r("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(`
|
|
1041
|
+
`))}var yj={requiresFreshTool:!1,allowedToolNames:[]},cte=["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"],bw=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${cte.join("|")})\\b`,"i"),lte=/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,ute=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,dte=/(?: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,pte=/(?: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,mte=/(?: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,gte=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,fte=/https?:\/\/\S+/i,hte=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,yte=/(?:\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,vte=/(?:\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,bte=/(?:\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,kte=/^(?:hi|hello|hey|ping|test|yo|在吗|在不在|你在吗|你好|您好|早上好|中午好|晚上好|哈喽|嗨|有人吗|能听到吗|你是谁|你还在吗)[?!!?.。~\s]*$/i;function bj(t){let e=typeof t=="string"?t:xj(t);return e.trim()?bte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"music",allowedToolNames:["music_generate"]}:vte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"tts",allowedToolNames:["tts"]}:yte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"image",allowedToolNames:["image_generate"]}:fte.test(e)&&hte.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:ute.test(e)&&bw.test(e)||dte.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:lte.test(e)&&bw.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:bw.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:pte.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:mte.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:gte.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:yj:yj}function kj(t){let r=(typeof t=="string"?t:xj(t)).trim();return!r||r.length>24?!1:kte.test(r)}var wte=new Set(["think","task","agent","ask_user","team","send_message"]);function wj(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(i=>{let s=vj(i);return r.has(s)||wte.has(s)});return n.some(i=>r.has(vj(i)))?n:[...t]}function Sj(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");if(t.reason==="file-mutation")return _r("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
1042
|
`));if(t.reason==="memory-mutation")return _r("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(`
|
|
1043
1043
|
`));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 _r("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(`
|
|
1044
1044
|
`))}return _r("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(`
|
|
@@ -1189,12 +1189,12 @@ ${s.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.
|
|
|
1189
1189
|
`)}],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(`
|
|
1190
1190
|
`)}],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(`
|
|
1191
1191
|
`)}],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 kU from"node:path";ve();function Tne(t){if(t&&typeof t=="object"&&"content"in t){let e=t.content;if(typeof e=="string")return e}return""}function Pne(t,e){return`[message from ${e}]
|
|
1192
|
-
${t}`}function wU(t,e,r){let n=new Map,o={info:s=>e.info(s),warn:s=>e.warn(s)},i=new Vt({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&&Ta(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:kU.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 ta(),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 lE(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=Ta(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(
|
|
1192
|
+
${t}`}function wU(t,e,r){let n=new Map,o={info:s=>e.info(s),warn:s=>e.warn(s)},i=new Vt({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&&Ta(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:kU.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 ta(),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 lE(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=Ta(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)=>Tne(await i.sendTask(g,Pne(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(Ta(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=Ta(s,u.name);r.unregister(d),i.kill(d),i.remove(d)}let c=await ta();if(c)for(let u of a.members)u.worktreePath&&u.worktreeBranch&&(await uE(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=Ta(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 Ta(t,e){return`team-${t}-${e}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()}function SU({host:t,log:e,toolCatalog:r,teamRegistry:n}){let o=wU(t,e,n);Ur(async()=>o.dispose()),r.addTool(bU(o))}var Ane="send_message",Ine={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 xU(t){return{name:Ane,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:Ine,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
1193
|
|
|
1194
1194
|
`+n.replies.map(s=>`${s.name} replied:
|
|
1195
1195
|
${s.reply}`).join(`
|
|
1196
1196
|
|
|
1197
|
-
`):"";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 RU({host:t,log:e,toolCatalog:r,teamRegistry:n}){r.addTool(xU({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 TU(t){let e=new Bd;QL({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}),cU({toolCatalog:t.toolCatalog,host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),gU({toolCatalog:t.toolCatalog,host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),vU({log:t.log,toolCatalog:t.toolCatalog}),oU({config:t.config,toolCatalog:t.toolCatalog,host:{currentSessionId:t.host.currentSessionId}}),SU({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}),RU({toolCatalog:t.toolCatalog,host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log,teamRegistry:e})}var Cne={id:"cli-core-tools",kind:"core",register:_ne};function PU(t){Cne.register(t)}function _ne(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};TU(r)}var Ene={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
|
|
1197
|
+
`):"";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 RU({host:t,log:e,toolCatalog:r,teamRegistry:n}){r.addTool(xU({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 TU(t){let e=new Bd;QL({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}),cU({toolCatalog:t.toolCatalog,host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),gU({toolCatalog:t.toolCatalog,host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),vU({log:t.log,toolCatalog:t.toolCatalog}),oU({config:t.config,toolCatalog:t.toolCatalog,host:{currentSessionId:t.host.currentSessionId}}),SU({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}),RU({toolCatalog:t.toolCatalog,host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log,teamRegistry:e})}var Cne={id:"cli-core-tools",kind:"core",register:_ne};function PU(t){Cne.register(t)}function _ne(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};TU(r)}var Ene={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
|
|
1198
1198
|
- goToDefinition: jump to symbol definition
|
|
1199
1199
|
- findReferences: find all usages of a symbol
|
|
1200
1200
|
- hover: get type/docs for symbol at position
|
|
@@ -1251,5 +1251,5 @@ CROSS-PROJECT RECALL: When you see '[Cross-project skill available]' in recalled
|
|
|
1251
1251
|
Available skills:
|
|
1252
1252
|
${n}`}ve();import{randomUUID as qoe}from"node:crypto";var Loe=10080*60*1e3;function Uoe(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=Lw(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=Lw(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??Loe,i=[];for(let s of Object.values(e.records)){if(!Foe(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 oF(){let t=Sr();return t?Uoe(t):null}function Lw(t){return t?.source!=="installed"||t.registrySourceTier==="official"?null:t.registryResourceId??t.name}function Foe(t,e,r){if(!Lw(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 mMe}from"node:child_process";function iF(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 sF(){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 Hoe(t={}){let e=t.availability??iF({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:Boe(r,e.available?"allowed":"blocked",o)}}let n=r.riskTier??"unknown";return!zoe(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 aF(){return Hoe()}function zoe(t){return t==="R2"||t==="R3"}function Boe(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:sF()}}async function uF(t){let{host:e,toolCatalog:r,skillName:n,skillContent:o,userArgs:i,signal:s}=t,a=`skill_${n}_${qoe().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??oF(),g=(t.skillSandbox??aF()).decide({origin:pF(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=dF(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 cF(e,d,a,f,"normal"),lF(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 cF(e,d,a,f,v?"error":"normal",v),v?(iw(u,n,!1),await m?.recordSkillUsage(p,"error"),`[skill "${n}"] error: ${v}`):(lF(u,n,!0),await m?.recordSkillUsage(p,"success"),w.join("")||`[skill "${n}"] completed (no output)`)}function dF(t,e){return Woe(e)?`community-skill:${t}`:`skill:${t}`}function Woe(t){return pF(t)}function pF(t){return t?.source!=="installed"?!1:t.registrySourceTier!=="official"}function cF(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 lF(t,e,r){iw(t,e,r);let n=Ae(t);oC(n,e),Ue(t,n)}var Goe={id:"skill-meta-tool",kind:"skill",register:({host:t,...e})=>Koe(t,e)};function mF(t,e){Goe.register({...e,host:t})}function Koe(t,e){let r=e.pathService;e.toolCatalog.addTool(nF({listSkills:()=>{let n=JI(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 io(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=so(n);if(!o)return null;try{return await tr.promises.readFile(o.filePath,"utf8")}catch{return null}},viewSkill:async(n,o)=>{let i=so(n);if(!i)return null;let s=o?Ai.join(i.baseDir,o):i.filePath;try{let a=await tr.promises.readFile(s,"utf8");return{name:n,content:a}}catch{return null}},executeSkillSubturn:async(n,o,i,s)=>uF({host:t,toolCatalog:e.toolCatalog,skillName:n,skillContent:o,userArgs:i,signal:s}),manageSkill:async n=>{let o=t.getActiveProjectRoot(),i=r.getUserSkillsDir(),s=Ai.join(i,n.name),a=Ai.join(s,"SKILL.md"),c=r.getOwnerProfileDir();switch(n.action){case"create":{let u=n.content??"",p=rb(u,n.name,`Skill: ${n.name}`)??u,m=ql(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&&tr.existsSync(a))return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};await tr.promises.mkdir(s,{recursive:!0}),await tr.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),Un(n.name),o&&Lr(o,n.name);let f=t.getMemoryLearningSink(),h=t.getMemoryUserId();if(f&&h){let S=p.split(`
|
|
1253
1253
|
`).slice(0,3).join(" ").slice(0,200),w=o?Ai.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=rb(d,n.name)??d;return await tr.promises.writeFile(a,m,"utf8"),Qv(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 tr.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 tr.promises.writeFile(a,p,"utf8"),Qv(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 tr.promises.rm(s,{recursive:!0,force:!0}),Fl(u,n.name),Ue(c,u),Oo(n.name),o&&Ln(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=so(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),Oo(n);let c=t.getActiveProjectRoot();c&&Ln(c,n);let u="";try{u=await tr.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 gF(t){let e=YU({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;FU({config:t.config,projectRoot:t.projectRoot,pathService:t.pathService,log:t.log,toolCatalog:t.toolCatalog,currentManager:t.currentMcpManager,setManager:t.setMcpManager,setReady:t.setMcpReady}),GU({config:t.config,hooks:r,log:t.log,pathService:t.pathService,toolCatalog:t.toolCatalog,setPluginLoader:t.setPluginLoader});let n=ZU({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 mF({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}),PU({config:t.config,host:t.coreToolHost,hooks:r,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),$U({config:t.config,pathService:t.pathService,toolCatalog:t.toolCatalog}),t.sessionId&&r.invoke("session.created",{sessionId:t.sessionId}).catch(()=>{}),rF({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 fF(t){let{provider:e,model:r,apiKey:n,baseUrl:o}=t.resolvedConfig,i=fu({provider:e,model:r,apiKey:n,baseUrl:o},t.providerRegistry);return i.transport=cM(i.transport,t.sessionId||"default"),{transport:i.transport,apiKey:n,model:r,provider:e,baseUrl:o??""}}function hF(t){return{agent:new Dn({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:pc()}),...t.client}}import{randomUUID as Voe}from"node:crypto";async function yF(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(`
|
|
1254
|
-
`),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,zL(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 vF(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_${Voe().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 RM(d,()=>s(a,c,o));return await yF({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 bF(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=vF({mediaPersistence:t.mediaPersistence,toolCatalog:t.toolCatalog,getSessionId:()=>t.sessionId,log:s=>t.log(s),sendNotification:t.sendNotification}),n=fF({resolvedConfig:t.resolvedTextConfig,providerRegistry:t.providerRegistry,sessionId:t.sessionId}),o=gF({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:hF({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 Joe=Zoe(import.meta.url);function Xoe(){for(let t of["../package.json","../../package.json"])try{return Joe(t).version}catch{}return"0.0.0"}var kF=Xoe();var Yoe=new Set(["thread.user_response"]);var Fw=class{running=!1;startedAt=Date.now();packageVersion=kF;rpcContract=new Ki;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;runtimeServices;runtimeSession=new Dd;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Ga;backgroundTasks=new Ka(this.taskStore);pendingTaskNotifications=[];memoryPrefetchState=rr();lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=Md();pendingAskUser=new Map;sessionTaskDomain;acpSessionMeta=null;multiAgentHandlerHost;acpServer=null;sessionHistory=new jd;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=GL({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 Ud({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=_L({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 Ld({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:()=>Uw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),listRecentSessions:()=>Wt(20,this.getActiveProjectRoot()),runDream:r=>Uo.call(this.createDreamHandlerHost(),r)}),W().onChange(()=>{this.invalidateResolvedLlmCache()}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ui({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(rx(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 Hn(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(eg(e)||Zi(e)){this.acpServer.dispatchMessage(e);return}if(Vi(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!Ym(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 Cx(),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=Dj(this);handleMessage(e){if(e.id!==void 0&&!Yoe.has(e.method)){let n=sc(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=jL({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return ML({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=EL(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=bF({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:()=>Qa(),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",NL(e,r,n))}createDreamHandlerHost(){return $L({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:()=>Uw.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 LL({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 DL({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)&&qx(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})}
|
|
1254
|
+
`),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,zL(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 vF(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_${Voe().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 RM(d,()=>s(a,c,o));return await yF({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 bF(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=vF({mediaPersistence:t.mediaPersistence,toolCatalog:t.toolCatalog,getSessionId:()=>t.sessionId,log:s=>t.log(s),sendNotification:t.sendNotification}),n=fF({resolvedConfig:t.resolvedTextConfig,providerRegistry:t.providerRegistry,sessionId:t.sessionId}),o=gF({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:hF({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 Joe=Zoe(import.meta.url);function Xoe(){for(let t of["../package.json","../../package.json"])try{return Joe(t).version}catch{}return"0.0.0"}var kF=Xoe();var Yoe=new Set(["thread.user_response"]);var Fw=class{running=!1;startedAt=Date.now();packageVersion=kF;rpcContract=new Ki;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;runtimeServices;runtimeSession=new Dd;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Ga;backgroundTasks=new Ka(this.taskStore);pendingTaskNotifications=[];memoryPrefetchState=rr();lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=Md();pendingAskUser=new Map;sessionTaskDomain;acpSessionMeta=null;multiAgentHandlerHost;acpServer=null;sessionHistory=new jd;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=GL({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 Ud({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=_L({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 Ld({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:()=>Uw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),listRecentSessions:()=>Wt(20,this.getActiveProjectRoot()),runDream:r=>Uo.call(this.createDreamHandlerHost(),r)}),W().onChange(()=>{this.invalidateResolvedLlmCache()}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ui({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(rx(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 Hn(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(eg(e)||Zi(e)){this.acpServer.dispatchMessage(e);return}if(Vi(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!Ym(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 Cx(),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=Dj(this);handleMessage(e){if(e.id!==void 0&&!Yoe.has(e.method)){let n=sc(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=jL({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return ML({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=EL(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=bF({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:()=>Qa(),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",NL(e,r,n))}createDreamHandlerHost(){return $L({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:()=>Uw.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 LL({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 DL({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)&&qx(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
1255
|
`)}enableIdleDream(e){this.idleDreamCoordinator.enable(e)}cancelIdleDreamTimer(){this.idleDreamCoordinator.cancelTimer()}disposeSessionRuntime(){this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.agent=null,this.lastLlmConfigKey="",this.memoryPrefetchState=rr(),this.runtimeSession.resetAfterSessionDispose()}closeMemoryProviders(){this.runtimeServices.closeMemoryProviders({memoryProvider:this.memoryProvider,memoryDreamProvider:this.memoryDreamProvider}),this.runtimeSession.resetMemoryProviders()}initAcpServer(){let e=TL(this,kF,this.createAcpExtendedHandlerHost());this.acpServer=new ac(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}};export{Dn as Agent,Fw as StdioServer,Ui as StdioTransport,$i as buildSkillInstruction,Ow as createHookRegistry,xz as parseCliArgs};
|
|
@@ -8,6 +8,7 @@ export interface CliCoreToolHostDeps {
|
|
|
8
8
|
getCurrentTransport(): LLMTransport | null;
|
|
9
9
|
getCurrentApiKey(): string;
|
|
10
10
|
getCurrentModel(): string;
|
|
11
|
+
getCurrentBaseUrl(): string;
|
|
11
12
|
getCurrentSessionId(): string;
|
|
12
13
|
getActiveProjectRoot(): string;
|
|
13
14
|
getVerbose(): boolean;
|