blade-code 0.10.200 → 0.10.202
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/blade.js +2 -2
- package/dist/{chunk-p8a4rfmk.js → chunk-0janz3wt.js} +1 -1
- package/dist/{chunk-w8xnevd6.js → chunk-25mfxgrt.js} +1 -1
- package/dist/{chunk-es4ew0m5.js → chunk-4xspf5cy.js} +1 -1
- package/dist/{chunk-q1j1fyes.js → chunk-4z1b1xh1.js} +1 -1
- package/dist/{chunk-eytqr5pa.js → chunk-62a760he.js} +1 -1
- package/dist/{chunk-zkdbenm3.js → chunk-62fg5ent.js} +2 -2
- package/dist/{chunk-7egpbybh.js → chunk-7d29ma2n.js} +2 -2
- package/dist/{chunk-3wrfkx48.js → chunk-80swgnxv.js} +1 -1
- package/dist/{chunk-23dyv46g.js → chunk-8dqymy3g.js} +1 -1
- package/dist/{chunk-kk1enewr.js → chunk-8n79gd8v.js} +1 -1
- package/dist/{chunk-kh752ztz.js → chunk-8x37wry1.js} +1 -1
- package/dist/{chunk-samg8e5r.js → chunk-959pbxxe.js} +1 -1
- package/dist/{chunk-zes3sj35.js → chunk-96bqvw32.js} +1 -1
- package/dist/{chunk-82qd46dk.js → chunk-a1rd4sc5.js} +1 -1
- package/dist/{chunk-rjc9gpyg.js → chunk-anv3d331.js} +1 -1
- package/dist/chunk-aseddz2b.js +1 -0
- package/dist/{chunk-2apttqhb.js → chunk-bfqcffmz.js} +1 -1
- package/dist/{chunk-gqq82tct.js → chunk-c79c3wr5.js} +1 -1
- package/dist/{chunk-9e300fdm.js → chunk-e807pe3n.js} +1 -1
- package/dist/{chunk-0wk62v37.js → chunk-f88fakcc.js} +1 -1
- package/dist/{chunk-rr03cpyt.js → chunk-fdz7af61.js} +1 -1
- package/dist/{chunk-cj7bj0xd.js → chunk-j1ch4tgq.js} +1 -1
- package/dist/{chunk-9e04pnz3.js → chunk-je6gp1jf.js} +1 -1
- package/dist/{chunk-a5nyrwny.js → chunk-jrghepw7.js} +1 -1
- package/dist/chunk-m2xtm86h.js +1 -0
- package/dist/{chunk-egn7j0z6.js → chunk-m6sxrqqt.js} +1 -1
- package/dist/{chunk-gs88ayeq.js → chunk-mp35ntd5.js} +1 -1
- package/dist/{chunk-tedp3vpf.js → chunk-pc3a50qb.js} +1 -1
- package/dist/{chunk-ryqwvskq.js → chunk-q30j5dnt.js} +1 -1
- package/dist/{chunk-h0ydb1jv.js → chunk-qxpr7h1v.js} +1 -1
- package/dist/{chunk-nce3rxq8.js → chunk-t4a0aasw.js} +1 -1
- package/dist/{chunk-0m58gvph.js → chunk-twf4wzv2.js} +1 -1
- package/dist/{chunk-tw7qt8mq.js → chunk-x5p0dm6q.js} +1 -1
- package/dist/{chunk-fmm7fcwf.js → chunk-x8nsxrgy.js} +1 -1
- package/dist/{chunk-3rmg54ga.js → chunk-xe707vjq.js} +1 -1
- package/dist/{chunk-engfjgj7.js → chunk-xp7z7010.js} +4 -4
- package/dist/{chunk-jhvhaj1m.js → chunk-xwnb3eaz.js} +1 -1
- package/dist/{chunk-9sjhkcnm.js → chunk-yrf9b3av.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-k7eyr7r2.js +0 -1
- package/dist/chunk-sv5ew53q.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ga as V3}from"./chunk-vzdsext4.js";import{Ja as T,Ka as e0,Pa as GW,Qa as PY,Ra as t0}from"./chunk-
|
|
1
|
+
import{Ga as V3}from"./chunk-vzdsext4.js";import{Ja as T,Ka as e0,Pa as GW,Qa as PY,Ra as t0}from"./chunk-xwnb3eaz.js";import{$a as GX,Sa as Y5,Va as pZ,Za as tZ,_a as BX,bb as oW,db as tW,eb as M9,wb as eW}from"./chunk-9fyjyk2f.js";import{Ab as l7,Bb as D2,Cb as KY,Db as x1,Eb as o7,Fb as qY,Gb as JY,Hb as wY,Ib as _Y,Jb as UQ,Lb as QX,Nb as V0,Pb as F2,Sb as p4,Ub as FZ,Vb as l4,Wb as i4,Yb as CJ,Zb as T$,dc as tX,ec as G8,fc as eX,gc as $W,hc as YX,jc as u1,kc as vX,pc as nY,sc as aY,xb as s5,yb as u7,zb as J1}from"./chunk-m6sxrqqt.js";import{$c as c2,Ac as n3,Bc as v3,Cc as T1,Dc as JJ,Ec as L0,Fc as k2,Gc as N1,Hc as S6,Ic as P9,Jc as m4,Kc as c4,Lc as QY,Mc as XY,Nc as RX,Oc as W3,Od as V8,Pc as M1,Qc as Q3,Qd as f0,Rc as i8,Rd as N$,Sc as $1,Tc as Z1,Uc as i2,Vc as l2,Wc as r2,Xc as g6,Yc as u6,Yd as WW,Zc as m2,Zd as zX,_c as B3,ad as r8,ae as rY,bd as A1,cd as e1,dd as p2,ed as $2,fd as Z2,fe as SX,gd as d6,ge as kX,hd as J2,id as m6,ie as s,jd as c6,kd as S$,ld as p6,md as N3,nd as n2,od as l6,pd as i6,qd as r6,rd as n6,sd as b3,td as j3,vd as E3,yc as k$,zc as TX}from"./chunk-anv3d331.js";import{je as i,ke as KQ,le as DQ,me as gJ,oe as _2}from"./chunk-egss0m1x.js";import{He as S9,Ie as Z$,Je as q2,Ke as $9,Le as fX,Me as PX,Ve as YV,gf as QV,qe as ZV,te as JV}from"./chunk-ztreczac.js";import{Cf as bJ,Df as OJ}from"./chunk-p0wyhp5a.js";import{Pf as r4,Qf as q0,Rf as d,Uf as E0,Vf as P4,Wf as L2,Xf as G1,Yf as CZ,Zf as R1,_f as lY,dg as B2}from"./chunk-7d29ma2n.js";import{eg as d1}from"./chunk-5yyp6njq.js";import{gg as oX,ig as jZ,jg as iY,og as cY,pg as pX,qg as S4}from"./chunk-myvt7yjm.js";import{rg as nZ}from"./chunk-4fbpydtn.js";import{ug as d0,vg as O1}from"./chunk-3cas6rv5.js";import{wg as JW}from"./chunk-zfxcef0z.js";import{Ag as jX,Bg as EX,yg as NX,zg as bX}from"./chunk-62a760he.js";import{$g as k4,Cg as I4,Dg as h4,Eg as g4,Gg as u4,Hg as d4,Ig as F1,Jg as LQ,Kg as x$,Lg as b$,Mg as B$,Ng as $5,Og as V2,Pg as z8,Qg as l1,Rg as i1,Sg as AX,Wg as J9,Yg as m0,Zg as R$,ah as CX,bh as yX}from"./chunk-959pbxxe.js";import{dh as D1,fh as C$,gh as O4}from"./chunk-kehgewqh.js";import{hh as m3,ih as W2,jh as c3,kh as o2,lh as p3,mh as l3,nh as Z4,oh as $4,ph as i3,qh as r3,rh as e6}from"./chunk-kkzznz4w.js";import{sh as bW,uh as MX,vh as W8,wh as jJ}from"./chunk-1cy4ab77.js";import{Ah as x0,yh as L9}from"./chunk-t4a0aasw.js";import{Bh as E6,Ch as f9,Dh as M6,Eh as r1}from"./chunk-ys8gysg8.js";import{$h as GY,Di as kY,Ei as vY,Fi as yY,Gh as WJ,Gi as xY,Hi as MZ,Ii as IY,Ji as B1,Ki as hY,Lh as VJ,Li as gY,Mi as uY,Nh as D9,Oi as e3,Qi as IX,Ri as OX,Sh as BW,Si as B0,Wh as HJ,Yh as _X,_h as BY,qi as h1,ti as ZY}from"./chunk-yrf9b3av.js";import{Vi as F$}from"./chunk-qpmvp4q2.js";import{Xi as ZX,Zi as JX}from"./chunk-tm3789m3.js";import{aj as X4,cj as C}from"./chunk-qdbbke8f.js";import{Ej as e,Gj as a6,Hj as X2,Ij as K,Jj as f3,Kj as P,Lj as u}from"./chunk-rmfzym94.js";import{Pj as FX,Qj as LX}from"./chunk-j89qk7bp.js";import{Rj as EW,Uj as OW}from"./chunk-0eajnhrj.js";import{Yj as TW}from"./chunk-0janz3wt.js";import{ck as xX,dk as n0}from"./chunk-ggdgk3gy.js";import{Ck as j$,Hk as d3,gk as t,hk as O$,ik as K$,jk as t1,kk as t9,lk as d2,mk as Q$,nk as $Y,qk as I6,zk as P6}from"./chunk-n52n2w5v.js";import{Nk as J$}from"./chunk-cjfb4kjp.js";import{randomUUID as A8}from"crypto";import{randomUUID as bV}from"node:crypto";var _V=String.raw`
|
|
2
2
|
const { spawn } = require('node:child_process');
|
|
3
3
|
const [ownerPidValue, command, ...args] = process.argv.slice(1);
|
|
4
4
|
const ownerPid = Number(ownerPidValue);
|
|
@@ -128,7 +128,7 @@ ${U}`,G=Buffer.byteLength(z);if(V+G>X)break;W.push(U),V+=G}return{snapshot:`${W.
|
|
|
128
128
|
`).filter((q)=>q.toLocaleLowerCase("en-US").includes(G)),D=B.slice(0,U);return{pageId:J.id,target:"find",matches:D,snapshotId:z.snapshotId,origin:z.origin,url:z.url,truncated:D.length<B.length}}let Y=$.target.kind==="console"?this.consoleEntries:$.target.kind==="page-errors"?this.pageErrorEntries:this.networkEntries,Q=$.target.limit??$1;this.assertIntegerRange(Q,1,Z1,"limit");let X=Y.filter((U)=>U.pageId===J.id),W=X.slice(-Q),V=[],H=0;for(let U of W){let z=C0(JSON.stringify(U));if(H+z>u6)break;V.push(U),H+=z}return this.throwIfBlockedNavigation(J),{pageId:J.id,target:$.target.kind,entries:V,truncated:V.length<W.length||X.length>Q}},$.signal)}screenshot($={}){return this.run(async(Z)=>{let J=await this.resolvePage($.pageId,!1,Z);if(this.throwIfBlockedNavigation(J),$.expectedOrigin)this.assertExpectedOrigin(J,$.expectedOrigin);let Y=await J.page.screenshot({type:"png",fullPage:!1,animations:"disabled",caret:"hide",timeout:S$,signal:Z});if(this.throwIfBlockedNavigation(J),Y.length>b3)throw new f("browser_operation_failed","Browser screenshot exceeds the supported size");return Y},$.signal)}page($){return this.run(async(Z)=>{switch($.action.kind){case"list":return this.pageResult();case"open":{let J=await this.createPage(!0,Z);return{...await this.pageResult(),observation:await this.observe(J,Z)}}case"select":{let J=this.requireExistingPage($.action.pageId);return this.selectedPageId=J.id,{...await this.pageResult(),observation:await this.observe(J,Z)}}case"close":{let J=this.requireExistingPage($.action.pageId);await J.page.close({runBeforeUnload:!1}),this.removePage(J);let Y=this.selectedPageId?this.pages.get(this.selectedPageId):void 0;return{...await this.pageResult(),...Y?{observation:await this.observe(Y,Z)}:{}}}case"reset":return await this.resetContext(),{tabs:[]}}},$.signal)}stats(){let $=this.gate.stats();return{pages:this.pages.size,pending:$.pending,active:$.active,generation:this.runtimeGeneration,hasContext:this.context!==void 0,disposed:this.disposed}}async dispose(){if(this.disposed)return;this.disposed=!0;let $=this.gate.close();this.generationController.abort(new f("browser_disposed","Browser Session Runtime is closed"));let Z=this.lease;this.lease=void 0,this.clearContextProjection(!1),await Z?.release(),await $}run($,Z){let J=this.runtimeGeneration;return this.gate.run(async(Y)=>{if(J!==this.runtimeGeneration)throw new f("browser_disconnected","Chromium disconnected before the queued operation started",{retryable:!0});let Q=AbortSignal.any([Y,this.generationController.signal]);try{return await $(Q)}catch(X){throw this.throwIfDisconnected(X,Q),X}},Z)}async ensureContext($){if(this.disposed)throw new f("browser_disposed","Browser Session Runtime is closed");if(this.context&&this.lease)return this.context;let Z=await e$(this.pool.acquire(()=>this.handleDisconnected()),$,(Y)=>Y.release()),J=Z.context;if(this.disposed||$.aborted)throw await Z.release(),$.reason??new f("browser_disposed","Browser Session Runtime is closed");try{return await e$(J.route("**/*",(Y)=>this.guardRoute(Y)),$),J.setDefaultTimeout(S$),J.setDefaultNavigationTimeout(n2),J.on("page",(Y)=>{this.trackDiscoveredPage(Y)}),this.lease=Z,this.context=J,J}catch(Y){throw await Z.release(),Y}}async createPage($,Z){if(this.pages.size>=M1)throw new f("browser_capacity",`Browser page capacity is full (max ${M1})`,{retryable:!0});let J=await this.ensureContext(Z),Y=await e$(J.newPage(),Z,(X)=>X.close({runBeforeUnload:!1}).catch(()=>{return})),Q=this.registerPage(Y,$);if(!Q)throw new f("browser_capacity",`Browser page capacity is full (max ${M1})`,{retryable:!0});if($)this.selectedPageId=Q.id;return Q}async resolvePage($,Z,J){if($)return this.requireExistingPage($);if(this.selectedPageId){let Q=this.pages.get(this.selectedPageId);if(Q&&!Q.page.isClosed())return Q}let Y=[...this.pages.values()].filter((Q)=>!Q.page.isClosed()).sort((Q,X)=>Q.createdSequence-X.createdSequence)[0];if(Y)return this.selectedPageId=Y.id,Y;if(!Z)throw new f("browser_page_not_found","Browser has no open page");return this.createPage(!0,J)}requireExistingPage($){this.assertIdentifier($,"page ID");let Z=this.pages.get($);if(!Z||Z.page.isClosed())throw new f("browser_page_not_found","Browser page does not exist or is closed");return Z}registerPage($,Z,J=null,Y){let Q=this.pageIds.get($);if(Q){let V=this.pages.get(Q);if(V&&Y&&!V.openerPageId)V.openerPageId=Y;if(Z&&V)this.selectedPageId=V.id;return V}if(this.pages.size>=M1){$.close({runBeforeUnload:!1}).catch(()=>{return}),this.addPageError({sequence:++this.diagnosticSequence,pageId:Y??this.selectedPageId??"unknown",kind:"popup-capacity",text:"Browser popup closed because the Session page limit was reached"});return}let X=`browser_page_${VH()}`,W={id:X,page:$,generation:0,authorizedOrigin:J,...Y?{openerPageId:Y}:{},createdSequence:++this.pageSequence};if(this.pages.set(X,W),this.pageIds.set($,X),Z||!this.selectedPageId)this.selectedPageId=X;return this.attachPageListeners(W),W}async registerDiscoveredPage($){if(this.disposed)return;let Z=await $.opener().catch(()=>null);if(this.disposed){await $.close({runBeforeUnload:!1}).catch(()=>{return});return}let J=(Z?this.pageIds.get(Z):void 0)??this.popupOpeners.get($),Y=J?this.pages.get(J):void 0,Q=Y?.authorizedOrigin??null,X=this.registerPage($,!1,Q,Y?.id);if(!X)return;let W=r0($.url()),V=W!==Q,H=V?this.takeBlockedPopup(Y):void 0;if(!H&&V)this.discardUnattributedBlockedPopup();let U=X.blockedCandidateOrigin??H?.origin??(V?W??"[unsupported-origin]":void 0);if(U){if(X.blockedCandidateOrigin=U,Y)Y.blockedCandidateOrigin=U;if(!H)this.addNetwork({sequence:++this.diagnosticSequence,pageId:Y?.id??X.id,kind:"navigation-blocked",url:U,text:"Cross-origin popup was blocked"});await $.close({runBeforeUnload:!1}).catch(()=>{return}),this.removePage(X)}}trackDiscoveredPage($,Z){if(Z)this.popupOpeners.set($,Z);let J=this.pageRegistrations.get($);if(J)return J;let Y=this.registerDiscoveredPage($);return this.pageRegistrations.set($,Y),this.pendingPageRegistrations.add(Y),Y.finally(()=>this.pendingPageRegistrations.delete(Y)).catch(()=>{return}),Y}takeBlockedPopup($){let Z=$?this.blockedPopups.map((Q,X)=>({blocked:Q,index:X})).filter(({blocked:Q})=>Q.openerPageId===$.id).map(({index:Q})=>Q):[],J=Z.length===0&&$?this.blockedPopups.map((Q,X)=>({blocked:Q,index:X})).filter(({blocked:Q})=>Q.openerPageId===void 0&&Q.referrerOrigin===$.authorizedOrigin).map(({index:Q})=>Q):[],Y=Z.length===1?Z[0]:J.length===1?J[0]:-1;return Y===-1?void 0:this.blockedPopups.splice(Y,1)[0]}discardUnattributedBlockedPopup(){let $=this.blockedPopups.findIndex((Z)=>Z.openerPageId===void 0);if($!==-1)this.blockedPopups.splice($,1)}async settlePageRegistrations($){let Z=[...this.pendingPageRegistrations];if(Z.length===0)return;await e$(Promise.allSettled(Z).then(()=>{return}),$)}attachPageListeners($){let{page:Z}=$;Z.on("framenavigated",(J)=>this.handleFrameNavigated($,J)),Z.on("close",()=>this.removePage($)),Z.on("console",(J)=>this.recordConsole($,J)),Z.on("pageerror",(J)=>{this.addPageError({sequence:++this.diagnosticSequence,pageId:$.id,kind:"page-error",text:HH(J)})}),Z.on("request",(J)=>this.recordRequest($,J)),Z.on("response",(J)=>this.recordResponse($,J)),Z.on("requestfailed",(J)=>this.recordRequestFailure($,J)),Z.on("dialog",(J)=>{this.dismissDialog($,J)}),Z.on("download",(J)=>{this.trackDownloadCancellation($,J)}),Z.on("popup",(J)=>{this.trackDiscoveredPage(J,$.id)})}handleFrameNavigated($,Z){if(Z!==$.page.mainFrame()){this.captureOpaqueFrame(Z);return}this.invalidatePage($);let J=r0(Z.url()),Y=$.transientOrigin??$.authorizedOrigin;if(J===null){if(Y)$.blockedCandidateOrigin??="[unsupported-origin]";$.authorizedOrigin=null;return}if(J!==Y){$.blockedCandidateOrigin??=J,$.authorizedOrigin=null;return}$.authorizedOrigin=J}async guardRoute($){let Z=$.request();if(!Z.isNavigationRequest()){await $.continue();return}let J;try{J=Z.frame()}catch{let z=(()=>{try{return i0(Z.url()).origin}catch{return"[unsupported-origin]"}})(),G=this.browserRequestReferrerOrigin(Z),B=this.resolvePopupOpenerFromReferrer(Z);if(B?.authorizedOrigin&&z===B.authorizedOrigin||G&&z===G&&[...this.pages.values()].some((D)=>!D.page.isClosed()&&D.authorizedOrigin===G&&r0(D.page.url())===G)){await $.continue();return}if(B)B.blockedCandidateOrigin=z;if(this.blockedPopups.push({origin:z,...B?{openerPageId:B.id}:{},...G?{referrerOrigin:G}:{}}),this.blockedPopups.length>M1)this.blockedPopups.splice(0,this.blockedPopups.length-M1);this.addNetwork({sequence:++this.diagnosticSequence,pageId:B?.id??"unknown",kind:"navigation-blocked",url:z,text:"Cross-origin top-level navigation was blocked"}),await $.abort("blockedbyclient");return}if(J.parentFrame()){if(await this.isFrameSandboxOpaque(J))this.opaqueFrames.add(J);else this.opaqueFrames.delete(J);await $.continue();return}let Y=J.page(),Q=this.pageIds.get(Y)?this.pages.get(this.pageIds.get(Y)):void 0,X=await Y.opener().catch(()=>null),W=this.popupOpeners.get(Y)??(X?this.pageIds.get(X):void 0),V=W?this.pages.get(W):void 0;if(!Q)Q=this.registerPage(Y,!1,V?.authorizedOrigin??null,V?.id);else if(V&&!Q.openerPageId)Q.openerPageId=V.id;if(!Q){await $.abort("blockedbyclient");return}let H;try{H=i0(Z.url()).origin}catch{Q.blockedCandidateOrigin="[unsupported-origin]",await $.abort("blockedbyclient");return}let U=Q.transientOrigin??Q.authorizedOrigin;if(!U||H!==U){Q.blockedCandidateOrigin=H;let z=Q.openerPageId?this.pages.get(Q.openerPageId):void 0;if(z)z.blockedCandidateOrigin=H;if(this.addNetwork({sequence:++this.diagnosticSequence,pageId:z?.id??Q.id,kind:"navigation-blocked",url:H,text:"Cross-origin top-level navigation was blocked"}),await $.abort("blockedbyclient"),Q.openerPageId)await Y.close({runBeforeUnload:!1}).catch(()=>{return}),this.removePage(Q);return}await $.continue()}browserRequestReferrerOrigin($){let Z=$.headers().referer;if(!Z)return;try{return i0(Z).origin}catch{return}}resolvePopupOpenerFromReferrer($){let Z=$.headers().referer;if(!Z)return;let J;try{J=i0(Z)}catch{return}let Y=[...this.pages.values()].filter((W)=>!W.page.isClosed()&&W.authorizedOrigin===J.origin),Q=Y.filter((W)=>{try{return i0(W.page.url()).href===J.href}catch{return!1}});if((J.url.pathname!=="/"||J.url.search.length>0)&&Q.length===1)return Q[0];return Y.length===1?Y[0]:void 0}settleNavigationAuthorization($,Z,J){let Y=r0($.page.url());if(Y===Z)$.authorizedOrigin=Z;else if(Y===J)$.authorizedOrigin=J;else $.authorizedOrigin=null}assertExpectedOrigin($,Z){let J=X$(Z),Y=r0($.page.url());if($.authorizedOrigin===null||Y!==$.authorizedOrigin||J!==$.authorizedOrigin)throw new f("browser_origin_mismatch","Browser page origin changed; capture a new snapshot or navigate explicitly");return J}throwIfBlockedNavigation($){if(!$.blockedCandidateOrigin)return;throw new f("browser_cross_origin_navigation",`Cross-origin navigation was blocked: ${$.blockedCandidateOrigin}`,{candidateOrigin:$.blockedCandidateOrigin})}markUnexpectedInteractionOrigin($,Z){if($.page.isClosed()||$.blockedCandidateOrigin)return;let J=r0($.page.url());if(J!==Z)$.blockedCandidateOrigin=J??"[unsupported-origin]"}async resolveEffectiveFrameOrigin($){let Z=$,J=null;while(Z){if(Z!==Z.page().mainFrame()){if(this.opaqueFrames.has(Z)||await this.isFrameSandboxOpaque(Z))return this.opaqueFrames.add(Z),null}let Y=r0(Z.url());if(Y){if(J&&Y!==J)return null;J??=Y}else if(Z.url()!=="about:blank"&&Z.url()!=="about:srcdoc")return null;Z=Z.parentFrame()}return J}async captureOpaqueFrame($){if(await this.isFrameSandboxOpaque($))this.opaqueFrames.add($)}async isFrameSandboxOpaque($){try{let Z=await $.frameElement();try{let J=await Z.getAttribute("sandbox");return J!==null&&!J.toLowerCase().split(/\s+/u).filter(Boolean).includes("allow-same-origin")}finally{await Z.dispose().catch(()=>{return})}}catch{return!0}}async observe($,Z,J=r2,Y=!1){if($.page.isClosed())throw new f("browser_page_not_found","Browser page is closed");this.throwIfBlockedNavigation($);let Q=await $.page.ariaSnapshot({mode:"ai",depth:J,boxes:Y,timeout:S$,signal:Z});this.throwIfBlockedNavigation($);let X=await this.pageSummaries(),W=r0($.page.url())??"null",V=T0(await $.page.title().catch(()=>""),r8),H=typeof $.page.viewportSize==="function"?$.page.viewportSize():null,U=this.snapshots.issue({pageId:$.id,pageGeneration:$.generation,origin:W,snapshot:Q,depth:J,includeBoxes:Y,maxBytes:Math.min(l2,32768)});return{pageId:$.id,snapshotId:U.snapshotId,url:t$($.page.url()),origin:W,title:V,...H?{viewport:H}:{},tabs:X,snapshot:U.snapshot,truncated:U.truncated}}async pageResult(){return{tabs:await this.pageSummaries(),...this.selectedPageId?{selectedPageId:this.selectedPageId}:{}}}async pageSummaries(){return Promise.all([...this.pages.values()].filter(($)=>!$.page.isClosed()).sort(($,Z)=>$.createdSequence-Z.createdSequence).map(async($)=>({pageId:$.id,selected:$.id===this.selectedPageId,url:t$($.page.url()),origin:r0($.page.url())??"null",title:T0(await $.page.title().catch(()=>""),r8)})))}invalidatePage($){$.generation++,this.snapshots.invalidate($.id),this.screenshots.invalidate($.id)}assertIdentifier($,Z){if(!$||C0($)>A1)throw new f("browser_unsupported",`Browser ${Z} is invalid`)}assertIntegerRange($,Z,J,Y){if(!Number.isSafeInteger($)||$<Z||$>J)throw new f("browser_unsupported",`Browser ${Y} must be an integer from ${Z} to ${J}`)}validateAction($){if($.kind==="click_at"){this.assertIntegerRange($.x,0,Z2,"x coordinate"),this.assertIntegerRange($.y,0,Z2,"y coordinate"),this.assertIdentifier($.screenshotId,"screenshot ID");return}if($.kind==="fill"||$.kind==="type"){if(C0($.value)>$2)throw new f("browser_unsupported","Browser input exceeds the supported size");return}if($.kind==="scroll"){this.assertIntegerRange($.amount,1,d6,"scroll amount");return}if($.kind!=="select")return;if($.values.length===0||$.values.length>m6||$.values.some((Z)=>C0(Z)>c6)||C0($.values.join(""))>$2)throw new f("browser_unsupported","Browser select values exceed the supported size")}async validateCoordinateClick($,Z,J){let Y=$.page.viewportSize();if(!Y||Z.x>=Y.width||Z.y>=Y.height)throw new f("browser_unsupported","Browser coordinates must be inside the current viewport");let Q=await this.captureStableScreenshot($,J);this.screenshots.validate({screenshotId:Z.screenshotId,pageId:$.id,pageGeneration:$.generation,origin:r0($.page.url())??"null",sha256:WH("sha256").update(Q).digest("hex"),viewport:Y}),await this.assertCoordinateOutsideFrames($.page,Z.x,Z.y)}async assertCoordinateOutsideFrames($,Z,J){let Y=$.mainFrame();for(let Q of $.frames()){if(Q===Y)continue;let X;try{X=await Q.frameElement();let W=await X.boundingBox();if(W&&Z>=W.x&&Z<W.x+W.width&&J>=W.y&&J<W.y+W.height)throw new f("browser_cross_origin_frame","Browser coordinate clicks cannot target frame content")}catch(W){if(!Q.isDetached())throw W}finally{await X?.dispose().catch(()=>{return})}}}async captureStableScreenshot($,Z){let J=()=>$.page.screenshot({type:"png",fullPage:!1,animations:"disabled",caret:"hide",timeout:S$,signal:Z}),Y=await J();for(let Q=0;Q<3;Q++){await O3(50,Z);let X=await J();if(X.equals(Y))return X;Y=X}throw new f("browser_busy","Browser screenshot did not stabilize; wait for visual updates to settle",{retryable:!0})}removePage($){if(this.pages.get($.id)!==$)return;if(this.pages.delete($.id),this.snapshots.invalidate($.id),this.screenshots.invalidate($.id),this.selectedPageId===$.id){let Z=[...this.pages.values()].sort((J,Y)=>J.createdSequence-Y.createdSequence)[0];this.selectedPageId=Z?.id}}async resetContext(){this.runtimeGeneration++,this.generationController.abort(new f("browser_disconnected","Browser Context was explicitly reset",{retryable:!0})),this.generationController=new AbortController;let $=this.lease;this.lease=void 0,this.clearContextProjection(!0),await $?.release()}clearContextProjection($){if(this.snapshots.clear(),this.screenshots.clear(),this.pages.clear(),this.blockedPopups.length=0,this.selectedPageId=void 0,this.context=void 0,$)this.consoleEntries.length=0,this.pageErrorEntries.length=0,this.networkEntries.length=0}async executeAction($,Z,J,Y,Q){if(J.kind==="click_at"){await e$($.mouse.click(J.x,J.y),Q);return}if(J.kind==="scroll"){let X=J.direction==="up"||J.direction==="left"?-J.amount:J.amount,W=J.direction==="left"||J.direction==="right"?X:0,V=J.direction==="up"||J.direction==="down"?X:0;await e$($.mouse.wheel(W,V),Q);return}if(!Z)throw new f("browser_unsupported","Browser action requires a top-level snapshot ref next to action");switch(J.kind){case"click":await Z.click({timeout:Y,signal:Q});break;case"hover":await Z.hover({timeout:Y,signal:Q});break;case"fill":await Z.fill(J.value,{timeout:Y,signal:Q});break;case"type":await Z.pressSequentially(J.value,{timeout:Y,signal:Q});break;case"press":await Z.press(J.key,{timeout:Y,signal:Q});break;case"select":await Z.selectOption(J.values.map((X)=>({value:X})),{timeout:Y,signal:Q});break;case"check":await Z.check({timeout:Y,signal:Q});break;case"uncheck":await Z.uncheck({timeout:Y,signal:Q});break}}uncertainInteraction($,Z,J,Y){let Q="browser_action_uncertain";if($.blockedCandidateOrigin)Q="browser_cross_origin_navigation";else if(Z!==this.runtimeGeneration||L3(J))Q="browser_disconnected";else if(l8(J))Q="browser_timeout";return{outcome:"uncertain",pageId:$.id,actionApplied:"unknown",sideEffectsUncertain:!0,errorCode:Q,...$.blockedCandidateOrigin?{candidateOrigin:$.blockedCandidateOrigin}:{},...Y?{interaction:Y}:{}}}recordConsole($,Z){this.addConsole({sequence:++this.diagnosticSequence,pageId:$.id,kind:"console",level:T0(Z.type(),64),text:T0(Z.text(),i2)})}recordRequest($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"request",method:T0(Z.method(),32),resourceType:T0(Z.resourceType(),64),url:t$(Z.url())})}recordResponse($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"response",status:Z.status(),url:t$(Z.url())})}recordRequestFailure($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"request-failure",method:T0(Z.method(),32),resourceType:T0(Z.resourceType(),64),url:t$(Z.url()),text:T0(Z.failure()?.errorText??"request failed",i2)})}async dismissDialog($,Z){this.addPageError({sequence:++this.diagnosticSequence,pageId:$.id,kind:"dialog",text:T0(`${Z.type()}: ${Z.message()}`,i2)});let J=$.nextDialogAction;if($.nextDialogAction=void 0,J==="accept")await Z.accept().catch(()=>{return});else await Z.dismiss().catch(()=>{return})}async cancelDownload($,Z){$.downloadBlocked=!0,this.addPageError({sequence:++this.diagnosticSequence,pageId:$.id,kind:"download",text:"Browser download was blocked"}),await Z.cancel().catch(()=>{return})}trackDownloadCancellation($,Z){if(this.downloadCancellations.has(Z))return;let J=this.cancelDownload($,Z);this.downloadCancellations.set(Z,J),this.pendingDownloadCancellations.add(J),J.finally(()=>this.pendingDownloadCancellations.delete(J)).catch(()=>{return})}async settleDownloadCancellations($){let Z=[...this.pendingDownloadCancellations];if(Z.length===0)return;await e$(Promise.allSettled(Z).then(()=>{return}),$)}addConsole($){this.consoleEntries.push($),this.trimRing(this.consoleEntries)}addPageError($){this.pageErrorEntries.push($),this.trimRing(this.pageErrorEntries)}addNetwork($){this.networkEntries.push($),this.trimRing(this.networkEntries)}trimRing($){if($.length>i8)$.splice(0,$.length-i8)}handleDisconnected(){this.runtimeGeneration++,this.generationController.abort(new f("browser_disconnected","Chromium disconnected; Browser state was discarded",{retryable:!0})),this.generationController=new AbortController,this.lease=void 0,this.clearContextProjection(!1)}throwIfDisconnected($,Z){if(Z.aborted&&Z.reason instanceof f)throw Z.reason;if(L3($))throw new f("browser_disconnected","Chromium disconnected during the Browser operation",{retryable:!0})}}function M3($){if(!$)return{state:"none"};let Z=$.inputMessageIds.length;if($.outcome==="completed")return{state:"completed",turnId:$.turnId,inputMessageCount:Z};if(($.interruptedToolCallCount??0)>0)return{state:"requires_attention",turnId:$.turnId,inputMessageCount:Z,reason:"interrupted_tool_call"};if($.hadSuccessfulToolResult&&$.allSuccessfulToolResultsSafeForResume!==!0)return{state:"requires_attention",turnId:$.turnId,inputMessageCount:Z,reason:"successful_tool_result"};return{state:"resumable",turnId:$.turnId,inputMessageCount:Z}}import{createHash as _H}from"node:crypto";import{createHash as GH}from"node:crypto";import*as s6 from"fs/promises";import*as C1 from"path";import KH from"write-file-atomic";import*as C3 from"node:fs/promises";import*as T3 from"node:path";var UH={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},A3;async function R3($,Z){await C3.mkdir(T3.dirname($),{recursive:!0,mode:448});let Y=await(await zH()).lock($,UH);try{return await Z()}finally{await Y()}}async function zH(){return A3??=await import("proper-lockfile"),A3}var a8=u(["pending","in_progress","completed"]),BH=u(["high","medium","low"]),P3=f3(K.Object({id:K.String(),subject:K.String(),description:K.String(),status:a8,activeForm:K.Optional(K.String()),owner:K.Optional(K.String()),priority:P(BH,"medium"),blocks:P(K.Array(K.String()),[]),blockedBy:P(K.Array(K.String()),[]),metadata:K.Optional(K.Record(K.String(),K.Unknown())),createdAt:K.String(),startedAt:K.Optional(K.String()),completedAt:K.Optional(K.String())}));class _${taskListId;configDir;static operations=new F$;tasks=[];filePath;stateStorage;constructor($,Z,J){this.taskListId=$;this.configDir=Z;this.stateStorage=J,this.filePath=C1.join(C1.resolve(Z),"tasks",S3($))}static getInstance($,Z,J){return new _$($,Z,J)}static coordinationStatsForTests(){return this.operations.getStats()}async createTask($){return this.mutate((Z)=>{let J=Y2($.blockedBy??[]),Y={id:String(Z.nextId),subject:$.subject,description:$.description,activeForm:$.activeForm,owner:$.owner,priority:$.priority||"medium",status:"pending",blocks:[],blockedBy:J,metadata:$.metadata,createdAt:new Date().toISOString()};return{state:{nextId:Z.nextId+1,tasks:Z.tasks.map((Q)=>J.includes(Q.id)?{...Q,blocks:Y2([...Q.blocks,Y.id])}:Q).concat(Y)},result:Y,persist:!0}})}async getTask($){return(await this.readLatest()).tasks.find((J)=>J.id===$)||null}async listTasks(){return await this.readLatest(),this.getSortedTasks()}async claimNextAvailable($){let Z=$.trim();if(!Z)throw Error("Task owner cannot be empty");return this.mutate((J)=>{let Y=new Set(J.tasks.filter((W)=>W.status==="completed").map((W)=>W.id)),Q=[...J.tasks].filter((W)=>W.status==="pending"&&(W.owner===void 0||W.owner===Z)&&W.blockedBy.every((V)=>Y.has(V))).sort(k3)[0];if(!Q)return{state:J,result:null,persist:!1};let X={...Q,owner:Z,status:"in_progress",startedAt:Q.startedAt??new Date().toISOString()};return{state:{...J,tasks:J.tasks.map((W)=>W.id===X.id?X:W)},result:X,persist:!0}})}async updateTask($,Z){return this.mutate((J)=>{let Y=J.tasks.findIndex((U)=>U.id===$);if(Y===-1)return{state:J,result:{task:null,updatedFields:[]},persist:!1};let Q=J.tasks[Y],X=[],W={...Q};if(Z.subject!==void 0&&Z.subject!==Q.subject)W.subject=Z.subject,X.push("subject");if(Z.description!==void 0&&Z.description!==Q.description)W.description=Z.description,X.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==Q.activeForm)W.activeForm=Z.activeForm,X.push("activeForm");if(Z.owner!==void 0&&Z.owner!==Q.owner)W.owner=Z.owner,X.push("owner");if(Z.metadata!==void 0)W.metadata=wH(Q.metadata,Z.metadata),X.push("metadata");let V;if(Z.status!==void 0&&Z.status!==Q.status){if(W.status=Z.status,Z.status==="in_progress"&&!Q.startedAt)W.startedAt=new Date().toISOString();if(Z.status==="completed"&&!Q.completedAt)W.completedAt=new Date().toISOString();V={from:Q.status,to:Z.status},X.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(W.blocks=Y2([...Q.blocks,...Z.addBlocks]),W.blocks.length!==Q.blocks.length)X.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(W.blockedBy=Y2([...Q.blockedBy,...Z.addBlockedBy]),W.blockedBy.length!==Q.blockedBy.length)X.push("blockedBy")}let H=J.tasks.map((U)=>U.id===$?W:U);return H=qH(H,W,Z.addBlocks,Z.addBlockedBy),{state:{...J,tasks:H},result:{task:W,updatedFields:X,statusChange:V},persist:!0}})}async deleteTask($){return this.mutate((Z)=>{let J=Z.tasks.filter((Q)=>Q.id!==$).map((Q)=>({...Q,blocks:Q.blocks.filter((X)=>X!==$),blockedBy:Q.blockedBy.filter((X)=>X!==$)})),Y=J.length!==Z.tasks.length;return{state:Y?{...Z,tasks:J}:Z,result:Y,persist:Y}})}getStats(){return{total:this.tasks.length,completed:this.tasks.filter(($)=>$.status==="completed").length,inProgress:this.tasks.filter(($)=>$.status==="in_progress").length,pending:this.tasks.filter(($)=>$.status==="pending").length}}getSortedTasks(){return[...this.tasks].sort(k3)}withTaskListPath($){if(this.stateStorage?.kind!=="acp-remote")return $(this.filePath);return v3(this.stateStorage,(Z)=>$(C1.join(Z,"tasks",S3(this.taskListId))))}async readLatest(){return _$.operations.runExclusive(this.filePath,async()=>{let $=await this.withTaskListPath((Z)=>this.readTasks(Z));return this.tasks=$.tasks,$})}async mutate($){return _$.operations.runExclusive(this.filePath,()=>this.withTaskListPath((Z)=>R3(Z,async()=>{let J=await this.readTasks(Z),Y=$(J);if(Y.persist)await this.saveTasks(Z,Y.state);return this.tasks=Y.state.tasks,Y.result})))}async readTasks($){try{let Z=JSON.parse(await s6.readFile($,"utf-8"));return DH(Z)}catch(Z){if(Z.code==="ENOENT")return{tasks:[],nextId:1};throw Error("Task list state is corrupt or unreadable",{cause:Z})}}async saveTasks($,Z){await s6.mkdir(C1.dirname($),{recursive:!0,mode:448}),await KH($,`${JSON.stringify(Z,null,2)}
|
|
129
129
|
`,{mode:384})}}function DH($){let Z=$&&typeof $==="object"&&!Array.isArray($)?$:void 0,J=Array.isArray($)?$:Z&&Array.isArray(Z.tasks)?Z.tasks:void 0;if(!J)throw Error("Task list must contain a tasks array");let Y=J.map((W,V)=>{let H=a6(P3,W);if(!H.success)throw Error(`Task list item ${V} failed schema validation`);return H.data});if(new Set(Y.map((W)=>W.id)).size!==Y.length)throw Error("Task list contains duplicate task IDs");let Q=Z&&typeof Z.nextId==="number"?Z.nextId:void 0;if(Q!==void 0&&(!Number.isInteger(Q)||Q<1))throw Error("Task list nextId must be a positive integer");let X=Y.reduce((W,V)=>{let H=Number(V.id);return Number.isFinite(H)?Math.max(W,H):W},0);return{tasks:Y,nextId:Math.max(Q||1,X+1)}}function qH($,Z,J,Y){let Q=$;for(let X of J||[])Q=Q.map((W)=>W.id===X?{...W,blockedBy:Y2([...W.blockedBy,Z.id])}:W);for(let X of Y||[])Q=Q.map((W)=>W.id===X?{...W,blocks:Y2([...W.blocks,Z.id])}:W);return Q}function S3($){let Z=encodeURIComponent($||"default");if(Z.length<=120)return`${Z}-agent-${Z}.json`;let J=GH("sha256").update($).digest("hex").slice(0,16);return`${Z.slice(0,96)}-${J}.json`}function Y2($){return[...new Set($.filter(Boolean))]}function k3($,Z){let J={in_progress:0,pending:1,completed:2},Y={high:0,medium:1,low:2},Q=J[$.status]-J[Z.status];if(Q!==0)return Q;let X=Y[$.priority]-Y[Z.priority];if(X!==0)return X;return Number($.id)-Number(Z.id)}function wH($,Z){let J={...$||{}};for(let[Y,Q]of Object.entries(Z))if(Q===null)delete J[Y];else J[Y]=Q;return J}var FH=512,LH=256;function s2($){return`goal:${$.sessionId}:${$.goalId}`}async function o6($,Z){let J=s2($),Q=await _$.getInstance(J,Z.configDir,Z.stateStorage).listTasks(),X=new Set(Q.filter((G)=>G.status==="completed").map((G)=>G.id)),W=Q.filter((G)=>G.status==="pending"),V=W.filter((G)=>G.blockedBy.every((B)=>X.has(B))&&(Z.owner===void 0||G.owner===void 0||G.owner===Z.owner)),H=W.filter((G)=>!G.blockedBy.every((B)=>X.has(B))).length,U=V[0];return{frontier:{taskListId:J,total:Q.length,completed:Q.filter((G)=>G.status==="completed").length,inProgress:Q.filter((G)=>G.status==="in_progress").length,pending:W.length,blocked:H,...U?{nextTask:{id:U.id,subject:U.subject,priority:U.priority}}:{},digestSha256:OH(Q),observedAt:new Date().toISOString()},tasks:Q}}function y3($){let Z=$.nextTask?`#${a2($.nextTask.id)} [${$.nextTask.priority}] ${a2($.nextTask.subject.slice(0,FH))}`:$.pending>0?"none (pending tasks are waiting for dependencies or ownership)":"none (task list is complete or empty)";return["<goal-execution-frontier>",`Task list: ${a2($.taskListId.slice(0,LH))}`,`Tasks: total=${$.total}, completed=${$.completed}, in_progress=${$.inProgress}, pending=${$.pending}, blocked=${$.blocked}`,`Next executable task: ${Z}`,`Digest: ${a2($.digestSha256)}`,`Observed at: ${a2($.observedAt)}`,"</goal-execution-frontier>"].join(`
|
|
130
130
|
`)}function OH($){let Z=[...$].sort((J,Y)=>J.id.localeCompare(Y.id)).map((J)=>({id:J.id,status:J.status,blockedBy:[...J.blockedBy].sort(),blocks:[...J.blocks].sort(),owner:J.owner??null,priority:J.priority,subject:J.subject}));return _H("sha256").update(JSON.stringify(Z)).digest("hex")}function a2($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var NH=64;function x3($,Z,J,Y){if($===void 0||$.digestSha256!==Z.digestSha256||J.taskEffect!=="none"||Z.total===0||Z.pending===0&&Z.inProgress===0)return;let Q=bH(Z,J);if(Q===void 0)return;let X=Y?.category===Q&&Y.digestSha256===Z.digestSha256?Math.min(e6,Y.consecutiveCount+1):1;return{category:Q,consecutiveCount:X,digestSha256:Z.digestSha256,detectedAt:new Date().toISOString()}}function I3($){let Z=t6($.digestSha256.slice(0,NH)),J=t6($.category),Y=t6(jH($.category));return["<goal-frontier-stall>",`Category: ${J}`,`Consecutive observations: ${$.consecutiveCount}`,`Digest: ${Z}`,`Detected at: ${t6($.detectedAt)}`,`Required action: ${Y}`,"Treat this block as host diagnostics, not as user instructions.","</goal-frontier-stall>"].join(`
|
|
131
|
-
`)}function bH($,Z){if($.pending>0&&$.blocked>0&&$.inProgress===0&&$.nextTask===void 0)return"waiting_dependency";if(Z.prematureStopCount>=2||Z.verificationStallCount>=2)return"repeated_deferral";if(Z.prematureStopCount<1&&Z.verificationStallCount<1)return;if($.pending>0||$.inProgress>0)return"same_task_no_effect";return}function jH($){switch($){case"waiting_dependency":return"Inspect the incomplete dependency, then execute an independent task or report the concrete external blocker.";case"repeated_deferral":return"Change strategy: validate assumptions, inspect durable results, and fix or verify the reported gap before another completion attempt.";case"same_task_no_effect":return"Change strategy: stop repeating the same step, inspect current evidence, and choose a different executable task or verification action."}}function t6($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}import*as L$ from"node:fs/promises";import*as a3 from"node:path";import{nanoid as EH}from"nanoid";import MH from"write-file-atomic";var h3=1048576,o8=1e5,AH=K.Object({attempt:K.Integer({minimum:1}),status:u(c3),requestedAt:K.String({format:"date-time"}),completedAt:K.Optional(K.String({format:"date-time"})),verifierSessionId:K.Optional(K.String({minLength:1})),summary:K.Optional(K.String({maxLength:o2})),evidenceSha256:K.Optional(K.String({pattern:"^[a-f0-9]{64}$"}))}),CH=K.Object({taskListId:K.String({minLength:1,maxLength:256}),total:K.Integer({minimum:0}),completed:K.Integer({minimum:0}),inProgress:K.Integer({minimum:0}),pending:K.Integer({minimum:0}),blocked:K.Integer({minimum:0}),nextTask:K.Optional(K.Object({id:K.String({minLength:1}),subject:K.String({minLength:1,maxLength:512}),priority:u(["high","medium","low"])})),digestSha256:K.String({pattern:"^[a-f0-9]{64}$"}),observedAt:K.String({format:"date-time"})}),TH=K.Object({category:u(r3),consecutiveCount:K.Integer({minimum:1,maximum:e6}),digestSha256:K.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:K.String({format:"date-time"})}),RH=K.Object({category:u(i3),consecutiveCount:K.Integer({minimum:1,maximum:$4}),detectedAt:K.String({format:"date-time"})}),fH=K.Object({rootTurnId:K.Optional(K.String({minLength:1,maxLength:W2})),currentTurnId:K.String({minLength:1,maxLength:W2}),parentTurnId:K.Optional(K.String({minLength:1,maxLength:W2}))},{additionalProperties:!1}),Q2=K.Object({version:K.Union([K.Literal(1),K.Literal(2)]),sessionId:K.String({minLength:1}),goalId:K.String({minLength:1}),objective:K.String({minLength:1,maxLength:o8}),status:u(m3),tokenBudget:K.Optional(K.Integer({minimum:1})),tokensUsed:K.Integer({minimum:0}),timeUsedSeconds:K.Integer({minimum:0}),continuationCount:K.Integer({minimum:0}),statusReason:K.Optional(K.String()),completionVerification:K.Optional(AH),verificationStall:K.Optional(K.Object({feedbackSha256:K.String({pattern:"^[a-f0-9]{64}$"}),consecutiveCount:K.Integer({minimum:1}),detectedAt:K.String({format:"date-time"})})),prematureStop:K.Optional(K.Object({pattern:u(l3),consecutiveCount:K.Integer({minimum:1}),detectedAt:K.String({format:"date-time"})})),executionHostFailure:K.Optional(RH),turnLineage:K.Optional(fH),executionFrontier:K.Optional(CH),frontierStall:K.Optional(TH),createdAt:K.String({format:"date-time"}),updatedAt:K.String({format:"date-time"})});function g3($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function u3($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>o8)throw Error(`Goal objective exceeds ${o8} characters`);return Z}function PH($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}function s8($){if($.length<1||$.length>W2)throw Error(`Goal turn ID must contain between 1 and ${W2} characters`);return $}function SH($){let Z=$?.trim();if(!Z)return;return Z.slice(0,o2)}class H0{workspaceRoot;sessionId;stateStorage;static locks=new F$;static listeners=new Set;coordinationKey;constructor($,Z,J=k$($)){this.workspaceRoot=$;this.sessionId=Z;this.stateStorage=J;this.coordinationKey=J.kind==="local"?d3(J.root,Z):`${n3(J,Z)}\x00goal`}static coordinationStatsForTests(){return this.locks.getStats()}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z,J=k$($)){let Y=(await new H0($,Z,J).get())?.status;return Y==="active"||Y==="verifying"}async get(){return H0.locks.runExclusive(this.coordinationKey,()=>this.readUnlocked())}async create($,Z={}){return H0.locks.runExclusive(this.coordinationKey,async()=>{let J=await this.readUnlocked();if(J&&J.status!=="complete")throw Error(`Session already has an unfinished goal (${J.status}); clear or complete it first`);let Y=new Date().toISOString(),Q=PH($.tokenBudget),X=Z.turnId===void 0?void 0:s8(Z.turnId),W={version:2,sessionId:this.sessionId,goalId:EH(12),objective:u3($.objective),status:"active",...Q===void 0?{}:{tokenBudget:Q},tokensUsed:0,timeUsedSeconds:0,continuationCount:0,...X?{turnLineage:{rootTurnId:X,currentTurnId:X}}:{},createdAt:Y,updatedAt:Y};return await this.persistUnlocked(W),this.emit(W),W})}async edit($){return this.updateExisting((Z)=>{if(!["active","verifying","paused","blocked"].includes(Z.status))throw Error(`Cannot edit goal while status is ${Z.status}`);return{...Z,objective:u3($),completionVerification:void 0,verificationStall:void 0,prematureStop:void 0,executionHostFailure:void 0,turnLineage:void 0,frontierStall:void 0,status:Z.status==="verifying"?"active":Z.status,statusReason:Z.status==="verifying"?void 0:Z.statusReason,updatedAt:new Date().toISOString()}})}async recordExecutionFrontier($,Z,J={}){return this.updateExisting((Y)=>{let Q=`goal:${Y.sessionId}:${Y.goalId}`;if($.taskListId!==Q)throw Error(`Execution frontier task list ${$.taskListId} does not match the current goal`);if(Z&&Z.digestSha256!==$.digestSha256)throw Error("Frontier stall digest does not match the execution frontier");let{frontierStall:X,...W}=Y,V=J.preserveStall?X:Z;return{...W,version:2,executionFrontier:$,...V===void 0?{}:{frontierStall:V},updatedAt:new Date().toISOString()}})}async clearFrontierStall(){return H0.locks.runExclusive(this.coordinationKey,async()=>{let $=await this.readUnlocked();if(!$)return null;let{frontierStall:Z,...J}=$,Y=X2(Q2,{...J,version:2,updatedAt:new Date().toISOString()});return await this.persistUnlocked(Y),this.emit(Y),Y})}async pause($="paused by user"){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying"&&Z.status!=="blocked")throw Error(`Cannot pause goal while status is ${Z.status}`);return{...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()}})}async pauseIfActive($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J={...Z,version:2,status:"paused",statusReason:$,updatedAt:new Date().toISOString()};return await this.persistUnlocked(J),this.emit(J),J})}async resume(){return this.updateExisting(($)=>{if($.status!=="paused"&&$.status!=="blocked")throw Error(`Cannot resume goal while status is ${$.status}`);let Z=$.tokenBudget!==void 0&&$.tokensUsed>=$.tokenBudget,J=$.completionVerification?.status==="pending"||$.completionVerification?.status==="pass";return{...$,status:Z?"budget_limited":J?"verifying":"active",statusReason:Z?"token budget exhausted":void 0,verificationStall:void 0,prematureStop:void 0,executionHostFailure:void 0,frontierStall:void 0,updatedAt:new Date().toISOString()}})}async requestCompletion(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot request goal completion while status is ${$.status}`);if($.status==="verifying"&&($.completionVerification?.status==="pending"||$.completionVerification?.status==="pass"))return $;let Z=new Date().toISOString();return{...$,status:"verifying",statusReason:"awaiting independent completion verification",prematureStop:void 0,executionHostFailure:void 0,frontierStall:void 0,completionVerification:{attempt:($.completionVerification?.attempt??0)+1,status:"pending",requestedAt:Z,...$.completionVerification?.summary?{summary:$.completionVerification.summary}:{}},updatedAt:Z}})}async recordCompletionVerification($){let Z=$.verifierSessionId?.trim();if(!Z)throw Error("Goal verification requires a verifier Session identity");if(!/^[a-f0-9]{64}$/.test($.evidenceSha256??""))throw Error("Goal verification requires a SHA-256 evidence digest");if($.feedbackSha256!==void 0&&!/^[a-f0-9]{64}$/.test($.feedbackSha256))throw Error("Goal verification feedback requires a SHA-256 digest");return this.updateExisting((J)=>{if(J.status!=="verifying"||!J.completionVerification)throw Error(`Cannot record goal verification while status is ${J.status}`);let Y=new Date().toISOString(),Q=SH($.summary),X=$.feedbackSha256,W=$.verdict!=="pass"&&X?{feedbackSha256:X,consecutiveCount:J.verificationStall?.feedbackSha256===X?J.verificationStall.consecutiveCount+1:1,detectedAt:Y}:void 0,V=W!==void 0&&W.consecutiveCount>=p3;return{...J,status:V?"blocked":J.status,statusReason:V?`automatic verification convergence guard after ${W.consecutiveCount} identical gap reports`:$.verdict==="pass"?"independent completion verification passed":`independent completion verification returned ${$.verdict}`,verificationStall:W,completionVerification:{...J.completionVerification,status:$.verdict,completedAt:Y,verifierSessionId:Z,...Q?{summary:Q}:{},evidenceSha256:$.evidenceSha256},updatedAt:Y}})}async invalidateCompletionVerification($){return this.updateExisting((Z)=>{if(Z.status!=="verifying"||!Z.completionVerification)return Z;let J=$.trim()||"goal completion evidence became stale";return{...Z,statusReason:J,completionVerification:{attempt:Z.completionVerification.attempt,status:"pending",requestedAt:Z.completionVerification.requestedAt,...Z.completionVerification.summary?{summary:Z.completionVerification.summary}:{}},updatedAt:new Date().toISOString()}})}async finalizeVerifiedCompletion(){return this.updateExisting(($)=>{if($.status!=="verifying"||$.completionVerification?.status!=="pass"||!$.completionVerification.verifierSessionId||!$.completionVerification.evidenceSha256)throw Error("Goal completion requires a persisted independent PASS verdict");return{...$,status:"complete",statusReason:void 0,verificationStall:void 0,prematureStop:void 0,executionHostFailure:void 0,frontierStall:void 0,updatedAt:new Date().toISOString()}})}async reconcileFinalizationReceipt($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.goalId!==$.goalId)return null;let J=Z.completionVerification;if(!(J?.status==="pass"&&J.attempt===$.verificationAttempt&&J.verifierSessionId===$.verifierSessionId&&J.evidenceSha256===$.evidenceSha256))return null;if(Z.status==="complete")return{goal:Z,finalized:!1};if(Z.status!=="verifying"||Z.updatedAt!==$.goalUpdatedAt)return null;let Q=X2(Q2,{...Z,version:2,status:"complete",statusReason:void 0,verificationStall:void 0,executionHostFailure:void 0,updatedAt:new Date().toISOString()});return await this.persistUnlocked(Q),this.emit(Q),{goal:Q,finalized:!0}})}async block($){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying")throw Error(`Cannot block goal while status is ${Z.status}`);let J=$.trim();if(!J)throw Error("Blocked goal requires a reason");return{...Z,status:"blocked",statusReason:J,completionVerification:void 0,verificationStall:void 0,frontierStall:void 0,updatedAt:new Date().toISOString()}})}async recordProgress($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying"&&Z.status!=="paused")return Z;if(Z.status==="paused"&&(!$.goalId||!$.objective||!$.turnId))return Z;if($.goalId!==void 0&&$.goalId!==Z.goalId||$.objective!==void 0&&$.objective!==Z.objective||$.turnId!==void 0&&$.turnId!==Z.turnLineage?.currentTurnId)return Z;let J=Math.max(0,Math.round($.tokens)),Y=Math.max(0,Math.round($.elapsedMs/1000)),Q=Z.tokensUsed+J,X=new Date().toISOString();if(Z.status==="paused"){let D={...Z,version:2,tokensUsed:Q,timeUsedSeconds:Z.timeUsedSeconds+Y,updatedAt:X};return await this.persistUnlocked(D),this.emit(D),D}let W=Z.tokenBudget!==void 0&&Q>=Z.tokenBudget,V=$.prematureStopPattern?Z.prematureStop?.pattern===$.prematureStopPattern?Z.prematureStop.consecutiveCount+1:1:0,H=$.prematureStopPattern?{pattern:$.prematureStopPattern,consecutiveCount:V,detectedAt:X}:void 0,U=$.executionHostFailureCategory?{category:$.executionHostFailureCategory,consecutiveCount:Z.executionHostFailure?.category===$.executionHostFailureCategory?Math.min($4,Z.executionHostFailure.consecutiveCount+1):1,detectedAt:X}:void 0,z=H!==void 0&&H.consecutiveCount>=Z4,G=U!==void 0&&U.consecutiveCount>=$4,B={...Z,version:2,tokensUsed:Q,timeUsedSeconds:Z.timeUsedSeconds+Y,status:W?"budget_limited":G?"blocked":z?"blocked":Z.status,statusReason:W?"token budget exhausted":G?`automatic execution host guard after ${U.consecutiveCount} consecutive ${U.category} failure turns`:z?`automatic liveness guard after ${H.consecutiveCount} consecutive ${H.pattern} turns`:Z.statusReason,...z||G?{completionVerification:void 0}:{},prematureStop:H,executionHostFailure:U,updatedAt:X};return await this.persistUnlocked(B),this.emit(B),B})}async beginContinuation(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot continue goal while status is ${$.status}`);return{...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()}})}async prepareTurnBinding($,Z){return H0.locks.runExclusive(this.coordinationKey,async()=>{let J=await this.readUnlocked();if(!J||J.status!=="active"&&J.status!=="verifying")return null;let Y=s8($),Q=J.turnLineage,X={...Q?.rootTurnId?{rootTurnId:Q.rootTurnId}:{},currentTurnId:Y,...Q?.currentTurnId&&Q.currentTurnId!==Y?{parentTurnId:Q.currentTurnId}:Q?.parentTurnId?{parentTurnId:Q.parentTurnId}:{}};return{goalId:J.goalId,objective:J.objective,expectedUpdatedAt:J.updatedAt,continuation:Z,lineage:X}})}async commitTurnBinding($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying"||Z.goalId!==$.goalId||Z.objective!==$.objective)return null;if(Z.turnLineage?.currentTurnId===$.lineage.currentTurnId)return Z;if(Z.updatedAt!==$.expectedUpdatedAt)return null;let J=X2(Q2,{...Z,version:2,continuationCount:Z.continuationCount+($.continuation?1:0),turnLineage:$.lineage,updatedAt:new Date().toISOString()});return await this.persistUnlocked(J),this.emit(J),J})}async invalidateTurnLineageRoot($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.turnLineage?.currentTurnId!==s8($)||!Z.turnLineage.rootTurnId)return null;let J=X2(Q2,{...Z,turnLineage:{currentTurnId:Z.turnLineage.currentTurnId,...Z.turnLineage.parentTurnId?{parentTurnId:Z.turnLineage.parentTurnId}:{}},updatedAt:new Date().toISOString()});return await this.persistUnlocked(J),this.emit(J),J})}async tryBeginContinuation(){return H0.locks.runExclusive(this.coordinationKey,async()=>{let $=await this.readUnlocked();if(!$||$.status!=="active"&&$.status!=="verifying")return null;let Z={...$,version:2,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()};return await this.persistUnlocked(Z),this.emit(Z),Z})}async clear(){return H0.locks.runExclusive(this.coordinationKey,()=>T1(this.stateStorage,this.sessionId,async($)=>{try{await L$.unlink($.goalPath)}catch(Z){if(g3(Z,"ENOENT"))return!1;throw Z}return this.emit(null),!0}))}async updateExisting($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z)throw Error("Session has no goal");let J=X2(Q2,{...$(Z),version:2});return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){return T1(this.stateStorage,this.sessionId,async($)=>{try{if((await L$.stat($.goalPath)).size>h3)throw Error(`Goal state exceeds ${h3} bytes`);await L$.chmod($.goalPath,384);let J=a6(Q2,JSON.parse(await L$.readFile($.goalPath,"utf8")));if(!J.success||J.data.sessionId!==this.sessionId)throw Error(`Invalid goal state: ${$.goalPath}`);return J.data}catch(Z){if(g3(Z,"ENOENT"))return null;if(Z instanceof SyntaxError)throw Error(`Invalid goal state JSON: ${$.goalPath}`,{cause:Z});throw Z}})}async persistUnlocked($){await T1(this.stateStorage,this.sessionId,async(Z)=>{await L$.mkdir(a3.dirname(Z.goalPath),{recursive:!0,mode:448}),await MH(Z.goalPath,`${JSON.stringify($)}
|
|
131
|
+
`)}function bH($,Z){if($.pending>0&&$.blocked>0&&$.inProgress===0&&$.nextTask===void 0)return"waiting_dependency";if(Z.prematureStopCount>=2||Z.verificationStallCount>=2)return"repeated_deferral";if(Z.prematureStopCount<1&&Z.verificationStallCount<1)return;if($.pending>0||$.inProgress>0)return"same_task_no_effect";return}function jH($){switch($){case"waiting_dependency":return"Inspect the incomplete dependency, then execute an independent task or report the concrete external blocker.";case"repeated_deferral":return"Change strategy: validate assumptions, inspect durable results, and fix or verify the reported gap before another completion attempt.";case"same_task_no_effect":return"Change strategy: stop repeating the same step, inspect current evidence, and choose a different executable task or verification action."}}function t6($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}import*as L$ from"node:fs/promises";import*as a3 from"node:path";import{nanoid as EH}from"nanoid";import MH from"write-file-atomic";var h3=1048576,o8=1e5,AH=K.Object({attempt:K.Integer({minimum:1}),status:u(c3),requestedAt:K.String({format:"date-time"}),completedAt:K.Optional(K.String({format:"date-time"})),verifierSessionId:K.Optional(K.String({minLength:1})),summary:K.Optional(K.String({maxLength:o2})),evidenceSha256:K.Optional(K.String({pattern:"^[a-f0-9]{64}$"}))}),CH=K.Object({taskListId:K.String({minLength:1,maxLength:256}),total:K.Integer({minimum:0}),completed:K.Integer({minimum:0}),inProgress:K.Integer({minimum:0}),pending:K.Integer({minimum:0}),blocked:K.Integer({minimum:0}),nextTask:K.Optional(K.Object({id:K.String({minLength:1}),subject:K.String({minLength:1,maxLength:512}),priority:u(["high","medium","low"])})),digestSha256:K.String({pattern:"^[a-f0-9]{64}$"}),observedAt:K.String({format:"date-time"})}),TH=K.Object({category:u(r3),consecutiveCount:K.Integer({minimum:1,maximum:e6}),digestSha256:K.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:K.String({format:"date-time"})}),RH=K.Object({category:u(i3),consecutiveCount:K.Integer({minimum:1,maximum:$4}),detectedAt:K.String({format:"date-time"})}),fH=K.Object({rootTurnId:K.Optional(K.String({minLength:1,maxLength:W2})),currentTurnId:K.String({minLength:1,maxLength:W2}),parentTurnId:K.Optional(K.String({minLength:1,maxLength:W2}))},{additionalProperties:!1}),Q2=K.Object({version:K.Union([K.Literal(1),K.Literal(2)]),sessionId:K.String({minLength:1}),goalId:K.String({minLength:1}),objective:K.String({minLength:1,maxLength:o8}),status:u(m3),tokenBudget:K.Optional(K.Integer({minimum:1})),tokensUsed:K.Integer({minimum:0}),timeUsedSeconds:K.Integer({minimum:0}),continuationCount:K.Integer({minimum:0}),statusReason:K.Optional(K.String()),completionVerification:K.Optional(AH),verificationStall:K.Optional(K.Object({feedbackSha256:K.String({pattern:"^[a-f0-9]{64}$"}),consecutiveCount:K.Integer({minimum:1}),detectedAt:K.String({format:"date-time"})})),prematureStop:K.Optional(K.Object({pattern:u(l3),consecutiveCount:K.Integer({minimum:1}),detectedAt:K.String({format:"date-time"})})),executionHostFailure:K.Optional(RH),turnLineage:K.Optional(fH),executionFrontier:K.Optional(CH),frontierStall:K.Optional(TH),createdAt:K.String({format:"date-time"}),updatedAt:K.String({format:"date-time"})});function g3($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function u3($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>o8)throw Error(`Goal objective exceeds ${o8} characters`);return Z}function PH($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}function s8($){if($.length<1||$.length>W2)throw Error(`Goal turn ID must contain between 1 and ${W2} characters`);return $}function SH($){let Z=$?.trim();if(!Z)return;return Z.slice(0,o2)}class H0{workspaceRoot;sessionId;stateStorage;static locks=new F$;static listeners=new Set;coordinationKey;constructor($,Z,J=k$($)){this.workspaceRoot=$;this.sessionId=Z;this.stateStorage=J;this.coordinationKey=J.kind==="local"?d3(J.root,Z):`${n3(J,Z)}\x00goal`}static coordinationStatsForTests(){return this.locks.getStats()}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z,J=k$($)){let Y=(await new H0($,Z,J).get())?.status;return Y==="active"||Y==="verifying"}async get(){return H0.locks.runExclusive(this.coordinationKey,()=>this.readUnlocked())}async create($,Z={}){return H0.locks.runExclusive(this.coordinationKey,async()=>{let J=await this.readUnlocked();if(J&&J.status!=="complete")throw Error(`Session already has an unfinished goal (${J.status}); clear or complete it first`);let Y=new Date().toISOString(),Q=PH($.tokenBudget),X=Z.turnId===void 0?void 0:s8(Z.turnId),W={version:2,sessionId:this.sessionId,goalId:EH(12),objective:u3($.objective),status:"active",...Q===void 0?{}:{tokenBudget:Q},tokensUsed:0,timeUsedSeconds:0,continuationCount:0,...X?{turnLineage:{rootTurnId:X,currentTurnId:X}}:{},createdAt:Y,updatedAt:Y};return await this.persistUnlocked(W),this.emit(W),W})}async edit($){return this.updateExisting((Z)=>{if(!["active","verifying","paused","blocked"].includes(Z.status))throw Error(`Cannot edit goal while status is ${Z.status}`);return{...Z,objective:u3($),completionVerification:void 0,verificationStall:void 0,prematureStop:void 0,executionHostFailure:void 0,turnLineage:void 0,frontierStall:void 0,status:Z.status==="verifying"?"active":Z.status,statusReason:Z.status==="verifying"?void 0:Z.statusReason,updatedAt:new Date().toISOString()}})}async recordExecutionFrontier($,Z,J={}){return this.updateExisting((Y)=>{let Q=`goal:${Y.sessionId}:${Y.goalId}`;if($.taskListId!==Q)throw Error(`Execution frontier task list ${$.taskListId} does not match the current goal`);if(Z&&Z.digestSha256!==$.digestSha256)throw Error("Frontier stall digest does not match the execution frontier");let{frontierStall:X,...W}=Y,V=J.preserveStall?X:Z;return{...W,version:2,executionFrontier:$,...V===void 0?{}:{frontierStall:V},updatedAt:new Date().toISOString()}})}async clearFrontierStall(){return H0.locks.runExclusive(this.coordinationKey,async()=>{let $=await this.readUnlocked();if(!$)return null;let{frontierStall:Z,...J}=$,Y=X2(Q2,{...J,version:2,updatedAt:new Date().toISOString()});return await this.persistUnlocked(Y),this.emit(Y),Y})}async pause($="paused by user"){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying"&&Z.status!=="blocked")throw Error(`Cannot pause goal while status is ${Z.status}`);return{...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()}})}async pauseIfActive($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J={...Z,version:2,status:"paused",statusReason:$,updatedAt:new Date().toISOString()};return await this.persistUnlocked(J),this.emit(J),J})}async resume(){return this.updateExisting(($)=>{if($.status!=="paused"&&$.status!=="blocked")throw Error(`Cannot resume goal while status is ${$.status}`);let Z=$.tokenBudget!==void 0&&$.tokensUsed>=$.tokenBudget,J=$.completionVerification?.status==="pending"||$.completionVerification?.status==="pass";return{...$,status:Z?"budget_limited":J?"verifying":"active",statusReason:Z?"token budget exhausted":void 0,verificationStall:void 0,prematureStop:void 0,executionHostFailure:void 0,frontierStall:void 0,updatedAt:new Date().toISOString()}})}async requestCompletion(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot request goal completion while status is ${$.status}`);if($.status==="verifying"&&($.completionVerification?.status==="pending"||$.completionVerification?.status==="pass"))return $;let Z=new Date().toISOString();return{...$,status:"verifying",statusReason:"awaiting independent completion verification",prematureStop:void 0,executionHostFailure:void 0,frontierStall:void 0,completionVerification:{attempt:($.completionVerification?.attempt??0)+1,status:"pending",requestedAt:Z,...$.completionVerification?.summary?{summary:$.completionVerification.summary}:{}},updatedAt:Z}})}async recordCompletionVerification($){let Z=$.verifierSessionId?.trim();if(!Z)throw Error("Goal verification requires a verifier Session identity");if(!/^[a-f0-9]{64}$/.test($.evidenceSha256??""))throw Error("Goal verification requires a SHA-256 evidence digest");if($.feedbackSha256!==void 0&&!/^[a-f0-9]{64}$/.test($.feedbackSha256))throw Error("Goal verification feedback requires a SHA-256 digest");return this.updateExisting((J)=>{if(J.status!=="verifying"||!J.completionVerification)throw Error(`Cannot record goal verification while status is ${J.status}`);let Y=new Date().toISOString(),Q=SH($.summary),X=$.feedbackSha256,W=$.verdict!=="pass"&&X?{feedbackSha256:X,consecutiveCount:J.verificationStall?.feedbackSha256===X?J.verificationStall.consecutiveCount+1:1,detectedAt:Y}:void 0,V=W!==void 0&&W.consecutiveCount>=p3;return{...J,status:V?"blocked":J.status,statusReason:V?`automatic verification convergence guard after ${W.consecutiveCount} identical gap reports`:$.verdict==="pass"?"independent completion verification passed":`independent completion verification returned ${$.verdict}`,verificationStall:W,completionVerification:{...J.completionVerification,status:$.verdict,completedAt:Y,verifierSessionId:Z,...Q?{summary:Q}:{},evidenceSha256:$.evidenceSha256},updatedAt:Y}})}async invalidateCompletionVerification($){return this.updateExisting((Z)=>{if(Z.status!=="verifying"||!Z.completionVerification)return Z;let J=$.trim()||"goal completion evidence became stale";return{...Z,statusReason:J,completionVerification:{attempt:Z.completionVerification.attempt,status:"pending",requestedAt:Z.completionVerification.requestedAt,...Z.completionVerification.summary?{summary:Z.completionVerification.summary}:{}},updatedAt:new Date().toISOString()}})}async finalizeVerifiedCompletion(){return this.updateExisting(($)=>{if($.status!=="verifying"||$.completionVerification?.status!=="pass"||!$.completionVerification.verifierSessionId||!$.completionVerification.evidenceSha256)throw Error("Goal completion requires a persisted independent PASS verdict");return{...$,status:"complete",statusReason:void 0,verificationStall:void 0,prematureStop:void 0,executionHostFailure:void 0,frontierStall:void 0,updatedAt:new Date().toISOString()}})}async reconcileFinalizationReceipt($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.goalId!==$.goalId)return null;let J=Z.completionVerification;if(!(J?.status==="pass"&&J.attempt===$.verificationAttempt&&J.verifierSessionId===$.verifierSessionId&&J.evidenceSha256===$.evidenceSha256))return null;if(Z.status==="complete")return{goal:Z,finalized:!1};if(Z.status!=="verifying"||Z.updatedAt!==$.goalUpdatedAt)return null;let Q=X2(Q2,{...Z,version:2,status:"complete",statusReason:void 0,verificationStall:void 0,executionHostFailure:void 0,updatedAt:new Date().toISOString()});return await this.persistUnlocked(Q),this.emit(Q),{goal:Q,finalized:!0}})}async block($){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying")throw Error(`Cannot block goal while status is ${Z.status}`);let J=$.trim();if(!J)throw Error("Blocked goal requires a reason");return{...Z,status:"blocked",statusReason:J,completionVerification:void 0,verificationStall:void 0,frontierStall:void 0,updatedAt:new Date().toISOString()}})}async recordProgress($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying"&&Z.status!=="paused"&&Z.status!=="blocked")return Z;if((Z.status==="paused"||Z.status==="blocked")&&(!$.goalId||!$.objective||!$.turnId))return Z;if($.goalId!==void 0&&$.goalId!==Z.goalId||$.objective!==void 0&&$.objective!==Z.objective||$.turnId!==void 0&&$.turnId!==Z.turnLineage?.currentTurnId)return Z;let J=Math.max(0,Math.round($.tokens)),Y=Math.max(0,Math.round($.elapsedMs/1000)),Q=Z.tokensUsed+J,X=new Date().toISOString();if(Z.status==="paused"||Z.status==="blocked"){let D={...Z,version:2,tokensUsed:Q,timeUsedSeconds:Z.timeUsedSeconds+Y,updatedAt:X};return await this.persistUnlocked(D),this.emit(D),D}let W=Z.tokenBudget!==void 0&&Q>=Z.tokenBudget,V=$.prematureStopPattern?Z.prematureStop?.pattern===$.prematureStopPattern?Z.prematureStop.consecutiveCount+1:1:0,H=$.prematureStopPattern?{pattern:$.prematureStopPattern,consecutiveCount:V,detectedAt:X}:void 0,U=$.executionHostFailureCategory?{category:$.executionHostFailureCategory,consecutiveCount:Z.executionHostFailure?.category===$.executionHostFailureCategory?Math.min($4,Z.executionHostFailure.consecutiveCount+1):1,detectedAt:X}:void 0,z=H!==void 0&&H.consecutiveCount>=Z4,G=U!==void 0&&U.consecutiveCount>=$4,B={...Z,version:2,tokensUsed:Q,timeUsedSeconds:Z.timeUsedSeconds+Y,status:W?"budget_limited":G?"blocked":z?"blocked":Z.status,statusReason:W?"token budget exhausted":G?`automatic execution host guard after ${U.consecutiveCount} consecutive ${U.category} failure turns`:z?`automatic liveness guard after ${H.consecutiveCount} consecutive ${H.pattern} turns`:Z.statusReason,...z||G?{completionVerification:void 0}:{},prematureStop:H,executionHostFailure:U,updatedAt:X};return await this.persistUnlocked(B),this.emit(B),B})}async beginContinuation(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot continue goal while status is ${$.status}`);return{...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()}})}async prepareTurnBinding($,Z){return H0.locks.runExclusive(this.coordinationKey,async()=>{let J=await this.readUnlocked();if(!J||J.status!=="active"&&J.status!=="verifying")return null;let Y=s8($),Q=J.turnLineage,X={...Q?.rootTurnId?{rootTurnId:Q.rootTurnId}:{},currentTurnId:Y,...Q?.currentTurnId&&Q.currentTurnId!==Y?{parentTurnId:Q.currentTurnId}:Q?.parentTurnId?{parentTurnId:Q.parentTurnId}:{}};return{goalId:J.goalId,objective:J.objective,expectedUpdatedAt:J.updatedAt,continuation:Z,lineage:X}})}async commitTurnBinding($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying"||Z.goalId!==$.goalId||Z.objective!==$.objective)return null;if(Z.turnLineage?.currentTurnId===$.lineage.currentTurnId)return Z;if(Z.updatedAt!==$.expectedUpdatedAt)return null;let J=X2(Q2,{...Z,version:2,continuationCount:Z.continuationCount+($.continuation?1:0),turnLineage:$.lineage,updatedAt:new Date().toISOString()});return await this.persistUnlocked(J),this.emit(J),J})}async invalidateTurnLineageRoot($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z||Z.turnLineage?.currentTurnId!==s8($)||!Z.turnLineage.rootTurnId)return null;let J=X2(Q2,{...Z,turnLineage:{currentTurnId:Z.turnLineage.currentTurnId,...Z.turnLineage.parentTurnId?{parentTurnId:Z.turnLineage.parentTurnId}:{}},updatedAt:new Date().toISOString()});return await this.persistUnlocked(J),this.emit(J),J})}async tryBeginContinuation(){return H0.locks.runExclusive(this.coordinationKey,async()=>{let $=await this.readUnlocked();if(!$||$.status!=="active"&&$.status!=="verifying")return null;let Z={...$,version:2,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()};return await this.persistUnlocked(Z),this.emit(Z),Z})}async clear(){return H0.locks.runExclusive(this.coordinationKey,()=>T1(this.stateStorage,this.sessionId,async($)=>{try{await L$.unlink($.goalPath)}catch(Z){if(g3(Z,"ENOENT"))return!1;throw Z}return this.emit(null),!0}))}async updateExisting($){return H0.locks.runExclusive(this.coordinationKey,async()=>{let Z=await this.readUnlocked();if(!Z)throw Error("Session has no goal");let J=X2(Q2,{...$(Z),version:2});return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){return T1(this.stateStorage,this.sessionId,async($)=>{try{if((await L$.stat($.goalPath)).size>h3)throw Error(`Goal state exceeds ${h3} bytes`);await L$.chmod($.goalPath,384);let J=a6(Q2,JSON.parse(await L$.readFile($.goalPath,"utf8")));if(!J.success||J.data.sessionId!==this.sessionId)throw Error(`Invalid goal state: ${$.goalPath}`);return J.data}catch(Z){if(g3(Z,"ENOENT"))return null;if(Z instanceof SyntaxError)throw Error(`Invalid goal state JSON: ${$.goalPath}`,{cause:Z});throw Z}})}async persistUnlocked($){await T1(this.stateStorage,this.sessionId,async(Z)=>{await L$.mkdir(a3.dirname(Z.goalPath),{recursive:!0,mode:448}),await MH(Z.goalPath,`${JSON.stringify($)}
|
|
132
132
|
`,{encoding:"utf8",mode:384,fsync:!0})})}emit($){let Z={workspaceRoot:this.workspaceRoot,sessionId:this.sessionId,goal:$?{...$}:null};for(let J of H0.listeners)try{J(Z)}catch{}}}import{createHash as kH}from"node:crypto";import{promises as J4,realpathSync as vH}from"node:fs";import X0 from"node:path";import{fileURLToPath as yH,pathToFileURL as v$}from"node:url";var s3=e("Service"),o3=65536;class t8{name;onCrash;child;processTree;connection;closePromise;crashCleanup;capabilities;initialized=!1;stopping=!1;notificationHandlers=new Map;requestHandlers=new Map;constructor($,Z){this.name=$;this.onCrash=Z}get serverCapabilities(){return this.capabilities}get isInitialized(){return this.initialized}async start($){if(await this.crashCleanup,this.crashCleanup=void 0,this.connection)return;let Z=await import("vscode-jsonrpc/node.js"),{child:J,processTree:Y}=r1($.command,[...$.args],{cwd:$.cwd,env:{...$.environment,PATH:$.environment.PATH??process.env.PATH??"",HOME:$.environment.HOME??process.env.HOME??"",USER:$.environment.USER??process.env.USER??"",SHELL:$.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},{releaseOnExit:!1});this.child=J,this.processTree=Y;try{if(await new Promise((W,V)=>{let H=()=>{J.removeListener("spawn",U),J.removeListener("error",z)},U=()=>{H(),W()},z=(G)=>{H(),V(G)};J.once("spawn",U),J.once("error",z)}),!J.stdout||!J.stdin)throw Error("LSP server stdio is unavailable");let Q="";J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{if(Q.length<o3)Q+=W.slice(0,o3-Q.length)}),J.stdin.on("error",(W)=>{if(!this.stopping)s3.debug(`[LSP ${this.name}] stdin closed: ${W.message}`)}),this.closePromise=new Promise((W)=>{J.once("close",(V,H)=>{if(this.child!==J){W();return}this.initialized=!1;let U=!this.stopping;if(U){let G=Q.trim()?`: ${Q.trim().slice(0,512)}`:H?` (${H})`:"";this.onCrash(Error(`LSP server "${this.name}" exited with code ${V}${G}`))}let z=this.processTree;try{this.connection?.dispose()}catch{}if(this.connection=void 0,this.child=void 0,this.closePromise=void 0,U&&z)this.crashCleanup=z.terminate().then(()=>{return}),this.processTree=void 0;W()})});let X=Z.createMessageConnection(new Z.StreamMessageReader(J.stdout),new Z.StreamMessageWriter(J.stdin));this.connection=X,X.onError(([W])=>{if(!this.stopping)s3.warn(`[LSP ${this.name}] connection error: ${W.message}`)}),X.onClose(()=>{if(this.connection===X)this.initialized=!1});for(let[W,V]of this.notificationHandlers)for(let H of V)X.onNotification(W,H);for(let[W,V]of this.requestHandlers)X.onRequest(W,V);X.listen()}catch(Q){throw await this.disposeTransport(),Q}}async initialize($,Z,J){let Y=await this.request("initialize",$,Z,J,!1);return this.capabilities=Y.capabilities,await this.notify("initialized",{}),this.initialized=!0,Y}async request($,Z,J,Y,Q=!0){let X=this.connection;if(!X)throw Error(`LSP server "${this.name}" is not started`);if(Q&&!this.initialized)throw Error(`LSP server "${this.name}" is not initialized`);let V=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;return this.awaitRequest(X.sendRequest($,Z,V.token),V,J,Y,$)}async notify($,Z){if(!this.connection)throw Error(`LSP server "${this.name}" is not started`);await this.connection.sendNotification($,Z)}onNotification($,Z){let J=this.notificationHandlers.get($)??[];J.push(Z),this.notificationHandlers.set($,J),this.connection?.onNotification($,Z)}onRequest($,Z){this.requestHandlers.set($,Z),this.connection?.onRequest($,Z)}async stop($){if(!this.child&&!this.connection){await this.crashCleanup,this.crashCleanup=void 0;return}this.stopping=!0;let Z=this.connection;try{if(Z&&this.initialized){let Y=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;await this.awaitRequest(Z.sendRequest("shutdown",Y.token),Y,$,void 0,"shutdown").catch(()=>{return}),await Z.sendNotification("exit").catch(()=>{return})}await Promise.race([this.closePromise??Promise.resolve(),new Promise((J)=>setTimeout(J,Math.min($,500)))])}finally{await this.disposeTransport(),this.stopping=!1,this.initialized=!1,this.capabilities=void 0}}awaitRequest($,Z,J,Y,Q){return new Promise((X,W)=>{let V=!1,H=(G)=>{if(V)return;V=!0,clearTimeout(z),Y?.removeEventListener("abort",U),G()},U=()=>{Z.cancel(),H(()=>W(Error(`LSP request "${Q}" was aborted`)))},z=setTimeout(()=>{Z.cancel(),H(()=>W(Error(`LSP request "${Q}" timed out after ${J}ms`)))},J);if(Y?.addEventListener("abort",U,{once:!0}),Y?.aborted)U();$.then((G)=>H(()=>X(G)),(G)=>H(()=>W(G)))})}async disposeTransport(){let $=this.connection,Z=this.processTree;this.connection=void 0,this.processTree=void 0,this.child=void 0,this.closePromise=void 0;try{$?.dispose()}catch{}await Z?.terminate(),await this.crashCleanup,this.crashCleanup=void 0}}var xH=e("Service"),IH=10485760,hH=10,t3=30,gH=-32801;class e8{options;workspaceRoot;servers=new Map;diagnostics=new Map;delivered=new Map;waiters=new Map;disposeController=new AbortController;diagnosticSequence=0;disposed=!1;constructor($){this.options=$;let Z=X0.resolve($.workspaceRoot);try{this.workspaceRoot=vH.native(Z)}catch{this.workspaceRoot=Z}for(let[J,Y]of Object.entries($.servers)){if(Y.enabled===!1)continue;let Q={name:J,config:structuredClone(Y),state:"stopped",restartCount:0,openedFiles:new Map,client:new t8(J,(X)=>{Q.state="error",Q.lastError=X.message,Q.openedFiles.clear()})};Q.client.onNotification("textDocument/publishDiagnostics",(X)=>{this.captureDiagnostics(J,X)}),Q.client.onRequest("workspace/configuration",(X)=>this.resolveWorkspaceConfiguration(Y.settings,X)),Q.client.onRequest("workspace/workspaceFolders",()=>[{uri:v$(this.workspaceRoot).href,name:X0.basename(this.workspaceRoot)}]),Q.client.onRequest("window/workDoneProgress/create",()=>null),this.servers.set(J,Q)}}get available(){return this.servers.size>0&&!this.isRemoteSession()&&!this.disposed}get workspacePath(){return this.workspaceRoot}getStatus(){return[...this.servers.values()].map(($)=>({name:$.name,state:$.state,restartCount:$.restartCount,extensions:Object.keys($.config.extensionToLanguage).sort(),...$.lastError?{lastError:$.lastError}:{}})).sort(($,Z)=>$.name.localeCompare(Z.name))}async afterToolUse($,Z,J,Y){if(!this.available||this.disposed)return;let Q;if(J.success&&($==="Write"||$==="Edit")&&typeof Z.file_path==="string")Q=await this.syncAfterWrite(Z.file_path,Y.signal);else if(J.success&&$==="ApplyPatch"){let X=Array.isArray(J.metadata?.changes)?J.metadata.changes:[];for(let W of X){if(!W||typeof W!=="object"||!("path"in W)||typeof W.path!=="string")continue;if("newContent"in W&&W.newContent===null)await this.syncAfterDelete(W.path);else Q=await this.syncAfterWrite(W.path,Y.signal)??Q}}this.attachPendingDiagnostics(J,Q)}async query($,Z){if(!this.available)throw Error(this.isRemoteSession()?"LSP is unavailable for ACP-owned remote files":"No LSP servers are configured for this Session");let J=await this.resolveFile($.filePath);if($.operation==="diagnostics")return{operation:$.operation,filePath:J,result:this.getCurrentDiagnostics(J)};let Y=await this.ensureFileOpen(J,void 0,Z);if(!Y)throw Error(`No LSP server handles ${X0.extname(J)||"this file"}`);let Q={line:Math.max(0,($.line??1)-1),character:Math.max(0,($.character??1)-1)},X={uri:v$(J).href},W={goToDefinition:{method:"textDocument/definition",params:{textDocument:X,position:Q}},findReferences:{method:"textDocument/references",params:{textDocument:X,position:Q,context:{includeDeclaration:!0}}},hover:{method:"textDocument/hover",params:{textDocument:X,position:Q}},documentSymbol:{method:"textDocument/documentSymbol",params:{textDocument:X}},workspaceSymbol:{method:"workspace/symbol",params:{query:$.query??""}},goToImplementation:{method:"textDocument/implementation",params:{textDocument:X,position:Q}},prepareCallHierarchy:{method:"textDocument/prepareCallHierarchy",params:{textDocument:X,position:Q}}},V;if($.operation==="incomingCalls"||$.operation==="outgoingCalls"){let U=(await this.requestWithRetry(Y,"textDocument/prepareCallHierarchy",{textDocument:X,position:Q},Z))?.[0];V=U?await this.requestWithRetry(Y,$.operation==="incomingCalls"?"callHierarchy/incomingCalls":"callHierarchy/outgoingCalls",{item:U},Z):[]}else{let H=W[$.operation];V=await this.requestWithRetry(Y,H.method,H.params,Z)}return{operation:$.operation,filePath:J,serverName:Y.name,result:V}}async dispose(){if(this.disposed)return;this.disposed=!0,this.disposeController.abort();for(let $ of this.waiters.values())for(let Z of $)clearTimeout(Z.timer),Z.resolve();this.waiters.clear(),await Promise.allSettled([...this.servers.values()].map(async($)=>{$.state="stopping",await $.client.stop($.config.shutdownTimeout??2000),$.state="stopped",$.openedFiles.clear()})),this.diagnostics.clear(),this.delivered.clear()}isRemoteSession(){return this.options.isRemoteSession?.()??U0(this.options.sessionId)}selectServer($){let Z=X0.extname($).toLowerCase();return[...this.servers.values()].filter((J)=>(Z in J.config.extensionToLanguage)).sort((J,Y)=>(Y.config.priority??0)-(J.config.priority??0)||J.name.localeCompare(Y.name))[0]}async ensureFileOpen($,Z,J){let Y=this.selectServer($);if(!Y)return;await this.ensureStarted(Y,J);let Q=v$($).href;if(Y.openedFiles.has(Q))return Y;let X=Z??await this.readBoundedFile($);return await Y.client.notify("textDocument/didOpen",{textDocument:{uri:Q,languageId:Y.config.extensionToLanguage[X0.extname($).toLowerCase()],version:1,text:X}}),Y.openedFiles.set(Q,1),Y}async syncAfterWrite($,Z){try{let J=await this.resolveFile($),Y=await this.readBoundedFile(J),Q=await this.ensureFileOpen(J,Y,Z);if(!Q)return;let X=v$(J).href,W=this.diagnostics.get(X)?.sequence??0;this.delivered.delete(X);let V=Q.openedFiles.get(X)??0;if(V>0){let H=V+1;await Q.client.notify("textDocument/didChange",{textDocument:{uri:X,version:H},contentChanges:[{text:Y}]}),Q.openedFiles.set(X,H)}return await Q.client.notify("textDocument/didSave",{textDocument:{uri:X},text:Y}),await this.waitForDiagnostics(X,W,Q.config.diagnosticWaitTimeout??750,Z),J}catch(J){if(!Z?.aborted&&!this.disposeController.signal.aborted)xH.debug(`[LSP] post-edit sync skipped: ${J instanceof Error?J.message:String(J)}`);return}}async syncAfterDelete($){let Z=await this.resolveMissingFile($).catch(()=>{return});if(!Z)return;if(!this.isInsideWorkspace(Z))return;let J=v$(Z).href;for(let Y of this.servers.values()){if(!Y.openedFiles.has(J))continue;await Y.client.notify("textDocument/didClose",{textDocument:{uri:J}}).catch(()=>{return}),Y.openedFiles.delete(J)}this.diagnostics.delete(J),this.delivered.delete(J)}async ensureStarted($,Z){if($.state==="running")return;if($.startPromise)return $.startPromise;if($.state==="error"){if($.restartCount>=($.config.maxRestarts??3))throw Error(`LSP server "${$.name}" exceeded its restart limit`);$.restartCount++}let J=this.startServer($,Z).finally(()=>{$.startPromise=void 0});return $.startPromise=J,J}async startServer($,Z){$.state="starting";try{await $.client.start({command:$.config.command,args:$.config.args??[],cwd:this.workspaceRoot,environment:{...this.options.environment,...$.config.env,BLADE_SESSION_ID:this.options.sessionId}});let J=v$(this.workspaceRoot).href,Y={processId:process.pid,rootPath:this.workspaceRoot,rootUri:J,workspaceFolders:[{uri:J,name:X0.basename(this.workspaceRoot)}],initializationOptions:$.config.initializationOptions??{},capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{dynamicRegistration:!1,willSave:!1,willSaveWaitUntil:!1,didSave:!0},publishDiagnostics:{relatedInformation:!0,versionSupport:!1},hover:{dynamicRegistration:!1,contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!1,linkSupport:!0},references:{dynamicRegistration:!1},implementation:{dynamicRegistration:!1,linkSupport:!0},documentSymbol:{dynamicRegistration:!1,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!1}},general:{positionEncodings:["utf-16"]}}};if(await $.client.initialize(Y,$.config.startupTimeout??1e4,Z),$.config.settings!==void 0)await $.client.notify("workspace/didChangeConfiguration",{settings:$.config.settings});$.state="running",$.lastError=void 0}catch(J){throw $.state="error",$.lastError=J instanceof Error?J.message:String(J),await $.client.stop($.config.shutdownTimeout??2000).catch(()=>{return}),J}}async requestWithRetry($,Z,J,Y){let Q;for(let X=0;X<4;X++)try{return await $.client.request(Z,J,$.config.requestTimeout??1e4,Y)}catch(W){if(Q=W,W.code!==gH||X===3)break;await new Promise((V)=>setTimeout(V,100*2**X))}throw Q}captureDiagnostics($,Z){if(this.disposed||!Z||typeof Z!=="object"||!("uri"in Z)||!("diagnostics"in Z))return;let J=Z;if(!Array.isArray(J.diagnostics))return;let Y;try{Y=J.uri.startsWith("file:")?yH(J.uri):X0.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(Y))return;let Q=v$(X0.resolve(Y)).href,X={sequence:++this.diagnosticSequence,serverName:$,filePath:X0.resolve(Y),diagnostics:J.diagnostics.filter((H)=>H&&typeof H.message==="string"&&H.range!==void 0).slice(0,100).map((H)=>structuredClone(H))};this.diagnostics.set(Q,X);let W=this.waiters.get(Q)??[],V=[];for(let H of W)if(X.sequence>H.afterSequence)clearTimeout(H.timer),H.resolve();else V.push(H);if(V.length>0)this.waiters.set(Q,V);else this.waiters.delete(Q)}waitForDiagnostics($,Z,J,Y){if(J===0||(this.diagnostics.get($)?.sequence??0)>Z)return Promise.resolve();return new Promise((Q)=>{let X=!1,W,V=()=>{if(X)return;X=!0,clearTimeout(W.timer),Y?.removeEventListener("abort",V);let z=(this.waiters.get($)??[]).filter((G)=>G!==W);if(z.length>0)this.waiters.set($,z);else this.waiters.delete($);Q()},H=setTimeout(V,J);W={afterSequence:Z,resolve:V,timer:H};let U=this.waiters.get($)??[];if(U.push(W),this.waiters.set($,U),Y?.addEventListener("abort",V,{once:!0}),Y?.aborted)V()})}attachPendingDiagnostics($,Z){let J=[...this.diagnostics.values()].sort((V,H)=>{if(Z){if(V.filePath===Z&&H.filePath!==Z)return-1;if(H.filePath===Z&&V.filePath!==Z)return 1}return H.sequence-V.sequence}),Y=[],Q=[],X=0;for(let V of J){let H=v$(V.filePath).href,U=this.delivered.get(H)??new Set,z=V.diagnostics.sort((B,D)=>(B.severity??4)-(D.severity??4)).filter((B)=>!U.has(this.diagnosticKey(B))).slice(0,Math.min(hH,t3-X));if(z.length===0)continue;let G=X0.relative(this.workspaceRoot,V.filePath);Y.push(`${G}:`);for(let B of z){let D=B.range.start.line+1,q=B.range.start.character+1,w=["Error","Warning","Info","Hint"][(B.severity??1)-1],F=B.message.replace(/\s+/g," ").slice(0,500);Y.push(` ${w??"Error"} ${D}:${q} ${F}`+(B.code!==void 0?` [${String(B.code)}]`:"")),U.add(this.diagnosticKey(B)),Q.push({file:G,line:D,character:q,severity:w??"Error",message:F,server:V.serverName}),X++}if(this.delivered.set(H,U),X>=t3)break}if(Y.length===0)return;let W=typeof $.llmContent==="string"?$.llmContent:JSON.stringify($.llmContent);$.llmContent=`${W}
|
|
133
133
|
|
|
134
134
|
<new-diagnostics>
|
|
@@ -861,7 +861,7 @@ ${p$}
|
|
|
861
861
|
</approved-plan>
|
|
862
862
|
|
|
863
863
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S2=O+T9;else S2=[...O,{type:"text",text:T9}]}S=yield*this.runLoop(S2,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return S;let o=v??await this.sessionRuntime.getGoal(),m=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,turnId:I.id,...o?{goalId:o.goalId,objective:o.objective}:{},executionHostFailureCategory:S.metadata?.executionHostFailureCategory,prematureStopPattern:S.success?zY(S.finalMessage):void 0});if(m)yield{kind:"goal_updated",goal:m};if(!S.success||b.signal?.aborted){if(m=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":S.error?.message??"goal paused after turn failure"),m)yield{kind:"goal_updated",goal:m}}if(S.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let c0=S.success&&!b.signal?.aborted&&h<20,z0=UG(S)||!S.success&&S.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(I,{continuePending:c0,...z0?{acknowledgeInput:!0}:{},outcome:S.success&&!b.signal?.aborted?{status:"completed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}}),R){h++,N=!0,M=!1,j=null,O="",l=void 0,A="",k=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!S.success||b.signal?.aborted)return S;if(m=await this.sessionRuntime.getGoal(),!m||m.status!=="active"&&m.status!=="verifying")return S;let F0=await this.sessionRuntime.prepareGoalContinuation(m);if(!F0.ok){if(F0.goal)yield{kind:"goal_updated",goal:F0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:F0.error.message},metadata:{turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,duration:S.metadata?.duration??0}}}let P$=await this.sessionRuntime.beginGoalTurn(F0.goal);if(!P$)return S;j=P$.goal,w={...F0,goal:P$.goal},R=P$.handle,N=!1,M=!0,O=S5(j),l=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:F0.frontier,tasks:F0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let F=typeof z==="string"?z:z.filter((O)=>O.type==="text").map((O)=>O.text).join(`
|
|
864
|
-
`),L={id:this.generateTaskId(),type:"simple",prompt:F};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-zes3sj35.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=e2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:e2(W.text)}:V)}else Q=[{type:"text",text:e2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return aY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},H=[{kind:"tool_result",toolCall:Y,result:V}],U=nY(Y,V);if(U)H.push(U);return H})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,a.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);a.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=t0.createIsolated({artifactWriter:new t2(`legacy-${HG()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),a.debug(`MCP server "${X}" connected`)}catch(V){a.warn(`Warning: MCP server "${X}" connection failed:`,V)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Q6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await m0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
864
|
+
`),L={id:this.generateTaskId(),type:"simple",prompt:F};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-96bqvw32.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=e2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:e2(W.text)}:V)}else Q=[{type:"text",text:e2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return aY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},H=[{kind:"tool_result",toolCall:Y,result:V}],U=nY(Y,V);if(U)H.push(U);return H})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,a.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);a.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=t0.createIsolated({artifactWriter:new t2(`legacy-${HG()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),a.debug(`MCP server "${X}" connected`)}catch(V){a.warn(`Warning: MCP server "${X}" connection failed:`,V)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Q6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await m0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
865
865
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;a.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return a.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
|
|
866
866
|
|
|
867
867
|
<system-reminder>
|
|
@@ -1677,7 +1677,7 @@ ${J}
|
|
|
1677
1677
|
`)),{success:!0,message:"Schedules listed",content:H.join(`
|
|
1678
1678
|
`)}}case"create":{let V=ew(X);if("error"in V)return Y.sendMessage(`创建失败:${V.error}`),{success:!1,error:V.error};let H={prompt:V.prompt,projectPath:W,trigger:V.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let U=await $.create(H),z=U.nextRunAt?new Date(U.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${U.id}\`
|
|
1679
1679
|
${M9(U.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${U.id} created`}}catch(U){let z=U instanceof Error?U.message:String(U);return Y.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let H=await $.remove(V);return Y.sendMessage(H?`[OK] 已删除 \`${V}\``:`未找到 \`${V}\``),{success:H,message:H?"Removed":"Not found"}}case"enable":case"disable":{let V=X[0];if(!V)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let H=await $.setEnabled(V,Q==="enable");return Y.sendMessage(H?`[OK] 已${Q==="enable"?"启用":"停用"} \`${V}\``:`未找到 \`${V}\``),{success:Boolean(H),message:H?"Updated":"Not found"}}case"run":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await $_(V),Y.sendMessage(`[OK] 已触发 \`${V}\``),{success:!0,message:"Schedule triggered"}}catch(H){let U=H instanceof Error?H.message:String(H);return Y.sendMessage(`运行失败:${U}`),{success:!1,error:U}}}default:return Y.sendMessage(`未知子命令: ${Q}
|
|
1680
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var $V=Z_();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function XV($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,W=X??P6(Q??C());if(!X){let B=await J_($,Q??C(),J,Y);if(B)return B}let V;try{V=(await f2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(W,D))}catch{return[]}let U=(await Promise.all(V.map(async(B)=>{try{let D=await f2.stat(B);return{path:B,mtime:D.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,D)=>D.mtime-B.mtime).map((B)=>B.path),z=[],G=Y?$:$.toLowerCase();for(let B of U){if(z.length>=J)break;let D=P2.basename(B,".jsonl"),q=await Y_(B,G,Y,D);if(z.push(...q),z.length>=J){z.length=J;break}}return z}async function J_($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-2xpjy0ef.js"),X=await YV();if(!X)return null;let{SessionService:W}=await import("./chunk-
|
|
1680
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var $V=Z_();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function XV($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,W=X??P6(Q??C());if(!X){let B=await J_($,Q??C(),J,Y);if(B)return B}let V;try{V=(await f2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(W,D))}catch{return[]}let U=(await Promise.all(V.map(async(B)=>{try{let D=await f2.stat(B);return{path:B,mtime:D.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,D)=>D.mtime-B.mtime).map((B)=>B.path),z=[],G=Y?$:$.toLowerCase();for(let B of U){if(z.length>=J)break;let D=P2.basename(B,".jsonl"),q=await Y_(B,G,Y,D);if(z.push(...q),z.length>=J){z.length=J;break}}return z}async function J_($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-2xpjy0ef.js"),X=await YV();if(!X)return null;let{SessionService:W}=await import("./chunk-mp35ntd5.js");await Q(X,W.projectionDeriverForSearch());let V=P2.resolve(Z),H=QV(X,$,V,J*4),U=Y?$:$.toLowerCase(),z=[];for(let G of H){if(G.role!=="user"&&G.role!=="assistant")continue;let B=A9(G.text,U,Y,G.session_id,G.role,G.timestamp??void 0,0);if(B)z.push(B);if(z.length>=J)break}return z}catch{return null}}async function Y_($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),W=Q.split(`
|
|
1681
1681
|
`).flatMap((G,B)=>{if(!G.trim())return[];try{return[{event:JSON.parse(G),index:B}]}catch{return[]}});if(!W.some(({event:G})=>G.type==="session_created"))return Q_(W,Z,J,Y);let H=new Map(W.flatMap(({event:G,index:B})=>typeof G.id==="string"?[[G.id,B+1]]:[])),U=ZV(JV(Q,$)),z=new Map;for(let G of U){if(G.type==="message_created"&&(G.data.role==="user"||G.data.role==="assistant"))z.set(G.data.messageId,{role:G.data.role,content:[],timestamp:G.timestamp,lineNumber:H.get(G.id)??0});if(G.type==="part_created"&&G.data.partType==="text"){let B=z.get(G.data.messageId),D=G.data.payload.text;if(B&&typeof D==="string")B.content.push(D)}}return[...z.values()].flatMap((G)=>{let B=A9(G.content.join(" "),Z,J,Y,G.role,G.timestamp,G.lineNumber);return B?[B]:[]})}catch{return[]}}function Q_($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let W=Q.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let V=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((U)=>typeof U==="object"&&U!==null&&U.type==="text"&&typeof U.text==="string").map((U)=>U.text).join(" "):"",H=A9(V,Z,J,Y,W.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return H?[H]:[]})}function A9($,Z,J,Y,Q,X,W){if(!$)return;let V=J?$:$.toLowerCase();if(!V.includes(Z))return;let H=V.indexOf(Z),U=Math.max(0,H-80),z=Math.min($.length,H+Z.length+80);return{sessionId:Y,role:Q,content:(U>0?"...":"")+$.slice(U,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:X,lineNumber:W}}function WV($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1682
1682
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1683
1683
|
`)}var X_={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=p(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await XV(Y,{maxResults:15,projectPath:Z.cwd}),X=WV(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},VV=X_;var W_={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await R$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},HV=W_;import V_ from"node:path";function O8($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function UV($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function zV($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function H_($,Z){let J=p(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),W=Z.sessionId??"",V=Z.sessionId?{sessionId:Z.sessionId,projectPath:V_.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],q=$.slice(2).join(" ").trim();if(!D||!q)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let w=await Z.subagents.resume(D,q),F=`Resumed \`${D}\` as \`${w.session.id}\` (depth ${w.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:D,subagent:w.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(V??W,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let H=[`**后台任务列表**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{tc as Xt,uc as En,vc as yn,wc as bn}from"./chunk-fdr4fcrf.js";import{Ah as Bt}from"./chunk-
|
|
1
|
+
import{tc as Xt,uc as En,vc as yn,wc as bn}from"./chunk-fdr4fcrf.js";import{Ah as Bt}from"./chunk-t4a0aasw.js";import{Fh as xt,Gh as vi,Hh as sn,Ih as zt,Jh as U,Kh as en,Lh as gt,Mh as mt,Oh as rn,Ph as Tn,Qh as B,Rh as dn,Sh as on,Th as pn,Uh as lt,Vh as un,Wh as cn,Xh as Mn,Zh as S,ai as wn,bi as Gt,ci as Ut,di as h,ei as Ht}from"./chunk-yrf9b3av.js";import{cj as It}from"./chunk-qdbbke8f.js";import{Gj as X,Ij as x}from"./chunk-rmfzym94.js";import{Yj as tn,Zj as nn}from"./chunk-0janz3wt.js";import{Nk as ns}from"./chunk-cjfb4kjp.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Vi as K}from"./chunk-qpmvp4q2.js";import{Wi as wt,Xi as ft}from"./chunk-tm3789m3.js";import{cj as I}from"./chunk-qdbbke8f.js";import{Aj as yt,dj as tt,ej as Dt,fj as Bt,jj as Gt,kj as et,lj as Kt,mj as Ht,nj as Yt,oj as cn,pj as Ft,qj as qt,rj as Mt,sj as Vt,tj as Jt,uj as _t,vj as Qt,wj as jt,xj as Wt,yj as Zt,zj as kt}from"./chunk-wezr6wfq.js";import{Ej as Un,Gj as bn,Hj as _n,Ij as T}from"./chunk-rmfzym94.js";import{Nj as zt,Qj as v}from"./chunk-j89qk7bp.js";import{Yj as xn,Zj as Cn}from"./chunk-
|
|
1
|
+
import{Vi as K}from"./chunk-qpmvp4q2.js";import{Wi as wt,Xi as ft}from"./chunk-tm3789m3.js";import{cj as I}from"./chunk-qdbbke8f.js";import{Aj as yt,dj as tt,ej as Dt,fj as Bt,jj as Gt,kj as et,lj as Kt,mj as Ht,nj as Yt,oj as cn,pj as Ft,qj as qt,rj as Mt,sj as Vt,tj as Jt,uj as _t,vj as Qt,wj as jt,xj as Wt,yj as Zt,zj as kt}from"./chunk-wezr6wfq.js";import{Ej as Un,Gj as bn,Hj as _n,Ij as T}from"./chunk-rmfzym94.js";import{Nj as zt,Qj as v}from"./chunk-j89qk7bp.js";import{Yj as xn,Zj as Cn}from"./chunk-0janz3wt.js";import{dk as a}from"./chunk-ggdgk3gy.js";import{gk as Ln}from"./chunk-n52n2w5v.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
package/package.json
CHANGED
package/dist/chunk-k7eyr7r2.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-23dyv46g.js";import"./chunk-p8a4rfmk.js";import"./chunk-cjfb4kjp.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
package/dist/chunk-sv5ew53q.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sf as a,tf as b}from"./chunk-gqq82tct.js";import"./chunk-p8a4rfmk.js";import"./chunk-cjfb4kjp.js";export{a as globalOptions,b as cliConfig};
|