blade-code 0.10.125 → 0.10.127

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.
Files changed (42) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-nym7zz07.js → chunk-23wg4jvz.js} +1 -1
  3. package/dist/{chunk-48btnfa3.js → chunk-2a0vs0a0.js} +1 -1
  4. package/dist/{chunk-rcstr6sb.js → chunk-462sbp8t.js} +1 -1
  5. package/dist/{chunk-90fwjr48.js → chunk-8k26rhcp.js} +1 -1
  6. package/dist/{chunk-zfm5e5h2.js → chunk-9cvq8w6k.js} +1 -1
  7. package/dist/{chunk-4s1eaeek.js → chunk-a0t558d4.js} +1 -1
  8. package/dist/{chunk-827422x9.js → chunk-a3ewfebr.js} +1 -1
  9. package/dist/{chunk-bey4af86.js → chunk-a552m4hx.js} +1 -1
  10. package/dist/{chunk-fyhks83r.js → chunk-az5eb47t.js} +1 -1
  11. package/dist/{chunk-mqm3mbmv.js → chunk-d4z5cp40.js} +1 -1
  12. package/dist/{chunk-g391y5wf.js → chunk-d71gxct6.js} +1 -1
  13. package/dist/{chunk-qprvj0mv.js → chunk-dknmpacf.js} +1 -1
  14. package/dist/{chunk-xz5s5ayj.js → chunk-eq1anf88.js} +1 -1
  15. package/dist/{chunk-359xeryx.js → chunk-g7f3nhg2.js} +1 -1
  16. package/dist/{chunk-2naedw9h.js → chunk-gna6njws.js} +1 -1
  17. package/dist/{chunk-rvg14b78.js → chunk-gqv0vkg9.js} +1 -1
  18. package/dist/{chunk-4vvpbrrf.js → chunk-hhmhs2q1.js} +1 -1
  19. package/dist/{chunk-37hmsd3h.js → chunk-hxfqcy5r.js} +1 -1
  20. package/dist/{chunk-ax0q681y.js → chunk-k0n2028d.js} +1 -1
  21. package/dist/{chunk-dm1yxsdx.js → chunk-m76jmvsf.js} +1 -1
  22. package/dist/{chunk-dwnysndf.js → chunk-mg4jnq0p.js} +1 -1
  23. package/dist/{chunk-15va76vr.js → chunk-mpwyf1fe.js} +1 -1
  24. package/dist/chunk-mxkezzj9.js +1 -0
  25. package/dist/{chunk-n3km6ncq.js → chunk-p0khbmbc.js} +1 -1
  26. package/dist/{chunk-5cqr7d6w.js → chunk-r5nvt35e.js} +2 -2
  27. package/dist/{chunk-zyj91sa5.js → chunk-rw2sq3mf.js} +1 -1
  28. package/dist/{chunk-m6pnnjq4.js → chunk-s20hq62y.js} +1 -1
  29. package/dist/{chunk-xf47kpaq.js → chunk-shd1ec3n.js} +1 -1
  30. package/dist/{chunk-k0d7eqd9.js → chunk-t23n4wn0.js} +1 -1
  31. package/dist/{chunk-dxhga3ag.js → chunk-t727txa9.js} +1 -1
  32. package/dist/{chunk-0gmzs677.js → chunk-ve4kvj1n.js} +1 -1
  33. package/dist/{chunk-hhnfd5xm.js → chunk-wmds1jq3.js} +1 -1
  34. package/dist/chunk-xba79vkf.js +1703 -0
  35. package/dist/{chunk-7sfhnmkv.js → chunk-xgp318dt.js} +1 -1
  36. package/dist/{chunk-afadq5w7.js → chunk-y3jbc2xx.js} +1 -1
  37. package/dist/chunk-yc64nfym.js +1 -0
  38. package/dist/{chunk-7td3f2hm.js → chunk-yqh061d8.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-k952hgkh.js +0 -1
  41. package/dist/chunk-nrz53vjn.js +0 -1
  42. package/dist/chunk-sw0g5xy1.js +0 -1700
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{Ae as W}from"./chunk-2naedw9h.js";import{De as F,Ee as M}from"./chunk-pezzyyyk.js";import"./chunk-rvg14b78.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-m6pnnjq4.js";import"./chunk-2t6b962t.js";import"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import{bi as N,ci as B}from"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import{Di as T}from"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import{kj as J}from"./chunk-hmwz31tc.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-ax0q681y.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-dwnysndf.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-54f7t2g3.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-4vvpbrrf.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-zyj91sa5.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-37hmsd3h.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-k952hgkh.js"),import("./chunk-afadq5w7.js"),import("./chunk-g2jx4y8f.js"),import("./chunk-5cqr7d6w.js"),import("./chunk-xdvn6yrd.js"),import("./chunk-hhnfd5xm.js"),import("./chunk-xvn80fge.js"),import("./chunk-9hm3hy8d.js"),import("./chunk-90fwjr48.js"),import("./chunk-n3km6ncq.js"),import("./chunk-zfm5e5h2.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(`
2
+ import{Ae as W}from"./chunk-gna6njws.js";import{De as F,Ee as M}from"./chunk-pezzyyyk.js";import"./chunk-gqv0vkg9.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-s20hq62y.js";import"./chunk-2t6b962t.js";import"./chunk-m76jmvsf.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import{bi as N,ci as B}from"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import{Di as T}from"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-a3ewfebr.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import{kj as J}from"./chunk-hmwz31tc.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-k0n2028d.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-mg4jnq0p.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-54f7t2g3.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-hhmhs2q1.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-rw2sq3mf.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-hxfqcy5r.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-yc64nfym.js"),import("./chunk-y3jbc2xx.js"),import("./chunk-g2jx4y8f.js"),import("./chunk-r5nvt35e.js"),import("./chunk-xdvn6yrd.js"),import("./chunk-wmds1jq3.js"),import("./chunk-xvn80fge.js"),import("./chunk-9hm3hy8d.js"),import("./chunk-8k26rhcp.js"),import("./chunk-p0khbmbc.js"),import("./chunk-9cvq8w6k.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-nrz53vjn.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-4s1eaeek.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};
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-mxkezzj9.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-a0t558d4.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{e as I$,f as q$}from"./chunk-8zftskf2.js";import{g as P1}from"./chunk-2xezz3nt.js";import{s as P0,t as O$}from"./chunk-bey4af86.js";import{u as x$,v as $$,w as Q$,x as j0}from"./chunk-qprvj0mv.js";import{A as h4,B as y4,C as eO,D as g4,y as ax,z as m4}from"./chunk-359xeryx.js";import{G as gx,H as I1,I as g$,L as ux,M as y0,N as U4,O as S1,P as Wx,Q as Z4,R as vx,S as $0,T as dx,U as lx,V as p4,W as r0,X as J4,Y as W0,Z as b0,aa as G1,ba as U1,ca as e$,da as cx,ea as ix,fa as w$,ga as G$,ha as U$,ia as B$,ja as _$,ka as K$,la as F$,ma as L$,na as D$,qa as T$,ta as W2,ya as u$}from"./chunk-sw0g5xy1.js";import{Fa as r4,La as fO}from"./chunk-15va76vr.js";import{$a as S$,Pa as v1,Sa as v$,Ta as B4,Ua as ox,Va as nx,Wa as d$,Xa as l$,Ya as _4,Za as c$,_a as I0,ab as f$,bb as C$,cb as tx,db as sx,eb as rx,fb as ex,gb as C4,hb as b4}from"./chunk-z1zr4wts.js";import{Hb as Q4,Qb as T0,sb as CO,tb as o,vb as E,wb as px}from"./chunk-rcstr6sb.js";import{$b as N4}from"./chunk-sca5q3tt.js";import{Ad as kx,Bc as Sx,Cc as e1,Dc as fx,Ec as Q1,Fc as Cx,Gd as mx,Hd as hx,Ic as n1,Jd as m0,Md as O4,Rd as yx,Sd as x4,Td as $4,Ud as y,Vc as Ex,ed as Px,od as N1,pd as A0,uc as Rx,wd as z1,xd as W4,yd as w1}from"./chunk-g391y5wf.js";import{Qe as s$,Ue as FO,Ye as $x,df as uO}from"./chunk-rvg14b78.js";import{ef as R1}from"./chunk-ye4wyq1k.js";import{vf as Ix}from"./chunk-8qp8v96d.js";import{xf as T1}from"./chunk-mqm3mbmv.js";import{Ff as r$,Hf as k$,Kf as z$,Of as O1,Pf as x1,Tf as B2,Wf as oO,Xf as $1,_f as _2}from"./chunk-0gmzs677.js";import{og as Qx,pg as qx}from"./chunk-adkpwx6c.js";import{tg as o4,ug as E0}from"./chunk-m6pnnjq4.js";import{Hh as n4,Mg as s4,Mh as e0,ah as Dx,dh as Hx,fh as bx,gh as jx,hh as Yx,ih as Nx,jh as E4,ph as Mx,sh as Ax,uh as Tx}from"./chunk-dm1yxsdx.js";import{Ph as s1}from"./chunk-y94239bb.js";import{Qh as p,Sh as V,Th as tO,Vh as zO}from"./chunk-cw2b3383.js";import{Xh as C1,_h as r1}from"./chunk-2j2mnzdg.js";import{ci as $O}from"./chunk-s6562rsq.js";import{Ei as ZO}from"./chunk-68sf54n4.js";import{Ki as L0}from"./chunk-sv833k2e.js";import{Mi as Ox,Ni as Fx,Pi as xx,Qi as Lx}from"./chunk-w7n73ag8.js";import{Si as C0}from"./chunk-827422x9.js";import{Zi as H4}from"./chunk-1g0d9yw0.js";import{dj as j1,hj as d4,ij as f1}from"./chunk-9xzw649r.js";import{kj as F4}from"./chunk-hmwz31tc.js";var v5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function d5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as j4,readFileSync as _1}from"node:fs";import{createServer as F5}from"node:http";import{networkInterfaces as L5}from"node:os";import{dirname as D5,extname as H5,join as G0}from"node:path";import{fileURLToPath as b5}from"node:url";import{brotliCompressSync as j5,gzipSync as M5,constants as A5}from"node:zlib";import{Hono as T5}from"hono";import{cors as I5}from"hono/cors";import{WebSocketServer as q5}from"ws";var f0=ZO("Service"),S2=30000,f2=new Set(["completed","failed","cancelled","interrupted"]);class d1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??C4.getInstance(),this.tickMs=O.tickMs??S2}start(){if(this.timer)return;f0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=E.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!f2.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,f0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){f0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),f0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Q=x.toISOString();try{let Z=await this.dispatch({prompt:O.prompt,title:O.title??C2(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:v1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:Q,lastRunSessionId:Z.session.sessionId,lastStatus:Z.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),E.publish({sessionId:Z.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Q,sessionId:Z.session.sessionId,runId:Z.runId,status:Z.status}),f0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Z.session.sessionId} (${Z.status})`)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);f0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Z);let W=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:v1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:Q,lastStatus:"error",lastError:Y,nextRunAt:W?W.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Z=(await this.store.list()).find((Y)=>Y.lastRunSessionId===O);if(!Z)return;await this.store.update(Z.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function C2(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class WO extends Error{code;statusCode;details;constructor(O,x,$=500,Q){super(x);this.code=O;this.statusCode=$;this.details=Q;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class v extends WO{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class K extends WO{constructor(O){super("BAD_REQUEST",O,400)}}class g extends WO{constructor(O){super("CONFLICT",O,409)}}class dO extends WO{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class KO extends WO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class H1 extends WO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class SO extends WO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class JO extends WO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var s5=V.Object({error:V.Object({code:V.String(),message:V.String(),details:V.Optional(V.Record(V.String(),V.Unknown()))})});import{Hono as E2}from"hono";var l1=ZO("Service"),P2=V.Object({updates:V.Record(V.String(),V.Any()),options:V.Optional(V.Object({scope:V.Optional(zO(["local","project","global"])),immediate:V.Optional(V.Boolean())}))});function k2(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var P4=()=>{let O=new E2;return O.get("/",async(x)=>{try{let $=FO();return x.json($?k2($):{})}catch($){return l1.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),Q=p(P2,$);if(!Q.success)throw new K("Invalid config update format");let{updates:Z,options:Y}=Q.data;return await uO().updateConfig(Z,Y),x.json({success:!0,updates:Z})}catch($){if($ instanceof E4)throw new K($.message);throw l1.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=FO();return x.json($?.permissions||{})}catch($){return l1.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as m2}from"hono";import{streamSSE as h2}from"hono/streaming";function k4(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
1
+ import{e as I$,f as q$}from"./chunk-8zftskf2.js";import{g as P1}from"./chunk-2xezz3nt.js";import{s as P0,t as O$}from"./chunk-a552m4hx.js";import{u as x$,v as $$,w as Q$,x as j0}from"./chunk-dknmpacf.js";import{A as h4,B as y4,C as eO,D as g4,y as ax,z as m4}from"./chunk-g7f3nhg2.js";import{G as gx,H as I1,I as g$,L as ux,M as y0,N as U4,O as S1,P as Wx,Q as Z4,R as vx,S as $0,T as dx,U as lx,V as p4,W as r0,X as J4,Y as W0,Z as b0,aa as G1,ba as U1,ca as e$,da as cx,ea as ix,fa as w$,ga as G$,ha as U$,ia as B$,ja as _$,ka as K$,la as F$,ma as L$,na as D$,qa as T$,ta as W2,ya as u$}from"./chunk-xba79vkf.js";import{Fa as r4,La as fO}from"./chunk-mpwyf1fe.js";import{$a as S$,Pa as v1,Sa as v$,Ta as B4,Ua as ox,Va as nx,Wa as d$,Xa as l$,Ya as _4,Za as c$,_a as I0,ab as f$,bb as C$,cb as tx,db as sx,eb as rx,fb as ex,gb as C4,hb as b4}from"./chunk-z1zr4wts.js";import{Hb as Q4,Qb as T0,sb as CO,tb as o,vb as E,wb as px}from"./chunk-462sbp8t.js";import{$b as N4}from"./chunk-sca5q3tt.js";import{Ad as kx,Bc as Sx,Cc as e1,Dc as fx,Ec as Q1,Fc as Cx,Gd as mx,Hd as hx,Ic as n1,Jd as m0,Md as O4,Rd as yx,Sd as x4,Td as $4,Ud as y,Vc as Ex,ed as Px,od as N1,pd as A0,uc as Rx,wd as z1,xd as W4,yd as w1}from"./chunk-d71gxct6.js";import{Qe as s$,Ue as FO,Ye as $x,df as uO}from"./chunk-gqv0vkg9.js";import{ef as R1}from"./chunk-ye4wyq1k.js";import{vf as Ix}from"./chunk-8qp8v96d.js";import{xf as T1}from"./chunk-d4z5cp40.js";import{Ff as r$,Hf as k$,Kf as z$,Of as O1,Pf as x1,Tf as B2,Wf as oO,Xf as $1,_f as _2}from"./chunk-ve4kvj1n.js";import{og as Qx,pg as qx}from"./chunk-adkpwx6c.js";import{tg as o4,ug as E0}from"./chunk-s20hq62y.js";import{Hh as n4,Mg as s4,Mh as e0,ah as Dx,dh as Hx,fh as bx,gh as jx,hh as Yx,ih as Nx,jh as E4,ph as Mx,sh as Ax,uh as Tx}from"./chunk-m76jmvsf.js";import{Ph as s1}from"./chunk-y94239bb.js";import{Qh as p,Sh as V,Th as tO,Vh as zO}from"./chunk-cw2b3383.js";import{Xh as C1,_h as r1}from"./chunk-2j2mnzdg.js";import{ci as $O}from"./chunk-s6562rsq.js";import{Ei as ZO}from"./chunk-68sf54n4.js";import{Ki as L0}from"./chunk-sv833k2e.js";import{Mi as Ox,Ni as Fx,Pi as xx,Qi as Lx}from"./chunk-w7n73ag8.js";import{Si as C0}from"./chunk-a3ewfebr.js";import{Zi as H4}from"./chunk-1g0d9yw0.js";import{dj as j1,hj as d4,ij as f1}from"./chunk-9xzw649r.js";import{kj as F4}from"./chunk-hmwz31tc.js";var v5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function d5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as j4,readFileSync as _1}from"node:fs";import{createServer as F5}from"node:http";import{networkInterfaces as L5}from"node:os";import{dirname as D5,extname as H5,join as G0}from"node:path";import{fileURLToPath as b5}from"node:url";import{brotliCompressSync as j5,gzipSync as M5,constants as A5}from"node:zlib";import{Hono as T5}from"hono";import{cors as I5}from"hono/cors";import{WebSocketServer as q5}from"ws";var f0=ZO("Service"),S2=30000,f2=new Set(["completed","failed","cancelled","interrupted"]);class d1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??C4.getInstance(),this.tickMs=O.tickMs??S2}start(){if(this.timer)return;f0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=E.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!f2.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,f0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){f0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),f0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Q=x.toISOString();try{let Z=await this.dispatch({prompt:O.prompt,title:O.title??C2(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:v1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:Q,lastRunSessionId:Z.session.sessionId,lastStatus:Z.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),E.publish({sessionId:Z.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Q,sessionId:Z.session.sessionId,runId:Z.runId,status:Z.status}),f0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Z.session.sessionId} (${Z.status})`)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);f0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Z);let W=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:v1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:Q,lastStatus:"error",lastError:Y,nextRunAt:W?W.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Z=(await this.store.list()).find((Y)=>Y.lastRunSessionId===O);if(!Z)return;await this.store.update(Z.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function C2(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class WO extends Error{code;statusCode;details;constructor(O,x,$=500,Q){super(x);this.code=O;this.statusCode=$;this.details=Q;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class v extends WO{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class K extends WO{constructor(O){super("BAD_REQUEST",O,400)}}class g extends WO{constructor(O){super("CONFLICT",O,409)}}class dO extends WO{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class KO extends WO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class H1 extends WO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class SO extends WO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class JO extends WO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var s5=V.Object({error:V.Object({code:V.String(),message:V.String(),details:V.Optional(V.Record(V.String(),V.Unknown()))})});import{Hono as E2}from"hono";var l1=ZO("Service"),P2=V.Object({updates:V.Record(V.String(),V.Any()),options:V.Optional(V.Object({scope:V.Optional(zO(["local","project","global"])),immediate:V.Optional(V.Boolean())}))});function k2(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var P4=()=>{let O=new E2;return O.get("/",async(x)=>{try{let $=FO();return x.json($?k2($):{})}catch($){return l1.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),Q=p(P2,$);if(!Q.success)throw new K("Invalid config update format");let{updates:Z,options:Y}=Q.data;return await uO().updateConfig(Z,Y),x.json({success:!0,updates:Z})}catch($){if($ instanceof E4)throw new K($.message);throw l1.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=FO();return x.json($?.permissions||{})}catch($){return l1.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as m2}from"hono";import{streamSSE as h2}from"hono/streaming";function k4(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)x+=`event: ${O.event}
3
3
  `;for(let $ of O.data.split(/\r\n|\r|\n/))x+=`data: ${$}
4
4
  `;if(O.retry!==void 0)x+=`retry: ${O.retry}
@@ -1 +1 @@
1
- import{Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g}from"./chunk-g391y5wf.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import"./chunk-8qp8v96d.js";import"./chunk-adkpwx6c.js";import"./chunk-2t6b962t.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-68sf54n4.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.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
+ import{Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g}from"./chunk-d71gxct6.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import"./chunk-8qp8v96d.js";import"./chunk-adkpwx6c.js";import"./chunk-2t6b962t.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-68sf54n4.js";import"./chunk-w7n73ag8.js";import"./chunk-a3ewfebr.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.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,4 +1,4 @@
1
- import{dc as M4}from"./chunk-sca5q3tt.js";import{$c as m2,Jd as g0,Ld as Q6,Md as h1,Nd as X6,Ud as o$,Xc as IJ,Zc as uJ,_c as gJ,ad as l2,fc as X$,gd as pJ,hd as R4,id as h4,jd as u2,kd as v1,ld as x4,md as k4,nd as S1,rd as wJ,zd as K1}from"./chunk-g391y5wf.js";import{Zd as T4}from"./chunk-q265drks.js";import{$d as B0,ce as EJ,de as I0}from"./chunk-xnbzrh8b.js";import{ef as $4}from"./chunk-ye4wyq1k.js";import{ff as E4,gf as i0,hf as y4,if as jJ,lf as E1,mf as K6,nf as BJ,of as UJ,qf as DJ}from"./chunk-7n7swtwg.js";import{$f as J$,ag as r0,dg as S4,hg as z4}from"./chunk-0zzh482s.js";import{ug as P$}from"./chunk-m6pnnjq4.js";import{Ph as oJ}from"./chunk-y94239bb.js";import{ci as j0}from"./chunk-s6562rsq.js";import{Ei as v0}from"./chunk-68sf54n4.js";import{Si as CJ}from"./chunk-827422x9.js";import{bj as b$,dj as n6,ej as _0,fj as R1,hj as xJ,ij as kJ,jj as vJ}from"./chunk-9xzw649r.js";import{kj as O8}from"./chunk-hmwz31tc.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class y1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(f$),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)=>!y$(W)&&!f$(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(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,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)=>!y$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!y$(J)&&!f$(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 E6($){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 S6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function T6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var l4=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"]),i4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){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(M6);if(!V)break;let K=V[1];if(!l4.has(K))break;J=Y}return J}function gZ($){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(M6);if(!V)break;let K=V[1];if(i4.test(K))break;J=Y}return J}var r4=[/^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 w2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of r4){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 i$($){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 R6($){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 K$($){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 n4=new Set(["npm","pnpm","yarn","bun"]),h6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),o4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),a4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function s4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function x6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function t4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function e4($){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 $5($){let J=K$($),[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 J5($){let J=x6($.replace(a4,"").trim()),Z=e4(J);if(!Z)return;if(Z.length===0)return k6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=x6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!$5(V))return;return k6(Y)}function k6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(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 A$($,J){let Z=J5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||R6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:t4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((j)=>[...o4].some((B)=>j===B||j.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if(n4.has(Q??""))return s4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h6.has(X??""))return!0;if(h6.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 lZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var q2=v0("Agent"),Z5=3;function G2($,J,Z){if($!=="length")return{action:"none"};if(J>=Z5)return{action:"truncated"};if(E6(Z)==="stop")return q2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var W5=[/:\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],Y5=/```[\s\S]{50,}```/,v6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",V5=2;function F2($,J,Z=!0){if(!$||J>=V5)return{action:"none"};if(!Z&&Y5.test($))return{action:"retry",prompt:v6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(W5.some((K)=>K.test(W)))return{action:"retry",prompt:v6};return{action:"none"}}var K5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},Q5={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},X5="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.",H5="Required verification did not run successfully before the retry limit.",z5=3;function u6($,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&&A$(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"&&A$(V,W))$.add(V)}function L2($,J,Z){if(!$||!K5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Q5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>A$(X)))return{action:"none"};if(Z>=z5)return{action:"fail",message:H5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${X5}${Q}`}}var j5=[/\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|子代理|子智能体)/],g6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function p6($){return typeof $==="string"&&g6.some((J)=>J.test($))}var B5=[/\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|子代理)/],U5=[/\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 D5($){if(typeof $!=="string")return;if(U5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=D5(J);if(Z!==void 0)return Z==="required"}return!1}var w5="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.",q5="Required delegation did not complete before the retry limit.",G5=3;function d6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(g6.some((Q)=>Q.test(K)))break;if(j5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=G5)return{action:"fail",message:q5};return{action:"retry",prompt:w5}}var F5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],L5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],O5=[/\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 c6($){return O5.reduce((J,Z)=>J.replace(Z," "),$)}function P1($){if(typeof $!=="string")return!1;let J=c6($);return F5.some((Z)=>Z.test(J))}var f5="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.",y5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",P5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=c6($);if(!P1(W))return{action:"none"};let Y=L5.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>=P5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?f5:y5}}var I6=30000;async function O2($){try{let Z=P$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),I6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return q2.warn(`[Loop] Stop hook 超时 (${I6}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 q2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var _5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function b5($){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 E5($){let J=$;for(let X of _5)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 l6($){return E5(b5($))}import{EventEmitter as S5}from"events";import i6 from"node:path";function f2($){if(n6($.sessionId),!i6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:i6.resolve($.projectPath)}}function r6($){let J=f2($);return JSON.stringify([J.projectPath,J.sessionId])}function W3($,J){return r6($)===r6(J)}class N$ extends S5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!N$.instance)N$.instance=new N$;return N$.instance}publish($,J,Z,W){let Y=f2($);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 n$=N$.getInstance();var t0=v0("Agent"),N1=new Set;async function T5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(N1.has(Z))return;if(N1.size>=5000)N1.clear();N1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=l6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var y2=`<turn_aborted>
1
+ import{dc as M4}from"./chunk-sca5q3tt.js";import{$c as m2,Jd as g0,Ld as Q6,Md as h1,Nd as X6,Ud as o$,Xc as IJ,Zc as uJ,_c as gJ,ad as l2,fc as X$,gd as pJ,hd as R4,id as h4,jd as u2,kd as v1,ld as x4,md as k4,nd as S1,rd as wJ,zd as K1}from"./chunk-d71gxct6.js";import{Zd as T4}from"./chunk-q265drks.js";import{$d as B0,ce as EJ,de as I0}from"./chunk-xnbzrh8b.js";import{ef as $4}from"./chunk-ye4wyq1k.js";import{ff as E4,gf as i0,hf as y4,if as jJ,lf as E1,mf as K6,nf as BJ,of as UJ,qf as DJ}from"./chunk-7n7swtwg.js";import{$f as J$,ag as r0,dg as S4,hg as z4}from"./chunk-0zzh482s.js";import{ug as P$}from"./chunk-s20hq62y.js";import{Ph as oJ}from"./chunk-y94239bb.js";import{ci as j0}from"./chunk-s6562rsq.js";import{Ei as v0}from"./chunk-68sf54n4.js";import{Si as CJ}from"./chunk-a3ewfebr.js";import{bj as b$,dj as n6,ej as _0,fj as R1,hj as xJ,ij as kJ,jj as vJ}from"./chunk-9xzw649r.js";import{kj as O8}from"./chunk-hmwz31tc.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class y1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(f$),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)=>!y$(W)&&!f$(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(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,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)=>!y$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!y$(J)&&!f$(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 E6($){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 S6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function T6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var l4=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"]),i4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){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(M6);if(!V)break;let K=V[1];if(!l4.has(K))break;J=Y}return J}function gZ($){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(M6);if(!V)break;let K=V[1];if(i4.test(K))break;J=Y}return J}var r4=[/^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 w2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of r4){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 i$($){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 R6($){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 K$($){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 n4=new Set(["npm","pnpm","yarn","bun"]),h6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),o4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),a4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function s4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function x6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function t4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function e4($){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 $5($){let J=K$($),[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 J5($){let J=x6($.replace(a4,"").trim()),Z=e4(J);if(!Z)return;if(Z.length===0)return k6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=x6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!$5(V))return;return k6(Y)}function k6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(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 A$($,J){let Z=J5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||R6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:t4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((j)=>[...o4].some((B)=>j===B||j.startsWith(`${B}=`))))return!1;let[Q,X,H]=K;if(n4.has(Q??""))return s4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&h6.has(X??""))return!0;if(h6.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 lZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var q2=v0("Agent"),Z5=3;function G2($,J,Z){if($!=="length")return{action:"none"};if(J>=Z5)return{action:"truncated"};if(E6(Z)==="stop")return q2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var W5=[/:\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],Y5=/```[\s\S]{50,}```/,v6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",V5=2;function F2($,J,Z=!0){if(!$||J>=V5)return{action:"none"};if(!Z&&Y5.test($))return{action:"retry",prompt:v6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(W5.some((K)=>K.test(W)))return{action:"retry",prompt:v6};return{action:"none"}}var K5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},Q5={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},X5="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.",H5="Required verification did not run successfully before the retry limit.",z5=3;function u6($,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&&A$(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"&&A$(V,W))$.add(V)}function L2($,J,Z){if(!$||!K5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Q5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>A$(X)))return{action:"none"};if(Z>=z5)return{action:"fail",message:H5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${X5}${Q}`}}var j5=[/\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|子代理|子智能体)/],g6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function p6($){return typeof $==="string"&&g6.some((J)=>J.test($))}var B5=[/\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|子代理)/],U5=[/\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 D5($){if(typeof $!=="string")return;if(U5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=D5(J);if(Z!==void 0)return Z==="required"}return!1}var w5="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.",q5="Required delegation did not complete before the retry limit.",G5=3;function d6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(g6.some((Q)=>Q.test(K)))break;if(j5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=G5)return{action:"fail",message:q5};return{action:"retry",prompt:w5}}var F5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],L5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],O5=[/\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 c6($){return O5.reduce((J,Z)=>J.replace(Z," "),$)}function P1($){if(typeof $!=="string")return!1;let J=c6($);return F5.some((Z)=>Z.test(J))}var f5="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.",y5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",P5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=c6($);if(!P1(W))return{action:"none"};let Y=L5.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>=P5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?f5:y5}}var I6=30000;async function O2($){try{let Z=P$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),I6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return q2.warn(`[Loop] Stop hook 超时 (${I6}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 q2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var _5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function b5($){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 E5($){let J=$;for(let X of _5)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 l6($){return E5(b5($))}import{EventEmitter as S5}from"events";import i6 from"node:path";function f2($){if(n6($.sessionId),!i6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:i6.resolve($.projectPath)}}function r6($){let J=f2($);return JSON.stringify([J.projectPath,J.sessionId])}function W3($,J){return r6($)===r6(J)}class N$ extends S5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!N$.instance)N$.instance=new N$;return N$.instance}publish($,J,Z,W){let Y=f2($);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 n$=N$.getInstance();var t0=v0("Agent"),N1=new Set;async function T5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(N1.has(Z))return;if(N1.size>=5000)N1.clear();N1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=l6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var y2=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",o6="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 _$ 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 z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),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)T5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new _$("user_message",{cause:Q})}return null}async function C0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let j=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!j)throw Error("Durable assistant-message commit returned no identity");return j}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new _$("assistant_message",{cause:X})}return null}async function a6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",y2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function s6($,J,Z,W,Y){try{let V=z$($);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){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function A2($,J,Z,W,Y,V={}){try{let K=z$($);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(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function _1($,J,Z,W,Y,V,K,Q,X,H={}){try{let j=z$($);if(j&&J.sessionId){let B=await j.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(j){if(t0.warn("[Loop] 保存工具结果失败:",j),H.required)throw j}return null}async function a$($,J,Z,W,Y={}){try{let V=z$($);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(t0.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,j=await C0(J,Z,Y,H,V);if(j)H=j;if(Q!==void 0){let B={role:"user",content:Q};if(X)B.metadata=X;W.appendControl("user",B);let z=await l0(J,Z,B.content,H,X);if(z)H=z}return H}import{createHash as H6}from"node:crypto";import{promises as i5}from"node:fs";import r5 from"node:path";import{nanoid as e0}from"nanoid";import*as Y0 from"node:fs/promises";import*as j$ from"node:path";var t6={enabled:!0,maxIndexLines:200};var M5="memory",e6="MEMORY.md";class P2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=b$($);this.memoryDir=j$.join(W,M5)}this.config={...t6,...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 $=j$.join(this.memoryDir,e6);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(`
@@ -1 +1 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-nym7zz07.js";import"./chunk-8zftskf2.js";import"./chunk-2xezz3nt.js";import"./chunk-bey4af86.js";import"./chunk-qprvj0mv.js";import"./chunk-359xeryx.js";import"./chunk-sw0g5xy1.js";import"./chunk-zm2bbagg.js";import"./chunk-15va76vr.js";import"./chunk-z1zr4wts.js";import"./chunk-rcstr6sb.js";import"./chunk-sca5q3tt.js";import"./chunk-g391y5wf.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import{ze as n}from"./chunk-2naedw9h.js";import"./chunk-pezzyyyk.js";import{Ve as s}from"./chunk-rvg14b78.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import"./chunk-dh03cybw.js";import"./chunk-8qp8v96d.js";import"./chunk-mqm3mbmv.js";import"./chunk-0gmzs677.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-m6pnnjq4.js";import"./chunk-2t6b962t.js";import"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.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
+ import{a,b as i,c as l,d as m}from"./chunk-23wg4jvz.js";import"./chunk-8zftskf2.js";import"./chunk-2xezz3nt.js";import"./chunk-a552m4hx.js";import"./chunk-dknmpacf.js";import"./chunk-g7f3nhg2.js";import"./chunk-xba79vkf.js";import"./chunk-zm2bbagg.js";import"./chunk-mpwyf1fe.js";import"./chunk-z1zr4wts.js";import"./chunk-462sbp8t.js";import"./chunk-sca5q3tt.js";import"./chunk-d71gxct6.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import{ze as n}from"./chunk-gna6njws.js";import"./chunk-pezzyyyk.js";import{Ve as s}from"./chunk-gqv0vkg9.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import"./chunk-dh03cybw.js";import"./chunk-8qp8v96d.js";import"./chunk-d4z5cp40.js";import"./chunk-ve4kvj1n.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-s20hq62y.js";import"./chunk-2t6b962t.js";import"./chunk-m76jmvsf.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-a3ewfebr.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.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{a as T,b as W,c as X,d as Y}from"./chunk-nym7zz07.js";import"./chunk-8zftskf2.js";import"./chunk-2xezz3nt.js";import"./chunk-bey4af86.js";import"./chunk-qprvj0mv.js";import"./chunk-359xeryx.js";import"./chunk-sw0g5xy1.js";import"./chunk-zm2bbagg.js";import"./chunk-15va76vr.js";import"./chunk-z1zr4wts.js";import"./chunk-rcstr6sb.js";import"./chunk-sca5q3tt.js";import"./chunk-g391y5wf.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import{ze as R}from"./chunk-2naedw9h.js";import"./chunk-pezzyyyk.js";import{Ve as Q}from"./chunk-rvg14b78.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import"./chunk-dh03cybw.js";import"./chunk-8qp8v96d.js";import"./chunk-mqm3mbmv.js";import"./chunk-0gmzs677.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-m6pnnjq4.js";import"./chunk-2t6b962t.js";import"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import{Si as M}from"./chunk-827422x9.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";import m from"chalk";import K from"open";var A=`
1
+ import{a as T,b as W,c as X,d as Y}from"./chunk-23wg4jvz.js";import"./chunk-8zftskf2.js";import"./chunk-2xezz3nt.js";import"./chunk-a552m4hx.js";import"./chunk-dknmpacf.js";import"./chunk-g7f3nhg2.js";import"./chunk-xba79vkf.js";import"./chunk-zm2bbagg.js";import"./chunk-mpwyf1fe.js";import"./chunk-z1zr4wts.js";import"./chunk-462sbp8t.js";import"./chunk-sca5q3tt.js";import"./chunk-d71gxct6.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import{ze as R}from"./chunk-gna6njws.js";import"./chunk-pezzyyyk.js";import{Ve as Q}from"./chunk-gqv0vkg9.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import"./chunk-dh03cybw.js";import"./chunk-8qp8v96d.js";import"./chunk-d4z5cp40.js";import"./chunk-ve4kvj1n.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-s20hq62y.js";import"./chunk-2t6b962t.js";import"./chunk-m76jmvsf.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import{Si as M}from"./chunk-a3ewfebr.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";import m from"chalk";import K from"open";var A=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1,4 +1,4 @@
1
- import{e as L3,f as w3}from"./chunk-8zftskf2.js";import{i as BX,j as AX,k as bX}from"./chunk-xz5s5ayj.js";import{v as P9,w as M9,x as T8}from"./chunk-qprvj0mv.js";import{$ as I9,F as bY,J as vX,L as m4,M as v4,N as _Y,T as e9,U as $Y,Z as g$,aa as S9,ca as JY,ea as j2,fa as V3,ga as j3,ja as E3,ka as h3,oa as rJ,pa as xY,ra as gY,sa as mY,ta as VX,ua as m9,wa as p9,ya as PY}from"./chunk-sw0g5xy1.js";import"./chunk-zm2bbagg.js";import{Ga as e6,Ha as $3,Ia as J3,La as DX}from"./chunk-15va76vr.js";import{Na as s9}from"./chunk-z1zr4wts.js";import{Hb as t9,Qb as I4,ub as o9,vb as n9}from"./chunk-rcstr6sb.js";import{$b as m2}from"./chunk-sca5q3tt.js";import{Fd as D9,Gd as C4,Hd as v9,Jd as A8,Rd as V2,Ud as x0,ed as u9,od as b9,pd as z2,td as R9,yd as C9}from"./chunk-g391y5wf.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import{xe as LX}from"./chunk-1b2dkwpv.js";import{Be as X1,ye as p2,ze as R8}from"./chunk-2naedw9h.js";import"./chunk-pezzyyyk.js";import{Fe as Y2,Ge as W$,He as k1,Ie as zJ,Je as w8,Ke as y9,Le as B6,Me as SJ,Ne as q3,Oe as A6,Pe as Q2,Qe as _$,Re as kX,Se as F$,Te as FX,Ue as K4,Ve as h2,Ye as h9,df as G$}from"./chunk-rvg14b78.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import{tf as kJ}from"./chunk-dh03cybw.js";import"./chunk-8qp8v96d.js";import"./chunk-mqm3mbmv.js";import{Ff as S8,If as o3,Nf as v3,Wf as fX}from"./chunk-0gmzs677.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import{sg as NJ,ug as D$}from"./chunk-m6pnnjq4.js";import"./chunk-2t6b962t.js";import{Hh as IX,Mh as D3,Nh as SX}from"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import{Wh as O2,Xh as b8,Zh as HJ}from"./chunk-2j2mnzdg.js";import{ci as U$}from"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import{Bi as CX,Ei as S1}from"./chunk-68sf54n4.js";import{Gi as H3,Hi as W3,Ki as _1}from"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import{Wi as Z3}from"./chunk-827422x9.js";import{Zi as lJ}from"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import{ij as R4}from"./chunk-9xzw649r.js";import{kj as _J}from"./chunk-hmwz31tc.js";import{useMemoizedFn as L4}from"ahooks";import{useEffect as gK,useState as w4}from"react";import{useMemoizedFn as z$}from"ahooks";import WX from"ansi-escapes";import{Box as M1,useStdout as fK}from"ink";import{useEffect as y1,useMemo as DK,useRef as $8,useState as vK}from"react";import{useShallow as EX}from"zustand/react/shallow";import{useStore as jX}from"zustand";function U0($){return jX(Q2,$)}var hX=[],K2=()=>U0(($)=>$.session.sessionId),Y1=()=>U0(($)=>$.session.workspaceRoot),Z8=()=>U0(($)=>$.session.messages),aJ=()=>U0(($)=>$.session.clearCount),iJ=()=>U0(($)=>$.session.isCompacting),oJ=()=>U0(($)=>$.session.tokenUsage.estimatedCostUsd),nJ=()=>U0(($)=>{let{totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}=$.session.tokenUsage;return rJ({totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}).hitRate}),tJ=()=>U0(($)=>$.session.providerCircuit),sJ=()=>U0(($)=>$.session.providerAdmission),eJ=()=>U0(($)=>$.session.providerRetry),$9=()=>U0(($)=>$.session.providerStall),J9=()=>U0(($)=>$.session.actionStationarity),C1=()=>U0(($)=>$.session.actions),Y9=()=>U0(($)=>{let{totalTokens:J,maxContextTokens:X}=$.session.tokenUsage;if(X<=0)return 100;let Y=Math.max(0,100-J/X*100);return Math.round(Y)}),X9=()=>U0(($)=>$.app.initializationStatus),Z9=()=>U0(($)=>$.app.initializationError),Q8=()=>U0(($)=>$.app.activeModal),Q9=()=>U0(($)=>$.app.tasks),K9=()=>U0(($)=>$.app.modelEditorTarget),U9=()=>U0(($)=>$.app.sessionSelectorData),G9=()=>U0(($)=>$.app.awaitingSecondCtrlC),I1=()=>U0(($)=>$.app.actions),K8=()=>U0(($)=>$.app.sideConversation),q9=()=>U0(($)=>$.app.teams),U8=()=>U0(($)=>$.app.initializationStatus==="ready"),z9=()=>U0(($)=>$.app.tasks.length>0),U2=()=>U0(($)=>$.config.config?.permissionMode||"default"),O9=()=>U0(($)=>$.config.config?.models??hX),G8=()=>U0(($)=>{let J=$.config.config;if(!J)return;let X=J.currentModelId;return J.models.find((Z)=>Z.id===X)??J.models[0]}),q8=()=>U0(($)=>$.config.config?.currentModelId),_9=()=>U0(($)=>$.config.config?.agentTeamsEnabled===!0),k0=()=>U0(($)=>{return W$.getTheme()}),N9=()=>U0(($)=>$.config.config?.codeTheme??"default"),K$=()=>U0(($)=>$.focus.currentFocus),H9=()=>U0(($)=>$.focus.actions),G2=()=>U0(($)=>$.command.isProcessing),W9=()=>U0(($)=>$.command.actions),q2=()=>U0(($)=>$.command.pendingCommands),F9=()=>U0(($)=>$.command.recoveredSteeringCount),z8=()=>U0(($)=>$.app.reasoningEffort!=="off"),O8=()=>U0(($)=>$.app.reasoningEffort),_8=()=>U0(($)=>$.app.serviceTier),N8=()=>U0(($)=>$.app.responseVerbosity),H8=()=>U0(($)=>$.app.communicationStyle),W8=()=>U0(($)=>$.session.currentThinkingContent),L9=()=>U0(($)=>$.session.thinkingExpanded),F8=()=>U0(($)=>$.session.currentStreamingMessageId),L8=()=>U0(EX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),w9=()=>U0(($)=>$.session.finalizingStreamingMessageId),B9=()=>U0(($)=>$.session.historyExpanded),A9=()=>U0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as O1}from"ahooks";import{useEffect as u1,useMemo as UZ,useRef as I8}from"react";function gX($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class B4{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((X)=>{this.handleUnexpectedFailure(X,$)})})}catch(X){this.handleUnexpectedFailure(X,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},X=new AbortController,Y=this.wakeEpoch,Z=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=X;let Q=await this.options.run(X.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let K=this.wakeEpoch!==Y;if(this.clearEpisode(),K)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==Z)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let X=z2($.taskFailure),Y=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Y||!gX($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,X);return}let Z=M9({sessionIdentity:Y,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(Z.phase!=="retry_scheduled"){this.terminate(Z.phase,this.attempt,X);return}this.requested=!0,this.waitingForIdle=!1;let Q={},K=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},Z.delayMs);this.retryTimer={handle:K,token:Q},K.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),z2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},X=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),b9("timeout"),"pending-resume-recovery-deadline-exceeded")},P9);this.deadlineTimer={handle:X,token:J},X.unref?.()}terminate($,J,X,Y){let Z=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.activeAttemptToken=null,this.activeRunController=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Y)Z?.abort(Y);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:X})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class D2{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)w8(J,$.extraContent);y9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function mX($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let K=JSON.parse(Y.responseBody)?.error?.message;if(K){let U=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function pX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function xX($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function B8($){let J=pX($),X=xX($),Y;if(X)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=mX($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:X}}import{appendFileSync as cX,mkdirSync as uX,writeFileSync as dX}from"node:fs";import lX from"node:os";import A4 from"node:path";var T9=null;function rX(){let $=process.env.BLADE_STORAGE_ROOT||A4.join(lX.homedir(),".blade");return A4.join($,"logs","stream-debug.log")}function aX($){if(T9===$)return;let J=A4.dirname($);uX(J,{recursive:!0,mode:493}),dX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{e as L3,f as w3}from"./chunk-8zftskf2.js";import{i as BX,j as AX,k as bX}from"./chunk-eq1anf88.js";import{v as P9,w as M9,x as T8}from"./chunk-dknmpacf.js";import{$ as I9,F as bY,J as vX,L as m4,M as v4,N as _Y,T as e9,U as $Y,Z as g$,aa as S9,ca as JY,ea as j2,fa as V3,ga as j3,ja as E3,ka as h3,oa as rJ,pa as xY,ra as gY,sa as mY,ta as VX,ua as m9,wa as p9,ya as PY}from"./chunk-xba79vkf.js";import"./chunk-zm2bbagg.js";import{Ga as e6,Ha as $3,Ia as J3,La as DX}from"./chunk-mpwyf1fe.js";import{Na as s9}from"./chunk-z1zr4wts.js";import{Hb as t9,Qb as I4,ub as o9,vb as n9}from"./chunk-462sbp8t.js";import{$b as m2}from"./chunk-sca5q3tt.js";import{Fd as D9,Gd as C4,Hd as v9,Jd as A8,Rd as V2,Ud as x0,ed as u9,od as b9,pd as z2,td as R9,yd as C9}from"./chunk-d71gxct6.js";import"./chunk-q265drks.js";import"./chunk-xnbzrh8b.js";import{xe as LX}from"./chunk-1b2dkwpv.js";import{Be as X1,ye as p2,ze as R8}from"./chunk-gna6njws.js";import"./chunk-pezzyyyk.js";import{Fe as Y2,Ge as W$,He as k1,Ie as zJ,Je as w8,Ke as y9,Le as B6,Me as SJ,Ne as q3,Oe as A6,Pe as Q2,Qe as _$,Re as kX,Se as F$,Te as FX,Ue as K4,Ve as h2,Ye as h9,df as G$}from"./chunk-gqv0vkg9.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-7n7swtwg.js";import{tf as kJ}from"./chunk-dh03cybw.js";import"./chunk-8qp8v96d.js";import"./chunk-d4z5cp40.js";import{Ff as S8,If as o3,Nf as v3,Wf as fX}from"./chunk-ve4kvj1n.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import{sg as NJ,ug as D$}from"./chunk-s20hq62y.js";import"./chunk-2t6b962t.js";import{Hh as IX,Mh as D3,Nh as SX}from"./chunk-m76jmvsf.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import{Wh as O2,Xh as b8,Zh as HJ}from"./chunk-2j2mnzdg.js";import{ci as U$}from"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import{Bi as CX,Ei as S1}from"./chunk-68sf54n4.js";import{Gi as H3,Hi as W3,Ki as _1}from"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import{Wi as Z3}from"./chunk-a3ewfebr.js";import{Zi as lJ}from"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import{ij as R4}from"./chunk-9xzw649r.js";import{kj as _J}from"./chunk-hmwz31tc.js";import{useMemoizedFn as L4}from"ahooks";import{useEffect as gK,useState as w4}from"react";import{useMemoizedFn as z$}from"ahooks";import WX from"ansi-escapes";import{Box as M1,useStdout as fK}from"ink";import{useEffect as y1,useMemo as DK,useRef as $8,useState as vK}from"react";import{useShallow as EX}from"zustand/react/shallow";import{useStore as jX}from"zustand";function U0($){return jX(Q2,$)}var hX=[],K2=()=>U0(($)=>$.session.sessionId),Y1=()=>U0(($)=>$.session.workspaceRoot),Z8=()=>U0(($)=>$.session.messages),aJ=()=>U0(($)=>$.session.clearCount),iJ=()=>U0(($)=>$.session.isCompacting),oJ=()=>U0(($)=>$.session.tokenUsage.estimatedCostUsd),nJ=()=>U0(($)=>{let{totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}=$.session.tokenUsage;return rJ({totalInputTokens:J,cacheReadTokens:X,cacheWriteTokens:Y}).hitRate}),tJ=()=>U0(($)=>$.session.providerCircuit),sJ=()=>U0(($)=>$.session.providerAdmission),eJ=()=>U0(($)=>$.session.providerRetry),$9=()=>U0(($)=>$.session.providerStall),J9=()=>U0(($)=>$.session.actionStationarity),C1=()=>U0(($)=>$.session.actions),Y9=()=>U0(($)=>{let{totalTokens:J,maxContextTokens:X}=$.session.tokenUsage;if(X<=0)return 100;let Y=Math.max(0,100-J/X*100);return Math.round(Y)}),X9=()=>U0(($)=>$.app.initializationStatus),Z9=()=>U0(($)=>$.app.initializationError),Q8=()=>U0(($)=>$.app.activeModal),Q9=()=>U0(($)=>$.app.tasks),K9=()=>U0(($)=>$.app.modelEditorTarget),U9=()=>U0(($)=>$.app.sessionSelectorData),G9=()=>U0(($)=>$.app.awaitingSecondCtrlC),I1=()=>U0(($)=>$.app.actions),K8=()=>U0(($)=>$.app.sideConversation),q9=()=>U0(($)=>$.app.teams),U8=()=>U0(($)=>$.app.initializationStatus==="ready"),z9=()=>U0(($)=>$.app.tasks.length>0),U2=()=>U0(($)=>$.config.config?.permissionMode||"default"),O9=()=>U0(($)=>$.config.config?.models??hX),G8=()=>U0(($)=>{let J=$.config.config;if(!J)return;let X=J.currentModelId;return J.models.find((Z)=>Z.id===X)??J.models[0]}),q8=()=>U0(($)=>$.config.config?.currentModelId),_9=()=>U0(($)=>$.config.config?.agentTeamsEnabled===!0),k0=()=>U0(($)=>{return W$.getTheme()}),N9=()=>U0(($)=>$.config.config?.codeTheme??"default"),K$=()=>U0(($)=>$.focus.currentFocus),H9=()=>U0(($)=>$.focus.actions),G2=()=>U0(($)=>$.command.isProcessing),W9=()=>U0(($)=>$.command.actions),q2=()=>U0(($)=>$.command.pendingCommands),F9=()=>U0(($)=>$.command.recoveredSteeringCount),z8=()=>U0(($)=>$.app.reasoningEffort!=="off"),O8=()=>U0(($)=>$.app.reasoningEffort),_8=()=>U0(($)=>$.app.serviceTier),N8=()=>U0(($)=>$.app.responseVerbosity),H8=()=>U0(($)=>$.app.communicationStyle),W8=()=>U0(($)=>$.session.currentThinkingContent),L9=()=>U0(($)=>$.session.thinkingExpanded),F8=()=>U0(($)=>$.session.currentStreamingMessageId),L8=()=>U0(EX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),w9=()=>U0(($)=>$.session.finalizingStreamingMessageId),B9=()=>U0(($)=>$.session.historyExpanded),A9=()=>U0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as O1}from"ahooks";import{useEffect as u1,useMemo as UZ,useRef as I8}from"react";function gX($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class B4{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((X)=>{this.handleUnexpectedFailure(X,$)})})}catch(X){this.handleUnexpectedFailure(X,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},X=new AbortController,Y=this.wakeEpoch,Z=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=X;let Q=await this.options.run(X.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let K=this.wakeEpoch!==Y;if(this.clearEpisode(),K)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==Z)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let X=z2($.taskFailure),Y=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Y||!gX($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,X);return}let Z=M9({sessionIdentity:Y,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(Z.phase!=="retry_scheduled"){this.terminate(Z.phase,this.attempt,X);return}this.requested=!0,this.waitingForIdle=!1;let Q={},K=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},Z.delayMs);this.retryTimer={handle:K,token:Q},K.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),z2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},X=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),b9("timeout"),"pending-resume-recovery-deadline-exceeded")},P9);this.deadlineTimer={handle:X,token:J},X.unref?.()}terminate($,J,X,Y){let Z=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.activeAttemptToken=null,this.activeRunController=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Y)Z?.abort(Y);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:X})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class D2{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)w8(J,$.extraContent);y9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function mX($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let K=JSON.parse(Y.responseBody)?.error?.message;if(K){let U=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function pX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function xX($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function B8($){let J=pX($),X=xX($),Y;if(X)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=mX($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:X}}import{appendFileSync as cX,mkdirSync as uX,writeFileSync as dX}from"node:fs";import lX from"node:os";import A4 from"node:path";var T9=null;function rX(){let $=process.env.BLADE_STORAGE_ROOT||A4.join(lX.homedir(),".blade");return A4.join($,"logs","stream-debug.log")}function aX($){if(T9===$)return;let J=A4.dirname($);uX(J,{recursive:!0,mode:493}),dX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),T9=$}function b4($,J,X){try{let Y=rX();aX(Y);let Z=new Date().toISOString(),Q=X?` | ${JSON.stringify(X)}`:"",K=`[${Z}] [${$}] ${J}${Q}
3
3
  `;cX(Y,K)}catch{}}var v2=S1("UI");function M4($,J){if(J.state==="requires_attention"){let X=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:X?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function k9($,J){let X=$.streamSession??new D2({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)});return(Y)=>{switch(Y.kind){case"content_delta":if(Y.delta.length>0)J.outputStarted=!0;if(!X.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=Y.delta.length,b4("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:Y.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(Y.delta);break;case"thinking_delta":if(Y.delta.length>0)J.outputStarted=!0;if(!X.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(Y.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),v2.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:X.isFinalized,signalAborted:$.signal.aborted}),b4("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:X.isFinalized,signalAborted:$.signal.aborted}),X.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),X.discard();break;case"provider_admission":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderAdmission(Y.phase==="queued"?Q:null);break}case"provider_circuit":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderCircuit(Y.phase==="closed"?null:Q);break}case"provider_retry":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderRetry(Y.phase==="recovered"?null:Q);break}case"provider_stall":{let{kind:Z,...Q}=Y;$.sessionActions.setProviderStall(Y.phase==="detected"?Q:null);break}case"action_stationarity":{let{kind:Z,...Q}=Y;$.sessionActions.setActionStationarity(Y.phase==="recovered"?null:Q);break}case"turn_recovery":{M4($.sessionActions,Y.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===A8)break;if(v2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:Y.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let Q=JSON.parse(Z.function.arguments),K=I9(Z.function.name,Q);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:Q})}catch(Q){v2.error("[loopEventHandler] onToolStart error:",Q)}break}case"tool_progress":{J.toolExecutionStarted=!0;let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===A8)break;let Q=Y.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((Y.update.progress??0)/Y.update.total*100)))}%`:"",K=`${Z.function.name}${Q}: ${Y.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...Y.update.admission?{admission:Y.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let Z=Y.toolCall;if(!("function"in Z))break;if(Z.function.name===A8)break;v2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:Y.result.success});let Q=C9(S9(Z.function.name,Y.result),R9);$.sessionActions.addToolMessage(Q.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:Q.summary,detail:Q.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(Y.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(Y.usage);break;case"compaction":if($.sessionActions.setCompacting(Y.phase==="start"),Y.phase==="end"){if($.sessionActions.resetContextUsage(),Y.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1}break;case"turn_start":v2.debug("[loopEventHandler] turn_start",{turn:Y.turn,maxTurns:Y.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:Y.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),X.startTurn();break;case"task_update":$.appActions.setTasks(Y.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(Y.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${Y.contentKind} r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -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.125",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`}
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.127",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 Ri,p as Si,v as Ti,g as Ui,f as Vi,w as Wi};
@@ -1,2 +1,2 @@
1
- import{vh as H,wh as I}from"./chunk-dm1yxsdx.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
1
+ import{vh as H,wh as I}from"./chunk-m76jmvsf.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
2
2
  export{B as s,K as t};
@@ -1 +1 @@
1
- import{wf as a,xf as b,yf as c}from"./chunk-mqm3mbmv.js";import"./chunk-dm1yxsdx.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-827422x9.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
1
+ import{wf as a,xf as b,yf as c}from"./chunk-d4z5cp40.js";import"./chunk-m76jmvsf.js";import"./chunk-y94239bb.js";import"./chunk-cw2b3383.js";import"./chunk-2j2mnzdg.js";import"./chunk-s6562rsq.js";import"./chunk-hbafhk9y.js";import"./chunk-68sf54n4.js";import"./chunk-sv833k2e.js";import"./chunk-w7n73ag8.js";import"./chunk-a3ewfebr.js";import"./chunk-1g0d9yw0.js";import"./chunk-6kwg4hcv.js";import"./chunk-9xzw649r.js";import"./chunk-hmwz31tc.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1,2 +1,2 @@
1
- import{Mh as F}from"./chunk-dm1yxsdx.js";import{Ji as D,Ki as E}from"./chunk-sv833k2e.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
1
+ import{Mh as F}from"./chunk-m76jmvsf.js";import{Ji as D,Ki as E}from"./chunk-sv833k2e.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
2
  export{H as wf,Q as xf,T as yf};
@@ -1,4 +1,4 @@
1
- import{$d as n,ae as F$,be as h_,ce as D$,de as j,ee as c_,fe as f$,ge as n_,he as z$,ie as l_,je as p_,le as d0,oe as i_,pe as x$}from"./chunk-xnbzrh8b.js";import{uf as D0}from"./chunk-8qp8v96d.js";import{mg as f0}from"./chunk-adkpwx6c.js";import{yg as a1}from"./chunk-2t6b962t.js";import{Wh as K$,Xh as M$,Yh as B0,Zh as g0,_h as W0}from"./chunk-2j2mnzdg.js";import{ci as B1}from"./chunk-s6562rsq.js";import{Ei as h0}from"./chunk-68sf54n4.js";import{Li as M0,Oi as F0}from"./chunk-w7n73ag8.js";import{Si as a}from"./chunk-827422x9.js";import{aj as q$,bj as Q0,cj as A$,dj as x,ej as u,gj as A0,hj as t,ij as k}from"./chunk-9xzw649r.js";import{readdir as v_,readFile as T0,rm as G0,stat as o0}from"node:fs/promises";import*as Y from"node:path";import{nanoid as P}from"nanoid";import{createHash as u$,randomUUID as h$}from"node:crypto";import*as h from"node:fs/promises";import*as b0 from"node:path";import{execFileSync as j$}from"node:child_process";import{createHash as y$}from"node:crypto";import{readFileSync as I$}from"node:fs";var m$=/^[a-f0-9]{64}$/;function O1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&m$.test($.fingerprint)}var T1={readFile:(_)=>I$(_,"utf8"),execFile:(_,$)=>j$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},v$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function X_(_,$){return{platform:_,fingerprint:y$("sha256").update(`${_}\x00${$}`).digest("hex")}}function P$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let T=R.slice(O+2).split(/\s+/)[19];if(!T||!/^\d+$/.test(T))throw Error("Missing process start ticks");return T}function x0(_,$=process.platform,R=T1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return X_($,P$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?X_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,X=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return X?X_($,X):void 0}}catch{return}return}function X1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function j2(_,$,R=T1,O=v$){if(!Number.isInteger(_)||_<=1)return!1;let X=x0(_,$.platform,R);if(X)return X.fingerprint===$.fingerprint;return!O(_)}var C1=1;function c$(_,$){let R=u$("sha256").update($).digest("hex");return b0.join(Q0(_),".locks",`${R}.lock`)}function w0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==C1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!O1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function L1(_){let $=await L_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),L_(_)}function n$(_){try{return process.kill(_,0),!0}catch($){return w0($,"EPERM")}}async function W1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
1
+ import{$d as n,ae as F$,be as h_,ce as D$,de as j,ee as c_,fe as f$,ge as n_,he as z$,ie as l_,je as p_,le as d0,oe as i_,pe as x$}from"./chunk-xnbzrh8b.js";import{uf as D0}from"./chunk-8qp8v96d.js";import{mg as f0}from"./chunk-adkpwx6c.js";import{yg as a1}from"./chunk-2t6b962t.js";import{Wh as K$,Xh as M$,Yh as B0,Zh as g0,_h as W0}from"./chunk-2j2mnzdg.js";import{ci as B1}from"./chunk-s6562rsq.js";import{Ei as h0}from"./chunk-68sf54n4.js";import{Li as M0,Oi as F0}from"./chunk-w7n73ag8.js";import{Si as a}from"./chunk-a3ewfebr.js";import{aj as q$,bj as Q0,cj as A$,dj as x,ej as u,gj as A0,hj as t,ij as k}from"./chunk-9xzw649r.js";import{readdir as v_,readFile as T0,rm as G0,stat as o0}from"node:fs/promises";import*as Y from"node:path";import{nanoid as P}from"nanoid";import{createHash as u$,randomUUID as h$}from"node:crypto";import*as h from"node:fs/promises";import*as b0 from"node:path";import{execFileSync as j$}from"node:child_process";import{createHash as y$}from"node:crypto";import{readFileSync as I$}from"node:fs";var m$=/^[a-f0-9]{64}$/;function O1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&m$.test($.fingerprint)}var T1={readFile:(_)=>I$(_,"utf8"),execFile:(_,$)=>j$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},v$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function X_(_,$){return{platform:_,fingerprint:y$("sha256").update(`${_}\x00${$}`).digest("hex")}}function P$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let T=R.slice(O+2).split(/\s+/)[19];if(!T||!/^\d+$/.test(T))throw Error("Missing process start ticks");return T}function x0(_,$=process.platform,R=T1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return X_($,P$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?X_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,X=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return X?X_($,X):void 0}}catch{return}return}function X1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function j2(_,$,R=T1,O=v$){if(!Number.isInteger(_)||_<=1)return!1;let X=x0(_,$.platform,R);if(X)return X.fingerprint===$.fingerprint;return!O(_)}var C1=1;function c$(_,$){let R=u$("sha256").update($).digest("hex");return b0.join(Q0(_),".locks",`${R}.lock`)}function w0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==C1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!O1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function L1(_){let $=await L_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),L_(_)}function n$(_){try{return process.kill(_,0),!0}catch($){return w0($,"EPERM")}}async function W1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
2
2
  `,"utf8"),!0}catch(O){if(w0(O,"EEXIST"))return!1;if(R)await h.unlink(_).catch(()=>{return});throw O}finally{await R?.close().catch(()=>{return})}}class d extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class o{filePath;record;released=!1;constructor(_,$){this.filePath=_;this.record=$}static async acquire(_,$=B1()){let R=c$($,_),O={version:C1,sessionId:_,ownerId:h$(),pid:process.pid,processIdentity:x0(process.pid),acquiredAt:new Date().toISOString()};if(await h.mkdir(b0.dirname(R),{recursive:!0,mode:448}),await W1(R,O))return new o(R,O);let X=await L1(R);if(X&&n$(X.pid)&&(!X.processIdentity||X1(X.pid,X.processIdentity)))throw new d(X.pid);if(await h.unlink(R).catch((T)=>{if(!w0(T,"ENOENT"))throw T}),await W1(R,O))return new o(R,O);throw new d((await L1(R))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await L_(this.filePath))?.ownerId!==this.record.ownerId)return;await h.unlink(this.filePath).catch(($)=>{if(!w0($,"ENOENT"))throw $})}}import{createHash as k0}from"node:crypto";import{constants as s,promises as c}from"node:fs";import i from"node:path";import{Mutex as l$}from"async-mutex";var G1=128,V1=67108864,p$=24576,E1=65536,B_=1,H1=/^[a-f0-9]{64}$/,i$=/^[a-f0-9]{64}\.txt$/,U1=64,d$=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),j0=`
3
3
 
4
4
  ...[middle omitted; read the private prompt artifact for the complete request]...
@@ -1,4 +1,4 @@
1
- import{_ as p}from"./chunk-sw0g5xy1.js";import{xb as _}from"./chunk-rcstr6sb.js";import{Ud as O,bd as N,cd as U,dd as I,ed as A,fd as z,qd as q}from"./chunk-g391y5wf.js";import{de as o}from"./chunk-xnbzrh8b.js";import{ef as P}from"./chunk-ye4wyq1k.js";import{Cf as e}from"./chunk-0gmzs677.js";import{ej as j}from"./chunk-9xzw649r.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
1
+ import{_ as p}from"./chunk-xba79vkf.js";import{xb as _}from"./chunk-462sbp8t.js";import{Ud as O,bd as N,cd as U,dd as I,ed as A,fd as z,qd as q}from"./chunk-d71gxct6.js";import{de as o}from"./chunk-xnbzrh8b.js";import{ef as P}from"./chunk-ye4wyq1k.js";import{Cf as e}from"./chunk-ve4kvj1n.js";import{ej as j}from"./chunk-9xzw649r.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
3
3
  `).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
4
4
  `)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions:
@@ -1,2 +1,2 @@
1
- import{Si as S}from"./chunk-827422x9.js";import{kj as f}from"./chunk-hmwz31tc.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{Si as S}from"./chunk-a3ewfebr.js";import{kj as f}from"./chunk-hmwz31tc.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as h,u as i,g as j,C as k,V as l};
@@ -1,2 +1,2 @@
1
- import{S as I}from"./chunk-sw0g5xy1.js";import{Ud as M}from"./chunk-g391y5wf.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`)}}
1
+ import{S as I}from"./chunk-xba79vkf.js";import{Ud as M}from"./chunk-d71gxct6.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 y,$ as z,V as A,x as B,i as C,K as D};
@@ -1,4 +1,4 @@
1
- import{Qe as N}from"./chunk-rvg14b78.js";import{ug as $}from"./chunk-m6pnnjq4.js";import{ci as _}from"./chunk-s6562rsq.js";import{Ci as Y,Ei as Z}from"./chunk-68sf54n4.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Qe as N}from"./chunk-gqv0vkg9.js";import{ug as $}from"./chunk-s20hq62y.js";import{ci as _}from"./chunk-s6562rsq.js";import{Ci as Y,Ei as Z}from"./chunk-68sf54n4.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as ye,y as ze,j as Ae,C as Be};