blade-code 0.10.131 → 0.10.132
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-rwnfvbdh.js → chunk-0bkhpd72.js} +1 -1
- package/dist/{chunk-ybwfm7yp.js → chunk-0gmbvtpp.js} +1 -1
- package/dist/{chunk-p9fs659w.js → chunk-14z94k0r.js} +1 -1
- package/dist/{chunk-9ph0t3h8.js → chunk-3e0t25rq.js} +2 -2
- package/dist/{chunk-cz0n951t.js → chunk-53j6nh8j.js} +1 -1
- package/dist/{chunk-xrheg6xr.js → chunk-64kg5a9r.js} +1 -1
- package/dist/{chunk-c3qmbrjj.js → chunk-6q3g5e3m.js} +1 -1
- package/dist/{chunk-dbddc52r.js → chunk-749jzrbk.js} +1 -1
- package/dist/{chunk-wj44fpe7.js → chunk-7dy3mzgz.js} +1 -1
- package/dist/{chunk-25wwj0qb.js → chunk-8y08fytr.js} +1 -1
- package/dist/{chunk-rspcywmd.js → chunk-9d49tj9y.js} +1 -1
- package/dist/{chunk-gfbkrk60.js → chunk-b5z1rec4.js} +29 -29
- package/dist/{chunk-637yvyry.js → chunk-bavzm721.js} +1 -1
- package/dist/{chunk-af3qm97y.js → chunk-dhzbac1c.js} +1 -1
- package/dist/{chunk-h9wzvtmy.js → chunk-dvb89529.js} +1 -1
- package/dist/{chunk-5nssnxbd.js → chunk-e371f7xk.js} +1 -1
- package/dist/{chunk-tndrbmk1.js → chunk-fag8rk53.js} +1 -1
- package/dist/{chunk-v9qf59dy.js → chunk-g12kqs1b.js} +1 -1
- package/dist/{chunk-580dwa0h.js → chunk-g1bqjdeq.js} +1 -1
- package/dist/{chunk-7n268v68.js → chunk-j3nmt09e.js} +1 -1
- package/dist/{chunk-2bnpn8be.js → chunk-mg1s861p.js} +1 -1
- package/dist/{chunk-rd7b9tye.js → chunk-pkg1bvzc.js} +1 -1
- package/dist/{chunk-a7gyy1wb.js → chunk-pqsvz99n.js} +1 -1
- package/dist/{chunk-g0ra6hge.js → chunk-prt6y5fv.js} +1 -1
- package/dist/chunk-q7m0tvhw.js +1 -0
- package/dist/{chunk-k2e4yjsk.js → chunk-qcydkn1n.js} +1 -1
- package/dist/{chunk-dw22ns89.js → chunk-r7kevfd3.js} +1 -1
- package/dist/{chunk-c1w7e6c2.js → chunk-rj8mmwc6.js} +1 -1
- package/dist/{chunk-g59kv3v3.js → chunk-sbc90z9j.js} +1 -1
- package/dist/{chunk-svkdrxk9.js → chunk-sf9sbm6y.js} +1 -1
- package/dist/{chunk-xdf4m44y.js → chunk-sm9p1fkf.js} +1 -1
- package/dist/{chunk-j15db2db.js → chunk-t8rjxqp2.js} +1 -1
- package/dist/{chunk-hrjjhm84.js → chunk-td2jk2xn.js} +2 -2
- package/dist/{chunk-dnsb80qt.js → chunk-xjrmq0pg.js} +3 -3
- package/dist/{chunk-39d95twk.js → chunk-xyxjcehh.js} +1 -1
- package/dist/{chunk-7wbah1y5.js → chunk-y0kqkewg.js} +1 -1
- package/dist/{chunk-5nv95djf.js → chunk-z28dcrr9.js} +1 -1
- package/dist/chunk-z83xk6jn.js +1 -0
- package/dist/{chunk-ntdwkenx.js → chunk-znqt5g8v.js} +1 -1
- package/dist/{chunk-853cgxwv.js → chunk-zssz8hc4.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-92fmzgzv.js +0 -1
- package/dist/chunk-s3f85gtm.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{if as W}from"./chunk-
|
|
2
|
+
import{if as W}from"./chunk-y0kqkewg.js";import{lf as F,mf as M}from"./chunk-a60cmnmz.js";import"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import{Hi as N,Ii as B}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import{nj as T}from"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import{rk as J}from"./chunk-zkzhm39s.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-g12kqs1b.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-0gmbvtpp.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-9s8saznq.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-g1bqjdeq.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-zssz8hc4.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-xyxjcehh.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-q7m0tvhw.js"),import("./chunk-pkg1bvzc.js"),import("./chunk-p00f53yq.js"),import("./chunk-td2jk2xn.js"),import("./chunk-z03dtyh6.js"),import("./chunk-pqsvz99n.js"),import("./chunk-sfe4810k.js"),import("./chunk-9gs4eqt8.js"),import("./chunk-14z94k0r.js"),import("./chunk-prt6y5fv.js"),import("./chunk-z28dcrr9.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-z83xk6jn.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-znqt5g8v.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{zi as K}from"./chunk-jkfkyedn.js";import{Ai as wt,Bi as ft}from"./chunk-f8gb685p.js";import{Ii as I}from"./chunk-44jtpg8y.js";import{Ji as bn,Ki as _n,Li as T}from"./chunk-sj1dzeta.js";import{$i as Ft,Pi as tt,Qi as Dt,Ri as Bt,Vi as Gt,Wi as et,Xi as Kt,Yi as Ht,Zi as Yt,_i as cn,aj as qt,bj as Mt,cj as Vt,dj as Jt,ej as _t,fj as Qt,gj as jt,hj as Wt,ij as Zt,jj as kt,kj as yt}from"./chunk-2y1qngw7.js";import{oj as Un}from"./chunk-ar5np5h5.js";import{rj as zt,uj as v}from"./chunk-dfjmvj3d.js";import{Cj as xn,Dj as Cn}from"./chunk-
|
|
1
|
+
import{zi as K}from"./chunk-jkfkyedn.js";import{Ai as wt,Bi as ft}from"./chunk-f8gb685p.js";import{Ii as I}from"./chunk-44jtpg8y.js";import{Ji as bn,Ki as _n,Li as T}from"./chunk-sj1dzeta.js";import{$i as Ft,Pi as tt,Qi as Dt,Ri as Bt,Vi as Gt,Wi as et,Xi as Kt,Yi as Ht,Zi as Yt,_i as cn,aj as qt,bj as Mt,cj as Vt,dj as Jt,ej as _t,fj as Qt,gj as jt,hj as Wt,ij as Zt,jj as kt,kj as yt}from"./chunk-2y1qngw7.js";import{oj as Un}from"./chunk-ar5np5h5.js";import{rj as zt,uj as v}from"./chunk-dfjmvj3d.js";import{Cj as xn,Dj as Cn}from"./chunk-9d49tj9y.js";import{Jj as a}from"./chunk-qcvxff27.js";import{Mj as Ln}from"./chunk-pj69j4zp.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">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ag as a,Bg as b,Cg as c,Dg as d,Eg as e,Fg as f,Gg as g,Hg as h,Ig as i,Jg as j,Kg as k}from"./chunk-
|
|
1
|
+
import{Ag as a,Bg as b,Cg as c,Dg as d,Eg as e,Fg as f,Gg as g,Hg as h,Ig as i,Jg as j,Kg as k}from"./chunk-t8rjxqp2.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b as i,c as l,d as m}from"./chunk-
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-sm9p1fkf.js";import"./chunk-dvb89529.js";import"./chunk-grhsv55v.js";import"./chunk-bavzm721.js";import"./chunk-qcydkn1n.js";import"./chunk-6q3g5e3m.js";import"./chunk-xjrmq0pg.js";import"./chunk-6p6ts4kv.js";import"./chunk-sbc90z9j.js";import"./chunk-v52wc8yg.js";import"./chunk-3e0t25rq.js";import"./chunk-77efqpdc.js";import"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import"./chunk-b5z1rec4.js";import"./chunk-0z9nqbd0.js";import{hf as n}from"./chunk-y0kqkewg.js";import"./chunk-a60cmnmz.js";import{Df as s}from"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-e371f7xk.js";import"./chunk-t8rjxqp2.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{gc as C4}from"./chunk-77efqpdc.js";import{Id as I0,Kd as H2,Ld as k1,Md as j2,Td as n$,dd as m6,fd as l6,gd as i6,hc as z$,hd as iJ,id as rJ,jc as Y1,kc as c6,lc as W1,nc as K$,od as r6,pd as I4,qd as u4,rd as pJ,sd as I1,td as g4,ud as p4,vd as M1,zd as G6}from"./chunk-c1w7e6c2.js";import{Yd as v4}from"./chunk-53h87fmt.js";import{$d as B0,ce as T6,de as T$,oe as X1}from"./chunk-gfbkrk60.js";import{Of as K4}from"./chunk-mdew58v9.js";import{Pf as k4,Qf as m0,Rf as E4,Sf as U6,Vf as T1,Wf as X2,Xf as D6,Yf as w6,_f as q6}from"./chunk-ajsw4te2.js";import{Lg as e0,Mg as l0,Pg as h4,Tg as q4}from"./chunk-sx77dpxw.js";import{eh as A$}from"./chunk-dw22ns89.js";import{zi as J4}from"./chunk-jkfkyedn.js";import{Ii as Q0}from"./chunk-44jtpg8y.js";import{oj as h0}from"./chunk-ar5np5h5.js";import{Cj as d6}from"./chunk-rspcywmd.js";import{$j as x6,Mj as I6,ak as k6,dk as a$,gk as a2,hk as C1,jk as u6,ok as g6,pk as p6}from"./chunk-pj69j4zp.js";import{rk as _8}from"./chunk-zkzhm39s.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class P1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(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(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.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((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function T2($){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 M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function R2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import V$ from"node:path";var s4=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"]),t4=/^(LD_.+|DYLD_.+|PATH)$/,x2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function m$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(x2);if(!V)break;let K=V[1];if(!s4.has(K))break;J=Y}return J}function iZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(x2);if(!V)break;let K=V[1];if(t4.test(K))break;J=Y}return J}var e4=[/^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 GJ($){let J=$,Z=!0;while(Z){Z=!1;for(let W of e4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function k2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function Y$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var $5=new Set(["npm","pnpm","yarn","bun"]),h2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),J5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),Z5=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function W5($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function v2($){return $.replace(/\s+2>&1\s*$/,"").trim()}function Y5($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Y$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=V$.isAbsolute(V)?V$.resolve(V):V$.resolve(Z,V);if(!K$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function V5($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function K5($){let J=Y$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function Q5($){let J=v2($.replace(Z5,"").trim()),Z=V5(J);if(!Z)return;if(Z.length===0)return C2(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=v2(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!K5(V))return;return C2(Y)}function C2($){let Z=l$($)?.at(-1);if(!Z)return $;let W=Y$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=Q5($);if(!Z)return!1;let W=m$(Z),Y=l$(W);if(!Y||k2(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:Y5(W,Y,J);if(!V)return!1;let K=Y$(V);if(K.length===0||K.some((z)=>[...J5].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if($5.has(Q??""))return W5(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h2.has(X??""))return!0;if(h2.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function sZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!V$.isAbsolute($);let Z=V$.isAbsolute($)?V$.resolve($):V$.resolve(J,$);return K$.isWithinWorkspace(Z,J)}var FJ=h0("Agent"),X5=3;function LJ($,J,Z){if($!=="length")return{action:"none"};if(J>=X5)return{action:"truncated"};if(T2(Z)==="stop")return FJ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var H5=[/:\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],j5=/```[\s\S]{50,}```/,I2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",z5=2;function OJ($,J,Z=!0){if(!$||J>=z5)return{action:"none"};if(!Z&&j5.test($))return{action:"retry",prompt:I2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(H5.some((K)=>K.test(W)))return{action:"retry",prompt:I2};return{action:"none"}}var B5=[/\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}(?:测试|单测|集成测试|检查|构建)/],u2={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},U5={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},D5="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.",w5="Required verification did not run successfully before the retry limit.",q5=3;function p2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function fJ($,J,Z){if(!$||!B5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(u2).filter((X)=>u2[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>U5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${D5}${Q}`}}var G5=[/\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|子代理|子智能体)/],d2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function c2($){return typeof $==="string"&&d2.some((J)=>J.test($))}var F5=[/\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|子代理)/],L5=[/\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 O5($){if(typeof $!=="string")return;if(L5.some((J)=>J.test($)))return"multiple-allowed";return F5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=O5(J);if(Z!==void 0)return Z==="required"}return!1}var f5="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.",y5="Required delegation did not complete before the retry limit.",A5=3;function m2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(d2.some((Q)=>Q.test(K)))break;if(G5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=A5)return{action:"fail",message:y5};return{action:"retry",prompt:f5}}var P5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],N5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],_5=[/\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 l2($){return _5.reduce((J,Z)=>J.replace(Z," "),$)}function _1($){if(typeof $!=="string")return!1;let J=l2($);return P5.some((Z)=>Z.test(J))}var b5="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.",E5="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.",S5="Required worktree lifecycle did not complete before the retry limit.",T5=3;function i2($,J,Z){if(!$)return{action:"none"};let W=l2($);if(!_1(W))return{action:"none"};let Y=N5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=T5)return{action:"fail",message:S5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?b5:E5}}var g2=30000;async function yJ($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??Q0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),g2)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return FJ.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return FJ.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function M5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var R5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function x5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function k5($){let J=$;for(let X of R5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function r2($){return k5(x5($))}import{EventEmitter as h5}from"events";import n2 from"node:path";function AJ($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=AJ($);return JSON.stringify([J.projectPath,J.sessionId])}function j3($,J){return o2($)===o2(J)}class P$ extends h5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=AJ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var a0=h0("Agent"),b1=new Set;async function v5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(b1.has(Z))return;if(b1.size>=5000)b1.clear();b1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=r2(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){a0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var PJ=`<turn_aborted>
|
|
1
|
+
import{gc as C4}from"./chunk-77efqpdc.js";import{Id as I0,Kd as H2,Ld as k1,Md as j2,Td as n$,dd as m6,fd as l6,gd as i6,hc as z$,hd as iJ,id as rJ,jc as Y1,kc as c6,lc as W1,nc as K$,od as r6,pd as I4,qd as u4,rd as pJ,sd as I1,td as g4,ud as p4,vd as M1,zd as G6}from"./chunk-rj8mmwc6.js";import{Yd as v4}from"./chunk-53h87fmt.js";import{$d as B0,ce as T6,de as T$,oe as X1}from"./chunk-b5z1rec4.js";import{Of as K4}from"./chunk-mdew58v9.js";import{Pf as k4,Qf as m0,Rf as E4,Sf as U6,Vf as T1,Wf as X2,Xf as D6,Yf as w6,_f as q6}from"./chunk-ajsw4te2.js";import{Lg as e0,Mg as l0,Pg as h4,Tg as q4}from"./chunk-sx77dpxw.js";import{eh as A$}from"./chunk-r7kevfd3.js";import{zi as J4}from"./chunk-jkfkyedn.js";import{Ii as Q0}from"./chunk-44jtpg8y.js";import{oj as h0}from"./chunk-ar5np5h5.js";import{Cj as d6}from"./chunk-9d49tj9y.js";import{$j as x6,Mj as I6,ak as k6,dk as a$,gk as a2,hk as C1,jk as u6,ok as g6,pk as p6}from"./chunk-pj69j4zp.js";import{rk as _8}from"./chunk-zkzhm39s.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class P1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(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(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.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((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function T2($){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 M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function R2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import V$ from"node:path";var s4=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"]),t4=/^(LD_.+|DYLD_.+|PATH)$/,x2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function m$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(x2);if(!V)break;let K=V[1];if(!s4.has(K))break;J=Y}return J}function iZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(x2);if(!V)break;let K=V[1];if(t4.test(K))break;J=Y}return J}var e4=[/^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 GJ($){let J=$,Z=!0;while(Z){Z=!1;for(let W of e4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function k2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function Y$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var $5=new Set(["npm","pnpm","yarn","bun"]),h2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),J5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),Z5=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function W5($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function v2($){return $.replace(/\s+2>&1\s*$/,"").trim()}function Y5($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Y$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=V$.isAbsolute(V)?V$.resolve(V):V$.resolve(Z,V);if(!K$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function V5($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function K5($){let J=Y$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function Q5($){let J=v2($.replace(Z5,"").trim()),Z=V5(J);if(!Z)return;if(Z.length===0)return C2(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=v2(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!K5(V))return;return C2(Y)}function C2($){let Z=l$($)?.at(-1);if(!Z)return $;let W=Y$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=Q5($);if(!Z)return!1;let W=m$(Z),Y=l$(W);if(!Y||k2(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:Y5(W,Y,J);if(!V)return!1;let K=Y$(V);if(K.length===0||K.some((z)=>[...J5].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if($5.has(Q??""))return W5(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h2.has(X??""))return!0;if(h2.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function sZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!V$.isAbsolute($);let Z=V$.isAbsolute($)?V$.resolve($):V$.resolve(J,$);return K$.isWithinWorkspace(Z,J)}var FJ=h0("Agent"),X5=3;function LJ($,J,Z){if($!=="length")return{action:"none"};if(J>=X5)return{action:"truncated"};if(T2(Z)==="stop")return FJ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var H5=[/:\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],j5=/```[\s\S]{50,}```/,I2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",z5=2;function OJ($,J,Z=!0){if(!$||J>=z5)return{action:"none"};if(!Z&&j5.test($))return{action:"retry",prompt:I2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(H5.some((K)=>K.test(W)))return{action:"retry",prompt:I2};return{action:"none"}}var B5=[/\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}(?:测试|单测|集成测试|检查|构建)/],u2={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},U5={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},D5="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.",w5="Required verification did not run successfully before the retry limit.",q5=3;function p2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function fJ($,J,Z){if(!$||!B5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(u2).filter((X)=>u2[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>U5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${D5}${Q}`}}var G5=[/\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|子代理|子智能体)/],d2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function c2($){return typeof $==="string"&&d2.some((J)=>J.test($))}var F5=[/\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|子代理)/],L5=[/\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 O5($){if(typeof $!=="string")return;if(L5.some((J)=>J.test($)))return"multiple-allowed";return F5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=O5(J);if(Z!==void 0)return Z==="required"}return!1}var f5="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.",y5="Required delegation did not complete before the retry limit.",A5=3;function m2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(d2.some((Q)=>Q.test(K)))break;if(G5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=A5)return{action:"fail",message:y5};return{action:"retry",prompt:f5}}var P5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],N5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],_5=[/\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 l2($){return _5.reduce((J,Z)=>J.replace(Z," "),$)}function _1($){if(typeof $!=="string")return!1;let J=l2($);return P5.some((Z)=>Z.test(J))}var b5="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.",E5="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.",S5="Required worktree lifecycle did not complete before the retry limit.",T5=3;function i2($,J,Z){if(!$)return{action:"none"};let W=l2($);if(!_1(W))return{action:"none"};let Y=N5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=T5)return{action:"fail",message:S5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?b5:E5}}var g2=30000;async function yJ($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??Q0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),g2)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return FJ.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return FJ.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function M5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var R5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function x5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function k5($){let J=$;for(let X of R5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function r2($){return k5(x5($))}import{EventEmitter as h5}from"events";import n2 from"node:path";function AJ($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=AJ($);return JSON.stringify([J.projectPath,J.sessionId])}function j3($,J){return o2($)===o2(J)}class P$ extends h5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=AJ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var a0=h0("Agent"),b1=new Set;async function v5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(b1.has(Z))return;if(b1.size>=5000)b1.clear();b1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=r2(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){a0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var PJ=`<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>`,Q$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",s2="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 N$ extends Error{phase;constructor($,J){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.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function X$($){return $.executionEngine?.getContextManager()}async function c0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=X$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)v5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(a0.warn("[Loop] 保存用户消息失败:",Q),K)throw new N$("user_message",{cause:Q})}return null}async function v0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=X$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let z=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(a0.warn("[Loop] 保存助手消息失败:",X),Q)throw new N$("assistant_message",{cause:X})}return null}async function t2($,J,Z){try{let W=X$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",PJ,Z,void 0,J.subagentInfo)}catch(W){a0.warn("[Loop] 保存中断边界失败:",W)}return null}async function e2($,J,Z,W,Y){try{let V=X$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){a0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function NJ($,J,Z,W,Y,V={}){try{let K=X$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(a0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function E1($,J,Z,W,Y,V,K,Q,X,H={}){try{let z=X$($);if(z&&J.sessionId){let B=await z.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if(a0.warn("[Loop] 保存工具结果失败:",z),H.required)throw z}return null}async function o$($,J,Z,W,Y={}){try{let V=X$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(a0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function G0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,z=await v0(J,Z,Y,H,V);if(z)H=z;if(Q!==void 0){let B={role:"user",content:Q};if(X)B.metadata=X;W.appendControl("user",B);let j=await c0(J,Z,B.content,H,X);if(j)H=j}return H}import{createHash as z2}from"node:crypto";import{promises as t5}from"node:fs";import e5 from"node:path";import{nanoid as s0}from"nanoid";import*as Y0 from"node:fs/promises";import*as H$ from"node:path";var $6={enabled:!0,maxIndexLines:200};var C5="memory",J6="MEMORY.md";class _J{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=a$($);this.memoryDir=H$.join(W,C5)}this.config={...$6,...J}}async initialize(){if(this.initialized)return;await Y0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=H$.join(this.memoryDir,J6);try{let J=await Y0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -83,7 +83,7 @@ Full output saved to: ${Q}`}catch{return`${J}
|
|
|
83
83
|
|
|
84
84
|
${Y}`}}import C8 from"node:path";import{nanoid as I8}from"nanoid";import*as x0 from"node:fs/promises";import*as M6 from"node:path";import{Mutex as f8}from"async-mutex";import y8 from"write-file-atomic";var E6=120,uJ=128;function J1($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function O8($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1&&J.version!==2&&J.version!==3||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if((J.version===2||J.version===3)&&(!("interruptedToolCallCount"in J)||!Number.isSafeInteger(J.interruptedToolCallCount)||J.interruptedToolCallCount<0))return[];if(J.version===3&&(!("allSuccessfulToolResultsSafeForResume"in J)||typeof J.allSuccessfulToolResultsSafeForResume!=="boolean"))return[];let Z=J1(J.inputMessageIds),W=J1($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((V)=>Y.has(V))}function R1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=O8(Z.data);if(W.length===0)return[];let Y=-1;for(let K=J-1;K>=0;K--){let Q=$[K];if(Q.type==="turn_started"){if(Q.data.turnId!==Z.data.turnId)return[];Y=K;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let K=Y+1;K<J;K++){let Q=$[K];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let X=Q.data.metadata,H=Q.data.inboxMessageId!==void 0?Q.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((K)=>V.has(K))}var x1=1,Z1=8388608;function S6($,J){let Z={version:x1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
85
85
|
`}function gJ($,J){return $ instanceof Error&&"code"in $&&$.code===J}function A8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function P8($,J,Z){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==x1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!A8(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"||"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: ${J}`);let K="outputSchema"in V&&V.outputSchema!==void 0?k1(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))}:{},...K?{outputSchema:K}:{}}});return{version:x1,sessionId:Z,messages:Y}}function N8($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return R1($,Z);return[]}))}class h1{sessionId;stateStorage;mutex=new f8;messages=[];constructor($,J){this.sessionId=$;this.stateStorage=J}static async open($,J,Z=z$($)){let W=new h1(J,Z);return await W.loadAndReconcile(),W}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=S6(this.sessionId,Z);if(Buffer.byteLength(W)>Z1)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.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()=>{await W1(this.stateStorage,this.sessionId,async($)=>{let J={version:x1,sessionId:this.sessionId,messages:[]};try{if((await x0.stat($.inboxPath)).size>Z1)throw Error(`Steering inbox exceeds ${Z1} bytes: ${$.inboxPath}`);await x0.chmod($.inboxPath,384),J=P8(await x0.readFile($.inboxPath,"utf8"),$.inboxPath,this.sessionId)}catch(Y){if(!gJ(Y,"ENOENT"))throw Y}let Z=new Set;try{Z=N8(T6(await x0.readFile($.transcriptPath,"utf8"),$.transcriptPath))}catch(Y){if(!gJ(Y,"ENOENT"))throw Y}let W=J.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==J.messages.length)await this.persistAtPath(W,$)})})}async persist($,J){await W1(this.stateStorage,this.sessionId,(Z)=>this.persistAtPath($,Z,J))}async persistAtPath($,J,Z){if(await x0.mkdir(M6.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await x0.unlink(J.inboxPath).catch((Y)=>{if(!gJ(Y,"ENOENT"))throw Y});return}let W=Z??S6(this.sessionId,$);if(Buffer.byteLength(W)>Z1)throw Error(`Steering inbox exceeds ${Z1} bytes: ${J.inboxPath}`);await y8(J.inboxPath,W,{encoding:"utf8",mode:384,fsync:!0})}}import*as C0 from"node:fs/promises";import*as n6 from"node:path";import{nanoid as j0}from"nanoid";var R6=256;class F0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,J,Z){this.sessionId=$;this.projectPath=J;this.storage=Z}static for($,J,Z=z$(J)){let W=Y1(Z,$),Y=F0.instances.get(W);if(!Y)Y=new F0($,J,Z),F0.instances.set(W,Y),F0.pruneIdleInstances(W);else F0.instances.delete(W),F0.instances.set(W,Y);return Y}static release($,J,Z=z$(J)){F0.instances.delete(Y1(Z,$))}static pruneIdleInstances($){if(F0.instances.size<=R6)return;for(let[J,Z]of F0.instances){if(J===$||Z.subscribers.size>0)continue;if(F0.instances.delete(J),F0.instances.size<=R6)return}}get lastSeq(){return this.highestSeq}async readAll(){return this.withStore(async($,J,Z)=>{let W=J?await $.readAllValidated(J):await $.readAll();return Z(W),W})}async commit($){let[J]=await this.commitEntries([$]);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.commitEntries($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.withStore((Z,W,Y)=>Z.appendValidated((V)=>{return Y(V),$(V)},W));return this.record(J),J}async commitValidatedBatch($){let J=await this.withStore((Z,W,Y)=>Z.appendValidatedBatch((V)=>{return Y(V),$(V)},W));for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);r$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),F0.pruneIdleInstances()}}async replay($,J){let Z=await this.withStore(async(W,Y,V)=>{let K=Y?await W.readAllValidated(Y):await W.readAll();return V(K),K.filter((Q)=>(Q.seq??0)>=J)});for(let W of Z){if(pJ(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(pJ($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}r$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}commitEntries($){return this.withStore((J,Z,W)=>Z?J.appendValidatedBatch((Y)=>{return W(Y),$},Z):J.appendBatch($))}withStore($){return W1(this.storage,this.sessionId,async(J)=>{let Z=new T$(J.transcriptPath);if(!J.remoteScope)return $(Z,void 0,()=>{return});let W=J.remoteScope;return $(Z,{noFollow:!0,validateHandle:async(K)=>{await x6(W,J.transcriptPath,K)}},(K)=>{k6(K,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function B$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class N0 extends Error{}var b8="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 dJ($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+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 h6($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let V=Y.data.metadata,K=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof K==="string"&&K.length>0&&K.length<=uJ)W.push(K)}return[...new Set(W)]}function o6($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let J="inputMessageIds"in $?J1($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let Z=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(Z===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:Z,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function E8($,J){let Z=$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J);if(Z<0)return 0;let W=$.findIndex((Q,X)=>X>Z&&Q.type==="turn_started"&&Q.data.turnId!==J),Y=$.slice(Z+1,W<0?void 0:W),V=new Set(Y.flatMap((Q)=>{if(Q.type!=="part_created"||Q.data.partType!=="tool_call")return[];let X=Q.data.payload;return X&&typeof X==="object"&&!Array.isArray(X)?[typeof X.toolCallId==="string"?X.toolCallId:Q.data.partId]:[Q.data.partId]})),K=new Set;for(let Q of Y){if(Q.type!=="part_created"||Q.data.partType!=="tool_result")continue;let X=Q.data.payload;if(!X||typeof X!=="object"||Array.isArray(X))continue;let H=typeof X.toolCallId==="string"?X.toolCallId:Q.data.partId,z=X.metadata;if(V.has(H)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)K.add(H)}return K.size}function a6($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return R1($,Z);return[]}))}function cJ($,J,Z=[]){let W=o6(J.data.recovery);if(!W)return;if($.some((Q)=>Q.type==="turn_recovery_acknowledged"&&Q.data.turnId===J.data.turnId))return;let Y=a6($);for(let Q of Z)Y.add(Q);let V=W.inputMessageIds.filter((Q)=>!Y.has(Q)),K=W.version===1?E8($,J.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&K===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...K>0?{interruptedToolCallCount:K}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function V1($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=cJ($,Z);if(W)return W}return}function v1($,J){let Z=$.input,W=J?.metadata,Y=J?.subagentRef;if($.toolName!=="Task"||J?.toolCallId!==$.toolCallId||J.toolName!=="Task"||Z===null||typeof Z!=="object"||Array.isArray(Z)||W===null||typeof W!=="object"||Array.isArray(W)||!Y)return!1;let{subagent_session_id:V,subagent_type:K,description:Q}=Z,X=Y.subagentStatus==="completed"&&J.error===void 0&&typeof J.output==="string"||Y.subagentStatus==="failed"&&typeof J.error==="string"&&J.error.length>0&&J.output===null;return typeof V==="string"&&V===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof Q==="string"&&Y.subagentDescription===Q&&W.description===Q&&(K===void 0||typeof K==="string"&&K===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&X&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var S8=1e4,T8=1e5,M8=2592000000,v6=128,R8=1e6,x8=256;function k8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>v6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>R8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>v6||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function s6($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,V=Y.turnId,K=Y.inputMessageIds,Q=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,z=Array.isArray(K)?K.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=uJ):[];if(typeof V!=="string"||V.length===0||V.length>128||J!==void 0&&V!==J||!Array.isArray(K)||K.length>E6||z.length!==K.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>S8||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>T8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>M8)return;let B;if("goalFinalization"in Y){if(B=k8(Y.goalFinalization),!B)return}return{turnId:V,inputMessageIds:[...new Set(z)],turnsCount:Q,toolCallsCount:X,durationMs:H,...B?{goalFinalization:B}:{}}}function C6($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let V=s6(Y,J);if(V)return V}return}function h8($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=s6(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function M$($,J){let Z=J?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,K=new Set;for(let X of $.slice(Z+1)){if(X.type==="interaction_requested"){K.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 Q=[...W.values()];return{all:Q,orphaned:Q.filter((X)=>!Y.has(X.toolCallId)&&!K.has(X.toolCallId)),hadSuccessfulResult:Q.some((X)=>V.has(X.toolCallId))}}class _0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=Q0(),J=100,Z=d6(),W=z$($)){this.projectPath=$,this.maxSessions=J,this.version=Z,this.stateStorage=W}createEvent($,J,Z){return{id:j0(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:g6(this.projectPath)}:{},version:this.version,data:Z}}log($){return F0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,J){let Z=Y1(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=_0.sessionInitializationRuns.get(Z);if(!W)W=this.initializeSessionFile($,Z,J),_0.sessionInitializationRuns.set(Z,W);try{await W,this.rememberInitializedSession($)}finally{if(_0.sessionInitializationRuns.get(Z)===W)_0.sessionInitializationRuns.delete(Z)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>x8){let J=this.initializedSessions.values().next().value;if(J===void 0)return;this.initializedSessions.delete(J)}}async initializeSessionFile($,J,Z){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:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},K=this.createEvent("session_created",$,V);await this.log($).commit(K)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.preTokenSource)J.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)J.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.sampleAttempts!==void 0)J.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)J.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)J.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)J.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)J.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)J.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)J.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)J.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)J.failureReason=$.failureReason;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=l6;return J}async initialize(){try{await c6(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await C0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,V,K){try{await this.ensureSessionCreated($,V);let Q=new Date().toISOString(),X=j0(),H={messageId:X,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,H),B=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:"reasoning",payload:{text:K},createdAt:Q})]:[],j=typeof Z==="string"?[this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:"text",payload:{text:Z},createdAt:Q})]:Z.map((U)=>this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:v8(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:Q}));return await this.log($).commitBatch([z,...B,...j]),X}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async acknowledgeTurnRecovery($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=B0(Z);if(W.some((V)=>V.type==="turn_recovery_acknowledged"&&V.data.turnId===J))throw new N0;let Y=W.findLast((V)=>V.type==="turn_aborted"&&V.data.turnId===J);if(!Y||!cJ(W,Y))throw new N0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:J,acknowledgedAt:new Date().toISOString()})})}catch(Z){if(!(Z instanceof N0))throw Z}}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(J.inboxMessageId)),K=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===J.inboxMessageId),Q=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 P=U.input,_=P.resume_from??P.resume;return P.run_in_background===!0&&P.subagent_session_id===J.childSessionId&&P.description===J.subagentRef.subagentDescription&&(P.subagent_type===void 0||P.subagent_type===J.subagentRef.subagentType)&&(P.resume_from===void 0||P.resume===void 0||P.resume_from===P.resume)&&(_===void 0?J.subagentRef.subagentResumedFrom===void 0:_===J.subagentRef.subagentResumedFrom)});if(!Q)return Z={eligible:!1,acknowledged:V,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(V)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.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===J.childSessionId&&j.data.payload.status===J.subagentRef.subagentStatus);if(K&&X)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let H=new Date().toISOString(),z=K?.data.messageId??j0(),B=[];if(!K){let j={messageId:z,role:"user",inboxMessageId:J.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(J.metadata))};B.push(this.createEvent("message_created",$,j)),B.push(this.createEvent("part_created",$,{partId:j0(),messageId:z,partType:"text",payload:{text:J.content},createdAt:H}))}if(!X){let j=Y.findLast((P)=>P.type==="part_created"&&P.data.partType==="subtask_ref"&&P.data.messageId===Q.data.messageId&&P.data.payload!==null&&typeof P.data.payload==="object"&&!Array.isArray(P.data.payload)&&P.data.payload.childSessionId===J.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:j0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return Z={eligible:!0,acknowledged:!1,persisted:B.length>0,messageId:z},B}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=B0(Z);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===J.turnId))throw new N0;let Y=B$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof N0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),K=[...new Set(Z)].filter((H)=>!V.has(H)),Q=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===J.turnId);if(Q){if(Q.type==="turn_aborted"||K.length===0)throw new N0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let X=B$(Y).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof N0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=J1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let K,Q=[];try{await this.log($).commitValidatedBatch((X)=>{let H=B0(X),z=a6(H),B=H.findLast((i)=>(i.type==="turn_completed"||i.type==="turn_aborted")&&i.data.turnId===J.turnId);if(B){if(B.type==="turn_completed")throw K=void 0,Q=[],new N0;let i=o6(B.data.recovery),L0=i?V.filter((y0)=>i.inputMessageIds.includes(y0)):[],S=L0.filter((y0)=>!z.has(y0));if(Q=L0,K=cJ(H,B,L0),S.length===0)throw new N0;return[this.createEvent("inbox_acknowledged",$,{messageIds:S,acknowledgedAt:J.abortedAt})]}let j=B$(H).active;if(!j||j.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let U=M$(H,j.turnId),P=h6(H,j.turnId),_=V1(H),k=new Set(J.recovery?.inputMessageIds??[]),R=_?_.inputMessageIds.filter((i)=>k.has(i)):[],h=[...new Set([...P,...R])],d=U.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,x={version:3,inputMessageIds:h,hadSuccessfulToolResult:d,interruptedToolCallCount:U.orphaned.length+(J.recovery?.version===2||J.recovery?.version===3?J.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:d&&!U.hadSuccessfulResult&&J.recovery?.version===3&&J.recovery.hadSuccessfulToolResult&&J.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:dJ(H,j.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};K={turnId:J.turnId,outcome:"aborted",inputMessageIds:x.inputMessageIds,hadSuccessfulToolResult:x.hadSuccessfulToolResult,...x.interruptedToolCallCount>0?{interruptedToolCallCount:x.interruptedToolCallCount}:{},...x.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:x.emptyFinalCorrectionSpent};let o=V.filter((i)=>h.includes(i)),G=o.filter((i)=>!z.has(i));Q=o;let E=new Set(z);for(let i of o)E.add(i);let l=x.inputMessageIds.filter((i)=>!E.has(i)),g=x.hadSuccessfulToolResult||x.interruptedToolCallCount>0;K=l.length>0||g?{turnId:J.turnId,outcome:"aborted",inputMessageIds:l,hadSuccessfulToolResult:x.hadSuccessfulToolResult,...x.interruptedToolCallCount>0?{interruptedToolCallCount:x.interruptedToolCallCount}:{},...x.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:x.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:V0,...I}=J;return[this.createEvent("turn_aborted",$,{...I,...o.length>0?{acknowledgedInputMessageIds:o}:{},recovery:x}),...G.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:G,acknowledgedAt:J.abortedAt})]:[]]})}catch(X){if(!(X instanceof N0))throw X}return{...K?{recovery:K}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=B0(J),W=B$(Z).active;return W?M$(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let J=await this.loadEvents($);if(!J)return!1;let Z=B0(J),W=B$(Z).active;if(W){let Y=M$(Z,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(C6(Z,W.turnId))return!0}return V1(Z)!==void 0}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=B0(J).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(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=B$(Y).active,K=M$(Y);if(!V&&K.orphaned.length===0){if(Z=V1(Y),Z)return[];throw new N0}let Q=V?C6(Y,V.turnId):void 0;if(V&&Q&&K.orphaned.length===0){let E=M$(Y,V.turnId);Z={turnId:V.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:E.hadSuccessfulResult,emptyFinalCorrectionSpent:dJ(Y,V.turnId),finalization:Q};let l=new Set(Y.flatMap((I)=>I.type==="inbox_acknowledged"?I.data.messageIds:[])),g=Q.inputMessageIds.filter((I)=>!l.has(I)),V0=new Date().toISOString();return[...g.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:g,acknowledgedAt:V0})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:V0,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let X=V?M$(Y,V.turnId):void 0,H=X?.orphaned.some((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return v1(E,l)&&l?.error===void 0})??!1,z=X?.orphaned.filter((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return l?.toolCallId===E.toolCallId&&l.toolName===E.toolName&&l.error===void 0}).every((E)=>v1(E,J.adoptedToolResults?.get(E.toolCallId)))??!0,B=new Set(V?.inputMessageIds??[]),j=V?V1(Y):void 0,U=j?j.inputMessageIds.filter((E)=>B.has(E)):[],P=U.length>0,_=V?h6(Y,V.turnId):[],k=X?X.orphaned.filter((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return!v1(E,l)}).length:0,R=P&&j?.hadSuccessfulToolResult===!0,h=(X?.hadSuccessfulResult??!1)||H||R;Z=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([..._,...U])],hadSuccessfulToolResult:h,...(()=>{let E=k+(P?j?.interruptedToolCallCount??0:0);return E>0?{interruptedToolCallCount:E}:{}})(),...h&&!(X?.hadSuccessfulResult??!1)&&z&&(!R||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:dJ(Y,V.turnId)||P&&j?.emptyFinalCorrectionSpent===!0}:V1(Y);let d=V?X?.all.length??0:0,x=new Date().toISOString(),o=V?Date.parse(V.startedAt):Number.NaN,G=K.orphaned.flatMap((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId),g=v1(E,l)?l:void 0,V0=this.createEvent("part_created",$,{partId:E.toolCallId,messageId:g?E.messageId:E.toolCallId,partType:"tool_result",payload:g?{toolCallId:E.toolCallId,toolName:E.toolName,output:g.output,error:g.error??null,...g.metadata===void 0?{}:{metadata:g.metadata}}:{toolCallId:E.toolCallId,toolName:E.toolName,output:null,error:b8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:x});if(!g?.subagentRef)return[V0];let I=g.subagentRef;return[V0,this.createEvent("part_created",$,{partId:j0(),messageId:E.messageId,partType:"subtask_ref",payload:{childSessionId:I.subagentSessionId,agentType:I.subagentType,description:I.subagentDescription??"",status:I.subagentStatus,summary:I.subagentSummary??"",resumedFrom:I.subagentResumedFrom??null,rootAgentId:I.subagentRootId??I.subagentSessionId,resumeDepth:I.subagentResumeDepth??0,verificationVerdict:I.verificationVerdict??null,startedAt:x,finishedAt:x},createdAt:x})]});return V?[...G,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:x,turnsCount:0,toolCallsCount:d,durationMs:Number.isFinite(o)?Math.max(0,Date.now()-o):0,recovery:Z?{version:3,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,interruptedToolCallCount:Z.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:Z.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:G})}catch(W){if(!(W instanceof N0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?h8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_requested"&&V.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_recovered"&&V.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===V.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_completed"&&V.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,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 K=new Date().toISOString(),Q=W??j0(),X=[];if(!W){let B={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:K};X.push(this.createEvent("message_created",$,B))}let H=V??j0(),z={partId:H,messageId:Q,partType:"tool_call",payload:{toolCallId:H,toolName:J,input:Z},createdAt:K};if(X.push(this.createEvent("part_created",$,z)),J==="Task"&&Z&&typeof Z==="object"){let B=Z,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 P={partId:j0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:j,agentType:U,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:K},createdAt:K};X.push(this.createEvent("part_created",$,P))}}return await this.log($).commitBatch(X),H}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,J,Z,W,Y=null,V,K,Q,X){try{await this.ensureSessionCreated($,K);let H=new Date().toISOString(),z=Y??j0();return await this.log($).commitValidatedBatch((B)=>{let j=Q?.subagentStatus==="running"?B0(B).findLast((h)=>h.type==="part_created"&&h.data.partType==="subtask_ref"&&h.data.payload!==null&&typeof h.data.payload==="object"&&!Array.isArray(h.data.payload)&&h.data.payload.childSessionId===Q.subagentSessionId&&(h.data.payload.status==="completed"||h.data.payload.status==="failed"||h.data.payload.status==="cancelled")):void 0,U=j?.data.payload,P=X&&typeof X==="object"&&!Array.isArray(X)?X:{},_=U?{...P,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,k=[];if(!Y){let h={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:H};k.push(this.createEvent("message_created",$,h))}let R={partId:J,messageId:z,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:V??null,..._===void 0?{}:{metadata:_}},createdAt:H};if(k.push(this.createEvent("part_created",$,R)),Q&&!j){let h=Q.subagentStatus==="running"?null:H,d={partId:j0(),messageId:z,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:H,finishedAt:h},createdAt:H};k.push(this.createEvent("part_created",$,d))}return k}),J}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=j0(),K={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(Z),X={partId:j0(),messageId:V,partType:"summary",payload:{text:J,metadata:Q,...Z.replacementMessages?{replacementMessages:i6(Z.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,J){await this.ensureSessionCreated($);let Z=I1([]),W=await this.log($).commitValidatedBatch((V)=>{if(Z=I1(B0(V)),Z.kind!=="none")return[];let K=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${r6}${j0()}`,createdAt:K})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=I1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=await this.log($).readAll();return J.length>0?B0(J):null}catch{return null}}async loadSession($){try{let J=B0(await this.log($).readAll());if(J.length===0)return null;let Z=J.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Z?.timestamp??J[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=B0(await this.log($).readAll());if(J.length===0)return null;let Z=new Map;for(let K of J){if(K.type==="message_created")Z.set(K.data.messageId,{id:K.data.messageId,role:K.data.role,content:"",timestamp:new Date(K.timestamp).getTime()});if(K.type==="part_created"&&K.data.partType==="text"){let Q=Z.get(K.data.messageId);if(Q){let X=K.data.payload;Q.content=X.text??""}}if(K.type==="part_created"&&K.data.partType==="image"){let Q=Z.get(K.data.messageId);if(Q)Q.content=Q.content?`${Q.content}
|
|
86
|
-
[Image]`:"[Image]"}}let W=Array.from(Z.values()),Y=J[J.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 $=a$(this.projectPath);return(await C0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let J=C1(this.projectPath,$),Z=new T$(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=B0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let J=C1(this.projectPath,$);await new T$(J).delete(),await C0.unlink(u6(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await m6(this.projectPath,$,I6());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
86
|
+
[Image]`:"[Image]"}}let W=Array.from(Z.values()),Y=J[J.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 $=a$(this.projectPath);return(await C0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let J=C1(this.projectPath,$),Z=new T$(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=B0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let J=C1(this.projectPath,$);await new T$(J).delete(),await C0.unlink(u6(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await m6(this.projectPath,$,I6());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-mg1s861p.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}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(),J=0;for(let Z of $){let W=C1(this.projectPath,Z),V=await new T$(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,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 $=a$(this.projectPath);await C0.mkdir($,{recursive:!0,mode:493});let J=n6.join($,".health-check");return await C0.writeFile(J,"test","utf-8"),await C0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return p6()}}function v8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var t6=131072,mJ=new J4;function lJ($,J){return`${C8.resolve($)}\x00${J}`}function nJ($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>t6)throw Error(`${J} exceeds ${t6} bytes`);return JSON.parse(Z)}function e6($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function u8($,J){return JSON.stringify($)===JSON.stringify(J)}function g8($,J){if($.request.interactionType!=="elicitation")return nJ(J,"Interaction response");return nJ({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function $4($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function p8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function d8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
87
87
|
`)}function c8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=d8(J);return{toolOutput:`User answers:
|
|
88
88
|
${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
89
89
|
${K}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Nd as a,Od as b,Pd as c,Qd as d,Rd as e,Sd as f,Td as g}from"./chunk-
|
|
1
|
+
import{Nd as a,Od as b,Pd as c,Qd as d,Rd as e,Sd as f,Td as g}from"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import"./chunk-b5z1rec4.js";import"./chunk-0z9nqbd0.js";import"./chunk-edtxcqxa.js";import"./chunk-aaxc81jc.js";import"./chunk-g4xny949.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-ar5np5h5.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$b as p,Bb as a,Cb as b,Eb as c,Ib as d,Jb as e,Kb as f,Lb as g,Mb as h,Nb as i,Ob as j,Pb as k,Wb as l,Xb as m,Yb as n,Zb as o,ac as q,bc as r}from"./chunk-
|
|
1
|
+
import{$b as p,Bb as a,Cb as b,Eb as c,Ib as d,Jb as e,Kb as f,Lb as g,Mb as h,Nb as i,Ob as j,Pb as k,Wb as l,Xb as m,Yb as n,Zb as o,ac as q,bc as r}from"./chunk-3e0t25rq.js";import"./chunk-77efqpdc.js";import"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import"./chunk-b5z1rec4.js";import"./chunk-0z9nqbd0.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-edtxcqxa.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{V as I}from"./chunk-
|
|
1
|
+
import{V as I}from"./chunk-xjrmq0pg.js";import{Td as M}from"./chunk-rj8mmwc6.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
|
|
2
2
|
export{C as B,$ as C,V as D,x as E,i as F,K as G};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ff as v}from"./chunk-gmqpfm52.js";import{yf as e}from"./chunk-
|
|
1
|
+
import{ff as v}from"./chunk-gmqpfm52.js";import{yf as e}from"./chunk-j3nmt09e.js";import{Lh as y,Nh as D,Oh as h,Qh as A,Xh as P,Yh as T,_h as E,ai as _,bi as f,di as C,hi as S,ii as m,ji as c,ki as p,mi as u,ni as d,ri as l,wi as i,xi as t}from"./chunk-0bkhpd72.js";import{yi as Y}from"./chunk-jkfkyedn.js";import{Gi as X}from"./chunk-44jtpg8y.js";import{Ji as x,Li as k,Oi as Z}from"./chunk-sj1dzeta.js";import{$i as I,Qi as U,Ri as L,Xi as M,Yi as O,_i as $,aj as G,cj as N,dj as j,fj as F,gj as R}from"./chunk-2y1qngw7.js";import{oj as s}from"./chunk-ar5np5h5.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Cj as d,Ej as h}from"./chunk-
|
|
1
|
+
import{Cj as d,Ej as h}from"./chunk-9d49tj9y.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as af,w as bf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{xa as F,za as L}from"./chunk-
|
|
1
|
+
import{xa as F,za as L}from"./chunk-xjrmq0pg.js";import{Jd as $,Ld as B,Td as Q}from"./chunk-rj8mmwc6.js";import{Fg as y}from"./chunk-t8rjxqp2.js";import{Ii as V}from"./chunk-44jtpg8y.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
2
|
|
|
3
3
|
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{j as p,I as q,M as r,R as s,_ as t,C as u};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.132",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
2
|
export{y as Bj,p as Cj,v as Dj,g as Ej,f as Fj,w as Gj};
|