blade-code 0.10.150 → 0.10.152
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-cz77x04v.js → chunk-069ffeb6.js} +1 -1
- package/dist/{chunk-j8hbddjp.js → chunk-0b67y4j1.js} +2 -2
- package/dist/{chunk-8gg7zddg.js → chunk-0y8bxjwj.js} +1 -1
- package/dist/{chunk-3y2x6fb6.js → chunk-28tzj187.js} +1 -1
- package/dist/chunk-514va7ce.js +2 -0
- package/dist/{chunk-wcps5gjm.js → chunk-53vh6vpt.js} +1 -1
- package/dist/{chunk-mmcjckwx.js → chunk-5jabe6fh.js} +1 -1
- package/dist/{chunk-2mk914vk.js → chunk-5q4z0sfr.js} +2 -2
- package/dist/{chunk-mpexy01a.js → chunk-68y9kcyz.js} +1 -1
- package/dist/{chunk-qf6vf457.js → chunk-7mexgpjc.js} +1 -1
- package/dist/{chunk-4wx5sya5.js → chunk-7xtxvrh8.js} +1 -1
- package/dist/chunk-8g3dph9d.js +14 -0
- package/dist/{chunk-wkjdgbnx.js → chunk-9daqcc7x.js} +1 -1
- package/dist/{chunk-4cdk4mds.js → chunk-9kj19a8t.js} +1 -1
- package/dist/{chunk-jq5bhnrd.js → chunk-9tk6wq70.js} +1 -1
- package/dist/{chunk-3rv3fnwr.js → chunk-ae8966n2.js} +1 -1
- package/dist/{chunk-dxtbv0v7.js → chunk-azc480af.js} +1 -1
- package/dist/chunk-c0n0fxkt.js +1 -0
- package/dist/{chunk-3tvkp2yd.js → chunk-ce7e73tx.js} +1 -1
- package/dist/{chunk-87xebr2g.js → chunk-cv4h5c96.js} +1 -1
- package/dist/chunk-cvazye0h.js +733 -0
- package/dist/{chunk-d1navt68.js → chunk-d0q5n5ea.js} +3 -3
- package/dist/{chunk-cxenrejk.js → chunk-d5wbm0qg.js} +1 -1
- package/dist/chunk-dzeh2tx3.js +1 -0
- package/dist/{chunk-s1cs5ga0.js → chunk-e1j1gsr5.js} +2 -2
- package/dist/{chunk-3hgb942q.js → chunk-e8gmfajx.js} +1 -1
- package/dist/chunk-enf0egke.js +1 -0
- package/dist/{chunk-06hkf59s.js → chunk-erhaedch.js} +1 -1
- package/dist/{chunk-3kszepm6.js → chunk-ewwrss2w.js} +1 -1
- package/dist/{chunk-w6qfbea8.js → chunk-f2y0gxyq.js} +1 -1
- package/dist/chunk-fswy6tg3.js +1 -0
- package/dist/{chunk-mh9nqbwa.js → chunk-fx9vm1n5.js} +1 -1
- package/dist/{chunk-vj50xf5c.js → chunk-fxhjbst1.js} +1 -1
- package/dist/chunk-g3h54s6h.js +1 -0
- package/dist/chunk-genqngnt.js +10 -0
- package/dist/{chunk-rvs364rz.js → chunk-gm2yfq3r.js} +2 -2
- package/dist/chunk-gtajytct.js +1 -0
- package/dist/{chunk-6hb0pjmk.js → chunk-h1pw492p.js} +1 -1
- package/dist/{chunk-e12xrg41.js → chunk-ht8epjz2.js} +1 -1
- package/dist/{chunk-vbjgcn49.js → chunk-hv8nt7wj.js} +1 -1
- package/dist/chunk-j7784bxm.js +1 -0
- package/dist/{chunk-xmymx75h.js → chunk-jbpasjg9.js} +1 -1
- package/dist/{chunk-wv8dy886.js → chunk-jgqk2tmr.js} +3 -3
- package/dist/{chunk-2f8d0km4.js → chunk-jsv3e4k6.js} +1 -1
- package/dist/{chunk-z2k08r1h.js → chunk-k1tfry97.js} +1 -1
- package/dist/{chunk-shb7g2vr.js → chunk-k3ne93k8.js} +1 -1
- package/dist/{chunk-6vcqajdc.js → chunk-mt26v0vg.js} +1 -1
- package/dist/{chunk-ddvdc2p0.js → chunk-n34qsnks.js} +1 -1
- package/dist/{chunk-vw9paban.js → chunk-n9819k4p.js} +1 -1
- package/dist/chunk-nv1e4f05.js +1 -0
- package/dist/chunk-p9vtz642.js +1 -0
- package/dist/{chunk-zj1g4nbq.js → chunk-pv6cgfv1.js} +1 -1
- package/dist/{chunk-3a217980.js → chunk-q1rnvn85.js} +1 -1
- package/dist/{chunk-f71j03pq.js → chunk-qmveehgt.js} +1 -1
- package/dist/chunk-qv6s1q20.js +1 -0
- package/dist/{chunk-kv458q06.js → chunk-sd9bze9x.js} +1 -1
- package/dist/{chunk-eg3ms291.js → chunk-sdapqhj0.js} +1 -1
- package/dist/chunk-sgy87nrv.js +1 -0
- package/dist/{chunk-zyxfdewk.js → chunk-sj578593.js} +2 -2
- package/dist/chunk-sja01scc.js +1 -0
- package/dist/{chunk-2zzsyaf4.js → chunk-sncepfa3.js} +1 -1
- package/dist/{chunk-q5gcqckt.js → chunk-tq99wv62.js} +1 -1
- package/dist/{chunk-0tzecdv3.js → chunk-tya95jej.js} +1 -1
- package/dist/{chunk-wzqcea6x.js → chunk-v1mamd1x.js} +1 -1
- package/dist/{chunk-6a16zba3.js → chunk-v67st2xb.js} +1 -1
- package/dist/{chunk-ghqvews8.js → chunk-w1e6gagm.js} +1 -1
- package/dist/{chunk-9a0cy4z7.js → chunk-wfynmt9r.js} +2 -2
- package/dist/{chunk-mhb3gg9s.js → chunk-wpa74vxq.js} +2 -2
- package/dist/{chunk-01framym.js → chunk-y5dbpqzw.js} +1 -1
- package/dist/{chunk-sxvhv62s.js → chunk-yvccs002.js} +1 -1
- package/dist/chunk-zqjm9yd8.js +1 -0
- package/dist/{chunk-qm0j4szw.js → chunk-zrgfvc4k.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-0ktd3vpk.js +0 -10
- package/dist/chunk-25zrctsh.js +0 -1
- package/dist/chunk-5v0jcyea.js +0 -2
- package/dist/chunk-5y4btx3c.js +0 -1
- package/dist/chunk-66wk3exc.js +0 -1
- package/dist/chunk-8s93p05b.js +0 -1
- package/dist/chunk-ahz3sskk.js +0 -1
- package/dist/chunk-d9q5dn00.js +0 -1
- package/dist/chunk-ddxpgrcv.js +0 -14
- package/dist/chunk-fkbnsn0a.js +0 -1
- package/dist/chunk-h8s11k0r.js +0 -733
- package/dist/chunk-k5m9yj9n.js +0 -1
- package/dist/chunk-n14kcb52.js +0 -1
- package/dist/chunk-q8erftv7.js +0 -1
- package/dist/chunk-qypjj8rk.js +0 -1
- package/dist/chunk-rxc6mazk.js +0 -1
- package/dist/chunk-xtbcwn9q.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ti as K}from"./chunk-sd9bze9x.js";import{Ui as wt,Vi as ft}from"./chunk-514va7ce.js";import{aj as I}from"./chunk-jsv3e4k6.js";import{bj as tt,cj as Dt,dj as Bt,hj as Gt,ij as et,jj as Kt,kj as Ht,lj as Yt,mj as cn,nj as Ft,oj as qt,pj as Mt,qj as Vt,rj as Jt,sj as _t,tj as Qt,uj as jt,vj as Wt,wj as Zt,xj as kt,yj as yt}from"./chunk-n34qsnks.js";import{Cj as Un,Ej as bn,Fj as _n,Gj as T}from"./chunk-5q4z0sfr.js";import{Lj as zt,Oj as v}from"./chunk-0b67y4j1.js";import{Wj as xn,Xj as Cn}from"./chunk-e1j1gsr5.js";import{bk as a}from"./chunk-gm2yfq3r.js";import{ek as Ln}from"./chunk-7xtxvrh8.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -41,4 +41,4 @@ ${e.map((M)=>` - ${M}`).join(`
|
|
|
41
41
|
]
|
|
42
42
|
}
|
|
43
43
|
`)}}function W_(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)e.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)e.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)e.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;if(t.maxResidentSessionProjections!==void 0)e.maxResidentSessionProjections=t.maxResidentSessionProjections;if(t.sessionProjectionIdleMs!==void 0)e.sessionProjectionIdleMs=t.sessionProjectionIdleMs;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
|
|
44
|
-
export{B as
|
|
44
|
+
export{B as Dh,nn as Eh,f as Fh,En as Gh,hn as Hh,C as Ih,ot as Jh,VM as Kh,W as Lh,jM as Mh,WM as Nh,ZM as Oh,ct as Ph,Ce as Qh,kM as Rh,he as Sh,yM as Th,Pt as Uh,n_ as Vh,t_ as Wh,M_ as Xh,__ as Yh,r_ as Zh,Ct as _h,S_ as $h,E_ as ai,u_ as bi,o_ as ci,Y as di,Rn as ei,F as fi,q as gi,Xn as hi,V as ii,TM as ji,sM as ki,J as li,Q as mi,h as ni,xM as oi,zn as pi,Dn as qi,hM as ri,Bn as si,Gn as ti,Kn as ui,Hn as vi,Yn as wi,Fn as xi,XM as yi,qn as zi,Vn as Ai,Jn as Bi,Qn as Ci,jn as Di,Wn as Ei,Zn as Fi,kn as Gi,yn as Hi,ln as Ii,vn as Ji,nt as Ki,s as Li,d as Mi,Le as Ni,z as Oi,l as Pi,X as Qi,W_ as Ri};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{vc as H8}from"./chunk-wm896gnx.js";import{$d as P6,Ac as p1,Cc as X$,Dd as f2,Ed as j8,Fd as z8,Gd as Z6,Hd as r1,Id as B8,Jd as U8,Kd as u1,Od as uJ,Xd as I0,Zd as N6,_d as m1,ge as J1,sd as G2,ud as F2,vd as L2,wc as U$,wd as Q6,xd as K6,yc as B$,zc as q2}from"./chunk-f71j03pq.js";import{le as X8}from"./chunk-9xbwtjac.js";import{De as w1,oe as D0,re as W2,se as C$}from"./chunk-3a217980.js";import{cg as M2}from"./chunk-7xhw74hk.js";import{dg as Q8,eg as c0,fg as $8,gg as xJ,ig as I1,jg as A6,kg as vJ,lg as CJ,og as IJ}from"./chunk-z2k08r1h.js";import{bh as Z$,ch as l0,fh as K8}from"./chunk-3kszepm6.js";import{kh as d2,oh as aJ}from"./chunk-wcps5gjm.js";import{zh as b$}from"./chunk-wv8dy886.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as z0}from"./chunk-2f8d0km4.js";import{Dj as b0}from"./chunk-2mk914vk.js";import{Xj as D2}from"./chunk-s1cs5ga0.js";import{Bk as zJ,Ck as i1,Ek as B2,Jk as U2,Kk as w2,fk as z2,uk as Q2,vk as K2,yk as Y1}from"./chunk-4wx5sya5.js";import{Mk as vZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function P$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class T1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(P$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!P$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!P$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(P$),this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function l6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function i6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function r6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import K$ from"node:path";var P8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),y8=/^(LD_.+|DYLD_.+|PATH)$/,n6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function s$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(!P8.has(Q))break;Z=Y}return Z}function v5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(y8.test(Q))break;Z=Y}return Z}var _8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function _Z($){let Z=$,J=!0;while(J){J=!1;for(let W of _8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function t$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){J+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,J+=K;continue}if(K==='"'&&!W){Y=!Y,J+=K;continue}if(W||Y){J+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(K==="&")return null;if(K===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=K}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function o6($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!Z){W=!0;continue}if(V==="'"&&!J){Z=!Z;continue}if(V==='"'&&!Z){J=!J;continue}if(Z)continue;if(V==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(J)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;J+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(J)Z.push(J),J="";continue}J+=K}if(J)Z.push(J);return Z}var b8=new Set(["npm","pnpm","yarn","bun"]),a6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),E8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),S8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function R8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function s6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function T8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=K$.isAbsolute(V)?K$.resolve(V):K$.resolve(J,V);if(!X$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function M8($){let Z=[],J=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[V+1]==="|")return;Z.push(V)}return Z}function k8($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(Z.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function h8($){let Z=s6($.replace(S8,"").trim()),J=M8(Z);if(!J)return;if(J.length===0)return t6(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=s6(Z.slice(0,W).trim()),V=Z.slice(W+1).trim();if(!Y||!k8(V))return;return t6(Y)}function t6($){let J=t$($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((K)=>K==="--configLoader"||K.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function _$($,Z){let J=h8($);if(!J)return!1;let W=s$(J),Y=t$(W);if(!Y||o6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:T8(W,Y,Z);if(!V)return!1;let Q=Q$(V);if(Q.length===0||Q.some((z)=>[...E8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(b8.has(K??""))return R8(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&a6.has(X??""))return!0;if(a6.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function p5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!K$.isAbsolute($);let J=K$.isAbsolute($)?K$.resolve($):K$.resolve(Z,$);return X$.isWithinWorkspace(J,Z)}var bZ=b0("Agent"),x8=3;function EZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=x8)return{action:"truncated"};if(l6(J)==="stop")return bZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var v8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],C8=/```[\s\S]{50,}```/,e6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",I8=2;function SZ($,Z,J=!0){if(!$||Z>=I8)return{action:"none"};if(!J&&C8.test($))return{action:"retry",prompt:e6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(v8.some((Q)=>Q.test(W)))return{action:"retry",prompt:e6};return{action:"none"}}var u8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],$J={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},g8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},p8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",d8="Required verification did not run successfully before the retry limit.",m8=3;function JJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&_$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&_$(V,W))$.add(V)}function RZ($,Z,J){if(!$||!u8.some((X)=>X.test($)))return{action:"none"};let W=Object.keys($J).filter((X)=>$J[X].test($)),Y=[...Z],V=W.filter((X)=>!Y.some((H)=>g8[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>_$(X)))return{action:"none"};if(J>=m8)return{action:"fail",message:d8};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${p8}${K}`}}var c8=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],WJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function YJ($){return typeof $==="string"&&WJ.some((Z)=>Z.test($))}var l8=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],i8=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function r8($){if(typeof $!=="string")return;if(i8.some((Z)=>Z.test($)))return"multiple-allowed";return l8.some((Z)=>Z.test($))?"required":void 0}function $1($){for(let Z of $){let J=r8(Z);if(J!==void 0)return J==="required"}return!1}var n8="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",o8="Required delegation did not complete before the retry limit.",a8=3;function VJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=$1(W),V=!1;if(!Y)for(let Q of W){if(WJ.some((K)=>K.test(Q)))break;if(c8.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||Z.has("Task"))return{action:"none"};if(J>=a8)return{action:"fail",message:o8};return{action:"retry",prompt:n8}}var s8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],t8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],e8=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function QJ($){return e8.reduce((Z,J)=>Z.replace(J," "),$)}function M1($){if(typeof $!=="string")return!1;let Z=QJ($);return s8.some((J)=>J.test(Z))}var $9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",Z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",J9="Required worktree lifecycle did not complete before the retry limit.",W9=3;function KJ($,Z,J){if(!$)return{action:"none"};let W=QJ($);if(!M1(W))return{action:"none"};let Y=t8.some((Q)=>Q.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let V=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(J>=W9)return{action:"fail",message:J9};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?$9:Z9}}var ZJ=30000;async function TZ($){try{let J=b$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??z0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),ZJ)});try{let V=await Promise.race([J,Y]);if(V==="timeout")return bZ.warn(`[Loop] Stop hook 超时 (${ZJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return bZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function Y9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var V9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function Q9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function K9($){let Z=$;for(let X of V9)Z=Z.replace(X," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),Q=V.lastIndexOf(" ");return`${(Q>36?V.slice(0,Q):V).trimEnd()}…`}function XJ($){return K9(Q9($))}import{EventEmitter as X9}from"events";import HJ from"node:path";function MZ($){if(zJ($.sessionId),!HJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:HJ.resolve($.projectPath)}}function jJ($){let Z=MZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function $3($,Z){return jJ($)===jJ(Z)}class E$ extends X9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!E$.instance)E$.instance=new E$;return E$.instance}publish($,Z,J,W){let Y=MZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var Z1=E$.getInstance();var s0=b0("Agent"),k1=new Set;async function H9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(k1.has(J))return;if(k1.size>=5000)k1.clear();k1.add(J);try{let W=$.workspaceRoot,Y=await J1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=XJ(Z);if(!V)return;await J1.updateSessionMetadata(J,Y.projectPath,{title:V}),Z1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var kZ=`<turn_aborted>
|
|
1
|
+
import{vc as H8}from"./chunk-wm896gnx.js";import{$d as P6,Ac as p1,Cc as X$,Dd as f2,Ed as j8,Fd as z8,Gd as Z6,Hd as r1,Id as B8,Jd as U8,Kd as u1,Od as uJ,Xd as I0,Zd as N6,_d as m1,ge as J1,sd as G2,ud as F2,vd as L2,wc as U$,wd as Q6,xd as K6,yc as B$,zc as q2}from"./chunk-qmveehgt.js";import{le as X8}from"./chunk-9xbwtjac.js";import{De as w1,oe as D0,re as W2,se as C$}from"./chunk-q1rnvn85.js";import{cg as M2}from"./chunk-7xhw74hk.js";import{dg as Q8,eg as c0,fg as $8,gg as xJ,ig as I1,jg as A6,kg as vJ,lg as CJ,og as IJ}from"./chunk-k1tfry97.js";import{ah as Z$,bh as l0,eh as K8}from"./chunk-ewwrss2w.js";import{jh as d2,nh as aJ}from"./chunk-53vh6vpt.js";import{yh as b$}from"./chunk-jgqk2tmr.js";import{Ti as R$}from"./chunk-sd9bze9x.js";import{aj as z0}from"./chunk-jsv3e4k6.js";import{Cj as b0}from"./chunk-5q4z0sfr.js";import{Wj as D2}from"./chunk-e1j1gsr5.js";import{Ak as zJ,Bk as i1,Dk as B2,Ik as U2,Jk as w2,ek as z2,tk as Q2,uk as K2,xk as Y1}from"./chunk-7xtxvrh8.js";import{Lk as vZ}from"./chunk-sdapqhj0.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function P$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class T1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(P$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!P$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!P$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(P$),this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function l6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function i6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function r6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import K$ from"node:path";var P8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),y8=/^(LD_.+|DYLD_.+|PATH)$/,n6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function s$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(!P8.has(Q))break;Z=Y}return Z}function v5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(y8.test(Q))break;Z=Y}return Z}var _8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function _Z($){let Z=$,J=!0;while(J){J=!1;for(let W of _8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function t$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){J+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,J+=K;continue}if(K==='"'&&!W){Y=!Y,J+=K;continue}if(W||Y){J+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(K==="&")return null;if(K===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=K}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function o6($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!Z){W=!0;continue}if(V==="'"&&!J){Z=!Z;continue}if(V==='"'&&!Z){J=!J;continue}if(Z)continue;if(V==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(J)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;J+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(J)Z.push(J),J="";continue}J+=K}if(J)Z.push(J);return Z}var b8=new Set(["npm","pnpm","yarn","bun"]),a6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),E8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),S8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function R8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function s6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function T8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=K$.isAbsolute(V)?K$.resolve(V):K$.resolve(J,V);if(!X$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function M8($){let Z=[],J=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[V+1]==="|")return;Z.push(V)}return Z}function k8($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(Z.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function h8($){let Z=s6($.replace(S8,"").trim()),J=M8(Z);if(!J)return;if(J.length===0)return t6(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=s6(Z.slice(0,W).trim()),V=Z.slice(W+1).trim();if(!Y||!k8(V))return;return t6(Y)}function t6($){let J=t$($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((K)=>K==="--configLoader"||K.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function _$($,Z){let J=h8($);if(!J)return!1;let W=s$(J),Y=t$(W);if(!Y||o6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:T8(W,Y,Z);if(!V)return!1;let Q=Q$(V);if(Q.length===0||Q.some((z)=>[...E8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(b8.has(K??""))return R8(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&a6.has(X??""))return!0;if(a6.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function p5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!K$.isAbsolute($);let J=K$.isAbsolute($)?K$.resolve($):K$.resolve(Z,$);return X$.isWithinWorkspace(J,Z)}var bZ=b0("Agent"),x8=3;function EZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=x8)return{action:"truncated"};if(l6(J)==="stop")return bZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var v8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],C8=/```[\s\S]{50,}```/,e6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",I8=2;function SZ($,Z,J=!0){if(!$||Z>=I8)return{action:"none"};if(!J&&C8.test($))return{action:"retry",prompt:e6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(v8.some((Q)=>Q.test(W)))return{action:"retry",prompt:e6};return{action:"none"}}var u8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],$J={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},g8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},p8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",d8="Required verification did not run successfully before the retry limit.",m8=3;function JJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&_$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&_$(V,W))$.add(V)}function RZ($,Z,J){if(!$||!u8.some((X)=>X.test($)))return{action:"none"};let W=Object.keys($J).filter((X)=>$J[X].test($)),Y=[...Z],V=W.filter((X)=>!Y.some((H)=>g8[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>_$(X)))return{action:"none"};if(J>=m8)return{action:"fail",message:d8};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${p8}${K}`}}var c8=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],WJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function YJ($){return typeof $==="string"&&WJ.some((Z)=>Z.test($))}var l8=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],i8=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function r8($){if(typeof $!=="string")return;if(i8.some((Z)=>Z.test($)))return"multiple-allowed";return l8.some((Z)=>Z.test($))?"required":void 0}function $1($){for(let Z of $){let J=r8(Z);if(J!==void 0)return J==="required"}return!1}var n8="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",o8="Required delegation did not complete before the retry limit.",a8=3;function VJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=$1(W),V=!1;if(!Y)for(let Q of W){if(WJ.some((K)=>K.test(Q)))break;if(c8.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||Z.has("Task"))return{action:"none"};if(J>=a8)return{action:"fail",message:o8};return{action:"retry",prompt:n8}}var s8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],t8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],e8=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function QJ($){return e8.reduce((Z,J)=>Z.replace(J," "),$)}function M1($){if(typeof $!=="string")return!1;let Z=QJ($);return s8.some((J)=>J.test(Z))}var $9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",Z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",J9="Required worktree lifecycle did not complete before the retry limit.",W9=3;function KJ($,Z,J){if(!$)return{action:"none"};let W=QJ($);if(!M1(W))return{action:"none"};let Y=t8.some((Q)=>Q.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let V=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(J>=W9)return{action:"fail",message:J9};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?$9:Z9}}var ZJ=30000;async function TZ($){try{let J=b$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??z0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),ZJ)});try{let V=await Promise.race([J,Y]);if(V==="timeout")return bZ.warn(`[Loop] Stop hook 超时 (${ZJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return bZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function Y9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var V9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function Q9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function K9($){let Z=$;for(let X of V9)Z=Z.replace(X," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),Q=V.lastIndexOf(" ");return`${(Q>36?V.slice(0,Q):V).trimEnd()}…`}function XJ($){return K9(Q9($))}import{EventEmitter as X9}from"events";import HJ from"node:path";function MZ($){if(zJ($.sessionId),!HJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:HJ.resolve($.projectPath)}}function jJ($){let Z=MZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function $3($,Z){return jJ($)===jJ(Z)}class E$ extends X9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!E$.instance)E$.instance=new E$;return E$.instance}publish($,Z,J,W){let Y=MZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var Z1=E$.getInstance();var s0=b0("Agent"),k1=new Set;async function H9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(k1.has(J))return;if(k1.size>=5000)k1.clear();k1.add(J);try{let W=$.workspaceRoot,Y=await J1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=XJ(Z);if(!V)return;await J1.updateSessionMetadata(J,Y.projectPath,{title:V}),Z1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var kZ=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",BJ="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class S$ extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function j$($){return $.executionEngine?.getContextManager()}async function m0($,Z,J,W=null,Y,V={}){let Q=V.required??$.executionEngine!==void 0;try{let K=j$($),X=typeof J==="string"?J.trim()!=="":J.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(K&&Z.sessionId&&X){let H=await K.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(Q&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)H9(Z,J);return H}if(Q&&Z.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(K){if(s0.warn("[Loop] 保存用户消息失败:",K),Q)throw new S$("user_message",{cause:K})}return null}async function x0($,Z,J,W,Y,V,Q={}){let K=Q.required??$.executionEngine!==void 0;try{let X=j$($),H=Boolean(J.trim()||Y?.trim());if(X&&Z.sessionId&&H){let z=await X.saveMessage(Z.sessionId,"assistant",J,W,V,Z.subagentInfo,Y);if(K&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(K&&Z.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(s0.warn("[Loop] 保存助手消息失败:",X),K)throw new S$("assistant_message",{cause:X})}return null}async function UJ($,Z,J){try{let W=j$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",kZ,J,void 0,Z.subagentInfo)}catch(W){s0.warn("[Loop] 保存中断边界失败:",W)}return null}async function wJ($,Z,J,W,Y){try{let V=j$($);if(!V||!Z.sessionId||J.length===0)return null;return await V.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((Q)=>({...Q})))),triggerPaths:[...W]},Z.subagentInfo)}catch(V){s0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function hZ($,Z,J,W,Y,V={}){try{let Q=j$($);if(Q&&Z.sessionId){let K=await Q.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,V.providerToolCallId);if(V.required&&!K)throw Error("Durable tool-use commit returned no identity");return K}if(V.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(Q){if(s0.warn("[Loop] 保存工具调用失败:",Q),V.required)throw Q}return null}async function h1($,Z,J,W,Y,V,Q,K,X,H={}){try{let z=j$($);if(z&&Z.sessionId){let B=await z.saveToolResult(Z.sessionId,J,W,Y,V,Q,Z.subagentInfo,K,X);if(H.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(H.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if(s0.warn("[Loop] 保存工具结果失败:",z),H.required)throw z}return null}async function W1($,Z,J,W,Y={}){try{let V=j$($);if(V&&Z.sessionId){let Q=await V.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!Q)throw Error("Compaction checkpoint commit returned no identity");return Q||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(s0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function f0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:Q,controlPrompt:K,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=Q,z=await x0(Z,J,Y,H,V);if(z)H=z;if(K!==void 0){let B={role:"user",content:K};if(X)B.metadata=X;W.appendControl("user",B);let j=await m0(Z,J,B.content,H,X);if(j)H=j}return H}import{createHash as y6}from"node:crypto";import{promises as C9}from"node:fs";import I9 from"node:path";import{nanoid as e0}from"nanoid";import*as t from"node:fs/promises";import*as t0 from"node:path";import qJ from"write-file-atomic";var DJ={enabled:!0,maxIndexLines:200};var j9="memory",xZ="MEMORY.md",CZ="<!-- blade:auto-memory-topics:start -->",x1="<!-- blade:auto-memory-topics:end -->",z9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},B9=new R$,GJ;function LJ($){return $.trim().replace(/\s+/g," ")}function U9($){return LJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function w9($){return[CZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),x1].join(`
|
|
4
4
|
`)}function D9($,Z){let J=w9(Z),W=$.indexOf(CZ),Y=$.indexOf(x1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+x1.length);if(!$)return`${J}
|
|
@@ -93,7 +93,7 @@ Full output saved to: ${K}`}catch{return`${Z}
|
|
|
93
93
|
${Y}`}}function sJ(){return{successfulBash:!1}}function V4($){return typeof $==="string"&&aJ.some((Z)=>Z===$)}function j7($){switch($){case"timeout":case"admission":case"spawn":case"finalization":return $;case"unavailable":return"terminal";default:return}}function z7($){return["<goal-execution-host-failure>",`Category: ${$.category}`,`Consecutive turns: ${$.consecutiveCount}/3`,"</goal-execution-host-failure>","","The execution host has failed in consecutive Goal turns. Do not blindly","repeat the same command path. Validate shell, sandbox, and terminal","availability, then switch to a different executable strategy or call","UpdateGoal blocked with concrete evidence if external intervention is required."].join(`
|
|
94
94
|
`)}function tJ($,Z,J){if(Z!=="Bash")return;if(J.success){$.successfulBash=!0;return}let W=J.metadata?.execution_host_failure;if(V4(W))$.category=W}function eJ($){return $.successfulBash?void 0:$.category}import b4 from"node:path";import{nanoid as E4}from"nanoid";import{randomUUID as j1}from"node:crypto";import*as v0 from"node:fs/promises";import*as Y2 from"node:path";import{Mutex as z4}from"async-mutex";import B4 from"write-file-atomic";var $2=120,sZ=128;function H1($){if(!Array.isArray($)||$.length>120||!$.every((Z)=>typeof Z==="string"&&Z.length>0&&Z.length<=128))return;return[...new Set($)]}function Q4($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let Z=$.recovery;if(typeof Z!=="object"||Array.isArray(Z))return[];if(!("version"in Z)||Z.version!==1&&Z.version!==2&&Z.version!==3||!("inputMessageIds"in Z)||!("hadSuccessfulToolResult"in Z)||typeof Z.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in Z)||typeof Z.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if((Z.version===2||Z.version===3)&&(!("interruptedToolCallCount"in Z)||!Number.isSafeInteger(Z.interruptedToolCallCount)||Z.interruptedToolCallCount<0))return[];if(Z.version===3&&(!("allSuccessfulToolResultsSafeForResume"in Z)||typeof Z.allSuccessfulToolResultsSafeForResume!=="boolean"))return[];let J=H1(Z.inputMessageIds),W=H1($.acknowledgedInputMessageIds);if(!J||!W)return[];let Y=new Set(J);return W.filter((V)=>Y.has(V))}function g1($,Z){let J=$[Z];if(J?.type!=="turn_aborted")return[];let W=Q4(J.data);if(W.length===0)return[];let Y=-1;for(let Q=Z-1;Q>=0;Q--){let K=$[Q];if(K.type==="turn_started"){if(K.data.turnId!==J.data.turnId)return[];Y=Q;break}if(K.type==="turn_completed"||K.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let Q=Y+1;Q<Z;Q++){let K=$[Q];if(K.type!=="message_created"||K.data.role!=="user")continue;let X=K.data.metadata,H=K.data.inboxMessageId!==void 0?K.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=128)V.add(H)}return W.filter((Q)=>V.has(Q))}import*as d1 from"node:fs/promises";import*as J2 from"node:path";var K4={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},X4=new R$,Z2;async function x$($,Z,J,W=j4){let Y=B$($,Z);return X4.runExclusive(Y,()=>p1($,Z,async(V)=>{let Q=J2.dirname(V.inboxPath);await d1.mkdir(Q,{recursive:!0,mode:448}),await d1.chmod(Q,448);let K,X=await W(V.inboxPath,{...K4,onCompromised:(H)=>{K=H}});try{if(K)throw K;let H=await J(V);if(K)throw K;return H}finally{await X()}}))}async function H4(){return Z2??=await import("proper-lockfile"),Z2}async function j4($,Z){return(await H4()).lock($,Z)}var $6=2,v$=8388608;function tZ($,Z,J){let W={version:$6,sessionId:$,generation:Z,messages:J.map(({recovered:Y,...V})=>V)};return`${JSON.stringify(W)}
|
|
95
95
|
`}function eZ($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function U4($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((Z)=>{if(!Z||typeof Z!=="object"||!("type"in Z))return!1;if(Z.type==="text")return"text"in Z&&typeof Z.text==="string";return Z.type==="image_url"&&"image_url"in Z&&typeof Z.image_url==="object"&&Z.image_url!==null&&"url"in Z.image_url&&typeof Z.image_url.url==="string"})}function w4($,Z,J){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==$6||!("sessionId"in W)||W.sessionId!==J||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${Z}`);let Y=W.messages.map((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!U4(V.content)||!("queuedAt"in V)||typeof V.queuedAt!=="number"||"persisted"in V&&typeof V.persisted!=="boolean"||"origin"in V&&V.origin!=="user"&&V.origin!=="background_subagent"&&V.origin!=="team_message"&&V.origin!=="interaction_recovery"&&V.origin!=="user_shell"||"metadata"in V&&(V.metadata===null||typeof V.metadata!=="object"||Array.isArray(V.metadata))||"outputSchema"in V&&V.outputSchema!==void 0&&(!V.outputSchema||typeof V.outputSchema!=="object"||Array.isArray(V.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let Q="outputSchema"in V&&V.outputSchema!==void 0?m1(V.outputSchema).schema:void 0;return{id:V.id,content:V.content,queuedAt:V.queuedAt,..."persisted"in V&&V.persisted===!0?{persisted:!0}:{},..."origin"in V&&V.origin?{origin:V.origin}:{},..."metadata"in V&&V.metadata?{metadata:JSON.parse(JSON.stringify(V.metadata))}:{},...Q?{outputSchema:Q}:{}}});if(new Set(Y.map((V)=>V.id)).size!==Y.length)throw Error(`Duplicate steering inbox message: ${Z}`);if(W.version===1)return{version:1,sessionId:J,messages:Y};if(!("generation"in W)||typeof W.generation!=="string"||!/^[a-f0-9-]{36}$/.test(W.generation))throw Error(`Invalid steering inbox generation: ${Z}`);return{version:$6,sessionId:J,generation:W.generation,messages:Y}}function D4($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return g1($,J);return[]}))}function q4($){return new Set($.flatMap((Z)=>{if(Z.type!=="message_created"||Z.data.role!=="user")return[];let J=Z.data.metadata,W=Z.data.inboxMessageId!==void 0?Z.data.inboxMessageId:J!==null&&typeof J==="object"&&!Array.isArray(J)?J.inboxMessageId:void 0;return typeof W==="string"?[W]:[]}))}class c1{sessionId;stateStorage;writeFile;lockFile;mutex=new z4;generation=j1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=U$($),W={}){let Y=new c1(Z,J,W.writeFile??B4,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.messages.some((X)=>X.id===$.id))return{accepted:!0,snapshot:Y};if(Z&&!Z(Y.messages))return{accepted:!1,snapshot:Y};let V=[...Y.messages,{...$,recovered:!1}],Q=j1(),K=tZ(this.sessionId,Q,V);if(Buffer.byteLength(K)>v$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(V,Q,W,K),{accepted:!0,snapshot:{generation:Q,messages:V}}},this.lockFile);return this.install(J.snapshot),J.accepted})}async acknowledge($){if($.length===0)return;let Z=new Set($);await this.mutex.runExclusive(async()=>{let J=await x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),V=Y.messages.filter((K)=>!Z.has(K.id));if(V.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let Q=j1();return await this.persistAtPath(V,Q,W),{generation:Q,messages:V}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await x$(this.stateStorage,this.sessionId,(Z)=>this.readAndReconcileAtPath(Z),this.lockFile);return this.install($),this.snapshot()})}async replace($,Z){return this.mutex.runExclusive(async()=>{let J=await x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let V=j1(),Q=Z.map((X)=>({...X})),K=tZ(this.sessionId,V,Q);if(Buffer.byteLength(K)>v$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(Q,V,W,K),{replaced:!0,snapshot:{generation:V,messages:Q}}},this.lockFile);return this.install(J.snapshot),{replaced:J.replaced,snapshot:this.snapshot()}})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((Z)=>Z.type==="text"?{...Z}:{...Z,image_url:{...Z.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $=await x$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=j1();return await this.persistAtPath(J.messages,W,Z),{generation:W,messages:J.messages}}return J},this.lockFile);this.install($)})}install($){this.generation=$.generation,this.messages=$.messages}async readAndReconcileAtPath($){let Z;try{let Q=await v0.open($.inboxPath,"r");try{if((await Q.stat()).size>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${$.inboxPath}`);Z=w4(await Q.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await Q.close()}await v0.chmod($.inboxPath,384)}catch(Q){if(!eZ(Q,"ENOENT"))throw Q}let J=new Set,W=new Set;try{let Q=W2(await v0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=D4(Q),W=q4(Q)}catch(Q){if(!eZ(Q,"ENOENT"))throw Q}let Y=new Map(this.messages.map((Q)=>[Q.id,Q.recovered])),V=(Z?.messages??[]).filter((Q)=>!J.has(Q.id)).map((Q)=>({...Q,recovered:Y.get(Q.id)??!0,...Q.persisted===!0||W.has(Q.id)?{persisted:!0}:{}}));return{generation:Z?.version===2?Z.generation:this.generation,messages:V,...Z?.version===1&&V.length>0?{migrationRequired:!0}:{},...Z&&V.length!==Z.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,Z,J,W){if(await v0.mkdir(Y2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await v0.unlink(J.inboxPath).catch((V)=>{if(!eZ(V,"ENOENT"))throw V});return}let Y=W??tZ(this.sessionId,Z,$);if(Buffer.byteLength(Y)>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as C0 from"node:fs/promises";import*as O2 from"node:path";import{nanoid as B0}from"nanoid";var V2=256;class O0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,Z,J){this.sessionId=$;this.projectPath=Z;this.storage=J}static for($,Z,J=U$(Z)){let W=B$(J,$),Y=O0.instances.get(W);if(!Y)Y=new O0($,Z,J),O0.instances.set(W,Y),O0.pruneIdleInstances(W);else O0.instances.delete(W),O0.instances.set(W,Y);return Y}static release($,Z,J=U$(Z)){O0.instances.delete(B$(J,$))}static pruneIdleInstances($){if(O0.instances.size<=V2)return;for(let[Z,J]of O0.instances){if(Z===$||J.subscribers.size>0)continue;if(O0.instances.delete(Z),O0.instances.size<=V2)return}}get lastSeq(){return this.highestSeq}async readAll(){return this.withStore(async($,Z,J)=>{let W=Z?await $.readAllValidated(Z):await $.readAll();return J(W),W})}async commit($){let[Z]=await this.commitEntries([$]);return this.record(Z),Z}async commitBatch($){if($.length===0)return[];let Z=await this.commitEntries($);for(let J of Z)this.record(J);return Z}async commitValidated($){let Z=await this.withStore((J,W,Y)=>J.appendValidated((V)=>{return Y(V),$(V)},W));return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.withStore((J,W,Y)=>J.appendValidatedBatch((V)=>{return Y(V),$(V)},W));for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);Z1.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,Z){if(this.subscribers.add($),Z?.fromSeq!==void 0)this.replay($,Z.fromSeq);return()=>{this.subscribers.delete($),O0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,V)=>{let Q=Y?await W.readAllValidated(Y):await W.readAll();return V(Q),Q.filter((K)=>(K.seq??0)>=Z)});for(let W of J){if(Z6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(Z6($))return;for(let Z of this.subscribers){let J=Z.onCommitted($);if(J)Promise.resolve(J).catch(()=>{return})}Z1.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}commitEntries($){return this.withStore((Z,J,W)=>J?Z.appendValidatedBatch((Y)=>{return W(Y),$},J):Z.appendBatch($))}withStore($){return p1(this.storage,this.sessionId,async(Z)=>{let J=new C$(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(Q)=>{await Q2(W,Z.transcriptPath,Q)}},(Q)=>{K2(Q,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function w$($){let Z=null,J=null;for(let W of $){if(W.type==="turn_started"){Z=W.data;continue}if(W.type==="turn_completed")J={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")J={type:"turn_aborted",data:W.data};else continue;if(Z?.turnId===J.data.turnId)Z=null}return{active:Z,lastTerminal:J}}class _0 extends Error{}var G4="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function J6($,Z){let J=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===Z);if(J<0)return!1;return $.slice(J+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function X2($,Z){let J=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===Z);if(J<0)return[];let W=[];for(let Y of $.slice(J+1)){if(Y.type==="turn_started"&&Y.data.turnId!==Z||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===Z)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let V=Y.data.metadata,Q=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof Q==="string"&&Q.length>0&&Q.length<=sZ)W.push(Q)}return[...new Set(W)]}function A2($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let Z="inputMessageIds"in $?H1($.inputMessageIds):void 0;if(!Z||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let J=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(J===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:Z,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:J,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function F4($,Z){let J=$.findLastIndex((K)=>K.type==="turn_started"&&K.data.turnId===Z);if(J<0)return 0;let W=$.findIndex((K,X)=>X>J&&K.type==="turn_started"&&K.data.turnId!==Z),Y=$.slice(J+1,W<0?void 0:W),V=new Set(Y.flatMap((K)=>{if(K.type!=="part_created"||K.data.partType!=="tool_call")return[];let X=K.data.payload;return X&&typeof X==="object"&&!Array.isArray(X)?[typeof X.toolCallId==="string"?X.toolCallId:K.data.partId]:[K.data.partId]})),Q=new Set;for(let K of Y){if(K.type!=="part_created"||K.data.partType!=="tool_result")continue;let X=K.data.payload;if(!X||typeof X!=="object"||Array.isArray(X))continue;let H=typeof X.toolCallId==="string"?X.toolCallId:K.data.partId,z=X.metadata;if(V.has(H)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)Q.add(H)}return Q.size}function N2($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return g1($,J);return[]}))}function W6($,Z,J=[]){let W=A2(Z.data.recovery);if(!W)return;if($.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===Z.data.turnId))return;let Y=N2($);for(let K of J)Y.add(K);let V=W.inputMessageIds.filter((K)=>!Y.has(K)),Q=W.version===1?F4($,Z.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&Q===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...Q>0?{interruptedToolCallCount:Q}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function z1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=W6($,J);if(W)return W}return}function l1($,Z){let J=$.input,W=Z?.metadata,Y=Z?.subagentRef;if($.toolName!=="Task"||Z?.toolCallId!==$.toolCallId||Z.toolName!=="Task"||J===null||typeof J!=="object"||Array.isArray(J)||W===null||typeof W!=="object"||Array.isArray(W)||!Y)return!1;let{subagent_session_id:V,subagent_type:Q,description:K}=J,X=Y.subagentStatus==="completed"&&Z.error===void 0&&typeof Z.output==="string"||Y.subagentStatus==="failed"&&typeof Z.error==="string"&&Z.error.length>0&&Z.output===null;return typeof V==="string"&&V===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof K==="string"&&Y.subagentDescription===K&&W.description===K&&(Q===void 0||typeof Q==="string"&&Q===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&X&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var L4=1e4,f4=1e5,O4=2592000000,H2=128,A4=1e6,N4=256;function P4($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.goalId!=="string"||Z.goalId.length===0||Z.goalId.length>H2||typeof Z.verificationAttempt!=="number"||!Number.isSafeInteger(Z.verificationAttempt)||Z.verificationAttempt<1||Z.verificationAttempt>A4||typeof Z.verifierSessionId!=="string"||Z.verifierSessionId.length===0||Z.verifierSessionId.length>H2||typeof Z.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(Z.evidenceSha256)||typeof Z.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(Z.goalUpdatedAt)))return;return{goalId:Z.goalId,verificationAttempt:Z.verificationAttempt,verifierSessionId:Z.verifierSessionId,evidenceSha256:Z.evidenceSha256,goalUpdatedAt:Z.goalUpdatedAt}}function P2($,Z){let J=$.data.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let W=J.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,V=Y.turnId,Q=Y.inputMessageIds,K=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,z=Array.isArray(Q)?Q.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=sZ):[];if(typeof V!=="string"||V.length===0||V.length>128||Z!==void 0&&V!==Z||!Array.isArray(Q)||Q.length>$2||z.length!==Q.length||typeof K!=="number"||!Number.isSafeInteger(K)||K<0||K>L4||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>f4||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>O4)return;let B;if("goalFinalization"in Y){if(B=P4(Y.goalFinalization),!B)return}return{turnId:V,inputMessageIds:[...new Set(z)],turnsCount:K,toolCallsCount:X,durationMs:H,...B?{goalFinalization:B}:{}}}function j2($,Z){let J=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===Z);if(J<0)return;for(let W=$.length-1;W>J;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let V=P2(Y,Z);if(V)return V}return}function y4($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=P2(J);if(!W?.goalFinalization)continue;if(!$.slice(0,Z).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function I$($,Z){let J=Z?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===Z):-1;if(Z&&J<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,Q=new Set;for(let X of $.slice(J+1)){if(X.type==="interaction_requested"){Q.add(X.data.toolCallId);continue}if(X.type!=="part_created")continue;let H=X.data.payload&&typeof X.data.payload==="object"&&!Array.isArray(X.data.payload)?X.data.payload:{},z=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId;if(X.data.partType==="tool_call")W.set(z,{toolCallId:z,messageId:X.data.messageId,toolName:typeof H.toolName==="string"?H.toolName:"unknown",input:H.input??null});else if(X.data.partType==="tool_result"){if(Y.add(z),Y.add(X.data.partId),Y.add(X.data.messageId),W.has(z)&&H.error===null)V.add(z)}}let K=[...W.values()];return{all:K,orphaned:K.filter((X)=>!Y.has(X.toolCallId)&&!Q.has(X.toolCallId)),hadSuccessfulResult:K.some((X)=>V.has(X.toolCallId))}}class E0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=z0(),Z=100,J=D2(),W=U$($)){this.projectPath=$,this.maxSessions=Z,this.version=J,this.stateStorage=W}createEvent($,Z,J){return{id:B0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:U2(this.projectPath)}:{},version:this.version,data:J}}log($){return O0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=B$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=E0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,J,Z),E0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(E0.sessionInitializationRuns.get(J)===W)E0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>N4){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z,J){if((await this.log($).readAll()).length>0)return;if(this.stateStorage.kind==="acp-remote")throw Error("ACP remote session has no durable creation record");let Y=new Date().toISOString(),V={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},Q=this.createEvent("session_created",$,V);await this.log($).commit(Q)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.reason)Z.reason=$.reason;if($.strategy)Z.strategy=$.strategy;if($.preTokenSource)Z.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)Z.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.sampleAttempts!==void 0)Z.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)Z.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)Z.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)Z.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)Z.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)Z.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)Z.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)Z.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)Z.failureReason=$.failureReason;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;if($.replacementMessages)Z.checkpointVersion=F2;return Z}async initialize(){try{await q2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await C0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,V,Q){try{await this.ensureSessionCreated($,V);let K=new Date().toISOString(),X=B0(),H={messageId:X,role:Z,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:K,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,H),B=Z==="assistant"&&Q?.trim()?[this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:"reasoning",payload:{text:Q},createdAt:K})]:[],j=typeof J==="string"?[this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:"text",payload:{text:J},createdAt:K})]:J.map((U)=>this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:_4(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:K}));return await this.log($).commitBatch([z,...B,...j]),X}catch(K){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,K),K}}async acknowledgeInboxMessages($,Z){if(Z.length===0)return;await this.ensureSessionCreated($);let J=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...Z],acknowledgedAt:J}))}async acknowledgeTurnRecovery($,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=D0(J);if(W.some((V)=>V.type==="turn_recovery_acknowledged"&&V.data.turnId===Z))throw new _0;let Y=W.findLast((V)=>V.type==="turn_aborted"&&V.data.turnId===Z);if(!Y||!W6(W,Y))throw new _0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof _0))throw J}}async persistBackgroundSubagentCompletion($,Z){if(Z.inboxMessageId!==`background-subagent-completion:${Z.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let J={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=D0(W),V=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(Z.inboxMessageId)),Q=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===Z.inboxMessageId),K=Y.findLast((j)=>{if(j.type!=="part_created"||j.data.partType!=="tool_call"||!j.data.payload||typeof j.data.payload!=="object"||Array.isArray(j.data.payload))return!1;let U=j.data.payload;if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))return!1;let f=U.input,N=f.resume_from??f.resume;return f.run_in_background===!0&&f.subagent_session_id===Z.childSessionId&&f.description===Z.subagentRef.subagentDescription&&(f.subagent_type===void 0||f.subagent_type===Z.subagentRef.subagentType)&&(f.resume_from===void 0||f.resume===void 0||f.resume_from===f.resume)&&(N===void 0?Z.subagentRef.subagentResumedFrom===void 0:N===Z.subagentRef.subagentResumedFrom)});if(!K)return J={eligible:!1,acknowledged:V,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];if(V)return J={eligible:!0,acknowledged:!0,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];let X=Y.find((j)=>j.type==="part_created"&&j.data.partType==="subtask_ref"&&j.data.payload!==null&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)&&j.data.payload.childSessionId===Z.childSessionId&&j.data.payload.status===Z.subagentRef.subagentStatus);if(Q&&X)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:Q.data.messageId},[];let H=new Date().toISOString(),z=Q?.data.messageId??B0(),B=[];if(!Q){let j={messageId:z,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(Z.metadata))};B.push(this.createEvent("message_created",$,j)),B.push(this.createEvent("part_created",$,{partId:B0(),messageId:z,partType:"text",payload:{text:Z.content},createdAt:H}))}if(!X){let j=Y.findLast((f)=>f.type==="part_created"&&f.data.partType==="subtask_ref"&&f.data.messageId===K.data.messageId&&f.data.payload!==null&&typeof f.data.payload==="object"&&!Array.isArray(f.data.payload)&&f.data.payload.childSessionId===Z.childSessionId),U=j?.data.payload&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)?j.data.payload:void 0;B.push(this.createEvent("part_created",$,{partId:B0(),messageId:K.data.messageId,partType:"subtask_ref",payload:{childSessionId:Z.subagentRef.subagentSessionId,agentType:Z.subagentRef.subagentType,description:Z.subagentRef.subagentDescription??"",status:Z.subagentRef.subagentStatus,summary:Z.subagentRef.subagentSummary??"",resumedFrom:Z.subagentRef.subagentResumedFrom??null,rootAgentId:Z.subagentRef.subagentRootId??Z.subagentRef.subagentSessionId,resumeDepth:Z.subagentRef.subagentResumeDepth??0,verificationVerdict:Z.subagentRef.verificationVerdict??null,startedAt:typeof U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return J={eligible:!0,acknowledged:!1,persisted:B.length>0,messageId:z},B}),J}async saveTurnStart($,Z){if(Z.goalLineage&&Z.goalLineage.currentTurnId!==Z.turnId)throw Error("Goal lineage current turn must match turn start");await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=D0(J);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===Z.turnId))throw new _0;let Y=w$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,Z)})}catch(J){if(!(J instanceof _0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=D0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),Q=[...new Set(J)].filter((H)=>!V.has(H)),K=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===Z.turnId);if(K){if(K.type==="turn_aborted"||Q.length===0)throw new _0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]}let X=w$(Y).active;if(!X||X.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...Q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof _0))throw W}}async saveTurnAbort($,Z,J={}){let W=J.acknowledgeInputMessageIds??[],Y=H1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let Q,K=[];try{await this.log($).commitValidatedBatch((X)=>{let H=D0(X),z=N2(H),B=H.findLast((u)=>(u.type==="turn_completed"||u.type==="turn_aborted")&&u.data.turnId===Z.turnId);if(B){if(B.type==="turn_completed")throw Q=void 0,K=[],new _0;let u=A2(B.data.recovery),P0=u?V.filter((A0)=>u.inputMessageIds.includes(A0)):[],Z0=P0.filter((A0)=>!z.has(A0));if(K=P0,Q=W6(H,B,P0),Z0.length===0)throw new _0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Z0,acknowledgedAt:Z.abortedAt})]}let j=w$(H).active;if(!j||j.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let U=I$(H,j.turnId),f=X2(H,j.turnId),N=z1(H),b=new Set(Z.recovery?.inputMessageIds??[]),S=N?N.inputMessageIds.filter((u)=>b.has(u)):[],R=[...new Set([...f,...S])],g=U.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,h={version:3,inputMessageIds:R,hadSuccessfulToolResult:g,interruptedToolCallCount:U.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:g&&!U.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:J6(H,j.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};Q={turnId:Z.turnId,outcome:"aborted",inputMessageIds:h.inputMessageIds,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},...h.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent};let $0=V.filter((u)=>R.includes(u)),o=$0.filter((u)=>!z.has(u));K=$0;let T=new Set(z);for(let u of $0)T.add(u);let q=h.inputMessageIds.filter((u)=>!T.has(u)),l=h.hadSuccessfulToolResult||h.interruptedToolCallCount>0;Q=q.length>0||l?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:q,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},...h.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:G0,...v}=Z;return[this.createEvent("turn_aborted",$,{...v,...$0.length>0?{acknowledgedInputMessageIds:$0}:{},recovery:h}),...o.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:o,acknowledgedAt:Z.abortedAt})]:[]]})}catch(X){if(!(X instanceof _0))throw X}return{...Q?{recovery:Q}:{},acknowledgedInputMessageIds:K}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=D0(Z),W=w$(J).active;return W?I$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=D0(Z),W=w$(J).active;if(W){let Y=I$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(j2(J,W.turnId))return!0}return z1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=D0(Z).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let V=Y.input;return V.run_in_background===!0&&typeof V.subagent_session_id==="string"?[V.subagent_session_id]:[]});return new Set(J)}async recoverInterruptedTurn($,Z={}){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((W)=>{let Y=D0(W),V=w$(Y).active,Q=I$(Y);if(!V&&Q.orphaned.length===0){if(J=z1(Y),J)return[];throw new _0}let K=V?j2(Y,V.turnId):void 0;if(V&&K&&Q.orphaned.length===0){let T=I$(Y,V.turnId);J={turnId:V.turnId,outcome:"completed",inputMessageIds:K.inputMessageIds,hadSuccessfulToolResult:T.hadSuccessfulResult,emptyFinalCorrectionSpent:J6(Y,V.turnId),finalization:K};let q=new Set(Y.flatMap((v)=>v.type==="inbox_acknowledged"?v.data.messageIds:[])),l=K.inputMessageIds.filter((v)=>!q.has(v)),G0=new Date().toISOString();return[...l.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:l,acknowledgedAt:G0})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:G0,turnsCount:K.turnsCount,toolCallsCount:K.toolCallsCount,durationMs:K.durationMs})]}let X=V?I$(Y,V.turnId):void 0,H=X?.orphaned.some((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return l1(T,q)&&q?.error===void 0})??!1,z=X?.orphaned.filter((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return q?.toolCallId===T.toolCallId&&q.toolName===T.toolName&&q.error===void 0}).every((T)=>l1(T,Z.adoptedToolResults?.get(T.toolCallId)))??!0,B=new Set(V?.inputMessageIds??[]),j=V?z1(Y):void 0,U=j?j.inputMessageIds.filter((T)=>B.has(T)):[],f=U.length>0,N=V?X2(Y,V.turnId):[],b=X?X.orphaned.filter((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return!l1(T,q)}).length:0,S=f&&j?.hadSuccessfulToolResult===!0,R=(X?.hadSuccessfulResult??!1)||H||S;J=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([...N,...U])],hadSuccessfulToolResult:R,...(()=>{let T=b+(f?j?.interruptedToolCallCount??0:0);return T>0?{interruptedToolCallCount:T}:{}})(),...R&&!(X?.hadSuccessfulResult??!1)&&z&&(!S||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:J6(Y,V.turnId)||f&&j?.emptyFinalCorrectionSpent===!0}:z1(Y);let g=V?X?.all.length??0:0,h=new Date().toISOString(),$0=V?Date.parse(V.startedAt):Number.NaN,o=Q.orphaned.flatMap((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId),l=l1(T,q)?q:void 0,G0=this.createEvent("part_created",$,{partId:T.toolCallId,messageId:l?T.messageId:T.toolCallId,partType:"tool_result",payload:l?{toolCallId:T.toolCallId,toolName:T.toolName,output:l.output,error:l.error??null,...l.metadata===void 0?{}:{metadata:l.metadata}}:{toolCallId:T.toolCallId,toolName:T.toolName,output:null,error:G4,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:h});if(!l?.subagentRef)return[G0];let v=l.subagentRef;return[G0,this.createEvent("part_created",$,{partId:B0(),messageId:T.messageId,partType:"subtask_ref",payload:{childSessionId:v.subagentSessionId,agentType:v.subagentType,description:v.subagentDescription??"",status:v.subagentStatus,summary:v.subagentSummary??"",resumedFrom:v.subagentResumedFrom??null,rootAgentId:v.subagentRootId??v.subagentSessionId,resumeDepth:v.subagentResumeDepth??0,verificationVerdict:v.verificationVerdict??null,startedAt:h,finishedAt:h},createdAt:h})]});return V?[...o,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:h,turnsCount:0,toolCallsCount:g,durationMs:Number.isFinite($0)?Math.max(0,Date.now()-$0):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:o})}catch(W){if(!(W instanceof _0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?y4(Z):void 0}async saveInteractionRequest($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===Z.requestId))throw Error(`Interaction request already exists: ${Z.requestId}`);return this.createEvent("interaction_requested",$,Z)})}async saveInteractionResponse($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((V)=>V.type==="interaction_requested"&&V.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((V)=>V.type==="interaction_responded"&&V.data.requestId===Z.requestId))throw Error(`Interaction already responded: ${Z.requestId}`);return this.createEvent("interaction_responded",$,Z)})}async saveInteractionRecovery($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((V)=>V.type==="interaction_responded"&&V.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((V)=>V.type==="interaction_recovered"&&V.data.requestId===Z.requestId))throw Error(`Interaction already recovered: ${Z.requestId}`);return this.createEvent("interaction_recovered",$,Z)})}async saveReviewStart($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((V)=>V.type==="review_started"&&V.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((V)=>V.type==="review_started"&&!J.some((Q)=>Q.type==="review_completed"&&Q.data.reviewId===V.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,Z)})}async saveReviewCompletion($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((V)=>V.type==="review_started"&&V.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((V)=>V.type==="review_completed"&&V.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,Y,V){try{if(V!==void 0&&(V.length===0||V.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let Q=new Date().toISOString(),K=W??B0(),X=[];if(!W){let B={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:Q};X.push(this.createEvent("message_created",$,B))}let H=V??B0(),z={partId:H,messageId:K,partType:"tool_call",payload:{toolCallId:H,toolName:Z,input:J},createdAt:Q};if(X.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let B=J,j=typeof B.subagent_session_id==="string"?B.subagent_session_id:void 0,U=typeof B.subagent_type==="string"?B.subagent_type:void 0;if(j&&U){let f={partId:B0(),messageId:K,partType:"subtask_ref",payload:{childSessionId:j,agentType:U,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:Q},createdAt:Q};X.push(this.createEvent("part_created",$,f))}}return await this.log($).commitBatch(X),H}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Z,J,W,Y=null,V,Q,K,X){try{await this.ensureSessionCreated($,Q);let H=new Date().toISOString(),z=Y??B0();return await this.log($).commitValidatedBatch((B)=>{let j=K?.subagentStatus==="running"?D0(B).findLast((R)=>R.type==="part_created"&&R.data.partType==="subtask_ref"&&R.data.payload!==null&&typeof R.data.payload==="object"&&!Array.isArray(R.data.payload)&&R.data.payload.childSessionId===K.subagentSessionId&&(R.data.payload.status==="completed"||R.data.payload.status==="failed"||R.data.payload.status==="cancelled")):void 0,U=j?.data.payload,f=X&&typeof X==="object"&&!Array.isArray(X)?X:{},N=U?{...f,subagentSessionId:U.childSessionId,subagentType:U.agentType,description:U.description,subagentStatus:U.status,subagentSummary:U.summary,subagentResumedFrom:U.resumedFrom,subagentRootId:U.rootAgentId,subagentResumeDepth:U.resumeDepth,verificationVerdict:U.verificationVerdict}:X,b=[];if(!Y){let R={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:H};b.push(this.createEvent("message_created",$,R))}let S={partId:Z,messageId:z,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:V??null,...N===void 0?{}:{metadata:N}},createdAt:H};if(b.push(this.createEvent("part_created",$,S)),K&&!j){let R=K.subagentStatus==="running"?null:H,g={partId:B0(),messageId:z,partType:"subtask_ref",payload:{childSessionId:K.subagentSessionId,agentType:K.subagentType,description:K.subagentDescription??"",status:K.subagentStatus,summary:K.subagentSummary??"",resumedFrom:K.subagentResumedFrom??null,rootAgentId:K.subagentRootId??K.subagentSessionId,resumeDepth:K.subagentResumeDepth??0,verificationVerdict:K.verificationVerdict??null,startedAt:H,finishedAt:R},createdAt:H};b.push(this.createEvent("part_created",$,g))}return b}),Z}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=B0(),Q={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},K=this.buildCompactionMetadata(J),X={partId:B0(),messageId:V,partType:"summary",payload:{text:Z,metadata:K,...J.replacementMessages?{replacementMessages:L2(J.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,Q),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=r1([]),W=await this.log($).commitValidatedBatch((V)=>{if(J=r1(D0(V)),J.kind!=="none")return[];let Q=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${f2}${B0()}`,createdAt:Q})]});if(J.kind==="valid")return{outcome:"existing",event:J.event};if(J.kind==="suppressed")return{outcome:"suppressed",recordId:J.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=r1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,Z){await this.ensureSessionCreated($,Z)}async loadEvents($){try{let Z=await this.log($).readAll();return Z.length>0?D0(Z):null}catch{return null}}async loadSession($){try{let Z=D0(await this.log($).readAll());if(Z.length===0)return null;let J=Z.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(J?.timestamp??Z[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=D0(await this.log($).readAll());if(Z.length===0)return null;let J=new Map;for(let Q of Z){if(Q.type==="message_created")J.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let K=J.get(Q.data.messageId);if(K){let X=Q.data.payload;K.content=X.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let K=J.get(Q.data.messageId);if(K)K.content=K.content?`${K.content}
|
|
96
|
-
[Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],V=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:V}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=Y1(this.projectPath);return(await C0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=i1(this.projectPath,$),J=new C$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let V=D0(Y),Q=Y[Y.length-1],K=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(Q.timestamp).getTime(),messageCount:K,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=i1(this.projectPath,$);await new C$(Z).delete(),await C0.unlink(B2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await G2(this.projectPath,$,z2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
96
|
+
[Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],V=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:V}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=Y1(this.projectPath);return(await C0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=i1(this.projectPath,$),J=new C$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let V=D0(Y),Q=Y[Y.length-1],K=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(Q.timestamp).getTime(),messageCount:K,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=i1(this.projectPath,$);await new C$(Z).delete(),await C0.unlink(B2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await G2(this.projectPath,$,z2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-cv4h5c96.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=i1(this.projectPath,J),V=await new C$(W).getStats();Z+=V.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=Y1(this.projectPath);await C0.mkdir($,{recursive:!0,mode:493});let Z=O2.join($,".health-check");return await C0.writeFile(Z,"test","utf-8"),await C0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return w2()}}function _4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var y2=131072,Y6=new R$;function V6($,Z){return`${b4.resolve($)}\x00${Z}`}function X6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>y2)throw Error(`${Z} exceeds ${y2} bytes`);return JSON.parse(J)}function _2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function S4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function R4($,Z){if($.request.interactionType!=="elicitation")return X6(Z,"Interaction response");return X6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function b2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function T4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function M4($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
|
|
97
97
|
`)}function k4($,Z){let{request:J}=$;if(J.interactionType==="question"){let Q=M4(Z);return{toolOutput:`User answers:
|
|
98
98
|
${Q}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
99
99
|
${Q}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Qi as I}from"./chunk-wfynmt9r.js";import{Nj as G,Oj as H}from"./chunk-0b67y4j1.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
|
|
2
2
|
export{D as wg,Q as xg,T as yg,U as zg};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Qa as H}from"./chunk-
|
|
1
|
+
import{Qa as H}from"./chunk-h1pw492p.js";import"./chunk-wm896gnx.js";import"./chunk-9xbwtjac.js";import{Xf as $,bg as T}from"./chunk-68y9kcyz.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-jgqk2tmr.js";import"./chunk-28tzj187.js";import"./chunk-wfynmt9r.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import{aj as k}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-e1j1gsr5.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{rg as a,sg as b,tg as c}from"./chunk-k3ne93k8.js";import"./chunk-7wcxjbyg.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Lk as K}from"./chunk-sdapqhj0.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
|
|
2
2
|
export{P as Ea,V as Fa,R as Ga,N as Ha};
|
package/package.json
CHANGED
package/dist/chunk-0ktd3vpk.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-ddxpgrcv.js";import"./chunk-q5gcqckt.js";import"./chunk-zj1g4nbq.js";import"./chunk-2zzsyaf4.js";import"./chunk-qf6vf457.js";import"./chunk-ghqvews8.js";import"./chunk-d1navt68.js";import"./chunk-qm0j4szw.js";import"./chunk-6hb0pjmk.js";import"./chunk-e12xrg41.js";import"./chunk-mhb3gg9s.js";import"./chunk-wm896gnx.js";import"./chunk-f71j03pq.js";import"./chunk-9xbwtjac.js";import"./chunk-3a217980.js";import"./chunk-mh9nqbwa.js";import{xf as R}from"./chunk-3rv3fnwr.js";import"./chunk-wzqcea6x.js";import{Tf as Q}from"./chunk-mpexy01a.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-z2k08r1h.js";import"./chunk-w6qfbea8.js";import"./chunk-shb7g2vr.js";import"./chunk-7wcxjbyg.js";import"./chunk-01framym.js";import"./chunk-h8s11k0r.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-wv8dy886.js";import"./chunk-3y2x6fb6.js";import"./chunk-9a0cy4z7.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{Xj as M}from"./chunk-s1cs5ga0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
-
____ _ _
|
|
3
|
-
| __ )| | __ _ __| | ___
|
|
4
|
-
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
-
| |_) | | (_| | (_| | __/
|
|
6
|
-
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
-
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
-
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
-
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
-
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
package/dist/chunk-25zrctsh.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{qf as a,rf as b}from"./chunk-mmcjckwx.js";import"./chunk-s1cs5ga0.js";import"./chunk-eg3ms291.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-5v0jcyea.js
DELETED
package/dist/chunk-5y4btx3c.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{rg as a,sg as b,tg as c}from"./chunk-shb7g2vr.js";import"./chunk-7wcxjbyg.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
package/dist/chunk-66wk3exc.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ak as a,bk as b,ck as c}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
package/dist/chunk-8s93p05b.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$f as o,Nf as a,Of as b,Pf as c,Qf as d,Rf as e,Sf as f,Tf as g,Uf as h,Vf as i,Wf as j,Xf as k,Yf as l,Zf as m,_f as n,ag as p,bg as q}from"./chunk-mpexy01a.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-9a0cy4z7.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-s1cs5ga0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
package/dist/chunk-ahz3sskk.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b as i,c as l,d as m}from"./chunk-ddxpgrcv.js";import"./chunk-q5gcqckt.js";import"./chunk-zj1g4nbq.js";import"./chunk-2zzsyaf4.js";import"./chunk-qf6vf457.js";import"./chunk-ghqvews8.js";import"./chunk-d1navt68.js";import"./chunk-qm0j4szw.js";import"./chunk-6hb0pjmk.js";import"./chunk-e12xrg41.js";import"./chunk-mhb3gg9s.js";import"./chunk-wm896gnx.js";import"./chunk-f71j03pq.js";import"./chunk-9xbwtjac.js";import"./chunk-3a217980.js";import"./chunk-mh9nqbwa.js";import{xf as n}from"./chunk-3rv3fnwr.js";import"./chunk-wzqcea6x.js";import{Tf as s}from"./chunk-mpexy01a.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-z2k08r1h.js";import"./chunk-w6qfbea8.js";import"./chunk-shb7g2vr.js";import"./chunk-7wcxjbyg.js";import"./chunk-01framym.js";import"./chunk-h8s11k0r.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-wv8dy886.js";import"./chunk-3y2x6fb6.js";import"./chunk-9a0cy4z7.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-s1cs5ga0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
package/dist/chunk-d9q5dn00.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ae as a,be as b,ce as c,de as d,ee as e,fe as f,ge as g}from"./chunk-f71j03pq.js";import"./chunk-9xbwtjac.js";import"./chunk-3a217980.js";import"./chunk-mh9nqbwa.js";import"./chunk-7wcxjbyg.js";import"./chunk-vbjgcn49.js";import"./chunk-3y2x6fb6.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-2mk914vk.js";import"./chunk-4cdk4mds.js";import"./chunk-s1cs5ga0.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|