blade-code 0.10.114 → 0.10.116
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-5kygekjq.js → chunk-1hetgc98.js} +1 -1
- package/dist/{chunk-9yn39keb.js → chunk-1kxev3k5.js} +1 -1
- package/dist/{chunk-2br3zb3a.js → chunk-4qvm1786.js} +1 -1
- package/dist/{chunk-tdent43z.js → chunk-59y1c7c8.js} +1 -1
- package/dist/{chunk-f9b06ew7.js → chunk-61bb9kjb.js} +1 -1
- package/dist/{chunk-h0y3rk52.js → chunk-6321bw8w.js} +1 -1
- package/dist/{chunk-prfmqc67.js → chunk-667f1ksp.js} +1 -1
- package/dist/{chunk-9yfpthv2.js → chunk-6sp20f1b.js} +1 -1
- package/dist/{chunk-hk0s60z9.js → chunk-92q9s5w9.js} +1 -1
- package/dist/{chunk-nvty724y.js → chunk-93p6bxep.js} +1 -1
- package/dist/{chunk-c8sxf0w3.js → chunk-9cs45ath.js} +1 -1
- package/dist/{chunk-mvnzc93b.js → chunk-canb6jrj.js} +1 -1
- package/dist/chunk-ccw2786n.js +169 -0
- package/dist/{chunk-172c4qja.js → chunk-dq95vmj7.js} +1 -1
- package/dist/{chunk-svtjekx5.js → chunk-e9xtmkj4.js} +1 -1
- package/dist/{chunk-tnp6c929.js → chunk-fr2aaarj.js} +2 -2
- package/dist/{chunk-x74fkd67.js → chunk-jdzb8w1p.js} +1 -1
- package/dist/{chunk-0ev1dbx3.js → chunk-k60qgbsv.js} +1 -1
- package/dist/{chunk-a55yrrqz.js → chunk-m14jar1a.js} +1 -1
- package/dist/{chunk-my4twryw.js → chunk-n1vttsx4.js} +1 -1
- package/dist/{chunk-xm8fk5xn.js → chunk-n6sh5rz0.js} +1 -1
- package/dist/{chunk-eh0pdgvv.js → chunk-qd491f51.js} +5 -5
- package/dist/{chunk-0zhzqzg5.js → chunk-rj6aqdz9.js} +1 -1
- package/dist/{chunk-skvw1qja.js → chunk-rzg9yeg3.js} +1 -1
- package/dist/{chunk-24y7ekjs.js → chunk-scb86aq4.js} +1 -1
- package/dist/{chunk-q0gw11py.js → chunk-se9ar9b4.js} +1 -1
- package/dist/chunk-t74cwjdf.js +1 -0
- package/dist/{chunk-0vtamgkc.js → chunk-t88qf8dc.js} +1 -1
- package/dist/{chunk-n8h630d5.js → chunk-te5jzx47.js} +1 -1
- package/dist/{chunk-hb4669qa.js → chunk-vr20qr4k.js} +1 -1
- package/dist/{chunk-hjq84jxp.js → chunk-xcsz2qae.js} +1 -1
- package/dist/{chunk-jvmmg3yj.js → chunk-xfknqdp3.js} +1 -1
- package/dist/{chunk-7sw49eke.js → chunk-xmxhnz2f.js} +1 -1
- package/dist/{chunk-mkkrgmwk.js → chunk-ycz0vgss.js} +1 -1
- package/dist/chunk-yn52gmje.js +171 -0
- package/dist/chunk-yt80szvb.js +1 -0
- package/dist/{chunk-d1mk0b44.js → chunk-zpwxeeb4.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-2fwwc2j6.js +0 -171
- package/dist/chunk-8jb6qn7z.js +0 -1
- package/dist/chunk-jqnaakmv.js +0 -169
- package/dist/chunk-pt6h8re0.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{za as EZ}from"./chunk-ypbnczjp.js";import{Ca as A,Da as n0,Ia as dY,Ja as A7,Ka as i0}from"./chunk-
|
|
1
|
+
import{za as EZ}from"./chunk-ypbnczjp.js";import{Ca as A,Da as n0,Ia as dY,Ja as A7,Ka as i0}from"./chunk-6321bw8w.js";import{La as Y8,Na as AQ,Pa as CQ,Qa as VZ,gb as MQ}from"./chunk-23v8c9b8.js";import{Bb as B5,Cb as U4,Db as X4,Fb as g9,Gb as G$,Mb as C4,Nb as TY,Ob as rJ,Qb as S2,Rb as BY,Wb as m7,Zb as p7,hb as h$,ib as x1,jb as X7,kb as B1,lb as i3,mb as H7,nb as o3,ob as K7,pb as w7,qb as YJ,ub as V0,wb as u1,zb as W4}from"./chunk-yn52gmje.js";import{Ac as MZ,Ad as GZ,Bc as V2,Bd as r0,Cc as a4,Cd as h1,Dc as X1,Dd as HY,Ec as C1,Ed as KY,Fc as H2,Gc as M1,Hc as P1,Hd as IY,Ic as Q6,Jc as R1,Kc as W6,Lc as U6,Ld as d7,Mc as q$,Nc as X6,Oc as xZ,Pc as B2,Qc as V6,Qd as wY,Rc as H6,Rd as zY,Sc as K6,Tc as w6,Td as t,Uc as hZ,Vc as gZ,Xc as uZ,dc as G9,ec as _0,fc as $2,gc as Z1,hc as t2,ic as BZ,jc as Y4,kc as Q4,lc as t3,mc as e3,nc as VY,oc as NZ,od as b4,pc as U1,qc as OZ,qd as A0,rc as r4,rd as V$,sc as y$,tc as I$,uc as w2,vc as K2,wc as z2,xc as J6,yc as Y6,zc as X2}from"./chunk-92q9s5w9.js";import{Ud as d,Vd as XJ,Wd as VJ,Xd as a9,Zd as g1}from"./chunk-53h87fmt.js";import{_d as RQ,be as TQ,ke as fQ,qe as SQ}from"./chunk-qdv0n8yt.js";import{Be as y9,Ce as k9}from"./chunk-ng96f4xd.js";import{Oe as V4,Pe as B0,Qe as y,Te as L0,Ue as i6,Ve as d1,We as l$,Xe as E5,Ye as V1,Ze as g7,cf as y1}from"./chunk-xfknqdp3.js";import{df as q1}from"./chunk-pshyn3yy.js";import{hf as F5,if as u7,jf as x7,of as EY,pf as n6}from"./chunk-q2exry0f.js";import{rf as y0,sf as e$}from"./chunk-tj2efrs1.js";import{tf as SY}from"./chunk-hv6hrsnk.js";import{vf as YY,wf as QY,xf as WY}from"./chunk-667f1ksp.js";import{Af as $4,Cf as Z4,Df as J4,Ef as s$,Ff as BJ,Hf as O$,If as H$,Jf as Y$,Kf as Z8,Lf as S1,Mf as j4,Nf as b1,Of as N1,Pf as XY,Tf as d5,Vf as I0,Wf as D$,Yf as r6,Zf as GY,yf as t6,zf as e6}from"./chunk-9cs45ath.js";import{$f as n$,bg as B$,cg as I6,dg as J9,eg as Y9,fg as _2,gg as Q9,hg as W9,ig as L6,jg as U9,kg as _6}from"./chunk-cqqmkwvn.js";import{lg as sY,ng as UY,og as O4,pg as I9}from"./chunk-9g64g1np.js";import{rg as JZ,tg as T0}from"./chunk-n1vttsx4.js";import{ug as c2,vg as zZ,wg as l2,xg as E1}from"./chunk-eyb9psbc.js";import{Ah as H0,Eg as O9,Gg as s5,Lg as uY,Pg as b9,Rg as eJ,Tg as W7,Ug as U7,_g as D1,bh as a3,lh as M7,mh as P7,nh as R7,oh as T7,ph as b5,qh as f7,rh as c$,sh as S7,th as k7,uh as v7,wh as w9,yh as _Y,zg as L9,zh as JY}from"./chunk-61bb9kjb.js";import{Dh as x$}from"./chunk-4w4wjm49.js";import{Eh as z6,Fh as F6,Gh as z,Hh as iZ,Ih as f,Jh as I}from"./chunk-6k5k40p8.js";import{Lh as iJ,Nh as nJ}from"./chunk-p3m1jyg5.js";import{Qh as E6,Sh as M}from"./chunk-ecd727xh.js";import{si as a}from"./chunk-dvv28pkc.js";import{xi as $Y,yi as ZY}from"./chunk-dgf2xzzd.js";import{Ci as aY,zi as eY}from"./chunk-z52s82k7.js";import{Gi as YQ}from"./chunk-m14jar1a.js";import{Mi as DY,Ni as d0}from"./chunk-vbwvsgs1.js";import{Ri as s2,Ti as m$,Vi as tJ,Wi as Z9,Yi as s}from"./chunk-rkdxqx8m.js";import{_i as a0}from"./chunk-tf7ezqew.js";import{randomUUID as u4}from"crypto";import{randomUUID as sQ}from"node:crypto";var iQ=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);
|
|
@@ -125,7 +125,7 @@ Install with: blade browser install`)}if(this.disposed)throw await Z.close().cat
|
|
|
125
125
|
`)){let K=U.length===0?H:`
|
|
126
126
|
${H}`,w=Buffer.byteLength(K);if(X+w>W)break;U.push(H),X+=w}return{snapshot:`${U.length>0?U.join(`
|
|
127
127
|
`):S$(J,Math.max(0,W))}${c4}`,truncated:!0}}class l4{latestByPage=new Map;issue($){let Z=MW($.snapshot,$.maxBytes),J={snapshotId:`browser_snapshot_${vZ()}`,pageId:$.pageId,pageGeneration:$.pageGeneration,origin:$.origin,snapshot:Z.snapshot,truncated:Z.truncated,depth:$.depth,includeBoxes:$.includeBoxes,refs:kZ(Z.snapshot)};return this.latestByPage.set($.pageId,J),J}validate($){let Z=this.validateSnapshot($),J=Z.refs.get($.ref);if(!J)throw new P("browser_snapshot_stale","Browser ref is not present in the latest snapshot");return{ref:$.ref,fingerprint:J.value,fingerprintExceededLimit:J.exceededLimit,authority:Z}}validateSnapshot($){let Z=this.latestByPage.get($.pageId);if(!Z||Z.snapshotId!==$.snapshotId||Z.pageGeneration!==$.pageGeneration||Z.origin!==$.origin)throw new P("browser_snapshot_stale","Browser snapshot is stale; capture a new snapshot before interacting");return Z}verifyFreshFingerprint($,Z){let Y=kZ(Z).get($.ref);if(!Y||Y.value!==$.fingerprint||Y.exceededLimit!==$.fingerprintExceededLimit)throw new P("browser_snapshot_stale","Browser ref changed after the latest snapshot; capture a new snapshot")}invalidate($){this.latestByPage.delete($)}clear(){this.latestByPage.clear()}}class i4{latestByPage=new Map;issue($){let Z={screenshotId:`browser_screenshot_${vZ()}`,pageId:$.pageId,pageGeneration:$.pageGeneration,origin:$.origin,sha256:$.sha256,viewport:{...$.viewport}};return this.latestByPage.set($.pageId,Z),Z}validate($){let Z=this.latestByPage.get($.pageId);if(!Z||Z.screenshotId!==$.screenshotId||Z.pageGeneration!==$.pageGeneration||Z.origin!==$.origin)throw new P("browser_snapshot_stale","Browser screenshot is stale; capture a new screenshot before coordinate interaction");if(Z.viewport.width!==$.viewport.width||Z.viewport.height!==$.viewport.height)throw new P("browser_snapshot_stale","Browser screenshot viewport changed; capture a new screenshot before coordinate interaction");if(Z.sha256!==$.sha256)throw new P("browser_snapshot_stale","Browser screenshot pixels changed; capture a new screenshot before coordinate interaction");return Z}invalidate($){this.latestByPage.delete($)}clear(){this.latestByPage.clear()}}function n4($){return $ instanceof Error&&($.name==="TimeoutError"||/timeout/i.test($.message))}function yZ($){return $ instanceof Error&&/browser.*closed|target.*closed/i.test($.message)}function TW($){let Z=$ instanceof Error?$.message:String($);return E0(Z.replace(/https?:\/\/\S+/g,(J)=>k$(J)),w2)}function IZ($,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise((J,Y)=>{let Q=setTimeout(()=>{Z.removeEventListener("abort",W),J()},$),W=()=>{clearTimeout(Q),Y(Z.reason)};Z.addEventListener("abort",W,{once:!0})})}function v$($,Z,J){return new Promise((Y,Q)=>{let W=!1,U=()=>{if(W)return;W=!0,Q(Z.reason)};if(Z.aborted)U();else Z.addEventListener("abort",U,{once:!0});$.then((X)=>{if(Z.removeEventListener("abort",U),W){if(J)try{Promise.resolve(J(X)).catch(()=>{return})}catch{}return}W=!0,Y(X)},(X)=>{if(Z.removeEventListener("abort",U),W)return;W=!0,Q(X)})})}class o4{pool;gate=new m4;snapshots=new l4;screenshots=new i4;artifacts;pages=new Map;pageIds=new WeakMap;opaqueFrames=new WeakSet;popupOpeners=new WeakMap;pageRegistrations=new WeakMap;blockedPopups=[];downloadCancellations=new WeakMap;consoleEntries=[];pageErrorEntries=[];networkEntries=[];pendingPageRegistrations=new Set;pendingDownloadCancellations=new Set;lease;context;selectedPageId;pageSequence=0;diagnosticSequence=0;runtimeGeneration=0;generationController=new AbortController;disposed=!1;constructor($,Z,J={}){this.pool=J.pool??AZ(),this.artifacts=new uZ(gZ($,Z),{storageRoot:J.storageRoot,exposePaths:J.exposeArtifactPaths})}navigate($){return this.run(async(Z)=>{let J=$.action??"goto",Y=$.timeoutMs??B2;if(this.assertIntegerRange(Y,100,V6,"navigation timeout"),J==="goto"&&!$.url)throw new P("browser_unsupported","Browser goto requires a URL");if(J!=="goto"&&!$.expectedOrigin)throw new P("browser_origin_mismatch",`Browser ${J} requires expectedOrigin`);let Q=J==="goto"?g0($.url):void 0,W=J==="goto"?void 0:s0($.expectedOrigin),U=await this.resolvePage($.pageId,J==="goto",Z),X=U.authorizedOrigin,V=X;if(J==="goto"){V=Q.origin,U.transientOrigin=Q.origin,U.blockedCandidateOrigin=void 0,this.invalidatePage(U);try{await U.page.goto(Q.href,{waitUntil:$.waitUntil??"domcontentloaded",timeout:Y,signal:Z})}catch(H){return this.handleNavigationFailure(U,Q.origin,X,Z,H)}}else{this.assertExpectedOrigin(U,W),V=U.authorizedOrigin,U.transientOrigin=U.authorizedOrigin??void 0,U.blockedCandidateOrigin=void 0,this.invalidatePage(U);try{if(J==="back")await U.page.goBack({waitUntil:$.waitUntil??"domcontentloaded",timeout:Y,signal:Z});else if(J==="forward")await U.page.goForward({waitUntil:$.waitUntil??"domcontentloaded",timeout:Y,signal:Z});else await U.page.reload({waitUntil:$.waitUntil??"domcontentloaded",timeout:Y,signal:Z})}catch(H){return this.handleNavigationFailure(U,V,X,Z,H)}}if(this.settleNavigationAuthorization(U,V,X),U.transientOrigin=void 0,U.blockedCandidateOrigin)throw new P("browser_cross_origin_navigation",`Cross-origin navigation was blocked: ${U.blockedCandidateOrigin}`,{candidateOrigin:U.blockedCandidateOrigin});return this.observe(U,Z)},$.signal)}async handleNavigationFailure($,Z,J,Y,Q){this.settleNavigationAuthorization($,Z,J);let W=$.blockedCandidateOrigin;if($.transientOrigin=void 0,W)throw new P("browser_cross_origin_navigation",`Cross-origin navigation was blocked: ${W}`,{candidateOrigin:W});if(n4(Q))throw new P("browser_timeout","Browser navigation timed out",{retryable:!0});throw this.throwIfDisconnected(Q,Y),new P("browser_action_uncertain","Browser navigation failed after it started",{sideEffectsUncertain:!0})}snapshot($={}){return this.run(async(Z)=>{let J=$.depth??z2;this.assertIntegerRange(J,1,J6,"snapshot depth");let Y=await this.resolvePage($.pageId,!0,Z);return this.observe(Y,Z,J,$.includeBoxes??!1)},$.signal)}interact($){return this.run(async(Z)=>{this.assertIdentifier($.pageId,"page ID"),this.assertIdentifier($.snapshotId,"snapshot ID");let J=$.action.kind==="click_at"?$.action:void 0;if($.action.kind!=="scroll"&&!J&&!$.ref)throw new P("browser_unsupported","Browser action requires a top-level snapshot ref next to action");if(J&&$.ref)throw new P("browser_unsupported","Browser coordinate click cannot also use a snapshot ref");if($.ref&&(N0($.ref)>C1||!/^[a-z][a-z0-9]*$/.test($.ref)))throw new P("browser_unsupported","Browser ref is invalid");this.validateAction($.action);let Y=$.timeoutMs??q$;this.assertIntegerRange(Y,100,X6,"action timeout");let Q=this.requireExistingPage($.pageId);this.throwIfBlockedNavigation(Q);let W=this.assertExpectedOrigin(Q,$.expectedOrigin),U={pageId:Q.id,snapshotId:$.snapshotId,pageGeneration:Q.generation,origin:W},X=this.snapshots.validateSnapshot(U),V=$.ref?this.snapshots.validate({...U,ref:$.ref}):void 0;if(V){let L=await Q.page.ariaSnapshot({mode:"ai",depth:X.depth,boxes:X.includeBoxes,timeout:$.timeoutMs??q$,signal:Z});this.snapshots.verifyFreshFingerprint(V,L)}if(J)await this.validateCoordinateClick(Q,J,Z);let H=$.ref?Q.page.locator(`aria-ref=${$.ref}`):void 0;if(H&&await H.count()!==1)throw new P("browser_snapshot_stale","Browser ref no longer resolves to exactly one element");if(H){let L=await H.elementHandle(),q=null;try{q=await L?.ownerFrame()??null}finally{await L?.dispose().catch(()=>{return})}if((q?await this.resolveEffectiveFrameOrigin(q):null)!==Q.authorizedOrigin)throw new P("browser_cross_origin_frame","Browser ref belongs to a cross-origin frame")}if(H&&V&&($.action.kind==="fill"||$.action.kind==="type")){let[L,q,b,N,E,j]=await Promise.all([H.getAttribute("type"),H.getAttribute("autocomplete"),H.getAttribute("name"),H.getAttribute("id"),H.getAttribute("aria-label"),H.getAttribute("aria-labelledby")]);if(fZ({type:L,autocomplete:q,name:b,id:N,ariaLabel:E,accessibleName:V.fingerprint,accessibleNameExceededLimit:V.fingerprintExceededLimit,referencedAccessibleNameUnavailable:Boolean(j?.trim())&&!/^-\s+\S+\s+"/u.test(V.fingerprint)}))throw new P("browser_unsupported","Browser credential entry is not supported")}this.throwIfBlockedNavigation(Q),this.assertExpectedOrigin(Q,W);let K=typeof Q.page.viewportSize==="function"?Q.page.viewportSize():null,w={action:$.action.kind,...$.ref?{ref:$.ref}:{},...K?{viewport:K}:{},...J?{targetBox:{x:J.x,y:J.y,width:1,height:1}}:{}};Q.downloadBlocked=!1,this.invalidatePage(Q);let B=this.runtimeGeneration,G=!1,_,D=$.action.kind==="click"||J?Q.page.waitForEvent("download",{timeout:Math.min(Y,xZ)}).catch(()=>{return}):void 0;try{if($.action.kind==="click")Q.nextDialogAction=$.action.dialog?.action;else if(J)Q.nextDialogAction=J.dialog?.action;await this.executeAction(Q.page,H,$.action,Y,Z);let L=D?await v$(D,Z):void 0;if(L)this.trackDownloadCancellation(Q,L);await this.settlePageRegistrations(Z),await this.settleDownloadCancellations(Z)}catch(L){G=!0,_=L}finally{Q.nextDialogAction=void 0}let F=H&&typeof H.boundingBox==="function"?await H.boundingBox({timeout:Math.min(Y,500)}).catch(()=>null):null;if(F)w.targetBox=F;if(this.markUnexpectedInteractionOrigin(Q,W),Q.downloadBlocked)throw Q.downloadBlocked=!1,new P("browser_download_blocked","Browser download was blocked");if(G)return this.uncertainInteraction(Q,B,_,w);if(Q.blockedCandidateOrigin)return{outcome:"uncertain",pageId:Q.id,actionApplied:"unknown",sideEffectsUncertain:!0,errorCode:"browser_cross_origin_navigation",candidateOrigin:Q.blockedCandidateOrigin,interaction:w};if(B!==this.runtimeGeneration)return{outcome:"uncertain",pageId:Q.id,actionApplied:"unknown",sideEffectsUncertain:!0,errorCode:"browser_disconnected",interaction:w};try{let L=await this.observe(Q,Z);if(Q.blockedCandidateOrigin)return{outcome:"uncertain",pageId:Q.id,actionApplied:"unknown",sideEffectsUncertain:!0,errorCode:"browser_cross_origin_navigation",candidateOrigin:Q.blockedCandidateOrigin,interaction:w};return{outcome:"applied",pageId:Q.id,actionApplied:!0,sideEffectsUncertain:!1,observation:L,interaction:w}}catch(L){if(Q.blockedCandidateOrigin||L instanceof P&&L.code==="browser_cross_origin_navigation")return{outcome:"uncertain",pageId:Q.id,actionApplied:"unknown",sideEffectsUncertain:!0,errorCode:"browser_cross_origin_navigation",...Q.blockedCandidateOrigin?{candidateOrigin:Q.blockedCandidateOrigin}:{},interaction:w};return{outcome:"applied_observation_failed",pageId:Q.id,actionApplied:!0,sideEffectsUncertain:!1,observationError:"browser_observation_failed",interaction:w}}},$.signal)}wait($){return this.run(async(Z)=>{let J=await this.resolvePage($.pageId,!1,Z);if(this.throwIfBlockedNavigation(J),$.expectedOrigin)this.assertExpectedOrigin(J,$.expectedOrigin);let Y=$.timeoutMs??H6;this.assertIntegerRange(Y,100,K6,"wait timeout");try{switch($.condition.kind){case"load":await J.page.waitForLoadState($.condition.state,{timeout:Y,signal:Z});break;case"text":if(N0($.condition.text)===0||N0($.condition.text)>R1)throw new P("browser_unsupported","Browser wait text is empty or exceeds the supported size");await J.page.getByText($.condition.text,{exact:!0}).first().waitFor({state:"visible",timeout:Y,signal:Z});break;case"url":{let Q=g0($.condition.value);await J.page.waitForURL((W)=>{return W.hash="",W.href===Q.href},{timeout:Y,signal:Z});break}case"ref":{if(!$.expectedOrigin)throw new P("browser_origin_mismatch","Browser ref wait requires expectedOrigin");if(this.assertIdentifier($.condition.snapshotId,"snapshot ID"),N0($.condition.ref)>C1||!/^[a-z][a-z0-9]*$/.test($.condition.ref))throw new P("browser_unsupported","Browser ref is invalid");this.snapshots.validate({pageId:J.id,snapshotId:$.condition.snapshotId,pageGeneration:J.generation,origin:s0($.expectedOrigin),ref:$.condition.ref}),await J.page.locator(`aria-ref=${$.condition.ref}`).waitFor({state:$.condition.state,timeout:Y,signal:Z});break}case"time":this.assertIntegerRange($.condition.milliseconds,0,w6,"wait duration"),await IZ($.condition.milliseconds,Z);break}}catch(Q){if(this.throwIfBlockedNavigation(J),this.throwIfDisconnected(Q,Z),n4(Q))throw new P("browser_timeout","Browser wait timed out",{retryable:!0});throw Q}return this.observe(J,Z)},$.signal)}inspect($){return this.run(async(Z)=>{let J=await this.resolvePage($.pageId,!1,Z);if(this.throwIfBlockedNavigation(J),$.expectedOrigin)this.assertExpectedOrigin(J,$.expectedOrigin);if($.target.kind==="screenshot"){let H=await this.captureStableScreenshot(J,Z);this.throwIfBlockedNavigation(J);let K=J.page.viewportSize();if(!K)throw new P("browser_unsupported","Browser screenshot requires a fixed viewport");let w=u0(J.page.url())??"null",B=await this.artifacts.writeScreenshot(H),G=this.screenshots.issue({pageId:J.id,pageGeneration:J.generation,origin:w,sha256:B.sha256,viewport:K});return{pageId:J.id,target:"screenshot",screenshotId:G.screenshotId,origin:w,url:k$(J.page.url()),viewport:K,artifact:B,...$.includeScreenshotData?{screenshotDataUrl:`data:image/png;base64,${H.toString("base64")}`}:{},truncated:!1}}if($.target.kind==="find"){if(N0($.target.text)===0||N0($.target.text)>R1)throw new P("browser_unsupported","Browser find text is empty or exceeds the supported size");let H=$.target.limit??y$;this.assertIntegerRange(H,1,I$,"limit");let K=await this.observe(J,Z),w=$.target.text.toLocaleLowerCase("en-US"),B=K.snapshot.split(`
|
|
128
|
-
`).filter((_)=>_.toLocaleLowerCase("en-US").includes(w)),G=B.slice(0,H);return{pageId:J.id,target:"find",matches:G,snapshotId:K.snapshotId,origin:K.origin,url:K.url,truncated:G.length<B.length}}let Y=$.target.kind==="console"?this.consoleEntries:$.target.kind==="page-errors"?this.pageErrorEntries:this.networkEntries,Q=$.target.limit??y$;this.assertIntegerRange(Q,1,I$,"limit");let W=Y.filter((H)=>H.pageId===J.id),U=W.slice(-Q),X=[],V=0;for(let H of U){let K=N0(JSON.stringify(H));if(V+K>Y6)break;X.push(H),V+=K}return this.throwIfBlockedNavigation(J),{pageId:J.id,target:$.target.kind,entries:X,truncated:X.length<U.length||W.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:q$,signal:Z});if(this.throwIfBlockedNavigation(J),Y.length>hZ)throw new P("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 P("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 P("browser_disconnected","Chromium disconnected before the queued operation started",{retryable:!0});let Q=AbortSignal.any([Y,this.generationController.signal]);try{return await $(Q)}catch(W){throw this.throwIfDisconnected(W,Q),W}},Z)}async ensureContext($){if(this.disposed)throw new P("browser_disposed","Browser Session Runtime is closed");if(this.context&&this.lease)return this.context;let Z=await v$(this.pool.acquire(()=>this.handleDisconnected()),$,(Y)=>Y.release()),J=Z.context;if(this.disposed||$.aborted)throw await Z.release(),$.reason??new P("browser_disposed","Browser Session Runtime is closed");try{return await v$(J.route("**/*",(Y)=>this.guardRoute(Y)),$),J.setDefaultTimeout(q$),J.setDefaultNavigationTimeout(B2),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>=U1)throw new P("browser_capacity",`Browser page capacity is full (max ${U1})`,{retryable:!0});let J=await this.ensureContext(Z),Y=await v$(J.newPage(),Z,(W)=>W.close({runBeforeUnload:!1}).catch(()=>{return})),Q=this.registerPage(Y,$);if(!Q)throw new P("browser_capacity",`Browser page capacity is full (max ${U1})`,{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,W)=>Q.createdSequence-W.createdSequence)[0];if(Y)return this.selectedPageId=Y.id,Y;if(!Z)throw new P("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 P("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 X=this.pages.get(Q);if(X&&Y&&!X.openerPageId)X.openerPageId=Y;if(Z&&X)this.selectedPageId=X.id;return X}if(this.pages.size>=U1){$.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 W=`browser_page_${RW()}`,U={id:W,page:$,generation:0,authorizedOrigin:J,...Y?{openerPageId:Y}:{},createdSequence:++this.pageSequence};if(this.pages.set(W,U),this.pageIds.set($,W),Z||!this.selectedPageId)this.selectedPageId=W;return this.attachPageListeners(U),U}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,W=this.registerPage($,!1,Q,Y?.id);if(!W)return;let U=u0($.url()),X=U!==Q,V=X?this.takeBlockedPopup(Y):void 0;if(!V&&X)this.discardUnattributedBlockedPopup();let H=W.blockedCandidateOrigin??V?.origin??(X?U??"[unsupported-origin]":void 0);if(H){if(W.blockedCandidateOrigin=H,Y)Y.blockedCandidateOrigin=H;if(!V)this.addNetwork({sequence:++this.diagnosticSequence,pageId:Y?.id??W.id,kind:"navigation-blocked",url:H,text:"Cross-origin popup was blocked"});await $.close({runBeforeUnload:!1}).catch(()=>{return}),this.removePage(W)}}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,W)=>({blocked:Q,index:W})).filter(({blocked:Q})=>Q.openerPageId===$.id).map(({index:Q})=>Q):[],J=Z.length===0&&$?this.blockedPopups.map((Q,W)=>({blocked:Q,index:W})).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 v$(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:TW(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=u0(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 K=(()=>{try{return g0(Z.url()).origin}catch{return"[unsupported-origin]"}})(),w=this.browserRequestReferrerOrigin(Z),B=this.resolvePopupOpenerFromReferrer(Z);if(B?.authorizedOrigin&&K===B.authorizedOrigin||w&&K===w&&[...this.pages.values()].some((G)=>!G.page.isClosed()&&G.authorizedOrigin===w&&u0(G.page.url())===w)){await $.continue();return}if(B)B.blockedCandidateOrigin=K;if(this.blockedPopups.push({origin:K,...B?{openerPageId:B.id}:{},...w?{referrerOrigin:w}:{}}),this.blockedPopups.length>U1)this.blockedPopups.splice(0,this.blockedPopups.length-U1);this.addNetwork({sequence:++this.diagnosticSequence,pageId:B?.id??"unknown",kind:"navigation-blocked",url:K,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,W=await Y.opener().catch(()=>null),U=this.popupOpeners.get(Y)??(W?this.pageIds.get(W):void 0),X=U?this.pages.get(U):void 0;if(!Q)Q=this.registerPage(Y,!1,X?.authorizedOrigin??null,X?.id);else if(X&&!Q.openerPageId)Q.openerPageId=X.id;if(!Q){await $.abort("blockedbyclient");return}let V;try{V=g0(Z.url()).origin}catch{Q.blockedCandidateOrigin="[unsupported-origin]",await $.abort("blockedbyclient");return}let H=Q.transientOrigin??Q.authorizedOrigin;if(!H||V!==H){Q.blockedCandidateOrigin=V;let K=Q.openerPageId?this.pages.get(Q.openerPageId):void 0;if(K)K.blockedCandidateOrigin=V;if(this.addNetwork({sequence:++this.diagnosticSequence,pageId:K?.id??Q.id,kind:"navigation-blocked",url:V,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 g0(Z).origin}catch{return}}resolvePopupOpenerFromReferrer($){let Z=$.headers().referer;if(!Z)return;let J;try{J=g0(Z)}catch{return}let Y=[...this.pages.values()].filter((U)=>!U.page.isClosed()&&U.authorizedOrigin===J.origin),Q=Y.filter((U)=>{try{return g0(U.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=u0($.page.url());if(Y===Z)$.authorizedOrigin=Z;else if(Y===J)$.authorizedOrigin=J;else $.authorizedOrigin=null}assertExpectedOrigin($,Z){let J=s0(Z),Y=u0($.page.url());if($.authorizedOrigin===null||Y!==$.authorizedOrigin||J!==$.authorizedOrigin)throw new P("browser_origin_mismatch","Browser page origin changed; capture a new snapshot or navigate explicitly");return J}throwIfBlockedNavigation($){if(!$.blockedCandidateOrigin)return;throw new P("browser_cross_origin_navigation",`Cross-origin navigation was blocked: ${$.blockedCandidateOrigin}`,{candidateOrigin:$.blockedCandidateOrigin})}markUnexpectedInteractionOrigin($,Z){if($.page.isClosed()||$.blockedCandidateOrigin)return;let J=u0($.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=u0(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=z2,Y=!1){if($.page.isClosed())throw new P("browser_page_not_found","Browser page is closed");this.throwIfBlockedNavigation($);let Q=await $.page.ariaSnapshot({mode:"ai",depth:J,boxes:Y,timeout:q$,signal:Z});this.throwIfBlockedNavigation($);let W=await this.pageSummaries(),U=u0($.page.url())??"null",X=E0(await $.page.title().catch(()=>""),a4),V=typeof $.page.viewportSize==="function"?$.page.viewportSize():null,H=this.snapshots.issue({pageId:$.id,pageGeneration:$.generation,origin:U,snapshot:Q,depth:J,includeBoxes:Y,maxBytes:Math.min(K2,32768)});return{pageId:$.id,snapshotId:H.snapshotId,url:k$($.page.url()),origin:U,title:X,...V?{viewport:V}:{},tabs:W,snapshot:H.snapshot,truncated:H.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:k$($.page.url()),origin:u0($.page.url())??"null",title:E0(await $.page.title().catch(()=>""),a4)})))}invalidatePage($){$.generation++,this.snapshots.invalidate($.id),this.screenshots.invalidate($.id)}assertIdentifier($,Z){if(!$||N0($)>X1)throw new P("browser_unsupported",`Browser ${Z} is invalid`)}assertIntegerRange($,Z,J,Y){if(!Number.isSafeInteger($)||$<Z||$>J)throw new P("browser_unsupported",`Browser ${Y} must be an integer from ${Z} to ${J}`)}validateAction($){if($.kind==="click_at"){this.assertIntegerRange($.x,0,P1,"x coordinate"),this.assertIntegerRange($.y,0,P1,"y coordinate"),this.assertIdentifier($.screenshotId,"screenshot ID");return}if($.kind==="fill"||$.kind==="type"){if(N0($.value)>M1)throw new P("browser_unsupported","Browser input exceeds the supported size");return}if($.kind==="scroll"){this.assertIntegerRange($.amount,1,Q6,"scroll amount");return}if($.kind!=="select")return;if($.values.length===0||$.values.length>W6||$.values.some((Z)=>N0(Z)>U6)||N0($.values.join(""))>M1)throw new P("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 P("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:u0($.page.url())??"null",sha256:PW("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 W;try{W=await Q.frameElement();let U=await W.boundingBox();if(U&&Z>=U.x&&Z<U.x+U.width&&J>=U.y&&J<U.y+U.height)throw new P("browser_cross_origin_frame","Browser coordinate clicks cannot target frame content")}catch(U){if(!Q.isDetached())throw U}finally{await W?.dispose().catch(()=>{return})}}}async captureStableScreenshot($,Z){let J=()=>$.page.screenshot({type:"png",fullPage:!1,animations:"disabled",caret:"hide",timeout:q$,signal:Z}),Y=await J();for(let Q=0;Q<3;Q++){await IZ(50,Z);let W=await J();if(W.equals(Y))return W;Y=W}throw new P("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 P("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 v$($.mouse.click(J.x,J.y),Q);return}if(J.kind==="scroll"){let W=J.direction==="up"||J.direction==="left"?-J.amount:J.amount,U=J.direction==="left"||J.direction==="right"?W:0,X=J.direction==="up"||J.direction==="down"?W:0;await v$($.mouse.wheel(U,X),Q);return}if(!Z)throw new P("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((W)=>({value:W})),{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||yZ(J))Q="browser_disconnected";else if(n4(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:E0(Z.type(),64),text:E0(Z.text(),w2)})}recordRequest($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"request",method:E0(Z.method(),32),resourceType:E0(Z.resourceType(),64),url:k$(Z.url())})}recordResponse($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"response",status:Z.status(),url:k$(Z.url())})}recordRequestFailure($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"request-failure",method:E0(Z.method(),32),resourceType:E0(Z.resourceType(),64),url:k$(Z.url()),text:E0(Z.failure()?.errorText??"request failed",w2)})}async dismissDialog($,Z){this.addPageError({sequence:++this.diagnosticSequence,pageId:$.id,kind:"dialog",text:E0(`${Z.type()}: ${Z.message()}`,w2)});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 v$(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>r4)$.splice(0,$.length-r4)}handleDisconnected(){this.runtimeGeneration++,this.generationController.abort(new P("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 P)throw Z.reason;if(yZ($))throw new P("browser_disconnected","Chromium disconnected during the Browser operation",{retryable:!0})}}function dZ($){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)return{state:"requires_attention",turnId:$.turnId,inputMessageCount:Z,reason:"successful_tool_result"};return{state:"resumable",turnId:$.turnId,inputMessageCount:Z}}import{createHash as uW}from"node:crypto";import{createHash as vW}from"node:crypto";import*as B6 from"fs/promises";import*as f1 from"path";import yW from"write-file-atomic";import*as pZ from"node:fs/promises";import*as cZ from"node:path";var fW={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},mZ;async function lZ($,Z){await pZ.mkdir(cZ.dirname($),{recursive:!0,mode:448});let Y=await(await SW()).lock($,fW);try{return await Z()}finally{await Y()}}async function SW(){return mZ??=await import("proper-lockfile"),mZ}var s4=I(["pending","in_progress","completed"]),kW=I(["high","medium","low"]),nZ=iZ(z.Object({id:z.String(),subject:z.String(),description:z.String(),status:s4,activeForm:z.Optional(z.String()),owner:z.Optional(z.String()),priority:f(kW,"medium"),blocks:f(z.Array(z.String()),[]),blockedBy:f(z.Array(z.String()),[]),metadata:z.Optional(z.Record(z.String(),z.Unknown())),createdAt:z.String(),startedAt:z.Optional(z.String()),completedAt:z.Optional(z.String())}));class U${static operations=new x$;tasks=[];filePath;constructor($,Z){this.filePath=f1.join(f1.resolve(Z),"tasks",hW($))}static getInstance($,Z){return new U$($,Z)}static coordinationStatsForTests(){return this.operations.getStats()}async createTask($){return this.mutate((Z)=>{let J=T1($.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:T1([...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((U)=>U.status==="completed").map((U)=>U.id)),Q=[...J.tasks].filter((U)=>U.status==="pending"&&(U.owner===void 0||U.owner===Z)&&U.blockedBy.every((X)=>Y.has(X))).sort(rZ)[0];if(!Q)return{state:J,result:null,persist:!1};let W={...Q,owner:Z,status:"in_progress",startedAt:Q.startedAt??new Date().toISOString()};return{state:{...J,tasks:J.tasks.map((U)=>U.id===W.id?W:U)},result:W,persist:!0}})}async updateTask($,Z){return this.mutate((J)=>{let Y=J.tasks.findIndex((H)=>H.id===$);if(Y===-1)return{state:J,result:{task:null,updatedFields:[]},persist:!1};let Q=J.tasks[Y],W=[],U={...Q};if(Z.subject!==void 0&&Z.subject!==Q.subject)U.subject=Z.subject,W.push("subject");if(Z.description!==void 0&&Z.description!==Q.description)U.description=Z.description,W.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==Q.activeForm)U.activeForm=Z.activeForm,W.push("activeForm");if(Z.owner!==void 0&&Z.owner!==Q.owner)U.owner=Z.owner,W.push("owner");if(Z.metadata!==void 0)U.metadata=gW(Q.metadata,Z.metadata),W.push("metadata");let X;if(Z.status!==void 0&&Z.status!==Q.status){if(U.status=Z.status,Z.status==="in_progress"&&!Q.startedAt)U.startedAt=new Date().toISOString();if(Z.status==="completed"&&!Q.completedAt)U.completedAt=new Date().toISOString();X={from:Q.status,to:Z.status},W.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(U.blocks=T1([...Q.blocks,...Z.addBlocks]),U.blocks.length!==Q.blocks.length)W.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(U.blockedBy=T1([...Q.blockedBy,...Z.addBlockedBy]),U.blockedBy.length!==Q.blockedBy.length)W.push("blockedBy")}let V=J.tasks.map((H)=>H.id===$?U:H);return V=xW(V,U,Z.addBlocks,Z.addBlockedBy),{state:{...J,tasks:V},result:{task:U,updatedFields:W,statusChange:X},persist:!0}})}async deleteTask($){return this.mutate((Z)=>{let J=Z.tasks.filter((Q)=>Q.id!==$).map((Q)=>({...Q,blocks:Q.blocks.filter((W)=>W!==$),blockedBy:Q.blockedBy.filter((W)=>W!==$)})),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(rZ)}async readLatest(){return U$.operations.runExclusive(this.filePath,async()=>{let $=await this.readTasks();return this.tasks=$.tasks,$})}async mutate($){return U$.operations.runExclusive(this.filePath,()=>lZ(this.filePath,async()=>{let Z=await this.readTasks(),J=$(Z);if(J.persist)await this.saveTasks(J.state);return this.tasks=J.state.tasks,J.result}))}async readTasks(){try{let $=JSON.parse(await B6.readFile(this.filePath,"utf-8"));return IW($)}catch($){if($.code==="ENOENT")return{tasks:[],nextId:1};throw Error("Task list state is corrupt or unreadable",{cause:$})}}async saveTasks($){await B6.mkdir(f1.dirname(this.filePath),{recursive:!0,mode:448}),await yW(this.filePath,`${JSON.stringify($,null,2)}
|
|
128
|
+
`).filter((_)=>_.toLocaleLowerCase("en-US").includes(w)),G=B.slice(0,H);return{pageId:J.id,target:"find",matches:G,snapshotId:K.snapshotId,origin:K.origin,url:K.url,truncated:G.length<B.length}}let Y=$.target.kind==="console"?this.consoleEntries:$.target.kind==="page-errors"?this.pageErrorEntries:this.networkEntries,Q=$.target.limit??y$;this.assertIntegerRange(Q,1,I$,"limit");let W=Y.filter((H)=>H.pageId===J.id),U=W.slice(-Q),X=[],V=0;for(let H of U){let K=N0(JSON.stringify(H));if(V+K>Y6)break;X.push(H),V+=K}return this.throwIfBlockedNavigation(J),{pageId:J.id,target:$.target.kind,entries:X,truncated:X.length<U.length||W.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:q$,signal:Z});if(this.throwIfBlockedNavigation(J),Y.length>hZ)throw new P("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 P("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 P("browser_disconnected","Chromium disconnected before the queued operation started",{retryable:!0});let Q=AbortSignal.any([Y,this.generationController.signal]);try{return await $(Q)}catch(W){throw this.throwIfDisconnected(W,Q),W}},Z)}async ensureContext($){if(this.disposed)throw new P("browser_disposed","Browser Session Runtime is closed");if(this.context&&this.lease)return this.context;let Z=await v$(this.pool.acquire(()=>this.handleDisconnected()),$,(Y)=>Y.release()),J=Z.context;if(this.disposed||$.aborted)throw await Z.release(),$.reason??new P("browser_disposed","Browser Session Runtime is closed");try{return await v$(J.route("**/*",(Y)=>this.guardRoute(Y)),$),J.setDefaultTimeout(q$),J.setDefaultNavigationTimeout(B2),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>=U1)throw new P("browser_capacity",`Browser page capacity is full (max ${U1})`,{retryable:!0});let J=await this.ensureContext(Z),Y=await v$(J.newPage(),Z,(W)=>W.close({runBeforeUnload:!1}).catch(()=>{return})),Q=this.registerPage(Y,$);if(!Q)throw new P("browser_capacity",`Browser page capacity is full (max ${U1})`,{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,W)=>Q.createdSequence-W.createdSequence)[0];if(Y)return this.selectedPageId=Y.id,Y;if(!Z)throw new P("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 P("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 X=this.pages.get(Q);if(X&&Y&&!X.openerPageId)X.openerPageId=Y;if(Z&&X)this.selectedPageId=X.id;return X}if(this.pages.size>=U1){$.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 W=`browser_page_${RW()}`,U={id:W,page:$,generation:0,authorizedOrigin:J,...Y?{openerPageId:Y}:{},createdSequence:++this.pageSequence};if(this.pages.set(W,U),this.pageIds.set($,W),Z||!this.selectedPageId)this.selectedPageId=W;return this.attachPageListeners(U),U}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,W=this.registerPage($,!1,Q,Y?.id);if(!W)return;let U=u0($.url()),X=U!==Q,V=X?this.takeBlockedPopup(Y):void 0;if(!V&&X)this.discardUnattributedBlockedPopup();let H=W.blockedCandidateOrigin??V?.origin??(X?U??"[unsupported-origin]":void 0);if(H){if(W.blockedCandidateOrigin=H,Y)Y.blockedCandidateOrigin=H;if(!V)this.addNetwork({sequence:++this.diagnosticSequence,pageId:Y?.id??W.id,kind:"navigation-blocked",url:H,text:"Cross-origin popup was blocked"});await $.close({runBeforeUnload:!1}).catch(()=>{return}),this.removePage(W)}}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,W)=>({blocked:Q,index:W})).filter(({blocked:Q})=>Q.openerPageId===$.id).map(({index:Q})=>Q):[],J=Z.length===0&&$?this.blockedPopups.map((Q,W)=>({blocked:Q,index:W})).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 v$(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:TW(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=u0(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 K=(()=>{try{return g0(Z.url()).origin}catch{return"[unsupported-origin]"}})(),w=this.browserRequestReferrerOrigin(Z),B=this.resolvePopupOpenerFromReferrer(Z);if(B?.authorizedOrigin&&K===B.authorizedOrigin||w&&K===w&&[...this.pages.values()].some((G)=>!G.page.isClosed()&&G.authorizedOrigin===w&&u0(G.page.url())===w)){await $.continue();return}if(B)B.blockedCandidateOrigin=K;if(this.blockedPopups.push({origin:K,...B?{openerPageId:B.id}:{},...w?{referrerOrigin:w}:{}}),this.blockedPopups.length>U1)this.blockedPopups.splice(0,this.blockedPopups.length-U1);this.addNetwork({sequence:++this.diagnosticSequence,pageId:B?.id??"unknown",kind:"navigation-blocked",url:K,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,W=await Y.opener().catch(()=>null),U=this.popupOpeners.get(Y)??(W?this.pageIds.get(W):void 0),X=U?this.pages.get(U):void 0;if(!Q)Q=this.registerPage(Y,!1,X?.authorizedOrigin??null,X?.id);else if(X&&!Q.openerPageId)Q.openerPageId=X.id;if(!Q){await $.abort("blockedbyclient");return}let V;try{V=g0(Z.url()).origin}catch{Q.blockedCandidateOrigin="[unsupported-origin]",await $.abort("blockedbyclient");return}let H=Q.transientOrigin??Q.authorizedOrigin;if(!H||V!==H){Q.blockedCandidateOrigin=V;let K=Q.openerPageId?this.pages.get(Q.openerPageId):void 0;if(K)K.blockedCandidateOrigin=V;if(this.addNetwork({sequence:++this.diagnosticSequence,pageId:K?.id??Q.id,kind:"navigation-blocked",url:V,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 g0(Z).origin}catch{return}}resolvePopupOpenerFromReferrer($){let Z=$.headers().referer;if(!Z)return;let J;try{J=g0(Z)}catch{return}let Y=[...this.pages.values()].filter((U)=>!U.page.isClosed()&&U.authorizedOrigin===J.origin),Q=Y.filter((U)=>{try{return g0(U.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=u0($.page.url());if(Y===Z)$.authorizedOrigin=Z;else if(Y===J)$.authorizedOrigin=J;else $.authorizedOrigin=null}assertExpectedOrigin($,Z){let J=s0(Z),Y=u0($.page.url());if($.authorizedOrigin===null||Y!==$.authorizedOrigin||J!==$.authorizedOrigin)throw new P("browser_origin_mismatch","Browser page origin changed; capture a new snapshot or navigate explicitly");return J}throwIfBlockedNavigation($){if(!$.blockedCandidateOrigin)return;throw new P("browser_cross_origin_navigation",`Cross-origin navigation was blocked: ${$.blockedCandidateOrigin}`,{candidateOrigin:$.blockedCandidateOrigin})}markUnexpectedInteractionOrigin($,Z){if($.page.isClosed()||$.blockedCandidateOrigin)return;let J=u0($.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=u0(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=z2,Y=!1){if($.page.isClosed())throw new P("browser_page_not_found","Browser page is closed");this.throwIfBlockedNavigation($);let Q=await $.page.ariaSnapshot({mode:"ai",depth:J,boxes:Y,timeout:q$,signal:Z});this.throwIfBlockedNavigation($);let W=await this.pageSummaries(),U=u0($.page.url())??"null",X=E0(await $.page.title().catch(()=>""),a4),V=typeof $.page.viewportSize==="function"?$.page.viewportSize():null,H=this.snapshots.issue({pageId:$.id,pageGeneration:$.generation,origin:U,snapshot:Q,depth:J,includeBoxes:Y,maxBytes:Math.min(K2,32768)});return{pageId:$.id,snapshotId:H.snapshotId,url:k$($.page.url()),origin:U,title:X,...V?{viewport:V}:{},tabs:W,snapshot:H.snapshot,truncated:H.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:k$($.page.url()),origin:u0($.page.url())??"null",title:E0(await $.page.title().catch(()=>""),a4)})))}invalidatePage($){$.generation++,this.snapshots.invalidate($.id),this.screenshots.invalidate($.id)}assertIdentifier($,Z){if(!$||N0($)>X1)throw new P("browser_unsupported",`Browser ${Z} is invalid`)}assertIntegerRange($,Z,J,Y){if(!Number.isSafeInteger($)||$<Z||$>J)throw new P("browser_unsupported",`Browser ${Y} must be an integer from ${Z} to ${J}`)}validateAction($){if($.kind==="click_at"){this.assertIntegerRange($.x,0,P1,"x coordinate"),this.assertIntegerRange($.y,0,P1,"y coordinate"),this.assertIdentifier($.screenshotId,"screenshot ID");return}if($.kind==="fill"||$.kind==="type"){if(N0($.value)>M1)throw new P("browser_unsupported","Browser input exceeds the supported size");return}if($.kind==="scroll"){this.assertIntegerRange($.amount,1,Q6,"scroll amount");return}if($.kind!=="select")return;if($.values.length===0||$.values.length>W6||$.values.some((Z)=>N0(Z)>U6)||N0($.values.join(""))>M1)throw new P("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 P("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:u0($.page.url())??"null",sha256:PW("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 W;try{W=await Q.frameElement();let U=await W.boundingBox();if(U&&Z>=U.x&&Z<U.x+U.width&&J>=U.y&&J<U.y+U.height)throw new P("browser_cross_origin_frame","Browser coordinate clicks cannot target frame content")}catch(U){if(!Q.isDetached())throw U}finally{await W?.dispose().catch(()=>{return})}}}async captureStableScreenshot($,Z){let J=()=>$.page.screenshot({type:"png",fullPage:!1,animations:"disabled",caret:"hide",timeout:q$,signal:Z}),Y=await J();for(let Q=0;Q<3;Q++){await IZ(50,Z);let W=await J();if(W.equals(Y))return W;Y=W}throw new P("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 P("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 v$($.mouse.click(J.x,J.y),Q);return}if(J.kind==="scroll"){let W=J.direction==="up"||J.direction==="left"?-J.amount:J.amount,U=J.direction==="left"||J.direction==="right"?W:0,X=J.direction==="up"||J.direction==="down"?W:0;await v$($.mouse.wheel(U,X),Q);return}if(!Z)throw new P("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((W)=>({value:W})),{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||yZ(J))Q="browser_disconnected";else if(n4(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:E0(Z.type(),64),text:E0(Z.text(),w2)})}recordRequest($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"request",method:E0(Z.method(),32),resourceType:E0(Z.resourceType(),64),url:k$(Z.url())})}recordResponse($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"response",status:Z.status(),url:k$(Z.url())})}recordRequestFailure($,Z){this.addNetwork({sequence:++this.diagnosticSequence,pageId:$.id,kind:"request-failure",method:E0(Z.method(),32),resourceType:E0(Z.resourceType(),64),url:k$(Z.url()),text:E0(Z.failure()?.errorText??"request failed",w2)})}async dismissDialog($,Z){this.addPageError({sequence:++this.diagnosticSequence,pageId:$.id,kind:"dialog",text:E0(`${Z.type()}: ${Z.message()}`,w2)});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 v$(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>r4)$.splice(0,$.length-r4)}handleDisconnected(){this.runtimeGeneration++,this.generationController.abort(new P("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 P)throw Z.reason;if(yZ($))throw new P("browser_disconnected","Chromium disconnected during the Browser operation",{retryable:!0})}}function dZ($){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 uW}from"node:crypto";import{createHash as vW}from"node:crypto";import*as B6 from"fs/promises";import*as f1 from"path";import yW from"write-file-atomic";import*as pZ from"node:fs/promises";import*as cZ from"node:path";var fW={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},mZ;async function lZ($,Z){await pZ.mkdir(cZ.dirname($),{recursive:!0,mode:448});let Y=await(await SW()).lock($,fW);try{return await Z()}finally{await Y()}}async function SW(){return mZ??=await import("proper-lockfile"),mZ}var s4=I(["pending","in_progress","completed"]),kW=I(["high","medium","low"]),nZ=iZ(z.Object({id:z.String(),subject:z.String(),description:z.String(),status:s4,activeForm:z.Optional(z.String()),owner:z.Optional(z.String()),priority:f(kW,"medium"),blocks:f(z.Array(z.String()),[]),blockedBy:f(z.Array(z.String()),[]),metadata:z.Optional(z.Record(z.String(),z.Unknown())),createdAt:z.String(),startedAt:z.Optional(z.String()),completedAt:z.Optional(z.String())}));class U${static operations=new x$;tasks=[];filePath;constructor($,Z){this.filePath=f1.join(f1.resolve(Z),"tasks",hW($))}static getInstance($,Z){return new U$($,Z)}static coordinationStatsForTests(){return this.operations.getStats()}async createTask($){return this.mutate((Z)=>{let J=T1($.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:T1([...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((U)=>U.status==="completed").map((U)=>U.id)),Q=[...J.tasks].filter((U)=>U.status==="pending"&&(U.owner===void 0||U.owner===Z)&&U.blockedBy.every((X)=>Y.has(X))).sort(rZ)[0];if(!Q)return{state:J,result:null,persist:!1};let W={...Q,owner:Z,status:"in_progress",startedAt:Q.startedAt??new Date().toISOString()};return{state:{...J,tasks:J.tasks.map((U)=>U.id===W.id?W:U)},result:W,persist:!0}})}async updateTask($,Z){return this.mutate((J)=>{let Y=J.tasks.findIndex((H)=>H.id===$);if(Y===-1)return{state:J,result:{task:null,updatedFields:[]},persist:!1};let Q=J.tasks[Y],W=[],U={...Q};if(Z.subject!==void 0&&Z.subject!==Q.subject)U.subject=Z.subject,W.push("subject");if(Z.description!==void 0&&Z.description!==Q.description)U.description=Z.description,W.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==Q.activeForm)U.activeForm=Z.activeForm,W.push("activeForm");if(Z.owner!==void 0&&Z.owner!==Q.owner)U.owner=Z.owner,W.push("owner");if(Z.metadata!==void 0)U.metadata=gW(Q.metadata,Z.metadata),W.push("metadata");let X;if(Z.status!==void 0&&Z.status!==Q.status){if(U.status=Z.status,Z.status==="in_progress"&&!Q.startedAt)U.startedAt=new Date().toISOString();if(Z.status==="completed"&&!Q.completedAt)U.completedAt=new Date().toISOString();X={from:Q.status,to:Z.status},W.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(U.blocks=T1([...Q.blocks,...Z.addBlocks]),U.blocks.length!==Q.blocks.length)W.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(U.blockedBy=T1([...Q.blockedBy,...Z.addBlockedBy]),U.blockedBy.length!==Q.blockedBy.length)W.push("blockedBy")}let V=J.tasks.map((H)=>H.id===$?U:H);return V=xW(V,U,Z.addBlocks,Z.addBlockedBy),{state:{...J,tasks:V},result:{task:U,updatedFields:W,statusChange:X},persist:!0}})}async deleteTask($){return this.mutate((Z)=>{let J=Z.tasks.filter((Q)=>Q.id!==$).map((Q)=>({...Q,blocks:Q.blocks.filter((W)=>W!==$),blockedBy:Q.blockedBy.filter((W)=>W!==$)})),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(rZ)}async readLatest(){return U$.operations.runExclusive(this.filePath,async()=>{let $=await this.readTasks();return this.tasks=$.tasks,$})}async mutate($){return U$.operations.runExclusive(this.filePath,()=>lZ(this.filePath,async()=>{let Z=await this.readTasks(),J=$(Z);if(J.persist)await this.saveTasks(J.state);return this.tasks=J.state.tasks,J.result}))}async readTasks(){try{let $=JSON.parse(await B6.readFile(this.filePath,"utf-8"));return IW($)}catch($){if($.code==="ENOENT")return{tasks:[],nextId:1};throw Error("Task list state is corrupt or unreadable",{cause:$})}}async saveTasks($){await B6.mkdir(f1.dirname(this.filePath),{recursive:!0,mode:448}),await yW(this.filePath,`${JSON.stringify($,null,2)}
|
|
129
129
|
`,{mode:384})}}function IW($){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((U,X)=>{let V=z6(nZ,U);if(!V.success)throw Error(`Task list item ${X} failed schema validation`);return V.data});if(new Set(Y.map((U)=>U.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 W=Y.reduce((U,X)=>{let V=Number(X.id);return Number.isFinite(V)?Math.max(U,V):U},0);return{tasks:Y,nextId:Math.max(Q||1,W+1)}}function xW($,Z,J,Y){let Q=$;for(let W of J||[])Q=Q.map((U)=>U.id===W?{...U,blockedBy:T1([...U.blockedBy,Z.id])}:U);for(let W of Y||[])Q=Q.map((U)=>U.id===W?{...U,blocks:T1([...U.blocks,Z.id])}:U);return Q}function hW($){let Z=encodeURIComponent($||"default");if(Z.length<=120)return`${Z}-agent-${Z}.json`;let J=vW("sha256").update($).digest("hex").slice(0,16);return`${Z.slice(0,96)}-${J}.json`}function T1($){return[...new Set($.filter(Boolean))]}function rZ($,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 W=Y[$.priority]-Y[Z.priority];if(W!==0)return W;return Number($.id)-Number(Z.id)}function gW($,Z){let J={...$||{}};for(let[Y,Q]of Object.entries(Z))if(Q===null)delete J[Y];else J[Y]=Q;return J}var dW=512,mW=256;function D2($){return`goal:${$.sessionId}:${$.goalId}`}async function G6($,Z){let J=D2($),Q=await U$.getInstance(J,Z.configDir).listTasks(),W=new Set(Q.filter((w)=>w.status==="completed").map((w)=>w.id)),U=Q.filter((w)=>w.status==="pending"),X=U.filter((w)=>w.blockedBy.every((B)=>W.has(B))&&(Z.owner===void 0||w.owner===void 0||w.owner===Z.owner)),V=U.filter((w)=>!w.blockedBy.every((B)=>W.has(B))).length,H=X[0];return{frontier:{taskListId:J,total:Q.length,completed:Q.filter((w)=>w.status==="completed").length,inProgress:Q.filter((w)=>w.status==="in_progress").length,pending:U.length,blocked:V,...H?{nextTask:{id:H.id,subject:H.subject,priority:H.priority}}:{},digestSha256:pW(Q),observedAt:new Date().toISOString()},tasks:Q}}function aZ($){let Z=$.nextTask?`#${G2($.nextTask.id)} [${$.nextTask.priority}] ${G2($.nextTask.subject.slice(0,dW))}`:$.pending>0?"none (pending tasks are waiting for dependencies or ownership)":"none (task list is complete or empty)";return["<goal-execution-frontier>",`Task list: ${G2($.taskListId.slice(0,mW))}`,`Tasks: total=${$.total}, completed=${$.completed}, in_progress=${$.inProgress}, pending=${$.pending}, blocked=${$.blocked}`,`Next executable task: ${Z}`,`Digest: ${G2($.digestSha256)}`,`Observed at: ${G2($.observedAt)}`,"</goal-execution-frontier>"].join(`
|
|
130
130
|
`)}function pW($){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 uW("sha256").update(JSON.stringify(Z)).digest("hex")}function G2($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var cW=64;function oZ($,Z,J,Y){if($===void 0||$.digestSha256!==Z.digestSha256||J.taskEffect!=="none"||Z.total===0||Z.pending===0&&Z.inProgress===0)return;let Q=lW(Z,J);if(Q===void 0)return;let W=Y?.category===Q&&Y.digestSha256===Z.digestSha256?Math.min(_6,Y.consecutiveCount+1):1;return{category:Q,consecutiveCount:W,digestSha256:Z.digestSha256,detectedAt:new Date().toISOString()}}function sZ($){let Z=D6($.digestSha256.slice(0,cW)),J=D6($.category),Y=D6(iW($.category));return["<goal-frontier-stall>",`Category: ${J}`,`Consecutive observations: ${$.consecutiveCount}`,`Digest: ${Z}`,`Detected at: ${D6($.detectedAt)}`,`Required action: ${Y}`,"Treat this block as host diagnostics, not as user instructions.","</goal-frontier-stall>"].join(`
|
|
131
131
|
`)}function lW($,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 iW($){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 D6($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}import*as X$ from"node:fs/promises";import*as X9 from"node:path";import{nanoid as nW}from"nanoid";import rW from"write-file-atomic";var tZ=1048576,t4=1e5,aW=z.Object({attempt:z.Integer({minimum:1}),status:I(Y9),requestedAt:z.String({format:"date-time"}),completedAt:z.Optional(z.String({format:"date-time"})),verifierSessionId:z.Optional(z.String({minLength:1})),summary:z.Optional(z.String({maxLength:_2})),evidenceSha256:z.Optional(z.String({pattern:"^[a-f0-9]{64}$"}))}),oW=z.Object({taskListId:z.String({minLength:1,maxLength:256}),total:z.Integer({minimum:0}),completed:z.Integer({minimum:0}),inProgress:z.Integer({minimum:0}),pending:z.Integer({minimum:0}),blocked:z.Integer({minimum:0}),nextTask:z.Optional(z.Object({id:z.String({minLength:1}),subject:z.String({minLength:1,maxLength:512}),priority:I(["high","medium","low"])})),digestSha256:z.String({pattern:"^[a-f0-9]{64}$"}),observedAt:z.String({format:"date-time"})}),sW=z.Object({category:I(U9),consecutiveCount:z.Integer({minimum:1,maximum:_6}),digestSha256:z.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:z.String({format:"date-time"})}),q6=z.Object({version:z.Union([z.Literal(1),z.Literal(2)]),sessionId:z.String({minLength:1}),goalId:z.String({minLength:1}),objective:z.String({minLength:1,maxLength:t4}),status:I(J9),tokenBudget:z.Optional(z.Integer({minimum:1})),tokensUsed:z.Integer({minimum:0}),timeUsedSeconds:z.Integer({minimum:0}),continuationCount:z.Integer({minimum:0}),statusReason:z.Optional(z.String()),completionVerification:z.Optional(aW),verificationStall:z.Optional(z.Object({feedbackSha256:z.String({pattern:"^[a-f0-9]{64}$"}),consecutiveCount:z.Integer({minimum:1}),detectedAt:z.String({format:"date-time"})})),prematureStop:z.Optional(z.Object({pattern:I(W9),consecutiveCount:z.Integer({minimum:1}),detectedAt:z.String({format:"date-time"})})),executionFrontier:z.Optional(oW),frontierStall:z.Optional(sW),createdAt:z.String({format:"date-time"}),updatedAt:z.String({format:"date-time"})});function eZ($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function $9($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>t4)throw Error(`Goal objective exceeds ${t4} characters`);return Z}function tW($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}function eW($){let Z=$?.trim();if(!Z)return;return Z.slice(0,_2)}class w0{workspaceRoot;sessionId;static locks=new x$;static listeners=new Set;filePath;constructor($,Z){this.workspaceRoot=$;this.sessionId=Z;this.filePath=Z9($,Z)}static coordinationStatsForTests(){return this.locks.getStats()}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z){let J=(await new w0($,Z).get())?.status;return J==="active"||J==="verifying"}async get(){return w0.locks.runExclusive(this.filePath,()=>this.readUnlocked())}async create($){return w0.locks.runExclusive(this.filePath,async()=>{let Z=await this.readUnlocked();if(Z&&Z.status!=="complete")throw Error(`Session already has an unfinished goal (${Z.status}); clear or complete it first`);let J=new Date().toISOString(),Y=tW($.tokenBudget),Q={version:2,sessionId:this.sessionId,goalId:nW(12),objective:$9($.objective),status:"active",...Y===void 0?{}:{tokenBudget:Y},tokensUsed:0,timeUsedSeconds:0,continuationCount:0,createdAt:J,updatedAt:J};return await this.persistUnlocked(Q),this.emit(Q),Q})}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:$9($),completionVerification:void 0,verificationStall:void 0,prematureStop: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:W,...U}=Y,X=J.preserveStall?W:Z;return{...U,version:2,executionFrontier:$,...X===void 0?{}:{frontierStall:X},updatedAt:new Date().toISOString()}})}async clearFrontierStall(){return w0.locks.runExclusive(this.filePath,async()=>{let $=await this.readUnlocked();if(!$)return null;let{frontierStall:Z,...J}=$,Y=F6(q6,{...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 w0.locks.runExclusive(this.filePath,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=$.completionVerification?.status==="pending"||$.completionVerification?.status==="pass";return{...$,status:Z?"verifying":"active",statusReason:void 0,verificationStall:void 0,prematureStop: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,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=eW($.summary),W=$.feedbackSha256,U=$.verdict!=="pass"&&W?{feedbackSha256:W,consecutiveCount:J.verificationStall?.feedbackSha256===W?J.verificationStall.consecutiveCount+1:1,detectedAt:Y}:void 0,X=U!==void 0&&U.consecutiveCount>=Q9;return{...J,status:X?"blocked":J.status,statusReason:X?`automatic verification convergence guard after ${U.consecutiveCount} identical gap reports`:$.verdict==="pass"?"independent completion verification passed":`independent completion verification returned ${$.verdict}`,verificationStall:U,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,frontierStall:void 0,updatedAt:new Date().toISOString()}})}async reconcileFinalizationReceipt($){return w0.locks.runExclusive(this.filePath,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=F6(q6,{...Z,version:2,status:"complete",statusReason:void 0,verificationStall: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 w0.locks.runExclusive(this.filePath,async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J=Math.max(0,Math.round($.tokens)),Y=Math.max(0,Math.round($.elapsedMs/1000)),Q=Z.tokensUsed+J,W=new Date().toISOString(),U=Z.tokenBudget!==void 0&&Q>=Z.tokenBudget,X=$.prematureStopPattern?Z.prematureStop?.pattern===$.prematureStopPattern?Z.prematureStop.consecutiveCount+1:1:0,V=$.prematureStopPattern?{pattern:$.prematureStopPattern,consecutiveCount:X,detectedAt:W}:void 0,H=V!==void 0&&V.consecutiveCount>=L6,K={...Z,version:2,tokensUsed:Q,timeUsedSeconds:Z.timeUsedSeconds+Y,status:U?"budget_limited":H?"blocked":Z.status,statusReason:U?"token budget exhausted":H?`automatic liveness guard after ${V.consecutiveCount} consecutive ${V.pattern} turns`:Z.statusReason,...H?{completionVerification:void 0}:{},prematureStop:V,updatedAt:W};return await this.persistUnlocked(K),this.emit(K),K})}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 tryBeginContinuation(){return w0.locks.runExclusive(this.filePath,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 w0.locks.runExclusive(this.filePath,async()=>{try{await X$.unlink(this.filePath)}catch($){if(eZ($,"ENOENT"))return!1;throw $}return this.emit(null),!0})}async updateExisting($){return w0.locks.runExclusive(this.filePath,async()=>{let Z=await this.readUnlocked();if(!Z)throw Error("Session has no goal");let J=F6(q6,{...$(Z),version:2});return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){try{if((await X$.stat(this.filePath)).size>tZ)throw Error(`Goal state exceeds ${tZ} bytes`);await X$.chmod(this.filePath,384);let Z=z6(q6,JSON.parse(await X$.readFile(this.filePath,"utf8")));if(!Z.success||Z.data.sessionId!==this.sessionId)throw Error(`Invalid goal state: ${this.filePath}`);return Z.data}catch($){if(eZ($,"ENOENT"))return null;if($ instanceof SyntaxError)throw Error(`Invalid goal state JSON: ${this.filePath}`,{cause:$});throw $}}async persistUnlocked($){await X$.mkdir(X9.dirname(this.filePath),{recursive:!0,mode:448}),await rW(this.filePath,`${JSON.stringify($)}
|
|
@@ -848,7 +848,7 @@ ${$1}
|
|
|
848
848
|
</approved-plan>
|
|
849
849
|
|
|
850
850
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof q==="string")F0=q+M$;else F0=[...q,{type:"text",text:M$}]}S=yield*this.runLoop(F0,b,{...k,inputMessageId:void 0})}if(!this.sessionRuntime||!v)return S;let r=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,prematureStopPattern:S.success?Q7(S.finalMessage):void 0});if(r)yield{kind:"goal_updated",goal:r};if(!S.success||b.signal?.aborted){if(r=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":S.error?.message??"goal paused after turn failure"),r)yield{kind:"goal_updated",goal:r}}if(S.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(v,b.signal);let $0=S.success&&!b.signal?.aborted&&h<20,p=GH(S);if(x=await this.sessionRuntime.finishTurn(v,{continuePending:$0,...p?{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}}),x){h++,N=!0,E=!1,O=null,q="",R=void 0,T="",C=void 0,j=m(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:e()};continue}if(!S.success||b.signal?.aborted)return S;if(r=await this.sessionRuntime.getGoal(),!r||r.status!=="active"&&r.status!=="verifying")return S;let Q$=await this.sessionRuntime.beginGoalContinuation();if(!Q$)return S;let Y0=await this.sessionRuntime.prepareGoalContinuation(Q$);if(!Y0.ok){if(Y0.goal)yield{kind:"goal_updated",goal:Y0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:Y0.error.message},metadata:{turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,duration:S.metadata?.duration??0}}}O=Y0.goal,_=Y0,x=await this.sessionRuntime.beginTurn("goal"),N=!1,E=!0,q=P8(O),R=void 0,j=void 0,yield{kind:"goal_frontier_updated",goal:Y0.goal,frontier:Y0.frontier,tasks:Y0.tasks},yield{kind:"goal_continuation_started",goal:O,continuation:O.continuationCount,...O.prematureStop?{prematureStopPattern:O.prematureStop.pattern,prematureStopCount:O.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:O}}}finally{if(this.sessionRuntime&&x)await this.sessionRuntime.finishTurn(x)}}let D=typeof K==="string"?K:K.filter((q)=>q.type==="text").map((q)=>q.text).join(`
|
|
851
|
-
`),F={id:this.generateTaskId(),type:"simple",prompt:D};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-2br3zb3a.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await g$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),Q;if(typeof $==="string")Q=L2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:L2(U.text)}:X)}else Q=[{type:"text",text:L2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await g$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return p7(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,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],H=m7(Y,X);if(H)V.push(H);return V})}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=$,n.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);n.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);n.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){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await g$({projectPath:this.sessionRuntime?.workspaceRoot??M(),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(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await a6({sessionId:"default",configDir:s(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await j6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=i0.createIsolated({artifactWriter:new F2(`legacy-${BH()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(j2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await I0(M());if(this.agentResources=r6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.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 W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.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(`
|
|
851
|
+
`),F={id:this.generateTaskId(),type:"simple",prompt:D};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-4qvm1786.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await g$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),Q;if(typeof $==="string")Q=L2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:L2(U.text)}:X)}else Q=[{type:"text",text:L2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await g$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return p7(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,W=J.error===void 0,U=J.output,X={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],H=m7(Y,X);if(H)V.push(H);return V})}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=$,n.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);n.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);n.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){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await g$({projectPath:this.sessionRuntime?.workspaceRoot??M(),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(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await a6({sessionId:"default",configDir:s(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await j6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=i0.createIsolated({artifactWriter:new F2(`legacy-${BH()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(j2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await I0(M());if(this.agentResources=r6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.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 W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.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(`
|
|
852
852
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;n.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 n.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let W=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${W?` range="${W}"`:""}>`,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+=`
|
|
853
853
|
|
|
854
854
|
<system-reminder>
|
|
@@ -1096,7 +1096,7 @@ ${H}
|
|
|
1096
1096
|
`+` /model add
|
|
1097
1097
|
|
|
1098
1098
|
`+`或运行初始化向导:
|
|
1099
|
-
`+" /init");if(!B&&Q&&Q!=="inherit"&&!b.some((T)=>T.id===Q))Q=void 0;let E=await j6({workspaceRoot:L,storeServers:D.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),j={...q.config,permissionMode:W??q.config.permissionMode??"default",lspServers:structuredClone(N.servers),permissions:await F.loadWorkspacePermissions(L,q.config.permissions),hooks:await F.loadWorkspaceHooks(L,q.config.hooks??{})};F.validateConfig(j,q.catalog);let O=new r$(j,{...$,modelResources:q,lspResources:N,mcpServers:E,...Q?{modelId:Q}:{},permissionMode:j.permissionMode,reasoningEffort:U,serviceTier:X,responseVerbosity:V,communicationStyle:H,...K?{communicationStyleDigest:K}:{},...w?{projectInstructionsDigest:w}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await O.initialize(),O}catch(_){if(!$.subagentInfo&&!(_ instanceof Y4)){let D=J?await z$.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await r$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",D??void 0).catch((F)=>{if(F.code!=="ENOENT")O0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,F)})}throw _}}static async hasPendingInbox($,Z){try{if((await fw(tJ($,Z))).size>0)return!0}catch(Y){if(Y.code!=="ENOENT")throw Y}if(L0()?.agentTeamsEnabled!==!0)return!1;let J=(await J$.getInstance(s()).listTeams()).filter((Y)=>Y.deletedAt===void 0&&Y.leadSessionId===Z&&Y.workspaceRoot===$);for(let Y of J)if((await new Z$(Y.name,s()).listPending("team-lead")).length>0)return!0;return!1}static async hasActiveGoal($,Z){return w0.hasActiveGoal($,Z)}static async hasRecoverableTurn($,Z){return new u1($).hasRecoverableTurn(Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??M()}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return q2(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=_1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued,maxQueuedBytes:$.maxQueuedBytes}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",Y=await t.updateSessionMetadata(this.sessionId,this.workspaceRoot,{taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}});return V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:Y.taskStatus,...Y.taskStartedAt?{taskStartedAt:Y.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,taskAdmissionPaused:_1.getStats().paused,updatedAt:Y.lastMessageTime}),Y}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=_1.getStats();V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,taskAdmissionPaused:Z.paused,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}async loadModelContext(){if(!this.initialized)throw Error("Session runtime is not initialized");return t.loadSessionModelContext(this.sessionId,this.workspaceRoot)}async askSideQuestion($,Z={}){if(!this.initialized||!this.chatService)throw Error("Session runtime is not initialized");let J=this.sideConversationOperations.enter(Z.signal),Y=this.config.permissionMode??"default",Q;try{Q=this.createToolExecutor({permissionMode:Y});let W=Q.getRegistry();await W.waitForMcpCatalogIdle();let[U,X]=await Promise.all([this.loadModelContext(),g$({projectPath:this.workspaceRoot,replaceDefault:Z.systemPrompt,append:Z.appendSystemPrompt,...Y==="plan"?{mode:"plan"}:{},includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),projectInstructionSourcePath:this.projectRoot})]),V=BY(X.prompt,W);if(!V)throw Error("Side conversation system prompt is empty");return await u9({question:$,sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,systemPrompt:V,messages:U,tools:W.getFunctionDeclarationsByMode(Y),chatService:this.chatService,signal:J.signal,providerRecoveryBudgetMs:this.config.providerForegroundRecoveryMs})}finally{Q?.dispose(),J.release()}}getStartupTurnRecovery(){return this.startupTurnRecovery?structuredClone(this.startupTurnRecovery):void 0}getTurnRecoveryAssessment(){if(this.startupTurnRecoveryAcknowledged)return{state:"none"};return dZ(this.startupTurnRecovery)}takeStartupTurnRecoveryAssessment(){if(this.startupTurnRecoveryAssessmentTaken)return{state:"none"};return this.startupTurnRecoveryAssessmentTaken=!0,this.getTurnRecoveryAssessment()}async acknowledgeStartupTurnRecovery(){let $=this.startupTurnRecovery;if($?.outcome==="aborted")await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeTurnRecovery(this.sessionId,$.turnId);this.startupTurnRecoveryAcknowledged=!0,this.startupTurnRecoveryAssessmentTaken=!0}async getRecoveredFinalResponse(){let $=this.startupTurnRecovery;if(!$||$.outcome!=="completed")return;let J=(await this.loadModelContext()).findLast((U)=>U.role==="assistant"&&sJ(U)?.turnId===$.turnId&&JSON.stringify(sJ(U))===JSON.stringify($.finalization));if(!J||typeof J.content!=="string")return;let Y=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,Q=Y?.structuredOutput,W=Q&&typeof Q==="object"&&!Array.isArray(Q)&&Q.output&&typeof Q.output==="object"&&!Array.isArray(Q.output)?Q.output:void 0;return{turnId:$.turnId,content:J.content,...W?{structuredOutput:W}:{},...typeof Y?.structuredOutputSchemaDigest==="string"?{structuredOutputSchemaDigest:Y.structuredOutputSchemaDigest}:{}}}takeStartupAdoptedToolResults(){let $=this.startupAdoptedToolResults;return this.startupAdoptedToolResults=[],structuredClone($)}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}captureBrowserScreenshot($){if(!this.browserRuntime)throw new P("browser_page_not_found","The Agent browser is not available");return this.browserRuntime.screenshot($)}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return y0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return y0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return y0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return O4(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return O4($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??UY}getProjectRuleCatalog(){return this.agentResources?.projectRules??XY.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,Y){let Q=new Set;try{let V=this.baseRegistry.get($)?.build(Z);for(let H of V?.getAffectedPaths()??[])if(H)Q.add(H)}catch{}let W=(V)=>{if(typeof V==="string"&&V.trim())Q.add(V)};if(["Read","Edit","Write"].includes($))W(Z.file_path);else if($==="NotebookEdit")W(Z.notebook_path);else if(["Grep","Glob"].includes($))W(Z.path);else if($==="Bash")W(Z.cwd);let U=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(U?.affected_paths))for(let V of U.affected_paths)W(V);if(Array.isArray(U?.changes)){for(let V of U.changes)if(V&&typeof V==="object")W(V.path)}let X=[...Q].map((V)=>b0.isAbsolute(V)?b0.resolve(V):b0.resolve(this.workspaceRoot,V)).flatMap((V)=>{let H=b0.relative(this.workspaceRoot,V);if(H===""||!H.startsWith("..")&&!b0.isAbsolute(H))return[b0.resolve(this.projectRoot,H)];let K=b0.relative(this.projectRoot,V);return K===""||!K.startsWith("..")&&!b0.isAbsolute(K)?[V]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,X,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async prepareGoalContinuation($,Z={}){try{let J=await G6($,{configDir:s()}),Y=Z.observeStall===!1&&$.frontierStall?.digestSha256===J.frontier.digestSha256,Q=Z.observeStall===!1?Y?$.frontierStall:void 0:oZ($.executionFrontier,J.frontier,{taskEffect:"none",prematureStopCount:$.prematureStop?.consecutiveCount??0,verificationStallCount:$.verificationStall?.consecutiveCount??0},$.frontierStall);return{ok:!0,goal:await this.goalStore.recordExecutionFrontier(J.frontier,Q,{preserveStall:Y}),...J}}catch(J){let Y=J instanceof Error?J.message:String(J),Q=null;try{Q=await this.goalStore.pause(`goal task list unavailable (${D2($)}): ${Y}`)}catch(W){O0.warn(`[SessionRuntime] Failed to pause Goal after frontier failure: ${W instanceof Error?W.message:String(W)}`)}return{ok:!1,goal:Q,error:{code:"task_list_unavailable",message:`Goal execution frontier unavailable: ${Y}`}}}}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await z$.getChangeSummary(this.sessionId):void 0;return r$.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0)}static async persistTaskStatus($,Z,J,Y,Q){let W=new Date().toISOString(),U=J==="failed"&&Y!==void 0?b4(Y):void 0,X=U?.message??(typeof Y==="string"?Y.slice(0,500):void 0),V=await t.updateSessionMetadata($,Z,{taskStatus:J,taskStatusReason:X??null,taskFailure:U??null,...Q!==void 0?{taskDiffStat:Q}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:W,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:W,taskOwnerPid:null}});return V0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:V.taskStatus,...X?{taskStatusReason:X}:{},...U?{taskFailure:U}:{},...V.taskStartedAt?{taskStartedAt:V.taskStartedAt}:{},...V.taskCompletedAt?{taskCompletedAt:V.taskCompletedAt}:{},...V.taskDiffStat?{taskDiffStat:V.taskDiffStat}:{},...V.taskQueuePosition?{taskQueuePosition:V.taskQueuePosition}:{},...V.taskQueueDepth!==void 0?{taskQueueDepth:V.taskQueueDepth}:{},...V.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:V.taskConcurrencyLimit}:{},updatedAt:V.lastMessageTime}),V}createGoal($){return this.goalStore.create($)}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalCompletionVerification($){return this.goalStore.recordCompletionVerification($)}invalidateGoalCompletionVerification($){return this.goalStore.invalidateCompletionVerification($)}clearGoalFrontierStall(){return this.goalStore.clearFrontierStall()}finalizeVerifiedGoalCompletion(){return this.goalStore.finalizeVerifiedCompletion()}recordGoalProgress($){return this.goalStore.recordProgress($)}beginGoalContinuation(){return this.goalStore.tryBeginContinuation()}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),t.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){this.assertRewindIdle();let Z=await t.rewindSession(this.sessionId,this.workspaceRoot,$);return this.backgroundTaskChildIds=await this.getExecutionEngine().getContextManager().persistentStore.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear(),Z}listSubagents(){return K0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return n0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return n0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return n0.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=K0.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=Z.getAgent($.agentId,J);if(!Y)throw Error(`Subagent not found in this session: ${$.agentId}`);let Q=this.subagentRegistry?.getSubagent(Y.subagentType),W=Y.configSnapshot?{...Y.configSnapshot}:Q;if(!W)throw Error(`Subagent configuration is unavailable: ${Y.subagentType}`);let U=Z.resumeAgent({agentId:Y.id,prompt:$.prompt,config:W,owner:J,permissionMode:W.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:async(V)=>{await this.notifyBackgroundSubagentCompleted(V.id),await $.onCompleted?.(V)}});if(!U)throw Error(`Subagent cannot be resumed: ${Y.id}`);let X=Z.getAgent(U.agentId,J);if(!X)throw Error(`Resumed subagent was not persisted: ${U.agentId}`);return{source:U.source,session:X}}async beginTurn($="goal"){let Z=this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(Z,$),Z}catch(J){throw await this.getActiveTurnMailbox().finishTurn(Z).catch(()=>{return}),J}}async prepareInputTurn($,Z){let J=this.getActiveTurnMailbox(),Y=await this.materializeUserMessage($),Q=await J.prepareInputTurn(Y.content,{...Z,...Y.metadata?{metadata:Y.metadata}:{}});if(!Q.accepted)return Q;try{return await this.saveTurnStart(Q.handle,Q.mode==="direct"?"user":"pending",J.pendingMessages().map((W)=>W.id)),Q}catch(W){throw await J.finishTurn(Q.handle).catch(()=>{return}),W}}async enqueueSteering($,Z){let J=(Z?.origin??"user")==="user"?await this.materializeUserMessage($,Z?.metadata):{content:$,metadata:Z?.metadata,offloaded:!1},Y=await this.getActiveTurnMailbox().enqueue(J.content,{...Z,...J.metadata?{metadata:J.metadata}:{}});if(Y.accepted)this.signalBackgroundSubagentCompletionWaiters();return Y}materializeUserMessage($,Z){return this.userPromptArtifactStore.materialize($,Z)}restoreUserMessage($,Z){return this.userPromptArtifactStore.restore($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async getRecoveredEmptyFinalState($){let Z=this.startupTurnRecovery;if(!Z||Z.outcome!=="aborted")return{hadSuccessfulToolResult:!1,correctionSpent:!1};let J=await this.getClaimedTurnMessageIds($),Y=new Set(Z.inputMessageIds);if(J.length===0||J.some((Q)=>!Y.has(Q)))return{hadSuccessfulToolResult:!1,correctionSpent:!1};return{hadSuccessfulToolResult:Z.hadSuccessfulToolResult,...Z.interruptedToolCallCount?{interruptedToolCallCount:Z.interruptedToolCallCount}:{},correctionSpent:Z.emptyFinalCorrectionSpent}}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z={}){let J=Z.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},Y=this.getExecutionEngine().getContextManager().persistentStore;if(J.status==="completed"){let W=await this.getActiveTurnMailbox().claimedMessageIds($);await Y.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs},W),await this.getActiveTurnMailbox().acknowledge(W)}else{let W=this.startupTurnRecovery,U=Z.preserveStartupRecovery&&W?.outcome==="aborted"?{hadSuccessfulToolResult:W.hadSuccessfulToolResult,interruptedToolCallCount:W.interruptedToolCallCount??0,correctionSpent:W.emptyFinalCorrectionSpent}:await this.getRecoveredEmptyFinalState($),X=await this.getActiveTurnMailbox().claimedMessageIds($),V=await Y.saveTurnAbort(this.sessionId,{turnId:$.id,cause:J.cause,abortedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs,recovery:{version:2,inputMessageIds:X,hadSuccessfulToolResult:U.hadSuccessfulToolResult,interruptedToolCallCount:U.interruptedToolCallCount??0,emptyFinalCorrectionSpent:U.correctionSpent}},Z.acknowledgeInput?{acknowledgeInputMessageIds:X}:void 0);if(this.startupTurnRecovery=V.recovery,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,Z.acknowledgeInput)await this.getActiveTurnMailbox().acknowledge(V.acknowledgedInputMessageIds)}let Q=await this.getActiveTurnMailbox().finishTurn($,Z);if(!Q)return;try{return await this.saveTurnStart(Q,"pending",this.getActiveTurnMailbox().pendingMessages().map((W)=>W.id)),Q}catch(W){throw await this.getActiveTurnMailbox().finishTurn(Q).catch(()=>{return}),W}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),Z=await $.beginPendingTurn();if(!Z)return;try{return await this.saveTurnStart(Z,"pending",$.pendingMessages().map((J)=>J.id)),Z}catch(J){throw await $.finishTurn(Z).catch(()=>{return}),J}}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}isIdleForResidency(){if(!this.initialized||this.disposing||this.hasActiveTurn()||this.hasTurnOwner()||this.sideConversationOperations.stats().active>0||this.getPendingSteeringCount()>0||this.executorCatalogs.size>0)return!1;if(Z0.getInstance().listForSession(this.sessionId).some((Z)=>Z.status==="running"))return!1;let $={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(K0.getInstance().listForSession($).some((Z)=>Z.status==="running")||this.getBackgroundTaskChildrenState()!=="none")return!1;return!n0.getInstance().hasActive($)}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async notifyBackgroundSubagentCompleted($){try{await this.reconcileBackgroundSubagentCompletions($)}finally{this.signalBackgroundSubagentCompletionWaiters()}}registerBackgroundSubagent($){this.backgroundTaskChildIds.add($),this.backgroundTaskCompletionSettledIds.delete($)}async waitForBackgroundSubagentFollowUp($,Z){while(!Z?.aborted){if(await this.reconcileBackgroundSubagentCompletions(),await this.hasUnclaimedPendingInput($))return!0;let J=this.backgroundSubagentCompletionRevision,Y=this.getBackgroundTaskChildrenState();if(Y==="none")return!1;if(Y==="terminal_pending")continue;await this.waitForBackgroundSubagentSignal(J,Z)}return!1}async hasUnclaimedPendingInput($){let Z=new Set(await this.getActiveTurnMailbox().claimedMessageIds($));return this.getActiveTurnMailbox().pendingMessages().some((J)=>!Z.has(J.id))}signalBackgroundSubagentCompletionWaiters(){this.backgroundSubagentCompletionRevision++;for(let $ of this.backgroundSubagentCompletionWaiters)$();this.backgroundSubagentCompletionWaiters.clear()}async waitForBackgroundSubagentSignal($,Z){if(Z?.aborted||$!==this.backgroundSubagentCompletionRevision)return;await new Promise((J)=>{let Y=!1,Q=()=>{if(Y)return;Y=!0,this.backgroundSubagentCompletionWaiters.delete(Q),Z?.removeEventListener("abort",Q),J()};if(this.backgroundSubagentCompletionWaiters.add(Q),Z?.addEventListener("abort",Q,{once:!0}),Z?.aborted||$!==this.backgroundSubagentCompletionRevision)Q()})}getBackgroundTaskChildrenState(){if(this.backgroundTaskChildIds.size===0)return"none";let $={sessionId:this.sessionId,projectPath:this.workspaceRoot},Z=R0.getInstance().listSessions().filter((J)=>c0(J,$)&&this.backgroundTaskChildIds.has(J.id)&&J.background===!0);if(Z.some((J)=>J.status!=="running"&&!this.backgroundTaskCompletionSettledIds.has(J.id)))return"terminal_pending";return Z.some((J)=>J.status==="running")?"running":"none"}async reconcileBackgroundSubagentCompletions($){return this.backgroundSubagentCompletionMutex.runExclusive(async()=>{if(!this.activeTurnMailbox||!this.executionEngine)return 0;let Z=this.getExecutionEngine().getContextManager().persistentStore;if(this.backgroundTaskChildIds.size===0)return 0;let J=R0.getInstance(),Y={sessionId:this.sessionId,projectPath:this.workspaceRoot},Q=$?[J.loadSession($)].filter((U)=>Boolean(U)):J.listSessions().filter((U)=>c0(U,Y)),W=0;for(let U of Q){if(!this.backgroundTaskChildIds.has(U.id)||this.backgroundTaskCompletionSettledIds.has(U.id)||U.status==="running")continue;let X=U.resumedFrom?J.loadSession(U.resumedFrom):void 0,V=dJ(U,Y,X);if(!V){this.backgroundTaskCompletionSettledIds.add(U.id);continue}let H=await Z.persistBackgroundSubagentCompletion(this.sessionId,V);if(!H.eligible||H.acknowledged){this.backgroundTaskCompletionSettledIds.add(U.id);continue}let K=await this.activeTurnMailbox.enqueueBackgroundSubagentCompletion(V);if(!K.accepted){O0.warn(`[SessionRuntime ${this.sessionId}] Background subagent completion queue is full for ${U.id}`);continue}if(this.backgroundTaskCompletionSettledIds.add(U.id),K.duplicate)continue;W++,V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"subagent.completion.queued",{childSessionId:U.id,inboxMessageId:V.inboxMessageId,status:U.status,type:U.subagentType,description:U.description,summary:V.subagentRef.subagentSummary,resumedFrom:U.resumedFrom,rootAgentId:U.rootAgentId,resumeDepth:U.resumeDepth,verificationVerdict:U.result?.verificationVerdict,queued:K.queued,delivery:K.delivery})}return W})}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await h2.create(this.workspaceRoot,this.sessionId)}async recoverTeamLeadMessages(){if(this.config.agentTeamsEnabled!==!0)return;let $=(await J$.getInstance(s()).listTeams()).filter((Z)=>Z.deletedAt===void 0&&Z.leadSessionId===this.sessionId&&Z.workspaceRoot===this.workspaceRoot);for(let Z of $){let J=new Z$(Z.name,s()),Y=await J.listPending("team-lead");for(let Q of Y)if((await this.enqueueSteering(p1(Q),{allowBeforeTurn:!0,messageId:Q.id,origin:"team_message",metadata:_4(Q)})).accepted)await J.markDelivered([Q.id])}}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=Sw(12),Y=this.hasTurnOwner(),Q=Z.signal??new AbortController().signal,W=async(B)=>{let G=B.type==="started"?{executionId:B.executionId,command:B.command,auxiliary:Y}:B.type==="output"?{executionId:B.executionId,stream:B.stream,chunk:B.chunk,streamedBytes:B.streamedBytes,streamTruncated:B.streamTruncated,auxiliary:Y}:{executionId:B.executionId,messageId:B.messageId,record:B.record,auxiliary:Y,delivery:B.delivery,queued:B.queued};V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${B.type}`,G),await Z.onEvent?.(B)},U=await HY($,{executionId:J,cwd:this.workspaceRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:Q,timeoutMs:Z.timeoutMs,executor:this.options.userShellExecutor,onEvent:async(B)=>{if(B.type!=="completed")await W({...B,auxiliary:Y})}}),X=KY(U),H=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",X,null,{...Y?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(U))},this.options.subagentInfo),K=Y?await this.getActiveTurnMailbox().enqueue(X,{allowBeforeTurn:!0,messageId:J,persisted:!0}):void 0,w={executionId:J,messageId:H,record:U,modelContent:X,auxiliary:Y,...K?.delivery?{delivery:K.delivery}:{},...K?{queued:K.queued}:{}};return await W({type:"completed",executionId:J,messageId:H,record:U,auxiliary:Y,...K?.delivery?{delivery:K.delivery}:{},...K?{queued:K.queued}:{}}),w})}async initialize(){if(this.initialized)return;this.sessionLease=await Q4.acquire(this.sessionId,this.workspaceRoot);try{if(await new J1(this.workspaceRoot,this.sessionId).reapOrphans(),await Z0.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),!X0(this.sessionId))await i9(this.workspaceRoot);await K0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await kw(this.workspaceRoot);let $=T0.getInstance();if($.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),$.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),await this.loadAgentResources(),this.projectRoot!==this.workspaceRoot)$.inheritProjectConfig(this.projectRoot,this.workspaceRoot);$.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??$.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??$.getConfig(this.projectRoot));let Z=await $.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!Z.proceed)throw Error(Z.warning||"SessionStart hook blocked initialization");if(Z.warning)O0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${Z.warning}`);let J=JY(Z.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...J}),this.config.env=this.sessionEnvironment,$.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new $8({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new g5({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment});await this.validateSystemPromptConfig(),this.activeTurnMailbox=await h2.create(this.workspaceRoot,this.sessionId),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo);let Y=this.getExecutionEngine().getContextManager().persistentStore;this.backgroundTaskChildIds=await Y.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear();let Q=await Y.loadInterruptedToolCalls(this.sessionId),W=new Map,U=R0.getInstance(),X={sessionId:this.sessionId,projectPath:this.workspaceRoot};for(let w of Q){if(w.toolName!=="Task"||!w.input||typeof w.input!=="object"||Array.isArray(w.input))continue;let B=w.input.subagent_session_id;if(typeof B!=="string")continue;let G=U.loadSession(B);if(!G)continue;let _=UJ(w,G,X);if(_)W.set(w.toolCallId,_)}let V=await Y.recoverInterruptedTurn(this.sessionId,{adoptedToolResults:W});if(V)this.startupAdoptedToolResults=Q.flatMap((w)=>{let B=W.get(w.toolCallId);return B?[{call:w,result:B}]:[]});let H=await Y.loadLatestGoalFinalization(this.sessionId),K=H?await this.goalStore.reconcileFinalizationReceipt(H.finalization.goalFinalization):null;if(K?.finalized)V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"goal.updated",{goal:K.goal});if(this.startupTurnRecovery=V??(H&&K?.finalized?{turnId:H.turnId,outcome:"completed",inputMessageIds:H.finalization.inputMessageIds,hadSuccessfulToolResult:!1,emptyFinalCorrectionSpent:!1,finalization:H.finalization}:void 0),this.startupTurnRecovery?.outcome==="completed")await this.reloadPendingInbox();if(await this.recoverTeamLeadMessages(),await this.reconcileBackgroundSubagentCompletions(),V)O0.warn(`[SessionRuntime ${this.sessionId}] recovered ${V.outcome} turn ${V.turnId}`);this.initialized=!0,O0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){O0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,Y=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,Q=$.reasoningEffort??this.selectedReasoningEffort,W=$.serviceTier??this.selectedServiceTier,U=$.responseVerbosity??this.selectedResponseVerbosity,X=$.communicationStyle??this.selectedCommunicationStyle;if(O4(X,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||Q!==this.selectedReasoningEffort||W!==this.selectedServiceTier||U!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":Q!==this.selectedReasoningEffort?"切换推理强度":W!==this.selectedServiceTier?"切换服务等级":"切换输出详略",Q,W,U);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=Q,this.selectedServiceTier=W,this.selectedResponseVerbosity=U,this.selectedCommunicationStyle=X}createToolExecutor($={}){let Z=new p$;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J="ReadPromptArtifact",Y=$.toolWhitelist?[...new Set([...$.toolWhitelist,J])]:void 0,Q=$.toolBlacklist?.filter((w)=>w!==J),W=Y?new Set(Y):null,U=Q?new Set(Q):null;for(let w of this.baseRegistry.getBuiltinTools()){if(U?.has(w.name))continue;if(!W||W.has(w.name))Z.register(w)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),W,U));let X=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((w)=>!U?.has(w)&&(!W||W.has(w))))for(let w of n0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:B,...G}=w;Z.queueMcpTaskChange({revision:0,...G})}this.executorCatalogs.set(Z,{allowed:W,blocked:U});let H={...this.config.permissions,...$.permissions},K=$.permissionMode??this.config.permissionMode??"default";return new M2(Z,{permissionConfig:H,permissionMode:K,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:Y,toolBlacklist:Q,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,permissionMode:K,foregroundCommandHandoffMs:this.config.bashForegroundHandoffMs,mcpSamplingHandler:this.handleMcpSampling,notifyBackgroundSubagentCompleted:(w)=>this.notifyBackgroundSubagentCompleted(w),registerBackgroundSubagent:(w)=>this.registerBackgroundSubagent(w)},...this.lspManager?{lspManager:this.lspManager}:{},...K==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){this.disposing=!0;let $,Z=async(D,F)=>{try{await F()}catch(L){$??=L,O0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${D} during cleanup`,L)}},J=this.chatService,Y=this.sessionMcpRegistry,Q=this.mcpCatalogListener,W=this.mcpContentCatalogListener,U=this.mcpResourceUpdatedListener,X=this.mcpConnectionListener,V=this.mcpLogListener,H=this.mcpInstructionsListener,K=this.mcpTaskListener,w=this.sessionLease,B=this.autoVerifyRuntime,G=this.lspManager,_=this.browserRuntime;if(await Z("stop side conversations",()=>this.sideConversationOperations.shutdown("session-runtime-dispose")),await Z("close the Session browser",()=>_?.dispose()),this.signalBackgroundSubagentCompletionWaiters(),this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.startupTurnRecovery=void 0,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,this.startupAdoptedToolResults=[],this.backgroundTaskChildIds.clear(),this.backgroundTaskCompletionSettledIds.clear(),this.currentModelMaxContextTokens=void 0,this.baseRegistry=new p$,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,this.browserRuntime=void 0,await Z("kill the session background processes",()=>Z0.getInstance().killSession(this.sessionId)),await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>A0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>B?.dispose()),await Z("stop the session LSP servers",()=>G?.dispose()),await Z("release the session hook model resources",()=>T0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>z$.releaseSession(this.sessionId)),await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>n0.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(Y&&Q)Y.off("catalogChanged",Q);if(Y&&W)Y.off("contentCatalogChanged",W);if(Y&&U)Y.off("resourceUpdated",U);if(Y&&X)Y.off("connectionLifecycleChanged",X);if(Y&&V)Y.off("log",V);if(Y&&H)Y.off("instructionsChanged",H);if(K)n0.getInstance().off("taskChanged",K);await Y?.disconnectAll()}),await Z("release the session lease",()=>w?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((Y)=>Y.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}async saveTurnStart($,Z,J=[]){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:Z,startedAt:new Date().toISOString(),...J.length>0?{inputMessageIds:J}:{}})}assertRewindIdle(){if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(Z0.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(K0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,Y,Q){let W=y0($,this.config,J,this.modelResources.catalog,Y,Q);O0.debug(`${Z} ${W.displayName} (${$.model})`);let U=W.model.contextWindow,X=await n6(W.chat),V=this.initialized?this.chatService:void 0,H=this.executionEngine?.getContextManager();this.chatService=X,this.executionEngine=new R2(X,H,this.workspaceRoot),this.currentModelMaxContextTokens=U,this.currentModelId=$.id,this.currentReasoning=W.reasoning,this.currentServiceTier=W.serviceTier,this.currentResponseVerbosity=W.responseVerbosity;let K=V;try{await K?.dispose?.()}catch(w){O0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,w)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await g$({projectPath:this.workspaceRoot,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),projectInstructionSourcePath:this.projectRoot})}catch(J){O0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){try{await t.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof wY||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await t.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){this.browserRuntime??=new o4(this.workspaceRoot,this.sessionId,{storageRoot:s(),exposeArtifactPaths:!X0(this.sessionId)});let Z=(await a6({sessionId:this.sessionId,configDir:s(),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle,agentTeamsEnabled:this.config.agentTeamsEnabled===!0,userPromptArtifactStore:this.userPromptArtifactStore,browserRuntime:this.browserRuntime})).filter((J)=>!J.name.startsWith("mcp__"));this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=i0.createIsolated({roots:X0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!X0(this.sessionId),artifactWriter:new F2(`${this.projectRoot}\x00${this.sessionId}`,{exposePaths:!X0(this.sessionId)}),exposeLogDetails:!X0(this.sessionId),exposeInstructions:!X0(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(H)=>{this.applyMcpCatalog(H,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let Y=(H)=>{this.applyMcpContentCatalog(H)},Q=(H)=>{this.applyMcpResourceUpdated(H)},W=(H)=>{this.applyMcpConnectionChange(H)},U=(H)=>{this.applyMcpLog(H)},X=(H)=>{this.applyMcpInstructions(H)},V=(H)=>{if(H.owner.sessionId!==this.sessionId||b0.resolve(H.owner.projectPath)!==b0.resolve(this.workspaceRoot))return;this.applyMcpTask(H);let{owner:K,result:w,...B}=H;V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",B)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=Q,this.mcpConnectionListener=W,this.mcpLogListener=U,this.mcpInstructionsListener=X,this.mcpTaskListener=V,Z.on("contentCatalogChanged",Y),Z.on("resourceUpdated",Q),Z.on("connectionLifecycleChanged",W),Z.on("log",U),Z.on("instructionsChanged",X),n0.getInstance().on("taskChanged",V);for(let[H,K]of Object.entries($))try{let w=K.type==="stdio"?{...this.sessionEnvironment,...K.env}:void 0;await Z.registerServer(H,K.type==="stdio"?{...K,...w&&Object.keys(w).length>0?{env:w}:{}}:K)}catch(w){O0.warn(`Warning: MCP server "${H}" connection failed:`,w)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(j2(Z)),this.baseRegistry.registerAll(V5(Z))}catch($){O0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((Y)=>!J?.has(Y.name)&&(!Z||Z.has(Y.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,Y]of this.executorCatalogs){let Q=this.filterMcpTools($.tools,Y.allowed,Y.blocked),W=(V)=>!Y.blocked?.has(V)&&(!Y.allowed||Y.allowed.has(V)),U={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(W),removed:$.removed.filter(W),updated:$.updated.filter(W)},X=U.added.length>0||U.removed.length>0||U.updated.length>0;J.replaceMcpTools(Q,Z&&X?U:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,Y]of this.executorCatalogs)if(Z.some((W)=>!Y.blocked?.has(W)&&(!Y.allowed||Y.allowed.has(W))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...Y}=$;for(let[Q,W]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((X)=>!W.blocked?.has(X)&&(!W.allowed||W.allowed.has(X))))Q.queueMcpTaskChange(Y)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),Y=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return eJ(Y,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:await I0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=r6($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function u5(){let $=await H0.getInstance().reload();B0().config.actions.setConfig($),await i0.getInstance().disconnectAll(),GY(),await I0(M())}import ZG from"fuse.js";import A$ from"node:path";import{Mutex as vw}from"async-mutex";var C$=new vw;async function qY($){let Z=$.getWorkspaceRoot();await D$(Z,async(J)=>{await $.reapplyEnabledSettings(),N1(Z),await b1(Z),await d5(J)})}async function yw($){let Z=$.getWorkspaceRoot();return D$(Z,async(J)=>{N1(Z);let Y=await $.refresh();return await b1(Z),await d5(J),Y})}async function m5($){return D$($,async(Z)=>{let J=Array.from(new Set([Z.plugins,...S1.getInitializedInstances()])),Y;for(let Q of J){let W=await yw(Q);if(Q===Z.plugins)Y=W}return Y??{plugins:[],errors:[]}})}async function Iw($,Z){let J=A$.resolve($),Y=D1();await Promise.all([Y.removePluginSetting(Z,{scope:"global",immediate:!0}),Y.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),Y.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function xw($){return A$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function FY($,Z){if(xw(Z)&&!DY(await d0.getInstance().getStatus($)))throw Error("Local plugin sources require a trusted workspace")}async function N4($,Z,J,Y="local"){return C$.runExclusive(async()=>{let Q=A$.resolve($);return D$(Q,async(W)=>{let U=W.plugins.get(Z);if(!U)throw Error(`Plugin not found: ${Z}`);if(U.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await D1().save({enabledPlugins:{[Z]:J}},{scope:Y,projectDir:Q,immediate:!0});let X=Y==="global"?Array.from(new Set([W.plugins,...S1.getInitializedInstances()])):[W.plugins];for(let K of X)await qY(K);let V=W.plugins.get(Z);if(!V)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let H=await H0.getInstance().loadWorkspacePluginSettingsResolution(Q);return{name:Z,requestedEnabled:J,effectiveEnabled:V.status==="active",scope:Y,source:V.source,status:V.status,effectiveScope:H.settings[Z]?.effectiveScope??"default"}})})}async function E4($){return C$.runExclusive(()=>D$($,async(Z)=>{N1(Z.workspaceRoot);let J=await Z.plugins.refresh();return await b1(Z.workspaceRoot),{registry:Z.plugins,discovery:J}}))}async function p5($,Z,J="global"){return C$.runExclusive(async()=>{let Y=A$.resolve($),Q={...Z,..._Y(Z)};return await D1().save({pluginSourcePolicy:Q},{scope:J,projectDir:Y,immediate:!0}),D$(Y,async(W)=>{let U=J==="global"?Array.from(new Set([W.plugins,...S1.getInitializedInstances()])):[W.plugins];for(let X of U)await qY(X);return H0.getInstance().loadWorkspacePluginSourcePolicy(Y)})})}async function c5($,Z,J={}){return C$.runExclusive(async()=>{let Y=A$.resolve($);await FY(Y,Z);let Q=await H0.getInstance().loadWorkspacePluginSourcePolicy(Y),W=await Y$().install(Z,{...J,workspaceRoot:Y,policy:Q});if(!W.success)return{result:W};let U=await m5(Y);return{result:W,discovery:U}})}async function l5($,Z,J={}){return C$.runExclusive(async()=>{let Y=A$.resolve($),Q=await H0.getInstance().loadWorkspacePluginSourcePolicy(Y),W=await Y$().update(Z,{...J,workspaceRoot:Y,policy:Q});if(!W.success)return{result:W};let U=await m5(Y);return{result:W,discovery:U}})}async function i5($,Z,J=!1){return C$.runExclusive(async()=>{let Y=A$.resolve($);return D$(Y,async(Q)=>{let W=Q.plugins.getAll().filter((V)=>V.manifest.name!==Z&&V.manifest.dependencies?.[Z]!==void 0).map((V)=>V.manifest.name).sort();if(W.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${W.join(", ")}`}};let U=await Y$().uninstall(Z,J);if(!U.success)return{result:U};await Iw(Y,Z);let X=await m5(Y);return{result:U,discovery:X}})})}async function n5($,Z,J){return C$.runExclusive(async()=>{let Y=A$.resolve($);await FY(Y,Z);let Q=await H0.getInstance().loadWorkspacePluginSourcePolicy(Y);return Y$().addMarketplace(Z,{workspaceRoot:Y,ref:J,policy:Q})})}async function r5($,Z){return C$.runExclusive(async()=>{let J=A$.resolve($),Y=await H0.getInstance().loadWorkspacePluginSourcePolicy(J);return Y$().refreshMarketplace(Z,Y)})}async function a5($,Z=!1){return C$.runExclusive(()=>Y$().removeMarketplace($,Z))}var hw={name:"btw",description:"Ask a side question without changing the main conversation",fullDescription:"Ask one context-aware question in an isolated, tool-free conversation.",usage:"/btw <question>",category:"conversation",examples:["/btw What did the last test failure mean?"],async handler($,Z){let J=$.join(" ").trim();if(!J)return{success:!1,error:"Usage: /btw <question>"};if(!Z.sideConversation)return{success:!1,error:"Side conversations require an active Session runtime"};let Y=await Z.sideConversation.ask(J,Z.signal);return{success:!0,content:`**/btw** ${J}
|
|
1099
|
+
`+" /init");if(!B&&Q&&Q!=="inherit"&&!b.some((T)=>T.id===Q))Q=void 0;let E=await j6({workspaceRoot:L,storeServers:D.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),j={...q.config,permissionMode:W??q.config.permissionMode??"default",lspServers:structuredClone(N.servers),permissions:await F.loadWorkspacePermissions(L,q.config.permissions),hooks:await F.loadWorkspaceHooks(L,q.config.hooks??{})};F.validateConfig(j,q.catalog);let O=new r$(j,{...$,modelResources:q,lspResources:N,mcpServers:E,...Q?{modelId:Q}:{},permissionMode:j.permissionMode,reasoningEffort:U,serviceTier:X,responseVerbosity:V,communicationStyle:H,...K?{communicationStyleDigest:K}:{},...w?{projectInstructionsDigest:w}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await O.initialize(),O}catch(_){if(!$.subagentInfo&&!(_ instanceof Y4)){let D=J?await z$.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await r$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",D??void 0).catch((F)=>{if(F.code!=="ENOENT")O0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,F)})}throw _}}static async hasPendingInbox($,Z){try{if((await fw(tJ($,Z))).size>0)return!0}catch(Y){if(Y.code!=="ENOENT")throw Y}if(L0()?.agentTeamsEnabled!==!0)return!1;let J=(await J$.getInstance(s()).listTeams()).filter((Y)=>Y.deletedAt===void 0&&Y.leadSessionId===Z&&Y.workspaceRoot===$);for(let Y of J)if((await new Z$(Y.name,s()).listPending("team-lead")).length>0)return!0;return!1}static async hasActiveGoal($,Z){return w0.hasActiveGoal($,Z)}static async hasRecoverableTurn($,Z){return new u1($).hasRecoverableTurn(Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??M()}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return q2(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=_1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued,maxQueuedBytes:$.maxQueuedBytes}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",Y=await t.updateSessionMetadata(this.sessionId,this.workspaceRoot,{taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}});return V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:Y.taskStatus,...Y.taskStartedAt?{taskStartedAt:Y.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,taskAdmissionPaused:_1.getStats().paused,updatedAt:Y.lastMessageTime}),Y}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=_1.getStats();V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,taskAdmissionPaused:Z.paused,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}async loadModelContext(){if(!this.initialized)throw Error("Session runtime is not initialized");return t.loadSessionModelContext(this.sessionId,this.workspaceRoot)}async askSideQuestion($,Z={}){if(!this.initialized||!this.chatService)throw Error("Session runtime is not initialized");let J=this.sideConversationOperations.enter(Z.signal),Y=this.config.permissionMode??"default",Q;try{Q=this.createToolExecutor({permissionMode:Y});let W=Q.getRegistry();await W.waitForMcpCatalogIdle();let[U,X]=await Promise.all([this.loadModelContext(),g$({projectPath:this.workspaceRoot,replaceDefault:Z.systemPrompt,append:Z.appendSystemPrompt,...Y==="plan"?{mode:"plan"}:{},includeEnvironment:!0,environmentOptions:S2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),projectInstructionSourcePath:this.projectRoot})]),V=BY(X.prompt,W);if(!V)throw Error("Side conversation system prompt is empty");return await u9({question:$,sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,systemPrompt:V,messages:U,tools:W.getFunctionDeclarationsByMode(Y),chatService:this.chatService,signal:J.signal,providerRecoveryBudgetMs:this.config.providerForegroundRecoveryMs})}finally{Q?.dispose(),J.release()}}getStartupTurnRecovery(){return this.startupTurnRecovery?structuredClone(this.startupTurnRecovery):void 0}getTurnRecoveryAssessment(){if(this.startupTurnRecoveryAcknowledged)return{state:"none"};return dZ(this.startupTurnRecovery)}takeStartupTurnRecoveryAssessment(){if(this.startupTurnRecoveryAssessmentTaken)return{state:"none"};return this.startupTurnRecoveryAssessmentTaken=!0,this.getTurnRecoveryAssessment()}async acknowledgeStartupTurnRecovery(){let $=this.startupTurnRecovery;if($?.outcome==="aborted")await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeTurnRecovery(this.sessionId,$.turnId);this.startupTurnRecoveryAcknowledged=!0,this.startupTurnRecoveryAssessmentTaken=!0}async getRecoveredFinalResponse(){let $=this.startupTurnRecovery;if(!$||$.outcome!=="completed")return;let J=(await this.loadModelContext()).findLast((U)=>U.role==="assistant"&&sJ(U)?.turnId===$.turnId&&JSON.stringify(sJ(U))===JSON.stringify($.finalization));if(!J||typeof J.content!=="string")return;let Y=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,Q=Y?.structuredOutput,W=Q&&typeof Q==="object"&&!Array.isArray(Q)&&Q.output&&typeof Q.output==="object"&&!Array.isArray(Q.output)?Q.output:void 0;return{turnId:$.turnId,content:J.content,...W?{structuredOutput:W}:{},...typeof Y?.structuredOutputSchemaDigest==="string"?{structuredOutputSchemaDigest:Y.structuredOutputSchemaDigest}:{}}}takeStartupAdoptedToolResults(){let $=this.startupAdoptedToolResults;return this.startupAdoptedToolResults=[],structuredClone($)}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}captureBrowserScreenshot($){if(!this.browserRuntime)throw new P("browser_page_not_found","The Agent browser is not available");return this.browserRuntime.screenshot($)}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return y0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return y0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return y0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return O4(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return O4($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??UY}getProjectRuleCatalog(){return this.agentResources?.projectRules??XY.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,Y){let Q=new Set;try{let V=this.baseRegistry.get($)?.build(Z);for(let H of V?.getAffectedPaths()??[])if(H)Q.add(H)}catch{}let W=(V)=>{if(typeof V==="string"&&V.trim())Q.add(V)};if(["Read","Edit","Write"].includes($))W(Z.file_path);else if($==="NotebookEdit")W(Z.notebook_path);else if(["Grep","Glob"].includes($))W(Z.path);else if($==="Bash")W(Z.cwd);let U=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(U?.affected_paths))for(let V of U.affected_paths)W(V);if(Array.isArray(U?.changes)){for(let V of U.changes)if(V&&typeof V==="object")W(V.path)}let X=[...Q].map((V)=>b0.isAbsolute(V)?b0.resolve(V):b0.resolve(this.workspaceRoot,V)).flatMap((V)=>{let H=b0.relative(this.workspaceRoot,V);if(H===""||!H.startsWith("..")&&!b0.isAbsolute(H))return[b0.resolve(this.projectRoot,H)];let K=b0.relative(this.projectRoot,V);return K===""||!K.startsWith("..")&&!b0.isAbsolute(K)?[V]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,X,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async prepareGoalContinuation($,Z={}){try{let J=await G6($,{configDir:s()}),Y=Z.observeStall===!1&&$.frontierStall?.digestSha256===J.frontier.digestSha256,Q=Z.observeStall===!1?Y?$.frontierStall:void 0:oZ($.executionFrontier,J.frontier,{taskEffect:"none",prematureStopCount:$.prematureStop?.consecutiveCount??0,verificationStallCount:$.verificationStall?.consecutiveCount??0},$.frontierStall);return{ok:!0,goal:await this.goalStore.recordExecutionFrontier(J.frontier,Q,{preserveStall:Y}),...J}}catch(J){let Y=J instanceof Error?J.message:String(J),Q=null;try{Q=await this.goalStore.pause(`goal task list unavailable (${D2($)}): ${Y}`)}catch(W){O0.warn(`[SessionRuntime] Failed to pause Goal after frontier failure: ${W instanceof Error?W.message:String(W)}`)}return{ok:!1,goal:Q,error:{code:"task_list_unavailable",message:`Goal execution frontier unavailable: ${Y}`}}}}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await z$.getChangeSummary(this.sessionId):void 0;return r$.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0)}static async persistTaskStatus($,Z,J,Y,Q){let W=new Date().toISOString(),U=J==="failed"&&Y!==void 0?b4(Y):void 0,X=U?.message??(typeof Y==="string"?Y.slice(0,500):void 0),V=await t.updateSessionMetadata($,Z,{taskStatus:J,taskStatusReason:X??null,taskFailure:U??null,...Q!==void 0?{taskDiffStat:Q}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:W,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:W,taskOwnerPid:null}});return V0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:V.taskStatus,...X?{taskStatusReason:X}:{},...U?{taskFailure:U}:{},...V.taskStartedAt?{taskStartedAt:V.taskStartedAt}:{},...V.taskCompletedAt?{taskCompletedAt:V.taskCompletedAt}:{},...V.taskDiffStat?{taskDiffStat:V.taskDiffStat}:{},...V.taskQueuePosition?{taskQueuePosition:V.taskQueuePosition}:{},...V.taskQueueDepth!==void 0?{taskQueueDepth:V.taskQueueDepth}:{},...V.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:V.taskConcurrencyLimit}:{},updatedAt:V.lastMessageTime}),V}createGoal($){return this.goalStore.create($)}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalCompletionVerification($){return this.goalStore.recordCompletionVerification($)}invalidateGoalCompletionVerification($){return this.goalStore.invalidateCompletionVerification($)}clearGoalFrontierStall(){return this.goalStore.clearFrontierStall()}finalizeVerifiedGoalCompletion(){return this.goalStore.finalizeVerifiedCompletion()}recordGoalProgress($){return this.goalStore.recordProgress($)}beginGoalContinuation(){return this.goalStore.tryBeginContinuation()}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),t.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){this.assertRewindIdle();let Z=await t.rewindSession(this.sessionId,this.workspaceRoot,$);return this.backgroundTaskChildIds=await this.getExecutionEngine().getContextManager().persistentStore.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear(),Z}listSubagents(){return K0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return n0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return n0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return n0.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=K0.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=Z.getAgent($.agentId,J);if(!Y)throw Error(`Subagent not found in this session: ${$.agentId}`);let Q=this.subagentRegistry?.getSubagent(Y.subagentType),W=Y.configSnapshot?{...Y.configSnapshot}:Q;if(!W)throw Error(`Subagent configuration is unavailable: ${Y.subagentType}`);let U=Z.resumeAgent({agentId:Y.id,prompt:$.prompt,config:W,owner:J,permissionMode:W.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:async(V)=>{await this.notifyBackgroundSubagentCompleted(V.id),await $.onCompleted?.(V)}});if(!U)throw Error(`Subagent cannot be resumed: ${Y.id}`);let X=Z.getAgent(U.agentId,J);if(!X)throw Error(`Resumed subagent was not persisted: ${U.agentId}`);return{source:U.source,session:X}}async beginTurn($="goal"){let Z=this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(Z,$),Z}catch(J){throw await this.getActiveTurnMailbox().finishTurn(Z).catch(()=>{return}),J}}async prepareInputTurn($,Z){let J=this.getActiveTurnMailbox(),Y=await this.materializeUserMessage($),Q=await J.prepareInputTurn(Y.content,{...Z,...Y.metadata?{metadata:Y.metadata}:{}});if(!Q.accepted)return Q;try{return await this.saveTurnStart(Q.handle,Q.mode==="direct"?"user":"pending",J.pendingMessages().map((W)=>W.id)),Q}catch(W){throw await J.finishTurn(Q.handle).catch(()=>{return}),W}}async enqueueSteering($,Z){let J=(Z?.origin??"user")==="user"?await this.materializeUserMessage($,Z?.metadata):{content:$,metadata:Z?.metadata,offloaded:!1},Y=await this.getActiveTurnMailbox().enqueue(J.content,{...Z,...J.metadata?{metadata:J.metadata}:{}});if(Y.accepted)this.signalBackgroundSubagentCompletionWaiters();return Y}materializeUserMessage($,Z){return this.userPromptArtifactStore.materialize($,Z)}restoreUserMessage($,Z){return this.userPromptArtifactStore.restore($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async getRecoveredEmptyFinalState($){let Z=this.startupTurnRecovery;if(!Z||Z.outcome!=="aborted")return{hadSuccessfulToolResult:!1,correctionSpent:!1};let J=await this.getClaimedTurnMessageIds($),Y=new Set(Z.inputMessageIds);if(J.length===0||J.some((Q)=>!Y.has(Q)))return{hadSuccessfulToolResult:!1,correctionSpent:!1};return{hadSuccessfulToolResult:Z.hadSuccessfulToolResult,...Z.interruptedToolCallCount?{interruptedToolCallCount:Z.interruptedToolCallCount}:{},...Z.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},correctionSpent:Z.emptyFinalCorrectionSpent}}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z={}){let J=Z.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},Y=this.getExecutionEngine().getContextManager().persistentStore;if(J.status==="completed"){let W=await this.getActiveTurnMailbox().claimedMessageIds($);await Y.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs},W),await this.getActiveTurnMailbox().acknowledge(W)}else{let W=this.startupTurnRecovery,U=Z.preserveStartupRecovery&&W?.outcome==="aborted"?{hadSuccessfulToolResult:W.hadSuccessfulToolResult,interruptedToolCallCount:W.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:W.allSuccessfulToolResultsSafeForResume,correctionSpent:W.emptyFinalCorrectionSpent}:await this.getRecoveredEmptyFinalState($),X=await this.getActiveTurnMailbox().claimedMessageIds($),V=await Y.saveTurnAbort(this.sessionId,{turnId:$.id,cause:J.cause,abortedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs,recovery:{version:3,inputMessageIds:X,hadSuccessfulToolResult:U.hadSuccessfulToolResult,interruptedToolCallCount:U.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:U.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:U.correctionSpent}},Z.acknowledgeInput?{acknowledgeInputMessageIds:X}:void 0);if(this.startupTurnRecovery=V.recovery,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,Z.acknowledgeInput)await this.getActiveTurnMailbox().acknowledge(V.acknowledgedInputMessageIds)}let Q=await this.getActiveTurnMailbox().finishTurn($,Z);if(!Q)return;try{return await this.saveTurnStart(Q,"pending",this.getActiveTurnMailbox().pendingMessages().map((W)=>W.id)),Q}catch(W){throw await this.getActiveTurnMailbox().finishTurn(Q).catch(()=>{return}),W}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),Z=await $.beginPendingTurn();if(!Z)return;try{return await this.saveTurnStart(Z,"pending",$.pendingMessages().map((J)=>J.id)),Z}catch(J){throw await $.finishTurn(Z).catch(()=>{return}),J}}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}isIdleForResidency(){if(!this.initialized||this.disposing||this.hasActiveTurn()||this.hasTurnOwner()||this.sideConversationOperations.stats().active>0||this.getPendingSteeringCount()>0||this.executorCatalogs.size>0)return!1;if(Z0.getInstance().listForSession(this.sessionId).some((Z)=>Z.status==="running"))return!1;let $={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(K0.getInstance().listForSession($).some((Z)=>Z.status==="running")||this.getBackgroundTaskChildrenState()!=="none")return!1;return!n0.getInstance().hasActive($)}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async notifyBackgroundSubagentCompleted($){try{await this.reconcileBackgroundSubagentCompletions($)}finally{this.signalBackgroundSubagentCompletionWaiters()}}registerBackgroundSubagent($){this.backgroundTaskChildIds.add($),this.backgroundTaskCompletionSettledIds.delete($)}async waitForBackgroundSubagentFollowUp($,Z){while(!Z?.aborted){if(await this.reconcileBackgroundSubagentCompletions(),await this.hasUnclaimedPendingInput($))return!0;let J=this.backgroundSubagentCompletionRevision,Y=this.getBackgroundTaskChildrenState();if(Y==="none")return!1;if(Y==="terminal_pending")continue;await this.waitForBackgroundSubagentSignal(J,Z)}return!1}async hasUnclaimedPendingInput($){let Z=new Set(await this.getActiveTurnMailbox().claimedMessageIds($));return this.getActiveTurnMailbox().pendingMessages().some((J)=>!Z.has(J.id))}signalBackgroundSubagentCompletionWaiters(){this.backgroundSubagentCompletionRevision++;for(let $ of this.backgroundSubagentCompletionWaiters)$();this.backgroundSubagentCompletionWaiters.clear()}async waitForBackgroundSubagentSignal($,Z){if(Z?.aborted||$!==this.backgroundSubagentCompletionRevision)return;await new Promise((J)=>{let Y=!1,Q=()=>{if(Y)return;Y=!0,this.backgroundSubagentCompletionWaiters.delete(Q),Z?.removeEventListener("abort",Q),J()};if(this.backgroundSubagentCompletionWaiters.add(Q),Z?.addEventListener("abort",Q,{once:!0}),Z?.aborted||$!==this.backgroundSubagentCompletionRevision)Q()})}getBackgroundTaskChildrenState(){if(this.backgroundTaskChildIds.size===0)return"none";let $={sessionId:this.sessionId,projectPath:this.workspaceRoot},Z=R0.getInstance().listSessions().filter((J)=>c0(J,$)&&this.backgroundTaskChildIds.has(J.id)&&J.background===!0);if(Z.some((J)=>J.status!=="running"&&!this.backgroundTaskCompletionSettledIds.has(J.id)))return"terminal_pending";return Z.some((J)=>J.status==="running")?"running":"none"}async reconcileBackgroundSubagentCompletions($){return this.backgroundSubagentCompletionMutex.runExclusive(async()=>{if(!this.activeTurnMailbox||!this.executionEngine)return 0;let Z=this.getExecutionEngine().getContextManager().persistentStore;if(this.backgroundTaskChildIds.size===0)return 0;let J=R0.getInstance(),Y={sessionId:this.sessionId,projectPath:this.workspaceRoot},Q=$?[J.loadSession($)].filter((U)=>Boolean(U)):J.listSessions().filter((U)=>c0(U,Y)),W=0;for(let U of Q){if(!this.backgroundTaskChildIds.has(U.id)||this.backgroundTaskCompletionSettledIds.has(U.id)||U.status==="running")continue;let X=U.resumedFrom?J.loadSession(U.resumedFrom):void 0,V=dJ(U,Y,X);if(!V){this.backgroundTaskCompletionSettledIds.add(U.id);continue}let H=await Z.persistBackgroundSubagentCompletion(this.sessionId,V);if(!H.eligible||H.acknowledged){this.backgroundTaskCompletionSettledIds.add(U.id);continue}let K=await this.activeTurnMailbox.enqueueBackgroundSubagentCompletion(V);if(!K.accepted){O0.warn(`[SessionRuntime ${this.sessionId}] Background subagent completion queue is full for ${U.id}`);continue}if(this.backgroundTaskCompletionSettledIds.add(U.id),K.duplicate)continue;W++,V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"subagent.completion.queued",{childSessionId:U.id,inboxMessageId:V.inboxMessageId,status:U.status,type:U.subagentType,description:U.description,summary:V.subagentRef.subagentSummary,resumedFrom:U.resumedFrom,rootAgentId:U.rootAgentId,resumeDepth:U.resumeDepth,verificationVerdict:U.result?.verificationVerdict,queued:K.queued,delivery:K.delivery})}return W})}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await h2.create(this.workspaceRoot,this.sessionId)}async recoverTeamLeadMessages(){if(this.config.agentTeamsEnabled!==!0)return;let $=(await J$.getInstance(s()).listTeams()).filter((Z)=>Z.deletedAt===void 0&&Z.leadSessionId===this.sessionId&&Z.workspaceRoot===this.workspaceRoot);for(let Z of $){let J=new Z$(Z.name,s()),Y=await J.listPending("team-lead");for(let Q of Y)if((await this.enqueueSteering(p1(Q),{allowBeforeTurn:!0,messageId:Q.id,origin:"team_message",metadata:_4(Q)})).accepted)await J.markDelivered([Q.id])}}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=Sw(12),Y=this.hasTurnOwner(),Q=Z.signal??new AbortController().signal,W=async(B)=>{let G=B.type==="started"?{executionId:B.executionId,command:B.command,auxiliary:Y}:B.type==="output"?{executionId:B.executionId,stream:B.stream,chunk:B.chunk,streamedBytes:B.streamedBytes,streamTruncated:B.streamTruncated,auxiliary:Y}:{executionId:B.executionId,messageId:B.messageId,record:B.record,auxiliary:Y,delivery:B.delivery,queued:B.queued};V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${B.type}`,G),await Z.onEvent?.(B)},U=await HY($,{executionId:J,cwd:this.workspaceRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:Q,timeoutMs:Z.timeoutMs,executor:this.options.userShellExecutor,onEvent:async(B)=>{if(B.type!=="completed")await W({...B,auxiliary:Y})}}),X=KY(U),H=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",X,null,{...Y?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(U))},this.options.subagentInfo),K=Y?await this.getActiveTurnMailbox().enqueue(X,{allowBeforeTurn:!0,messageId:J,persisted:!0}):void 0,w={executionId:J,messageId:H,record:U,modelContent:X,auxiliary:Y,...K?.delivery?{delivery:K.delivery}:{},...K?{queued:K.queued}:{}};return await W({type:"completed",executionId:J,messageId:H,record:U,auxiliary:Y,...K?.delivery?{delivery:K.delivery}:{},...K?{queued:K.queued}:{}}),w})}async initialize(){if(this.initialized)return;this.sessionLease=await Q4.acquire(this.sessionId,this.workspaceRoot);try{if(await new J1(this.workspaceRoot,this.sessionId).reapOrphans(),await Z0.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),!X0(this.sessionId))await i9(this.workspaceRoot);await K0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await kw(this.workspaceRoot);let $=T0.getInstance();if($.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),$.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),await this.loadAgentResources(),this.projectRoot!==this.workspaceRoot)$.inheritProjectConfig(this.projectRoot,this.workspaceRoot);$.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??$.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??$.getConfig(this.projectRoot));let Z=await $.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!Z.proceed)throw Error(Z.warning||"SessionStart hook blocked initialization");if(Z.warning)O0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${Z.warning}`);let J=JY(Z.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...J}),this.config.env=this.sessionEnvironment,$.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new $8({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new g5({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment});await this.validateSystemPromptConfig(),this.activeTurnMailbox=await h2.create(this.workspaceRoot,this.sessionId),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo);let Y=this.getExecutionEngine().getContextManager().persistentStore;this.backgroundTaskChildIds=await Y.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear();let Q=await Y.loadInterruptedToolCalls(this.sessionId),W=new Map,U=R0.getInstance(),X={sessionId:this.sessionId,projectPath:this.workspaceRoot};for(let w of Q){if(w.toolName!=="Task"||!w.input||typeof w.input!=="object"||Array.isArray(w.input))continue;let B=w.input.subagent_session_id;if(typeof B!=="string")continue;let G=U.loadSession(B);if(!G)continue;let _=UJ(w,G,X);if(_)W.set(w.toolCallId,_)}let V=await Y.recoverInterruptedTurn(this.sessionId,{adoptedToolResults:W});if(V)this.startupAdoptedToolResults=Q.flatMap((w)=>{let B=W.get(w.toolCallId);return B?[{call:w,result:B}]:[]});let H=await Y.loadLatestGoalFinalization(this.sessionId),K=H?await this.goalStore.reconcileFinalizationReceipt(H.finalization.goalFinalization):null;if(K?.finalized)V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"goal.updated",{goal:K.goal});if(this.startupTurnRecovery=V??(H&&K?.finalized?{turnId:H.turnId,outcome:"completed",inputMessageIds:H.finalization.inputMessageIds,hadSuccessfulToolResult:!1,emptyFinalCorrectionSpent:!1,finalization:H.finalization}:void 0),this.startupTurnRecovery?.outcome==="completed")await this.reloadPendingInbox();if(await this.recoverTeamLeadMessages(),await this.reconcileBackgroundSubagentCompletions(),V)O0.warn(`[SessionRuntime ${this.sessionId}] recovered ${V.outcome} turn ${V.turnId}`);this.initialized=!0,O0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){O0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,Y=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,Q=$.reasoningEffort??this.selectedReasoningEffort,W=$.serviceTier??this.selectedServiceTier,U=$.responseVerbosity??this.selectedResponseVerbosity,X=$.communicationStyle??this.selectedCommunicationStyle;if(O4(X,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||Q!==this.selectedReasoningEffort||W!==this.selectedServiceTier||U!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":Q!==this.selectedReasoningEffort?"切换推理强度":W!==this.selectedServiceTier?"切换服务等级":"切换输出详略",Q,W,U);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=Q,this.selectedServiceTier=W,this.selectedResponseVerbosity=U,this.selectedCommunicationStyle=X}createToolExecutor($={}){let Z=new p$;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J="ReadPromptArtifact",Y=$.toolWhitelist?[...new Set([...$.toolWhitelist,J])]:void 0,Q=$.toolBlacklist?.filter((w)=>w!==J),W=Y?new Set(Y):null,U=Q?new Set(Q):null;for(let w of this.baseRegistry.getBuiltinTools()){if(U?.has(w.name))continue;if(!W||W.has(w.name))Z.register(w)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),W,U));let X=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((w)=>!U?.has(w)&&(!W||W.has(w))))for(let w of n0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:B,...G}=w;Z.queueMcpTaskChange({revision:0,...G})}this.executorCatalogs.set(Z,{allowed:W,blocked:U});let H={...this.config.permissions,...$.permissions},K=$.permissionMode??this.config.permissionMode??"default";return new M2(Z,{permissionConfig:H,permissionMode:K,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:Y,toolBlacklist:Q,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,permissionMode:K,foregroundCommandHandoffMs:this.config.bashForegroundHandoffMs,mcpSamplingHandler:this.handleMcpSampling,notifyBackgroundSubagentCompleted:(w)=>this.notifyBackgroundSubagentCompleted(w),registerBackgroundSubagent:(w)=>this.registerBackgroundSubagent(w)},...this.lspManager?{lspManager:this.lspManager}:{},...K==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){this.disposing=!0;let $,Z=async(D,F)=>{try{await F()}catch(L){$??=L,O0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${D} during cleanup`,L)}},J=this.chatService,Y=this.sessionMcpRegistry,Q=this.mcpCatalogListener,W=this.mcpContentCatalogListener,U=this.mcpResourceUpdatedListener,X=this.mcpConnectionListener,V=this.mcpLogListener,H=this.mcpInstructionsListener,K=this.mcpTaskListener,w=this.sessionLease,B=this.autoVerifyRuntime,G=this.lspManager,_=this.browserRuntime;if(await Z("stop side conversations",()=>this.sideConversationOperations.shutdown("session-runtime-dispose")),await Z("close the Session browser",()=>_?.dispose()),this.signalBackgroundSubagentCompletionWaiters(),this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.startupTurnRecovery=void 0,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,this.startupAdoptedToolResults=[],this.backgroundTaskChildIds.clear(),this.backgroundTaskCompletionSettledIds.clear(),this.currentModelMaxContextTokens=void 0,this.baseRegistry=new p$,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,this.browserRuntime=void 0,await Z("kill the session background processes",()=>Z0.getInstance().killSession(this.sessionId)),await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>A0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>B?.dispose()),await Z("stop the session LSP servers",()=>G?.dispose()),await Z("release the session hook model resources",()=>T0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>z$.releaseSession(this.sessionId)),await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>n0.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(Y&&Q)Y.off("catalogChanged",Q);if(Y&&W)Y.off("contentCatalogChanged",W);if(Y&&U)Y.off("resourceUpdated",U);if(Y&&X)Y.off("connectionLifecycleChanged",X);if(Y&&V)Y.off("log",V);if(Y&&H)Y.off("instructionsChanged",H);if(K)n0.getInstance().off("taskChanged",K);await Y?.disconnectAll()}),await Z("release the session lease",()=>w?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((Y)=>Y.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}async saveTurnStart($,Z,J=[]){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:Z,startedAt:new Date().toISOString(),...J.length>0?{inputMessageIds:J}:{}})}assertRewindIdle(){if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(Z0.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(K0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,Y,Q){let W=y0($,this.config,J,this.modelResources.catalog,Y,Q);O0.debug(`${Z} ${W.displayName} (${$.model})`);let U=W.model.contextWindow,X=await n6(W.chat),V=this.initialized?this.chatService:void 0,H=this.executionEngine?.getContextManager();this.chatService=X,this.executionEngine=new R2(X,H,this.workspaceRoot),this.currentModelMaxContextTokens=U,this.currentModelId=$.id,this.currentReasoning=W.reasoning,this.currentServiceTier=W.serviceTier,this.currentResponseVerbosity=W.responseVerbosity;let K=V;try{await K?.dispose?.()}catch(w){O0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,w)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await g$({projectPath:this.workspaceRoot,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),projectInstructionSourcePath:this.projectRoot})}catch(J){O0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){try{await t.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof wY||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await t.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){this.browserRuntime??=new o4(this.workspaceRoot,this.sessionId,{storageRoot:s(),exposeArtifactPaths:!X0(this.sessionId)});let Z=(await a6({sessionId:this.sessionId,configDir:s(),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle,agentTeamsEnabled:this.config.agentTeamsEnabled===!0,userPromptArtifactStore:this.userPromptArtifactStore,browserRuntime:this.browserRuntime})).filter((J)=>!J.name.startsWith("mcp__"));this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=i0.createIsolated({roots:X0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!X0(this.sessionId),artifactWriter:new F2(`${this.projectRoot}\x00${this.sessionId}`,{exposePaths:!X0(this.sessionId)}),exposeLogDetails:!X0(this.sessionId),exposeInstructions:!X0(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(H)=>{this.applyMcpCatalog(H,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let Y=(H)=>{this.applyMcpContentCatalog(H)},Q=(H)=>{this.applyMcpResourceUpdated(H)},W=(H)=>{this.applyMcpConnectionChange(H)},U=(H)=>{this.applyMcpLog(H)},X=(H)=>{this.applyMcpInstructions(H)},V=(H)=>{if(H.owner.sessionId!==this.sessionId||b0.resolve(H.owner.projectPath)!==b0.resolve(this.workspaceRoot))return;this.applyMcpTask(H);let{owner:K,result:w,...B}=H;V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",B)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=Q,this.mcpConnectionListener=W,this.mcpLogListener=U,this.mcpInstructionsListener=X,this.mcpTaskListener=V,Z.on("contentCatalogChanged",Y),Z.on("resourceUpdated",Q),Z.on("connectionLifecycleChanged",W),Z.on("log",U),Z.on("instructionsChanged",X),n0.getInstance().on("taskChanged",V);for(let[H,K]of Object.entries($))try{let w=K.type==="stdio"?{...this.sessionEnvironment,...K.env}:void 0;await Z.registerServer(H,K.type==="stdio"?{...K,...w&&Object.keys(w).length>0?{env:w}:{}}:K)}catch(w){O0.warn(`Warning: MCP server "${H}" connection failed:`,w)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(j2(Z)),this.baseRegistry.registerAll(V5(Z))}catch($){O0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((Y)=>!J?.has(Y.name)&&(!Z||Z.has(Y.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,Y]of this.executorCatalogs){let Q=this.filterMcpTools($.tools,Y.allowed,Y.blocked),W=(V)=>!Y.blocked?.has(V)&&(!Y.allowed||Y.allowed.has(V)),U={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(W),removed:$.removed.filter(W),updated:$.updated.filter(W)},X=U.added.length>0||U.removed.length>0||U.updated.length>0;J.replaceMcpTools(Q,Z&&X?U:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,Y]of this.executorCatalogs)if(Z.some((W)=>!Y.blocked?.has(W)&&(!Y.allowed||Y.allowed.has(W))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...Y}=$;for(let[Q,W]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((X)=>!W.blocked?.has(X)&&(!W.allowed||W.allowed.has(X))))Q.queueMcpTaskChange(Y)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),Y=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return eJ(Y,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:await I0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=r6($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function u5(){let $=await H0.getInstance().reload();B0().config.actions.setConfig($),await i0.getInstance().disconnectAll(),GY(),await I0(M())}import ZG from"fuse.js";import A$ from"node:path";import{Mutex as vw}from"async-mutex";var C$=new vw;async function qY($){let Z=$.getWorkspaceRoot();await D$(Z,async(J)=>{await $.reapplyEnabledSettings(),N1(Z),await b1(Z),await d5(J)})}async function yw($){let Z=$.getWorkspaceRoot();return D$(Z,async(J)=>{N1(Z);let Y=await $.refresh();return await b1(Z),await d5(J),Y})}async function m5($){return D$($,async(Z)=>{let J=Array.from(new Set([Z.plugins,...S1.getInitializedInstances()])),Y;for(let Q of J){let W=await yw(Q);if(Q===Z.plugins)Y=W}return Y??{plugins:[],errors:[]}})}async function Iw($,Z){let J=A$.resolve($),Y=D1();await Promise.all([Y.removePluginSetting(Z,{scope:"global",immediate:!0}),Y.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),Y.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function xw($){return A$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function FY($,Z){if(xw(Z)&&!DY(await d0.getInstance().getStatus($)))throw Error("Local plugin sources require a trusted workspace")}async function N4($,Z,J,Y="local"){return C$.runExclusive(async()=>{let Q=A$.resolve($);return D$(Q,async(W)=>{let U=W.plugins.get(Z);if(!U)throw Error(`Plugin not found: ${Z}`);if(U.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await D1().save({enabledPlugins:{[Z]:J}},{scope:Y,projectDir:Q,immediate:!0});let X=Y==="global"?Array.from(new Set([W.plugins,...S1.getInitializedInstances()])):[W.plugins];for(let K of X)await qY(K);let V=W.plugins.get(Z);if(!V)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let H=await H0.getInstance().loadWorkspacePluginSettingsResolution(Q);return{name:Z,requestedEnabled:J,effectiveEnabled:V.status==="active",scope:Y,source:V.source,status:V.status,effectiveScope:H.settings[Z]?.effectiveScope??"default"}})})}async function E4($){return C$.runExclusive(()=>D$($,async(Z)=>{N1(Z.workspaceRoot);let J=await Z.plugins.refresh();return await b1(Z.workspaceRoot),{registry:Z.plugins,discovery:J}}))}async function p5($,Z,J="global"){return C$.runExclusive(async()=>{let Y=A$.resolve($),Q={...Z,..._Y(Z)};return await D1().save({pluginSourcePolicy:Q},{scope:J,projectDir:Y,immediate:!0}),D$(Y,async(W)=>{let U=J==="global"?Array.from(new Set([W.plugins,...S1.getInitializedInstances()])):[W.plugins];for(let X of U)await qY(X);return H0.getInstance().loadWorkspacePluginSourcePolicy(Y)})})}async function c5($,Z,J={}){return C$.runExclusive(async()=>{let Y=A$.resolve($);await FY(Y,Z);let Q=await H0.getInstance().loadWorkspacePluginSourcePolicy(Y),W=await Y$().install(Z,{...J,workspaceRoot:Y,policy:Q});if(!W.success)return{result:W};let U=await m5(Y);return{result:W,discovery:U}})}async function l5($,Z,J={}){return C$.runExclusive(async()=>{let Y=A$.resolve($),Q=await H0.getInstance().loadWorkspacePluginSourcePolicy(Y),W=await Y$().update(Z,{...J,workspaceRoot:Y,policy:Q});if(!W.success)return{result:W};let U=await m5(Y);return{result:W,discovery:U}})}async function i5($,Z,J=!1){return C$.runExclusive(async()=>{let Y=A$.resolve($);return D$(Y,async(Q)=>{let W=Q.plugins.getAll().filter((V)=>V.manifest.name!==Z&&V.manifest.dependencies?.[Z]!==void 0).map((V)=>V.manifest.name).sort();if(W.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${W.join(", ")}`}};let U=await Y$().uninstall(Z,J);if(!U.success)return{result:U};await Iw(Y,Z);let X=await m5(Y);return{result:U,discovery:X}})})}async function n5($,Z,J){return C$.runExclusive(async()=>{let Y=A$.resolve($);await FY(Y,Z);let Q=await H0.getInstance().loadWorkspacePluginSourcePolicy(Y);return Y$().addMarketplace(Z,{workspaceRoot:Y,ref:J,policy:Q})})}async function r5($,Z){return C$.runExclusive(async()=>{let J=A$.resolve($),Y=await H0.getInstance().loadWorkspacePluginSourcePolicy(J);return Y$().refreshMarketplace(Z,Y)})}async function a5($,Z=!1){return C$.runExclusive(()=>Y$().removeMarketplace($,Z))}var hw={name:"btw",description:"Ask a side question without changing the main conversation",fullDescription:"Ask one context-aware question in an isolated, tool-free conversation.",usage:"/btw <question>",category:"conversation",examples:["/btw What did the last test failure mean?"],async handler($,Z){let J=$.join(" ").trim();if(!J)return{success:!1,error:"Usage: /btw <question>"};if(!Z.sideConversation)return{success:!1,error:"Side conversations require an active Session runtime"};let Y=await Z.sideConversation.ask(J,Z.signal);return{success:!0,content:`**/btw** ${J}
|
|
1100
1100
|
|
|
1101
1101
|
${Y.response}`,data:{action:"show_side_conversation",question:J,response:Y.response,durationMs:Y.durationMs,usage:Y.usage}}}},LY=hw;import ZQ from"node:fs/promises";import JQ from"node:path";function o5($){return Number.isFinite($)?Math.max(0,$):0}function OY($){let Z=o5($.totalInputTokens),J=o5($.cacheReadTokens),Y=o5($.cacheWriteTokens),Q=Math.min(J,Z),W=Math.min(Y,Math.max(0,Z-Q)),U=Math.max(0,Z-Q-W),X=Z>0&&(J>0||Y>0);return{totalInputTokens:Z,cacheReadTokens:Q,cacheWriteTokens:W,uncachedInputTokens:U,...X?{hitRate:Q/Z}:{}}}function bY($){if($===void 0||!Number.isFinite($))return"—";return`${Math.round(Math.max(0,Math.min(1,$))*100)}%`}function NY($){return`${{model_changed:"model changed",system_prompt_changed:"system prompt changed",tools_changed:"tool definitions changed",request_policy_changed:"request policy changed",ttl_expired:"cache TTL expired",server_side:"likely Provider routing or eviction"}[$.reason]} (${$.previousCacheReadTokens.toLocaleString()} → ${$.cacheReadTokens.toLocaleString()} cache-read tokens)`}async function A4($,Z,J={}){let Y=Date.now(),Q=J.timeoutMs??20000,W="unknown";try{let U=y0($,Z,"off");W=U.model.api;let V=await new EY({...U.chat,temperature:0,maxOutputTokens:8,timeout:Q,streamIdleTimeout:Q,maxRetries:0,fallbackModels:[]}).chat([{role:"user",content:"Reply with OK."}],void 0,AbortSignal.timeout(Q),{providerAdmission:{sessionId:`provider-health:${$.id}`,ownerId:`provider-health:${$.id}`,requestClass:"internal"}});if(!Boolean(V.content||V.reasoningContent||V.finishReason||V.usage))throw Error("Provider returned an empty response");return{ok:!0,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:W,latencyMs:Date.now()-Y,code:"ok",message:"Provider responded successfully."}}catch(U){let X=b4(U);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:W,latencyMs:Date.now()-Y,code:X.code,message:X.message}}}import gw from"node:os";import jY from"node:path";function g($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
1102
1102
|
|
|
@@ -1658,7 +1658,7 @@ ${J}
|
|
|
1658
1658
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1659
1659
|
`)}}case"create":{let X=xB(W);if("error"in X)return Y.sendMessage(`创建失败:${X.error}`),{success:!1,error:X.error};let V={prompt:X.prompt,projectPath:U,trigger:X.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(V),K=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
|
|
1660
1660
|
${VZ(H.trigger)} · 下次运行: ${K}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let K=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${K}`),{success:!1,error:K}}}case"remove":case"rm":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(X);return Y.sendMessage(V?`[OK] 已删除 \`${X}\``:`未找到 \`${X}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let X=W[0];if(!X)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(X,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${X}\``:`未找到 \`${X}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await hB(X),Y.sendMessage(`[OK] 已触发 \`${X}\``),{success:!0,message:"Schedule triggered"}}catch(V){let H=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${Q}
|
|
1661
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var PQ=gB();import*as t1 from"node:fs/promises";import*as e1 from"node:path";async function kQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??s2(Q??M());if(!W){let B=await uB($,Q??M(),J,Y);if(B)return B}let X;try{X=(await t1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>e1.join(U,G))}catch{return[]}let H=(await Promise.all(X.map(async(B)=>{try{let G=await t1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),K=[],w=Y?$:$.toLowerCase();for(let B of H){if(K.length>=J)break;let G=e1.basename(B,".jsonl"),_=await dB(B,w,Y,G);if(K.push(..._),K.length>=J){K.length=J;break}}return K}async function uB($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-fqnqeca5.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-
|
|
1661
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var PQ=gB();import*as t1 from"node:fs/promises";import*as e1 from"node:path";async function kQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??s2(Q??M());if(!W){let B=await uB($,Q??M(),J,Y);if(B)return B}let X;try{X=(await t1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>e1.join(U,G))}catch{return[]}let H=(await Promise.all(X.map(async(B)=>{try{let G=await t1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),K=[],w=Y?$:$.toLowerCase();for(let B of H){if(K.length>=J)break;let G=e1.basename(B,".jsonl"),_=await dB(B,w,Y,G);if(K.push(..._),K.length>=J){K.length=J;break}}return K}async function uB($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-fqnqeca5.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-vr20qr4k.js");await Q(W,U.projectionDeriverForSearch());let X=e1.resolve(Z),V=SQ(W,$,X,J*4),H=Y?$:$.toLowerCase(),K=[];for(let w of V){if(w.role!=="user"&&w.role!=="assistant")continue;let B=HZ(w.text,H,Y,w.session_id,w.role,w.timestamp??void 0,0);if(B)K.push(B);if(K.length>=J)break}return K}catch{return null}}async function dB($,Z,J,Y){try{let Q=await t1.readFile($,"utf8"),U=Q.split(`
|
|
1662
1662
|
`).flatMap((w,B)=>{if(!w.trim())return[];try{return[{event:JSON.parse(w),index:B}]}catch{return[]}});if(!U.some(({event:w})=>w.type==="session_created"))return mB(U,Z,J,Y);let V=new Map(U.flatMap(({event:w,index:B})=>typeof w.id==="string"?[[w.id,B+1]]:[])),H=RQ(TQ(Q,$)),K=new Map;for(let w of H){if(w.type==="message_created"&&(w.data.role==="user"||w.data.role==="assistant"))K.set(w.data.messageId,{role:w.data.role,content:[],timestamp:w.timestamp,lineNumber:V.get(w.id)??0});if(w.type==="part_created"&&w.data.partType==="text"){let B=K.get(w.data.messageId),G=w.data.payload.text;if(B&&typeof G==="string")B.content.push(G)}}return[...K.values()].flatMap((w)=>{let B=HZ(w.content.join(" "),Z,J,Y,w.role,w.timestamp,w.lineNumber);return B?[B]:[]})}catch{return[]}}function mB($,Z,J,Y){return $.flatMap(({event:Q,index:W})=>{if(Q.type!=="message")return[];let U=Q.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let X=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",V=HZ(X,Z,J,Y,U.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,W+1);return V?[V]:[]})}function HZ($,Z,J,Y,Q,W,U){if(!$)return;let X=J?$:$.toLowerCase();if(!X.includes(Z))return;let V=X.indexOf(Z),H=Math.max(0,V-80),K=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(H>0?"...":"")+$.slice(H,K).replace(/\n/g," ")+(K<$.length?"...":""),timestamp:W,lineNumber:U}}function vQ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1663
1663
|
`];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(`
|
|
1664
1664
|
`)}var pB={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=g(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await kQ(Y,{maxResults:15,projectPath:Z.cwd}),W=vQ(Q);return J.sendMessage(W),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let W=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${W}`),{success:!1,error:W}}}},yQ=pB;var cB={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await D$(J,async(Y)=>{await Y.skills.refresh(),N1(J),await b1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return y().addAssistantMessage(Y),{success:!1,error:Y}}}},IQ=cB;import lB from"node:path";function v4($){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 xQ($){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 hQ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function iB($,Z){let J=g(Z),Y=$[0],Q=Z0.getInstance(),W=K0.getInstance(),U=Z.sessionId??"",X=Z.sessionId?{sessionId:Z.sessionId,projectPath:lB.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let G=$[1],_=$.slice(2).join(" ").trim();if(!G||!_)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 D=await Z.subagents.resume(G,_),F=`Resumed \`${G}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:G,subagent:D.session}}}if(Y==="clean"){let G=W.cleanupExpiredSessionsForParent(X??U,0);return J.sendMessage(`已清理 ${G} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${G} agent sessions`}}let V=[`**后台任务列表**
|