blade-code 0.10.117 → 0.10.119
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-ae7bcbmy.js → chunk-057qv2wd.js} +1 -1
- package/dist/{chunk-cqqmkwvn.js → chunk-0zzh482s.js} +1 -1
- package/dist/{chunk-sr10jsjs.js → chunk-207s8tns.js} +1 -1
- package/dist/{chunk-2gcwzk6m.js → chunk-2jdnjmbh.js} +1 -1
- package/dist/{chunk-eyb9psbc.js → chunk-2t6b962t.js} +1 -1
- package/dist/{chunk-jp4j9tnn.js → chunk-3jdt8kqf.js} +1 -1
- package/dist/{chunk-bksfg23m.js → chunk-3jqd18d8.js} +2 -2
- package/dist/{chunk-fgmwse2v.js → chunk-4v2t1xs5.js} +2 -2
- package/dist/chunk-5s4knzbg.js +1 -0
- package/dist/chunk-60092knz.js +1 -0
- package/dist/{chunk-b1w2mtq8.js → chunk-6437f0h4.js} +1 -1
- package/dist/{chunk-qdv0n8yt.js → chunk-7dykmcjj.js} +2 -2
- package/dist/chunk-82dckkw7.js +1 -0
- package/dist/{chunk-935v0gpc.js → chunk-85bamng3.js} +1 -1
- package/dist/{chunk-psatd34r.js → chunk-8nm03qtd.js} +1 -1
- package/dist/{chunk-khtbjdf7.js → chunk-8q0a693b.js} +1 -1
- package/dist/{chunk-hv6hrsnk.js → chunk-8qp8v96d.js} +1 -1
- package/dist/{chunk-6k5k40p8.js → chunk-9fgkg1vr.js} +1 -1
- package/dist/{chunk-x05zyqzf.js → chunk-9jtjq50j.js} +1 -1
- package/dist/{chunk-z52s82k7.js → chunk-a4dmw23t.js} +1 -1
- package/dist/chunk-a6nz99qf.js +1 -0
- package/dist/{chunk-9g64g1np.js → chunk-adkpwx6c.js} +1 -1
- package/dist/chunk-aeyvj4h8.js +10 -0
- package/dist/{chunk-3pwq56je.js → chunk-anjpwev3.js} +1 -1
- package/dist/{chunk-76f8ms39.js → chunk-apssk1cy.js} +1 -1
- package/dist/{chunk-yt629r3s.js → chunk-ar8a7kmt.js} +2 -2
- package/dist/{chunk-tj2efrs1.js → chunk-b41den40.js} +2 -2
- package/dist/{chunk-0msthyzv.js → chunk-b8a0sphn.js} +2 -2
- package/dist/chunk-b916gtwm.js +1 -0
- package/dist/{chunk-5dgnnf3n.js → chunk-bzaz3335.js} +2 -2
- package/dist/chunk-d5kjq9p5.js +8 -0
- package/dist/{chunk-ypbnczjp.js → chunk-dabq8kdx.js} +2 -2
- package/dist/{chunk-c3jb4xg7.js → chunk-dcy8s8rz.js} +1 -1
- package/dist/{chunk-b54vham2.js → chunk-dxjn1stn.js} +1 -1
- package/dist/{chunk-1tshkx4p.js → chunk-esk028rd.js} +2 -2
- package/dist/{chunk-j0pjrq3v.js → chunk-et8gsz80.js} +2 -2
- package/dist/{chunk-23v8c9b8.js → chunk-fpjhg6ce.js} +2 -2
- package/dist/chunk-g7ed3sfy.js +1 -0
- package/dist/{chunk-k5nfe6pe.js → chunk-g8hcxgg8.js} +2 -2
- package/dist/{chunk-4cq70wxs.js → chunk-h25505f0.js} +2 -2
- package/dist/chunk-h6hjbmk9.js +1 -0
- package/dist/{chunk-mqekerck.js → chunk-hgrdsef7.js} +1 -1
- package/dist/{chunk-n9ws6dzb.js → chunk-hna3c2ck.js} +4 -4
- package/dist/{chunk-1dttmp46.js → chunk-jekst6kh.js} +1 -1
- package/dist/{chunk-ymcekh5x.js → chunk-jvnf66a0.js} +1 -1
- package/dist/{chunk-c3evbzpa.js → chunk-ka1915vs.js} +2 -2
- package/dist/{chunk-q2exry0f.js → chunk-kpqdfn9z.js} +2 -2
- package/dist/{chunk-4w4wjm49.js → chunk-kz15jy62.js} +1 -1
- package/dist/{chunk-ecd727xh.js → chunk-kzzty3v5.js} +1 -1
- package/dist/{chunk-tf7ezqew.js → chunk-m7b779kd.js} +1 -1
- package/dist/{chunk-53rm14qc.js → chunk-mtaqnt1q.js} +1 -1
- package/dist/{chunk-vbwvsgs1.js → chunk-ncqagb27.js} +2 -2
- package/dist/{chunk-6rj0ek81.js → chunk-ncsp5n4k.js} +3 -3
- package/dist/{chunk-xv3a1se1.js → chunk-nq0w1j1a.js} +1 -1
- package/dist/{chunk-cz9mrg18.js → chunk-p357ac7b.js} +1 -1
- package/dist/chunk-p7k7hqtb.js +1 -0
- package/dist/{chunk-gmcwgmnr.js → chunk-pd9d22ss.js} +3 -3
- package/dist/chunk-pykxe413.js +2 -0
- package/dist/{chunk-53h87fmt.js → chunk-q265drks.js} +1 -1
- package/dist/chunk-qvqqapft.js +1 -0
- package/dist/{chunk-dgf2xzzd.js → chunk-r6svhe3w.js} +2 -2
- package/dist/chunk-saasrzn4.js +1 -0
- package/dist/{chunk-cnhw5mqv.js → chunk-sca5q3tt.js} +1 -1
- package/dist/{chunk-rkdxqx8m.js → chunk-spxb931p.js} +2 -2
- package/dist/{chunk-ng96f4xd.js → chunk-twdfyk78.js} +2 -2
- package/dist/{chunk-hy20r5ze.js → chunk-txzgwgqk.js} +2 -2
- package/dist/chunk-v1cmz2bw.js +1 -0
- package/dist/chunk-v6sfs4qf.js +1 -0
- package/dist/{chunk-dvv28pkc.js → chunk-w4xqaw4h.js} +2 -2
- package/dist/chunk-xede4817.js +1 -0
- package/dist/chunk-xvn45j67.js +1 -0
- package/dist/{chunk-pshyn3yy.js → chunk-ye4wyq1k.js} +1 -1
- package/dist/{chunk-y9vh6qxz.js → chunk-yt07a4zp.js} +1 -1
- package/dist/{chunk-jcxpq57d.js → chunk-yy0a99es.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-25ps9fxw.js +0 -1
- package/dist/chunk-3fsr03k4.js +0 -1
- package/dist/chunk-8p475et7.js +0 -1
- package/dist/chunk-97qjsb8n.js +0 -1
- package/dist/chunk-bdgq4k40.js +0 -1
- package/dist/chunk-bh7bswhj.js +0 -1
- package/dist/chunk-bp4s6mbz.js +0 -8
- package/dist/chunk-c3mdtd39.js +0 -1
- package/dist/chunk-erqfqfcj.js +0 -1
- package/dist/chunk-fqnqeca5.js +0 -1
- package/dist/chunk-p3m1jyg5.js +0 -2
- package/dist/chunk-rsc9mwdw.js +0 -1
- package/dist/chunk-ttv1n12k.js +0 -1
- package/dist/chunk-vpz847k8.js +0 -1
- package/dist/chunk-wyw17nfy.js +0 -1
- package/dist/chunk-yxg6xbr1.js +0 -10
- package/dist/chunk-zbkr8pvx.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{Ae as W}from"./chunk-ar8a7kmt.js";import{De as F,Ee as M}from"./chunk-twdfyk78.js";import"./chunk-g8hcxgg8.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-ncsp5n4k.js";import"./chunk-2t6b962t.js";import"./chunk-h25505f0.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import{Sh as N,Th as B}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import{si as T}from"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-b8a0sphn.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import{$i as J}from"./chunk-m7b779kd.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-h6hjbmk9.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-82dckkw7.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-a6nz99qf.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-2jdnjmbh.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-p357ac7b.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-8q0a693b.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-b916gtwm.js"),import("./chunk-5s4knzbg.js"),import("./chunk-hgrdsef7.js"),import("./chunk-et8gsz80.js"),import("./chunk-apssk1cy.js"),import("./chunk-8nm03qtd.js"),import("./chunk-3jdt8kqf.js"),import("./chunk-dcy8s8rz.js"),import("./chunk-60092knz.js"),import("./chunk-057qv2wd.js"),import("./chunk-aeyvj4h8.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-g7ed3sfy.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-dxjn1stn.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 +1 @@
|
|
|
1
|
-
import{h as o}from"./chunk-
|
|
1
|
+
import{h as o}from"./chunk-yt07a4zp.js";import"./chunk-b8a0sphn.js";import"./chunk-m7b779kd.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var n="verification",r="goal-verification",o="review";function e(t){return t==="verification"||t==="goal-verification"}function i(t){return e(t)||t==="review"}var s=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],c=["pending","pass","fail","partial"],l=4000,p=3,S=["unable_to_proceed","stopping_here","internal_wait","self_deferral","handoff"],u=3,_=["waiting_dependency","same_task_no_effect","repeated_deferral"],d=3;
|
|
2
|
-
export{n as
|
|
2
|
+
export{n as $f,r as ag,o as bg,e as cg,i as dg,s as eg,c as fg,l as gg,p as hg,S as ig,u as jg,_ as kg,d as lg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Pi,S as Qi};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as yH,n as bH,o as IH,p as RH,q as gH,r as kH}from"./chunk-53rm14qc.js";import{A as KH,B as VH,C as p,D as ZH,y as TH,z as JH}from"./chunk-ymcekh5x.js";import{$ as FH,E as XH,Y as GH,_ as PH,da as EH}from"./chunk-n9ws6dzb.js";import"./chunk-ypbnczjp.js";import"./chunk-5dgnnf3n.js";import"./chunk-23v8c9b8.js";import{Gb as UH,Pb as _H,ub as r}from"./chunk-gmcwgmnr.js";import"./chunk-cnhw5mqv.js";import{Id as m,Td as s,td as jH,xd as xH}from"./chunk-fgmwse2v.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{re as zH}from"./chunk-hy20r5ze.js";import{te as fH,ue as AH,ve as SH}from"./chunk-jcxpq57d.js";import{we as MH}from"./chunk-bksfg23m.js";import"./chunk-ng96f4xd.js";import{We as WH}from"./chunk-k5nfe6pe.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-c3evbzpa.js";import"./chunk-1tshkx4p.js";import{hg as qH}from"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-6rj0ek81.js";import"./chunk-eyb9psbc.js";import"./chunk-4cq70wxs.js";import{Ch as DH}from"./chunk-4w4wjm49.js";import{Eh as LH,Gh as H,Hh as $H,Jh as N}from"./chunk-6k5k40p8.js";import{Nh as i,Oh as o}from"./chunk-p3m1jyg5.js";import{Sh as k}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-0msthyzv.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new p("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(rH)}),eH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),$J=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),XJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),YJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),DJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),FJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),EJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),MJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),zJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),TJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(DH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
1
|
+
import{m as yH,n as bH,o as IH,p as RH,q as gH,r as kH}from"./chunk-mtaqnt1q.js";import{A as KH,B as VH,C as p,D as ZH,y as TH,z as JH}from"./chunk-jvnf66a0.js";import{$ as PH,E as XH,Z as GH,aa as FH,ea as EH}from"./chunk-hna3c2ck.js";import"./chunk-dabq8kdx.js";import"./chunk-bzaz3335.js";import"./chunk-fpjhg6ce.js";import{Hb as UH,Qb as _H,vb as r}from"./chunk-pd9d22ss.js";import"./chunk-sca5q3tt.js";import{Jd as m,Ud as s,ud as jH,yd as xH}from"./chunk-4v2t1xs5.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{se as zH}from"./chunk-txzgwgqk.js";import{ue as fH,ve as AH,we as SH}from"./chunk-yy0a99es.js";import{xe as MH}from"./chunk-3jqd18d8.js";import"./chunk-twdfyk78.js";import{Xe as WH}from"./chunk-g8hcxgg8.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-ka1915vs.js";import"./chunk-esk028rd.js";import{ig as qH}from"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-ncsp5n4k.js";import"./chunk-2t6b962t.js";import"./chunk-h25505f0.js";import{Dh as DH}from"./chunk-kz15jy62.js";import{Fh as LH,Hh as H,Ih as $H,Kh as N}from"./chunk-9fgkg1vr.js";import{Oh as i,Ph as o}from"./chunk-pykxe413.js";import{Th as k}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-b8a0sphn.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import IJ from"yargs";import{hideBin as RJ}from"yargs/helpers";function v(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function dH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,X)=>{let J=!1,Z=()=>{v(K,"drain",x),v(K,"error",j),V.removeEventListener("abort",P)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>X(F??Error("Writable emitted an error"))),P=()=>W(()=>X(V.reason??Error("Writable drain aborted")));if(V.aborted){P();return}let T=K.once?.bind(K)??K.on?.bind(K);T?.("drain",x),T?.("error",j),V.addEventListener("abort",P,{once:!0})})}async function pH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await dH(K,Q)}class l{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new p("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(X)=>new ZH({maxPendingItems:V.maxPendingItems??JH,maxPendingBytes:V.maxPendingBytes??KH,writeTimeoutMs:V.writeTimeoutMs??VH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>pH(K[X],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new p("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))v(K,"error",V)}}var YH=1;function D(K){return H.Object({event_version:H.Literal(YH),...K})}var vH=D({type:H.Literal("content_delta"),delta:H.String()}),lH=D({type:H.Literal("thinking_delta"),delta:H.String()}),aH=D({type:H.Literal("thinking"),content:H.String()}),iH=D({type:H.Literal("stream_end")}),oH=D({type:H.Literal("content"),content:H.String()}),sH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),a=N(["readonly","write","execute"]),rH=H.Object({kind:a,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),nH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a)}),tH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(rH)}),eH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),HJ=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(a),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(eH)}),JJ=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),KJ=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),VJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),ZJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),$J=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),qJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),XJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),YJ=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),BJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),NJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),QJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),DJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),LJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),WJ=D({type:H.Literal("task_update"),tasks:H.Array(XH)}),jJ=D({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:N(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),xJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(qH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(N(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),UJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),GJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(N(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),PJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),FJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),EJ=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),MJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),zJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),fJ=D({type:H.Literal("turn_recovery"),state:N(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(N(["successful_tool_result","interrupted_tool_call"]))}),AJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),SJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),TJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),yJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),bJ=D({type:H.Literal("error"),message:H.String()}),eJ=$H(H.Union([vH,lH,aH,iH,oH,sH,nH,tH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,FJ,EJ,PJ,MJ,zJ,fJ,AJ,SJ,TJ,yJ,bJ]));function BH(K,V){return{event_version:YH,type:K,...V}}function gJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function kJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},X=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",X),process.once("SIGTERM",X);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",X),process.removeListener("SIGTERM",X)}}}var CJ=N(["text","jsonl"]),hJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(DH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(CJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class CH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function OJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function wJ(K){let V=LH(hJ,K);if(!V.success)throw Error(`Invalid headless options: ${OJ(V.error)}`);return V.data}function mJ(K){return K.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let Q=await lJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
|
|
2
2
|
`)}function cJ(K){return`[task] [${K.status}] ${K.subject}`}function uJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function dJ(K){if(!(K instanceof Error))return"Unknown error";let X=K.lastError??K;if(X.responseBody)try{let W=JSON.parse(X.responseBody)?.error?.message;if(W)return X.statusCode?`${W} (HTTP ${X.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function pJ(K){return K==="jsonl"?"jsonl":"text"}function NH(K,V){let Q=(...X)=>{for(let J of X){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function vJ(K,V,Q,X){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!X.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(X.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:X.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function QH(K,V,Q=!1){let X=(J,Z)=>{K.stdout.write(`${JSON.stringify(BH(J,Z))}
|
|
3
3
|
`)};return{contentDelta(J){if(V==="jsonl"){X("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return X("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){X("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){X("stream_end",{});return}if(Z)K.stderr.write(`
|
|
4
4
|
`);if(J)K.stdout.write(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
|
|
2
|
-
export{G as
|
|
2
|
+
export{G as vg,F as wg,R as xg,v as yg};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{g as i}from"./chunk-
|
|
1
|
+
import{g as i}from"./chunk-nq0w1j1a.js";import{Th as s}from"./chunk-kzzty3v5.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
|
|
2
2
|
${e.path}`}).join(`
|
|
3
3
|
`)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{Z as
|
|
1
|
+
import{rg as Q}from"./chunk-85bamng3.js";import{Fh as F,Hh as k,Kh as G}from"./chunk-9fgkg1vr.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
|
+
export{Z as xe};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$d as
|
|
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-7dykmcjj.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{Lh as K$,Mh as M$,Nh as B0,Oh as g0,Ph as W0}from"./chunk-pykxe413.js";import{Th as B1}from"./chunk-kzzty3v5.js";import{ti as h0}from"./chunk-w4xqaw4h.js";import{Ai as M0,Di as F0}from"./chunk-a4dmw23t.js";import{Hi as a}from"./chunk-b8a0sphn.js";import{Ri as q$,Si as Q0,Ti as A$,Ui as x,Vi as u,Xi as A0,Yi as t,Zi as k}from"./chunk-spxb931p.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]...
|
|
@@ -115,4 +115,4 @@ ${[...X0,...L0].join(`
|
|
|
115
115
|
s.project_sort_key ASC,
|
|
116
116
|
s.session_sort_key ASC
|
|
117
117
|
LIMIT ?`).all(...X,_.limit+1),L=await Promise.all(T.map(async(C)=>{let G=JSON.parse(C.metadata_json);if(C.archive_root_id&&C.effective_archived_at)return this.reconcileInterruptedTask({...G,archivedAt:C.effective_archived_at,archivedBySessionId:C.archive_root_id});let{archivedAt:E,archivedBySessionId:B,...V}=G;return this.reconcileInterruptedTask(V)})),W=p_(L,_);return{sessions:W.sessions.map((C)=>this.toPublicMetadata(C)),nextCursor:W.nextCursor}}catch{return null}}static async listSessions(_={}){let $=n_(_),R=z$(_),O=await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,0,$.archived,R),X=new Set;return O.sort(l_).flatMap((T)=>{let L=`${T.projectPath}\x00${T.sessionId}`;if(X.has(L))return[];return X.add(L),[this.toPublicMetadata(T)]})}static async collectStaleEmptySessions(_={}){let $=_.now??Date.now(),R=_.olderThanMs??W2;if(!Number.isFinite(R)||R<0)throw Error("Stale empty session age must be a non-negative number");let O=_.projectPath?[{storagePath:Q0(this.resolveCatalogWorkspace(_.projectPath)),projectPath:this.resolveCatalogWorkspace(_.projectPath)}]:await this.listAllProjectStorageDirectories(),X=0;for(let T of O){let L;try{L=await v_(T.storagePath)}catch(W){if(W.code==="ENOENT")continue;throw W}for(let W of L){if(!W.endsWith(".jsonl"))continue;let C=W.slice(0,-6);if(!A$(C))continue;let G=Y.join(T.storagePath,W);try{let B=await o0(G);if($-B.mtimeMs<R)continue;if(await Promise.all([o0(Y.join(T.storagePath,`${C}.inbox.json`)).then(()=>!0).catch(()=>!1),o0(A0(T.projectPath,C)).then(()=>!0).catch(()=>!1)]).then((J)=>J.some(Boolean)))continue}catch(B){if(B.code==="ENOENT")continue;throw B}let E;try{E=await o.acquire(C,T.projectPath)}catch(B){if(B instanceof d)continue;throw B}try{if(!await new j(G).deleteValidated((V)=>V.length===1&&V[0]?.type==="session_created"&&V[0].data.relationType!=="subagent"))continue;X++,await G0(Y.join(T.storagePath,`${C}.inbox.json`),{force:!0}),await G0(A0(T.projectPath,C),{force:!0}),await this.removeFromProjection(C,T.projectPath)}catch(B){q0.warn(`[SessionService] Skipping stale empty session cleanup: ${C}`,B)}finally{await E.release()}}}return X}static async findSessionMetadata(_,$){if(x(_),$!==void 0){if(!Y.isAbsolute($))throw Error("Session catalog cwd must be absolute");let O=Y.resolve($),X=this.getSessionFilePath(O,_);try{let T=await this.readStoredSessionMetadata(X,_,O);if(T.projectPath!==O)return;if(!T.parentId||T.archivedAt)return this.toPublicMetadata(u_([T],null)[0]??T);let L=await this.scanStoredSessions(O,!0,0,null);return this.toPublicMetadata(L.find((W)=>W.sessionId===_)??T)}catch(T){if(T.code==="ENOENT")return;throw T}}let R=(await this.scanStoredSessions(void 0,!0,0,null)).filter((O)=>O.sessionId===_);if(R.length===0)return;if(R.length>1)throw Error(`Ambiguous session ID: ${_}`);return this.toPublicMetadata(R[0])}static async loadSession(_,$){try{if($){if(!Y.isAbsolute($))throw Error("Session catalog cwd must be absolute");let O=Y.resolve($),X=this.getSessionFilePath(O,_);try{return await this.loadSessionFromFile(X,_,O)}catch(T){if(T.code==="ENOENT")throw Error(`未找到会话: ${_}`);throw T}}let R=(await this.scanStoredSessions(void 0,!0,0,null)).find((O)=>O.sessionId===_);if(!R)throw Error(`未找到会话: ${_}`);return await this.loadSessionFromFile(R.filePath,_)}catch(R){throw q0.error(`[SessionService] 加载会话失败 (${_}):`,R),R}}static async loadSessionModelContext(_,$){try{if($){if(!Y.isAbsolute($))throw Error("Session catalog cwd must be absolute");let O=Y.resolve($),X=this.getSessionFilePath(O,_);try{return await this.loadSessionModelContextFromFile(X,_,O)}catch(T){if(T.code==="ENOENT")throw Error(`未找到会话: ${_}`);throw T}}let R=(await this.scanStoredSessions(void 0,!0,0,null)).find((O)=>O.sessionId===_);if(!R)throw Error(`未找到会话: ${_}`);return await this.loadSessionModelContextFromFile(R.filePath,_)}catch(R){throw q0.error(`[SessionService] 加载模型上下文失败 (${_}):`,R),R}}static async exportSessionMarkdown(_,$,R={}){x(_);let O=this.resolveCatalogWorkspace($),X=u(O,_),T;try{T=await this.readStableSessionSnapshot(X,_)}catch(C){throw this.sanitizeStoredSessionError(C,_)}let L=this.projectMetadataFromEntries(T,_,O,X);if(L.projectPath!==O)throw Error(`Session export workspace mismatch: ${_}`);let W=L.archivedAt;if(!W&&L.parentId)W=(await this.findArchivedAncestor(L.parentId,O))?.archivedAt;return R$(T,{...L,archivedAt:W},R)}static async listRewindCheckpoints(_,$){x(_);let R=this.resolveCatalogWorkspace($),O=u(R,_),X=await this.readStableSessionSnapshot(O,_);this.validateSessionWorkspace(X,_,R);let T=new c0({sessionId:_,workspaceRoot:R});await T.initialize();let L=F$(X),W=[];for(let C of L){let G=h_(X,C.messageId),E=await T.previewRewind(G.snapshotMessageIds);W.push({...C,fileCount:E.files.length})}return W}static async rewindSession(_,$,R){x(_);let O=this.resolveCatalogWorkspace($);await this.assertSessionWritable(_,O);let X=u(O,_),T=new j(X),L;try{await T.appendValidatedAsync(async(W)=>{this.validateSessionWorkspace(W,_,O);let C=h_(W,R.targetMessageId),G=new c0({sessionId:_,workspaceRoot:O});await G.initialize();let E=await G.previewRewind(C.snapshotMessageIds),B=R.mode==="conversation"?await G.commitSnapshots(C.snapshotMessageIds):await G.rewindSnapshots(C.snapshotMessageIds),V=new Date().toISOString(),J={id:P(),sessionId:_,timestamp:V,type:"session_rewound",cwd:O,gitBranch:t(O),version:a(),data:{rewindId:P(),targetMessageId:R.targetMessageId,mode:R.mode,restoredFiles:R.mode==="conversation"?[]:B.files,createdAt:V}},Q=n([...W,J]);return L={checkpoint:{...C.checkpoint,fileCount:E.files.length},mode:R.mode,removedTurns:C.removedTurns,restoredFiles:J.data.restoredFiles,messages:this.convertJSONLToMessages(Q)},J})}catch(W){throw this.sanitizeStoredSessionError(W,_)}if(!L)throw Error(`Session rewind did not produce a result: ${_}`);for(let W of L.restoredFiles)r.getInstance().clearFileRecord(W);return L}static async forkSession(_,$){x(_);let R=$.newSessionId??`fork-${Date.now()}-${P(8)}`;x(R);let O=this.resolveForkWorkspace($.sourceProjectPath),X=this.resolveForkWorkspace($.targetProjectPath);if(O!==X)throw Error("Session forks must stay in the source workspace");let T=u(O,_),L=await this.readStableSessionSnapshot(T,_),W=this.getSessionCreatedEntry(L,_);if(W.data.sessionId!==_)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!Y.isAbsolute(W.cwd)||Y.resolve(W.cwd)!==O)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let C=this.projectMetadataFromEntries(L,_,O,T);if(C.archivedAt)throw new V0(_,_);if(C.parentId){let U=await this.findArchivedAncestor(C.parentId,O);if(U)throw new V0(_,U.sessionId)}let G=n(L),E=new Date().toISOString(),B=W.data.rootId||_,V=t(X),J=a(),{status:Q,taskStatus:A,taskStatusReason:b,taskFailure:K,taskStartedAt:X0,taskCompletedAt:L0,taskOwnerPid:y,taskPromptSummary:I,taskPriority:f,taskKind:D,taskDueAt:w,taskDispatch:N,taskModelId:z,taskRetriedFrom:r_,taskDelivery:t_,taskIsolation:a_,taskSourceProjectPath:s0,taskWorktree:s_,taskDiffStat:e_,taskQueuePosition:_1,taskQueueDepth:$1,taskConcurrencyLimit:R1,pendingInteraction:e0,...__}=W.data,$_={id:P(),sessionId:R,timestamp:E,type:"session_created",cwd:X,gitBranch:V,version:J,data:{...__,sessionId:R,rootId:B,parentId:_,relationType:"fork",taskStatus:"completed",taskCompletedAt:E,taskIsolation:"local",taskSourceProjectPath:X,createdAt:E,updatedAt:E}},R_=G.filter((U)=>U.type!=="session_created"&&U.type!=="token_budget_handoff_recorded"&&U.type!=="inbox_acknowledged"&&U.type!=="interaction_requested"&&U.type!=="interaction_responded"&&U.type!=="interaction_recovered"&&U.type!=="review_started"&&U.type!=="review_completed").map((U)=>{let m={...U,id:P(),sessionId:R,cwd:X,gitBranch:V,version:J};if(U.type==="session_updated"){let{status:F,taskStatus:Y0,taskStatusReason:G2,taskFailure:V2,taskStartedAt:E2,taskCompletedAt:J2,taskOwnerPid:Y2,taskPromptSummary:Q2,taskPriority:Z2,taskKind:N2,taskDueAt:H2,taskDispatch:U2,taskModelId:q2,taskRetriedFrom:A2,taskDelivery:K2,taskIsolation:M2,taskSourceProjectPath:F2,taskWorktree:D2,taskDiffStat:f2,taskQueuePosition:z2,taskQueueDepth:x2,taskConcurrencyLimit:w2,pendingInteraction:b2,...g$}=U.data;return{...m,type:"session_updated",data:{...g$,sessionId:R,rootId:B,parentId:_,relationType:"fork"}}}if(U.type==="message_created"){let{inboxMessageId:F,...Y0}=U.data;return{...m,type:"message_created",data:Y0}}return m}),O_={id:P(),sessionId:R,timestamp:E,type:"session_updated",cwd:X,gitBranch:V,version:J,data:{sessionId:R,rootId:B,parentId:_,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:E,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:X,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:E}},E0=[$_,...R_,O_],J0=u(X,R),z0=!1;try{await new j(J0).createExclusive(E0),z0=!0;let U=q1(G.flatMap((m)=>m.type==="message_created"?[m.data.metadata]:[]));if(U.length>0){let m=new e(O,_,{storageRoot:k()}),F=new e(X,R,{storageRoot:k()});await m.copyReferencedTo(U,F)}}catch(U){if(z0)await new j(J0).delete().catch(()=>{return}),await new e(X,R,{storageRoot:k()}).removeAll().catch(()=>{return});if(U.code==="EEXIST")throw Error(`Fork session already exists: ${R}`,{cause:U});throw U}let T_=this.projectMetadataFromEntries(E0,R,X,J0);return{sessionId:R,parentSessionId:_,projectPath:X,messages:this.convertJSONLToMessages(E0),metadata:this.toPublicMetadata(T_)}}static async deleteSession(_,$){if(x(_),$){if(!Y.isAbsolute($))throw Error("Session catalog cwd must be absolute");let O=Y.resolve($),X=this.getSessionFilePath(O,_),T=new j(X),L;try{L=await T.deleteValidated((W)=>{return this.projectMetadataFromEntries(W,_,O,X).projectPath===O})}catch(W){if(!this.isCorruptSessionJSONLError(W))throw W;L=await T.delete()}if(!L)return 0;return await G0(Y.join(Y.dirname(X),`${_}.inbox.json`),{force:!0}),await G0(A0(O,_),{force:!0}),await new e(O,_,{storageRoot:k()}).removeAll(),await Q_(O,_,k()),await this.removeFromProjection(_,O),1}let R=(await this.scanStoredSessions(void 0,!0)).filter((O)=>O.sessionId===_);if(R.length===0)return 0;return await Promise.all(R.map(async(O)=>{await new j(O.filePath).delete(),await G0(Y.join(Y.dirname(O.filePath),`${O.sessionId}.inbox.json`),{force:!0}),await G0(A0(O.projectPath,O.sessionId),{force:!0}),await new e(O.projectPath,O.sessionId,{storageRoot:k()}).removeAll(),await Q_(O.projectPath,O.sessionId,k()),await this.removeFromProjection(O.sessionId,O.projectPath)})),R.length}static async removeFromProjection(_,$){try{let R=await d0();if(R)x$(R,_,$)}catch{}}static validateTaskMetadataUpdate(_,$){if(_.taskPromptSummary!==void 0&&_.taskPromptSummary!==null&&(!_.taskPromptSummary.trim()||_.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if(_.taskPriority!==void 0&&_.taskPriority!==null&&!t0.has(_.taskPriority))throw Error("Invalid session task priority");if(_.taskKind!==void 0&&_.taskKind!==null&&!a0.has(_.taskKind))throw Error("Invalid session task kind");if(_.taskDueAt!==void 0&&_.taskDueAt!==null&&!Number.isFinite(Date.parse(_.taskDueAt)))throw Error("Invalid session task due date");if(_.taskFailure!==void 0&&_.taskFailure!==null&&!D_(_.taskFailure))throw Error("Invalid session task failure");if(_.taskDispatch!==void 0&&_.taskDispatch!==null&&!N$(_.taskDispatch))throw Error("Invalid durable task dispatch");if(_.taskModelId!==void 0&&_.taskModelId!==null&&(!_.taskModelId.trim()||_.taskModelId.length>500))throw Error("Invalid session task model ID");if(_.selectedModelId!==void 0&&_.selectedModelId!==null&&(!_.selectedModelId.trim()||_.selectedModelId.length>500))throw Error("Invalid selected session model ID");if(_.permissionMode!==void 0&&_.permissionMode!==null&&!r0(_.permissionMode))throw Error("Invalid session permission mode");if(_.reasoningEffort!==void 0&&_.reasoningEffort!==null&&!D0(_.reasoningEffort))throw Error("Invalid session reasoning effort");if(_.serviceTier!==void 0&&_.serviceTier!==null&&!F0(_.serviceTier))throw Error("Invalid session service tier");if(_.responseVerbosity!==void 0&&_.responseVerbosity!==null&&!M0(_.responseVerbosity))throw Error("Invalid session response verbosity");if(_.communicationStyle!==void 0&&_.communicationStyle!==null&&!f0(_.communicationStyle))throw Error("Invalid session communication style");if(_.communicationStyleDigest!==void 0&&_.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test(_.communicationStyleDigest))throw Error("Invalid session communication style digest");if(_.projectInstructionsDigest!==void 0&&_.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test(_.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if(_.taskRetriedFrom!==void 0&&_.taskRetriedFrom!==null&&!H$(_.taskRetriedFrom))throw Error("Invalid session task retry source");if(_.taskDelivery!==void 0&&_.taskDelivery!==null&&!Q$(_.taskDelivery))throw Error("Invalid session task delivery");if(_.taskIsolation!==void 0&&_.taskIsolation!==null&&!d_.has(_.taskIsolation))throw Error(`Invalid session task isolation: ${String(_.taskIsolation)}`);if(_.taskSourceProjectPath!==void 0&&_.taskSourceProjectPath!==null&&!Y.isAbsolute(_.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if(_.taskWorktree!==void 0&&_.taskWorktree!==null){let R=Y$(_.taskWorktree);if(!R||R.sessionId!==$||![R.repositoryRoot,R.originalWorkspaceRoot,R.worktreeRoot,R.workspaceRoot].every((O)=>Y.isAbsolute(O)))throw Error("Invalid session task worktree metadata")}if(_.taskDiffStat!==void 0&&_.taskDiffStat!==null&&!Z$(_.taskDiffStat))throw Error("Invalid session task diff stat");if(_.taskQueuePosition!==void 0&&_.taskQueuePosition!==null&&(!Number.isInteger(_.taskQueuePosition)||_.taskQueuePosition<1))throw Error("Invalid session task queue position");if(_.taskQueueDepth!==void 0&&_.taskQueueDepth!==null&&(!Number.isInteger(_.taskQueueDepth)||_.taskQueueDepth<0))throw Error("Invalid session task queue depth");if(_.taskConcurrencyLimit!==void 0&&_.taskConcurrencyLimit!==null&&(!Number.isInteger(_.taskConcurrencyLimit)||_.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof _.taskQueuePosition==="number"&&typeof _.taskQueueDepth==="number"&&_.taskQueuePosition>_.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata(_,$,R={}){x(_),q.validateTaskMetadataUpdate(R,_);let O=q.resolveCatalogWorkspace($);if(R.taskWorktree&&Y.resolve(R.taskWorktree.workspaceRoot)!==O)throw Error("Session task worktree must match the catalog workspace");let X=new Date().toISOString(),T={id:P(),sessionId:_,timestamp:X,type:"session_created",cwd:O,gitBranch:t(O),version:a(),data:{sessionId:_,rootId:_,...R.title!==void 0?{title:R.title}:{},taskStatus:R.taskStatus??"queued",...R.taskPromptSummary!==void 0?{taskPromptSummary:R.taskPromptSummary}:{},...R.taskPriority!==void 0?{taskPriority:R.taskPriority}:{},...R.taskKind!==void 0?{taskKind:R.taskKind}:{},...typeof R.taskDueAt==="string"?{taskDueAt:new Date(R.taskDueAt).toISOString()}:{},...R.taskDispatch!==void 0?{taskDispatch:R.taskDispatch}:{},...R.taskModelId!==void 0?{taskModelId:R.taskModelId}:{},...R.taskRetriedFrom!==void 0?{taskRetriedFrom:R.taskRetriedFrom}:{},...R.taskIsolation!==void 0?{taskIsolation:R.taskIsolation}:{},...R.taskSourceProjectPath!==void 0?{taskSourceProjectPath:R.taskSourceProjectPath}:{},...R.taskWorktree!==void 0?{taskWorktree:R.taskWorktree}:{},...R.selectedModelId!==void 0?{selectedModelId:R.selectedModelId}:{},...R.permissionMode!==void 0?{permissionMode:R.permissionMode}:{},...R.reasoningEffort!==void 0?{reasoningEffort:R.reasoningEffort}:{},...R.serviceTier!==void 0?{serviceTier:R.serviceTier}:{},...R.responseVerbosity!==void 0?{responseVerbosity:R.responseVerbosity}:{},...R.communicationStyle!==void 0?{communicationStyle:R.communicationStyle}:{},...R.communicationStyleDigest!==void 0?{communicationStyleDigest:R.communicationStyleDigest}:{},...R.projectInstructionsDigest!==void 0?{projectInstructionsDigest:R.projectInstructionsDigest}:{},createdAt:X,updatedAt:X}},L=q.getSessionFilePath(O,_);return await new j(L).createExclusive([T]),q.toPublicMetadata(q.projectMetadataFromEntries([T],_,O,L))}static async assertSessionWritable(_,$){let R=await this.findSessionMetadata(_,$);if(!R)throw Error(`Session not found: ${_}`);if(R.archivedAt)throw new V0(_,R.archivedBySessionId??_);return R}static async findArchivedAncestor(_,$){let R=new Set,O=_;while(O){if(R.has(O))throw Error("Session lineage contains a cycle");R.add(O),x(O);let X=u($,O),T;try{T=await T0(X,"utf8")}catch(W){if(W.code==="ENOENT")return;throw W}let L=this.projectMetadataFromEntries(this.parseStoredSession(T,O),O,$,X);if(L.projectPath!==$)throw Error("Session lineage escapes the requested workspace");if(L.archivedAt)return{sessionId:L.sessionId,archivedAt:L.archivedAt};O=L.parentId}return}static async listSessionArchiveMembers(_,$){x(_);let R=this.resolveCatalogWorkspace($),O=await this.scanStoredSessions(R,!0,0,null);if(!O.some((L)=>L.sessionId===_))throw Error(`Session not found: ${_}`);let X=new Set([_]),T=!0;while(T){T=!1;for(let L of O)if(L.parentId&&X.has(L.parentId)&&!X.has(L.sessionId))X.add(L.sessionId),T=!0}return O.filter((L)=>X.has(L.sessionId)).sort((L,W)=>L.sessionId.localeCompare(W.sessionId)).map((L)=>this.toPublicMetadata(L))}static async archiveSession(_,$){x(_);let R=this.resolveCatalogWorkspace($),O=await this.findSessionMetadata(_,R);if(!O)throw Error(`Session not found: ${_}`);if(O.archivedAt)return O;let X=await this.listSessionArchiveMembers(_,R),T=X.find((W)=>W.taskStatus==="queued"||W.taskStatus==="running");if(T)throw new p(`Stop session ${T.sessionId} before archiving this session tree`);let L=[];try{for(let E of X)L.push(await o.acquire(E.sessionId,R));let W=u(R,_),C=new j(W),G=[];return await C.appendValidated((E)=>{let B=this.projectMetadataFromEntries(E,_,R,W);if(B.archivedAt)throw new p(`Session archive state changed concurrently: ${_}`);if(B.taskStatus==="queued"||B.taskStatus==="running")throw new p(`Stop session ${_} before archiving it`);let V=new Date().toISOString(),J={id:P(),sessionId:_,timestamp:V,type:"session_updated",cwd:R,gitBranch:t(R),version:a(),data:{sessionId:_,archivedAt:V,updatedAt:V}};return G=[...E,J],J}),this.toPublicMetadata({...this.projectMetadataFromEntries(G,_,R,W),archivedBySessionId:_})}catch(W){if(W instanceof p)throw W;if(W instanceof d)throw new p(W.message);throw this.sanitizeStoredSessionError(W,_)}finally{for(let W of L.reverse())await W.release()}}static async unarchiveSession(_,$){x(_);let R=this.resolveCatalogWorkspace($),O=await this.findSessionMetadata(_,R);if(!O)throw Error(`Session not found: ${_}`);if(!O.archivedAt)return O;if(O.archivedBySessionId&&O.archivedBySessionId!==_)throw new p(`Unarchive ancestor ${O.archivedBySessionId} to restore session ${_}`);let X;try{X=await o.acquire(_,R);let T=u(R,_),L=new j(T),W=[];return await L.appendValidated((C)=>{if(!this.projectMetadataFromEntries(C,_,R,T).archivedAt)throw new p(`Session archive state changed concurrently: ${_}`);let E=new Date().toISOString(),B={id:P(),sessionId:_,timestamp:E,type:"session_updated",cwd:R,gitBranch:t(R),version:a(),data:{sessionId:_,archivedAt:null,updatedAt:E}};return W=[...C,B],B}),this.toPublicMetadata(this.projectMetadataFromEntries(W,_,R,T))}catch(T){if(T instanceof p)throw T;if(T instanceof d)throw new p(T.message);throw this.sanitizeStoredSessionError(T,_)}finally{await X?.release()}}static async updateSessionMetadata(_,$,R){if(x(_),q.validateTaskMetadataUpdate(R,_),R.taskStatus!==void 0&&!E$.has(R.taskStatus))throw Error(`Invalid session task status: ${String(R.taskStatus)}`);if(R.taskOwnerPid!==void 0&&R.taskOwnerPid!==null&&(!Number.isInteger(R.taskOwnerPid)||R.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let O=q.resolveCatalogWorkspace($);if(R.taskWorktree&&Y.resolve(R.taskWorktree.workspaceRoot)!==O)throw Error("Session task worktree must match the catalog workspace");let X=q.getSessionFilePath(O,_),T=new j(X),L=[];try{await T.appendValidatedAsync(async(W)=>{let C=q.getSessionCreatedEntry(W,_);if(C.data.sessionId!==_)throw Error(`Session metadata creation record sessionId mismatch: ${_}`);if(!Y.isAbsolute(C.cwd)||Y.resolve(C.cwd)!==O)throw Error(`Session metadata creation record cwd mismatch: ${_}`);let G=q.projectMetadataFromEntries(W,_,O,X);if(G.archivedAt)throw new V0(_,_);if(G.parentId){let V=await q.findArchivedAncestor(G.parentId,O);if(V)throw new V0(_,V.sessionId)}let E=new Date().toISOString(),B={id:P(),sessionId:_,timestamp:E,type:"session_updated",cwd:O,gitBranch:t(O),version:a(),data:{sessionId:_,...R.title!==void 0?{title:R.title}:{},...R.taskStatus!==void 0?{taskStatus:R.taskStatus}:{},...R.taskStatusReason!==void 0?{taskStatusReason:R.taskStatusReason}:{},...R.taskFailure!==void 0?{taskFailure:R.taskFailure}:{},...R.taskStartedAt!==void 0?{taskStartedAt:R.taskStartedAt}:{},...R.taskCompletedAt!==void 0?{taskCompletedAt:R.taskCompletedAt}:{},...R.taskOwnerPid!==void 0?{taskOwnerPid:R.taskOwnerPid}:{},...R.taskPromptSummary!==void 0?{taskPromptSummary:R.taskPromptSummary}:{},...R.taskPriority!==void 0?{taskPriority:R.taskPriority}:{},...R.taskKind!==void 0?{taskKind:R.taskKind}:{},...R.taskDueAt!==void 0?{taskDueAt:R.taskDueAt===null?null:new Date(R.taskDueAt).toISOString()}:{},...R.taskDispatch!==void 0?{taskDispatch:R.taskDispatch}:{},...R.taskModelId!==void 0?{taskModelId:R.taskModelId}:{},...R.taskRetriedFrom!==void 0?{taskRetriedFrom:R.taskRetriedFrom}:{},...R.taskDelivery!==void 0?{taskDelivery:R.taskDelivery}:{},...R.taskIsolation!==void 0?{taskIsolation:R.taskIsolation}:{},...R.taskSourceProjectPath!==void 0?{taskSourceProjectPath:R.taskSourceProjectPath}:{},...R.taskWorktree!==void 0?{taskWorktree:R.taskWorktree}:{},...R.taskDiffStat!==void 0?{taskDiffStat:R.taskDiffStat}:{},...R.taskQueuePosition!==void 0?{taskQueuePosition:R.taskQueuePosition}:{},...R.taskQueueDepth!==void 0?{taskQueueDepth:R.taskQueueDepth}:{},...R.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:R.taskConcurrencyLimit}:{},...R.selectedModelId!==void 0?{selectedModelId:R.selectedModelId}:{},...R.permissionMode!==void 0?{permissionMode:R.permissionMode}:{},...R.reasoningEffort!==void 0?{reasoningEffort:R.reasoningEffort}:{},...R.serviceTier!==void 0?{serviceTier:R.serviceTier}:{},...R.responseVerbosity!==void 0?{responseVerbosity:R.responseVerbosity}:{},...R.communicationStyle!==void 0?{communicationStyle:R.communicationStyle}:{},...R.communicationStyleDigest!==void 0?{communicationStyleDigest:R.communicationStyleDigest}:{},...R.projectInstructionsDigest!==void 0?{projectInstructionsDigest:R.projectInstructionsDigest}:{},updatedAt:E}};return L=[...W,B],B})}catch(W){throw q.sanitizeStoredSessionError(W,_)}return q.toPublicMetadata(q.projectMetadataFromEntries(L,_,O,X))}static async setSessionPermissionMode(_,$,R){if(x(_),!r0(R))throw Error("Invalid session permission mode");let O=q.resolveCatalogWorkspace($),X=await q.findSessionMetadata(_,O);if(X?.permissionMode===R)return X;if(X)return q.updateSessionMetadata(_,O,{permissionMode:R});try{return await q.createSessionMetadata(_,O,{taskStatus:"completed",permissionMode:R})}catch(T){if(T.code!=="EEXIST")throw T;return q.updateSessionMetadata(_,O,{permissionMode:R})}}static async findSessionTaskWorktree(_,$){x(_);let R=q.resolveCatalogWorkspace($),O=q.getSessionFilePath(R,_);try{return(await q.readStoredSessionMetadata(O,_,R)).taskWorktree}catch(X){if(X.code==="ENOENT")return;throw q.sanitizeStoredSessionError(X,_)}}static async findSessionTaskDispatch(_,$){x(_);let R=q.resolveCatalogWorkspace($),O=q.getSessionFilePath(R,_);try{return(await q.readStoredSessionMetadata(O,_,R)).taskDispatch}catch(X){if(X.code==="ENOENT")return;throw q.sanitizeStoredSessionError(X,_)}}static async loadSessionFromFile(_,$,R){let O=await T0(_,"utf-8"),X=this.parseStoredSession(O,$);if(R!==void 0){if(this.projectMetadataFromEntries(X,$,R,_).projectPath!==R)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToMessages(X)}static async loadSessionModelContextFromFile(_,$,R){let O=await T0(_,"utf-8"),X=this.parseStoredSession(O,$);if(R!==void 0){if(this.projectMetadataFromEntries(X,$,R,_).projectPath!==R)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToModelContext(X)}static convertJSONLToModelContext(_){let $=n(_),R=-1,O;for(let T=0;T<$.length;T++){let L=$[T];if(L?.type!=="part_created"||L.data.partType!=="summary")continue;let W=L.data.payload;if(R=T,O=m0(W.replacementMessages),!O)O=[{role:"user",content:W.text??"",metadata:L.data.payload}]}if(R<0||!O)return this.convertJSONLToMessages($,{includeTokenBudgetHandoffs:!0});let X=this.convertJSONLToMessages($.slice(R+1),{includeTokenBudgetHandoffs:!0});return[...O,...X]}static convertJSONLToMessages(_,$={}){let R=[],O=new Map,X=new Map,T=new Map,L=new Map,W=new Map,C=n(_),G=$.includeTokenBudgetHandoffs?I1(C):{kind:"none"},E=new Set;for(let B of C){if(B.type==="token_budget_handoff_recorded"){if(G.kind==="valid"&&G.event.id===B.id){let V=m1(B);if(V)R.push(V)}continue}if(B.type==="message_created"){let V=B.data.metadata&&typeof B.data.metadata==="object"&&!Array.isArray(B.data.metadata)?B.data.metadata:void 0,J=V?.codeReview&&typeof V.codeReview==="object"&&!Array.isArray(V.codeReview)?V.codeReview:void 0;if(J?.phase==="completed"&&typeof J.reviewId==="string")E.add(J.reviewId);let Q=B.data.role==="assistant"&&B.data.parentMessageId?T.get(B.data.parentMessageId):void 0,A=Q??{role:B.data.role,content:"",...B.data.metadata||B.data.inboxMessageId?{metadata:{...B.data.metadata&&typeof B.data.metadata==="object"&&!Array.isArray(B.data.metadata)?B.data.metadata:{},...B.data.inboxMessageId?{inboxMessageId:B.data.inboxMessageId}:{}}}:{}};if(O.set(B.data.messageId,A),X.set(B.data.messageId,[]),!Q)R.push(A)}if(B.type==="part_created"){if(B.data.partType==="reasoning"){let V=O.get(B.data.messageId);if(V){let J=B.data.payload;V.reasoningContent=(V.reasoningContent??"")+(J.text??"")}}if(B.data.partType==="text"){let V=O.get(B.data.messageId);if(V){let J=B.data.payload,Q=X.get(B.data.messageId);if(Q)Q.push({type:"text",text:J.text??""}),V.content=U$(Q);else V.content=J.text??""}}if(B.data.partType==="image"){let V=O.get(B.data.messageId);if(V){let J=B.data.payload,Q=X.get(B.data.messageId);if(Q&&J.dataUrl)Q.push({type:"image_url",image_url:{url:J.dataUrl}}),V.content=U$(Q)}}if(B.data.partType==="tool_call"){let V=O.get(B.data.messageId);if(V?.role!=="assistant"){if(V=T.get(B.data.messageId),!V)V={role:"assistant",content:"",tool_calls:[]},T.set(B.data.messageId,V),R.push(V)}if(V.role==="assistant"){let J=B.data.payload,Q=J.toolCallId??B.data.partId;L.set(B.data.partId,Q),W.set(Q,V),V.tool_calls??=[],V.tool_calls.push({id:Q,type:"function",function:{name:J.toolName??"unknown",arguments:JSON.stringify(J.input??{})}})}}if(B.data.partType==="tool_result"){let V=B.data.payload,J=n1(V),Q=J.error?`Error: ${J.error.message}`:typeof J.llmContent==="string"?J.llmContent:JSON.stringify(J.llmContent),A=V;R.push({role:"tool",content:Q,tool_call_id:L.get(B.data.messageId)??V.toolCallId,name:V.toolName,metadata:A})}if(B.data.partType==="summary"){let V=B.data.payload,J=B.data.payload;R.push({role:"system",content:V.text??"",metadata:J})}if(B.data.partType==="subtask_ref"){let V=O.get(B.data.messageId)??W.get(B.data.messageId);if(V){let J=B.data.payload,Q=V.metadata??{};V.metadata={...Q,subtaskRef:J}}}}}for(let B of v0(C)){if(B.completion===void 0||E.has(B.start.reviewId))continue;R.push({role:"assistant",content:k1(B.start,B.completion),metadata:{codeReview:{...S1(B.start,B.completion),synthetic:!0}}})}return R}static projectionDeriver(){return(_,$,R)=>{try{let O=u(R,$);return this.projectMetadataFromEntries(_,$,R,O)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection(_,$,R=0,O=!1,X={}){try{let T=await d0();if(!T)return null;await i_(T,this.projectionDeriver(),R);let L=[],W=[];if(_!==void 0)L.push("project_path=?"),W.push(_);O2(X,"",L,W);let C=L.length>0?` WHERE ${L.join(" AND ")}`:"",G=T.prepare(`SELECT metadata_json, is_subagent FROM sessions${C}`).all(...W),E=[];for(let V of G){if(!$&&V.is_subagent===1)continue;try{let J=JSON.parse(V.metadata_json);if(_!==void 0&&J.projectPath!==_)continue;E.push(J)}catch{}}let B=await Promise.all(E.map((V)=>this.reconcileInterruptedTask(V)));return u_(B.filter((V)=>w$(V,X)),O)}catch{return null}}static async scanStoredSessions(_,$=!1,R=0,O=!1,X={}){let T=_?Y.resolve(_):void 0,L=await this.scanStoredSessionsFromProjection(T,$,R,O,X);if(L)return L;let W=T?[{storagePath:Q0(T),projectPath:T}]:await this.listAllProjectStorageDirectories(),C=[];for(let G of W){let E;try{E=await v_(G.storagePath)}catch(B){if(B.code==="ENOENT")continue;throw B}for(let B of E){if(!B.endsWith(".jsonl"))continue;let V=B.slice(0,-6),J=Y.join(G.storagePath,B);try{let Q=await this.readStoredSessionMetadata(J,V,G.projectPath);if(T!==void 0&&Q.projectPath!==T){q0.warn(`[SessionService] Skipping out-of-scope session transcript: ${V}`);continue}if(!$&&Q.relationType==="subagent")continue;if(!T2(Q,X))continue;C.push(Q)}catch(Q){let A=Q.code;if(A==="ENOENT")continue;if(A)throw Q;q0.warn(`[SessionService] Skipping invalid session transcript: ${V}`)}}}return u_(C,O)}static async listAllProjectStorageDirectories(){let _=Y.join(k(),"projects"),$;try{$=await v_(_,{withFileTypes:!0,encoding:"utf8"})}catch(R){if(R.code==="ENOENT")return[];throw R}return $.filter((R)=>R.isDirectory()).map((R)=>({storagePath:Y.join(_,R.name),projectPath:q$(R.name)}))}static async readStoredSessionMetadata(_,$,R){let O=await T0(_,"utf-8"),X=this.parseStoredSession(O,$);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(X,$,R,_))}static async reconcileInterruptedTask(_){let $=_.taskOwnerPid;if(_.taskStatus!=="running"||$===void 0||J$($))return _;let R;try{R=await o.acquire(_.sessionId,_.projectPath)}catch(T){if(!(T instanceof d))throw T;let L=await T0(_.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(L,_.sessionId),_.sessionId,_.projectPath,_.filePath)}let O=new j(_.filePath),X;try{try{await O.appendValidated((T)=>{let L=this.projectMetadataFromEntries(T,_.sessionId,_.projectPath,_.filePath);if(L.taskStatus!=="running"||L.taskOwnerPid!==$||J$($))throw new o_;let W=new Date().toISOString(),C={id:P(),sessionId:_.sessionId,timestamp:W,type:"session_updated",cwd:_.projectPath,gitBranch:t(_.projectPath),version:a(),data:{sessionId:_.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:W,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:W}};return X=[...T,C],C})}catch(T){if(!(T instanceof o_))throw T}if(!X){let T=await T0(_.filePath,"utf-8");X=this.parseStoredSession(T,_.sessionId)}return this.projectMetadataFromEntries(X,_.sessionId,_.projectPath,_.filePath)}finally{await R.release()}}static projectMetadataFromEntries(_,$,R,O){if(_.length===0)throw Error(`Empty session transcript: ${$}`);let X=this.getSessionCreatedEntry(_,$),T=_.reduce((F,Y0)=>Y0.type==="session_updated"?{...F,...Y0.data}:F,{...X.data}),L=n(_),W=b1(w1(L)),G=v0(L).at(-1),E=L.findLastIndex((F)=>F.type==="review_started"&&F.data.reviewId===G?.start.reviewId||F.type==="review_completed"&&F.data.reviewId===G?.start.reviewId),B=L.findLastIndex((F)=>(F.type==="session_created"||F.type==="session_updated")&&Object.hasOwn(F.data,"taskStatus")),V=G!==void 0&&E>B,J=V?G.completion===void 0?"running":G.completion.status==="completed"||G.completion.status==="stale"?"completed":G.completion.status==="aborted"?"cancelled":G.completion.status==="interrupted"?"interrupted":"failed":void 0,Q=L.filter((F)=>F.type==="message_created"&&["user","assistant"].includes(F.data.role)).length,A=L.some((F)=>F.type==="part_created"&&F.data.partType==="tool_result"&&typeof F.data.payload.error==="string"),b=E$.has(T.taskStatus)?T.taskStatus:void 0,K=J??b??(A?"failed":"completed"),X0=typeof T.taskOwnerPid==="number"&&Number.isInteger(T.taskOwnerPid)&&T.taskOwnerPid>0?T.taskOwnerPid:void 0,L0=d_.has(T.taskIsolation)?T.taskIsolation:void 0,y=typeof T.taskSourceProjectPath==="string"&&Y.isAbsolute(T.taskSourceProjectPath)?Y.resolve(T.taskSourceProjectPath):void 0,I=X.cwd;if(I!==void 0&&!Y.isAbsolute(I))throw Error(`Session catalog cwd must be absolute: ${$}`);let f=I===void 0?R:Y.resolve(I),D=Y$(T.taskWorktree),w=D?.sessionId===$&&Y.resolve(D.workspaceRoot)===f?D:void 0,N=Z$(T.taskDiffStat),z=N$(T.taskDispatch),r_=t0.has(T.taskPriority)?T.taskPriority:z?.taskPriority,t_=a0.has(T.taskKind)?T.taskKind:z?.taskKind,a_=typeof T.taskDueAt==="string"&&Number.isFinite(Date.parse(T.taskDueAt))?new Date(T.taskDueAt).toISOString():z?.taskDueAt,s0=typeof T.taskModelId==="string"&&T.taskModelId.trim()?T.taskModelId:z?.modelId,s_=typeof T.selectedModelId==="string"&&T.selectedModelId.trim()?T.selectedModelId:s0,e_=r0(T.permissionMode)?T.permissionMode:z?.permissionMode,_1=D0(T.reasoningEffort)?T.reasoningEffort:z?.reasoningEffort,$1=F0(T.serviceTier)?T.serviceTier:z?.serviceTier,R1=M0(T.responseVerbosity)?T.responseVerbosity:z?.responseVerbosity,e0=f0(T.communicationStyle)?T.communicationStyle:z?.communicationStyle,__=Object.hasOwn(T,"communicationStyleDigest")?typeof T.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(T.communicationStyleDigest)?T.communicationStyleDigest:void 0:e0===z?.communicationStyle?z?.communicationStyleDigest:void 0,$_=Object.hasOwn(T,"projectInstructionsDigest")?typeof T.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(T.projectInstructionsDigest)?T.projectInstructionsDigest:void 0:z?.projectInstructionsDigest,R_=S$(T.archivedAt)?T.archivedAt:void 0,O_=H$(T.taskRetriedFrom),E0=Q$(T.taskDelivery),J0=typeof T.taskQueuePosition==="number"&&Number.isInteger(T.taskQueuePosition)&&T.taskQueuePosition>0?T.taskQueuePosition:void 0,z0=typeof T.taskQueueDepth==="number"&&Number.isInteger(T.taskQueueDepth)&&T.taskQueueDepth>=0?T.taskQueueDepth:void 0,T_=typeof T.taskConcurrencyLimit==="number"&&Number.isInteger(T.taskConcurrencyLimit)&&T.taskConcurrencyLimit>0?T.taskConcurrencyLimit:void 0,U=V?G?.completion?G.completion.status==="completed"?void 0:`Code review ${N_(G.completion.status)}`:`Reviewing ${G?.start.target.label??"changes"}`:void 0,m=V?K==="failed"&&U?F_(U):void 0:D_(T.taskFailure)?T.taskFailure:K==="failed"&&typeof T.taskStatusReason==="string"?F_(T.taskStatusReason):void 0;return{sessionId:$,projectPath:f,gitBranch:X.gitBranch,rootId:T.rootId||$,parentId:T.parentId,relationType:T.relationType,resumedFrom:T.resumedFrom,rootAgentId:T.rootAgentId,resumeDepth:T.resumeDepth,title:T.title,agentType:T.agentType,model:T.model,selectedModelId:s_,permissionMode:e_,reasoningEffort:_1,serviceTier:$1,responseVerbosity:R1,communicationStyle:e0,communicationStyleDigest:__,projectInstructionsDigest:$_,pendingInteraction:W,taskStatus:K,taskStatusReason:m?.message??U??(typeof T.taskStatusReason==="string"?T.taskStatusReason:void 0),taskFailure:m,taskStartedAt:V?G?.start.startedAt:typeof T.taskStartedAt==="string"?T.taskStartedAt:void 0,taskCompletedAt:V?G?.completion?.completedAt:typeof T.taskCompletedAt==="string"?T.taskCompletedAt:void 0,taskPromptSummary:V?G?B2(G.start.target):"/review uncommitted":typeof T.taskPromptSummary==="string"?T.taskPromptSummary:void 0,taskPriority:r_,taskKind:t_,taskDueAt:a_,taskModelId:s0,taskRetryAvailable:z!==void 0,taskRetriedFrom:O_,taskDelivery:E0,taskIsolation:L0,taskSourceProjectPath:y,taskWorktreePath:w?.worktreeRoot,taskWorktreeBranch:w?.branch,taskBaseCommit:w?.baseCommit,taskDiffStat:N,taskQueuePosition:J0,taskQueueDepth:z0,taskConcurrencyLimit:T_,archivedAt:R_,taskOwnerPid:V?void 0:X0,taskWorktree:w,taskDispatch:z,messageCount:Q,firstMessageTime:_[0].timestamp,lastMessageTime:_.at(-1).timestamp,hasErrors:A||K==="failed",filePath:O}}static toPublicMetadata(_){let{filePath:$,taskOwnerPid:R,taskWorktree:O,taskDispatch:X,...T}=_;return T}static getSessionFilePath(_,$){return u(_,$)}static getSessionCreatedEntry(_,$){let R=_.find((O)=>O.type==="session_created");if(!R)throw new k$($);return R}static resolveCatalogWorkspace(_){if(!Y.isAbsolute(_))throw Error("Session catalog cwd must be absolute");return Y.resolve(_)}static validateSessionWorkspace(_,$,R){let O=this.getSessionCreatedEntry(_,$);if(O.data.sessionId!==$)throw Error(`Session creation record sessionId mismatch: ${$}`);if(!Y.isAbsolute(O.cwd)||Y.resolve(O.cwd)!==R)throw Error(`Session creation record cwd mismatch: ${$}`)}static resolveForkWorkspace(_){if(!Y.isAbsolute(_))throw Error("Fork workspace paths must be absolute");return Y.resolve(_)}static parseStoredSession(_,$){return D$(_,`session ${$}`)}static isCorruptSessionJSONLError(_){return _ instanceof Error&&_.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError(_,$){if(!this.isCorruptSessionJSONLError(_)||!(_ instanceof Error))return _;let R=_.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${$}${R?` at line ${R}`:""}`,{cause:_.cause})}static async readStableSessionSnapshot(_,$,R=3){for(let O=0;O<R;O+=1){let X=await K0.stat(_),T=await K0.readFile(_),L=this.parseStoredSession(T,$),W=await K0.stat(_);if(X.size===W.size&&X.mtimeNs===W.mtimeNs&&X.dev===W.dev&&X.ino===W.ino)return L}throw Error("Session changed while creating fork; retry the operation")}}function U$(_){if(_.length===1&&_[0]?.type==="text")return _[0].text;return[..._]}
|
|
118
|
-
export{J_ as
|
|
118
|
+
export{J_ as ec,f_ as fc,O1 as gc,x0 as hc,X1 as ic,j2 as jc,d as kc,o as lc,p$ as mc,E1 as nc,e as oc,e2 as pc,_O as qc,$O as rc,RO as sc,OO as tc,TO as uc,XO as vc,LO as wc,WO as xc,BO as yc,CO as zc,GO as Ac,VO as Bc,EO as Cc,JO as Dc,YO as Ec,QO as Fc,ZO as Gc,NO as Hc,HO as Ic,UO as Jc,qO as Kc,AO as Lc,KO as Mc,MO as Nc,FO as Oc,DO as Pc,fO as Qc,zO as Rc,xO as Sc,wO as Tc,bO as Uc,M1 as Vc,OR as Wc,Q_ as Xc,f1 as Yc,IO as Zc,mO as _c,w1 as $c,uO as ad,v0 as bd,cO as cd,N_ as dd,k1 as ed,S1 as fd,pO as gd,iO as hd,dO as id,QR as jd,I1 as kd,m1 as ld,ZR as md,oO as nd,C0 as od,F_ as pd,D_ as qd,r as rd,c0 as sd,CT as td,GT as ud,VT as vd,ET as wd,n1 as xd,JT as yd,QT as zd,l1 as Ad,NT as Bd,k_ as Cd,S_ as Dd,FT as Ed,DT as Fd,s1 as Gd,l0 as Hd,kT as Id,G$ as Jd,O$ as Kd,yT as Ld,V$ as Md,IT as Nd,W2 as Od,J4 as Pd,Y4 as Qd,k$ as Rd,V0 as Sd,p as Td,q as Ud};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ue as a,ve as b,we as c}from"./chunk-yy0a99es.js";import"./chunk-3jqd18d8.js";import"./chunk-g8hcxgg8.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-85bamng3.js";import"./chunk-h25505f0.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-b8a0sphn.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-d5kjq9p5.js";import"./chunk-anjpwev3.js";import"./chunk-nq0w1j1a.js";import"./chunk-6437f0h4.js";import"./chunk-jekst6kh.js";import"./chunk-jvnf66a0.js";import"./chunk-hna3c2ck.js";import"./chunk-dabq8kdx.js";import"./chunk-bzaz3335.js";import"./chunk-fpjhg6ce.js";import"./chunk-pd9d22ss.js";import"./chunk-sca5q3tt.js";import"./chunk-4v2t1xs5.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{ze as n}from"./chunk-ar8a7kmt.js";import"./chunk-twdfyk78.js";import{Ve as s}from"./chunk-g8hcxgg8.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-ka1915vs.js";import"./chunk-esk028rd.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-ncsp5n4k.js";import"./chunk-2t6b962t.js";import"./chunk-h25505f0.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-b8a0sphn.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.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,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{qd as C}from"./chunk-4v2t1xs5.js";import{kh as F,lh as L}from"./chunk-h25505f0.js";import{Mutex as G}from"async-mutex";class $ extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(j){super("Session runtime capacity is full");this.limit=j;this.name="SessionRuntimeCapacityError"}}class X extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class W extends Error{constructor(j){super(`Session runtime residency already owns key: ${j}`);this.name="SessionRuntimeResidencyConflictError"}}class U{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new G;nextGeneration=1;closed=!1;constructor(j){if(!F(j.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!L(j.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=j.maxResident,this.idleMs=j.idleMs,this.now=j.now??Date.now}acquire(j){let q=this.residents.get(j);if(!q||q.poisoned)return;return q.pins++,q.lastUsedAt=this.now(),this.createLease(q)}owns(j,q){let z=this.residents.get(j);return Boolean(z&&(q===void 0||z.value===q))}async reserve(j,q){if(!j.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new X;if(this.residents.has(j)||this.reservations.has(j))throw new W(j);while(this.retainedCount()>=this.maxResident){if(!q.allowEviction)throw new $(this.maxResident);let H=this.oldestEvictableWebResident();if(!H)throw new $(this.maxResident);await this.disposeResident(H,!0)}let z={generation:this.allocateGeneration(),surface:q.surface};return this.reservations.set(j,z),this.createReservation(j,z)})}async remove(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q)return!1;if(z.pins>0)return!1;return await this.disposeResident(z,!0),!0})}async forget(j,q){return this.operations.runExclusive(async()=>{let z=this.residents.get(j);if(!z||q!==void 0&&z.value!==q||z.pins>0)return!1;return this.residents.delete(j),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let j=0;while(!0){let q=this.oldestIdleWebResident();if(!q)return j;await this.disposeResident(q,!0),j++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let j;for(let q of[...this.residents.values()])try{await this.disposeResident(q,!1)}catch(z){j??=z}if(this.residents.clear(),j!==void 0)throw j})}getStats(){let j=0;for(let q of this.residents.values())if(q.pins>0)j++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:j,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let j=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,j}createReservation(j,q){let z=!1;return{commit:(H)=>{if(z)throw new W(j);if(H.key!==j||H.surface!==q.surface||this.reservations.get(j)!==q||this.closed)throw this.reservations.delete(j),z=!0,this.closed?new X:new W(j);this.reservations.delete(j);let J={...H,generation:q.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(j,J),z=!0,this.createLease(J)},cancel:()=>{if(z)return;if(this.reservations.get(j)===q)this.reservations.delete(j);z=!0}}}createLease(j){let q=!1;return{value:j.value,release:()=>{if(q)return;q=!0;let z=this.residents.get(j.key);if(z!==j||z.generation!==j.generation)return;z.pins=Math.max(0,z.pins-1),z.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((j)=>this.canEvict(j))}oldestIdleWebResident(){let j=this.now();return this.sortedWebResidents().find((q)=>j-q.lastUsedAt>=this.idleMs&&this.canEvict(q))}sortedWebResidents(){return[...this.residents.values()].filter((j)=>j.surface==="web").sort((j,q)=>j.lastUsedAt-q.lastUsedAt||j.generation-q.generation)}canEvict(j){if(j.pins>0||j.poisoned)return!1;try{return j.canEvict()}catch{return!1}}async disposeResident(j,q){if(this.residents.get(j.key)!==j)return;this.residents.delete(j.key);try{await j.dispose()}catch(z){if(q&&!this.closed&&!this.residents.has(j.key))j.lastUsedAt=this.now(),j.poisoned=!0,this.residents.set(j.key,j);throw z}}}import{createHash as B}from"node:crypto";var P=4,b=1000,Y=4000,D=120000,O=0.2;function w(j){try{return C(j)&&j.retryable}catch{return!1}}function N(j,q){let z=Number.isSafeInteger(q)&&q>0?q:1,H=z-1,J=Math.min(b*2**H,Y),K=B("sha256").update(`${j}\x00${z}`).digest().readUInt32BE(0)/4294967295,Q=1-O+2*O*K;return Math.min(Y,Math.max(0,Math.round(J*Q)))}function _(j){let q=N(j.sessionIdentity,j.failedAttempt),z=j.evidence,H=j.workStillPending===!0&&z!==void 0&&w(z.taskFailure)&&z.outputStarted===!1&&z.toolExecutionStarted===!1&&Number.isInteger(z.toolCallsCount)&&z.toolCallsCount===0,J=Number.isSafeInteger(j.failedAttempt)&&j.failedAttempt>0&&j.failedAttempt<P,Z=j.now??Date.now(),K=Z-j.recoveryStartedAt,Q=Number.isFinite(Z)&&Number.isFinite(j.recoveryStartedAt)&&Number.isFinite(K)&&K>=0&&K+q<=D;return{phase:H?J&&Q?"retry_scheduled":"exhausted":"failed",delayMs:q,retryable:H,withinAttemptBudget:J,withinTimeBudget:Q}}
|
|
2
2
|
export{$ as s,U as t,P as u,D as v,_ as w};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ti as r}from"./chunk-w4xqaw4h.js";import{Ri as d,Ti as x,Vi as j,Zi as u,_i as i}from"./chunk-spxb931p.js";import{$i as I}from"./chunk-m7b779kd.js";import{stat as a}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var e=50,__=100,E_=new Set(["queued","running","completed","failed","cancelled","interrupted"]),R_=new Set(["high","medium","low"]),W_=/^[A-Za-z0-9_-]+$/,$_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function H_(_){return typeof _==="string"&&$_.test(_)&&Number.isFinite(Date.parse(_))}function v(_){return typeof _==="string"&&U.isAbsolute(_)}function M_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function Q_(_){try{if(!W_.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||v(R.cwd))||!H_(R.lastMessageTime)||!v(R.projectPath)||!x(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function J(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function V_(_){if(!_.cursor)return;let E=Q_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function O_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:M=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let H=W===void 0?e:W;if(!Number.isInteger(H)||H<1||H>__)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:H,includeSubagents:$,archived:M}}function N_(_={}){let E=c(_.taskStatus,E_,"task status"),R=c(_.taskPriority,R_,"task priority"),W=S(_.taskDueAfter,"taskDueAfter"),$=S(_.taskDueBefore,"taskDueBefore");return X_(W,$),{...E?{taskStatuses:E}:{},...R?{taskPriorities:R}:{},...W?{taskDueAfter:W}:{},...$?{taskDueBefore:$}:{}}}function c(_,E,R){if(_===void 0)return;let W=Array.isArray(_)?_:[_];if(W.length===0)return;let $=new Set;for(let M of W){if(typeof M!=="string"||!E.has(M))throw Error(`Invalid session ${R} filter`);$.add(M)}return[...$].sort()}function S(_,E){if(_===void 0)return;if(typeof _!=="string"||!Number.isFinite(Date.parse(_)))throw Error(`Invalid session ${E} filter`);return new Date(_).toISOString()}function X_(_,E){if(_!==void 0&&E!==void 0&&_>E)throw Error("Session task due range is inverted")}function Y_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=V_(E);if(W)R=R.filter((H)=>Y_(H,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let M=$[$.length-1];return{sessions:$,nextCursor:M_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:M.lastMessageTime,projectPath:M.projectPath,sessionId:M.sessionId})}}function G_(_){return _.type==="message_created"||_.type==="token_budget_handoff_recorded"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="turn_recovery_acknowledged"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function O(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function N(_,E){let R=_.find((W)=>O(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:m(_,E),createdAt:R.data.createdAt}}function m(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function h(_,E){N(_,E);let R=_.findIndex((H)=>H.type==="message_created"&&H.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,M=new Set(_.flatMap((H)=>H.type==="turn_started"&&$&&H.data.inputMessageIds?.includes($)?[H.data.turnId]:[]));return _.filter((H,Q)=>{if((H.type==="turn_started"||H.type==="turn_completed"||H.type==="turn_aborted"||H.type==="turn_recovery_acknowledged")&&M.has(H.data.turnId))return!1;return Q<R||!G_(H)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(N(E,R.data.targetMessageId),R.data.mode!=="code")E=h(E,R.data.targetMessageId)}return E}function j_(_){let E=w(_);return E.filter(O).map((R)=>({messageId:R.data.messageId,preview:m(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function u_(_,E){let R=w(_),W=N(R,E),$=R.findIndex((H)=>H.type==="message_created"&&H.data.messageId===E),M=R.slice($);return{checkpoint:W,projectedEntries:h(R,E),removedTurns:M.filter(O).length,snapshotMessageIds:M.flatMap((H)=>H.type==="part_created"&&H.data.partType==="tool_call"?[H.data.partId]:[])}}import*as z from"node:fs";import{createReadStream as g_}from"node:fs";import*as X from"node:fs/promises";import*as f from"node:path";import{createInterface as T_}from"node:readline";var b=65536;function D(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function Z_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function y(_,E="session transcript"){let R=_.split(`
|
|
2
2
|
`),W=!_.endsWith(`
|
|
3
3
|
`),$=[];for(let[M,H]of R.entries())try{let Q=Z_(H,M+1,E);if(Q){if(typeof Q.seq!=="number")Q.seq=$.length+1;$.push(Q)}}catch(Q){if(W&&M===R.length-1)break;throw Q}return $}class G{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return G.stampSeqFrom(_,G.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await X.mkdir(f.dirname(this.filePath),{recursive:!0,mode:493});let E=await X.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=G.stampSeqFrom(_,W),M=`${$.map(D).join(`
|
|
4
4
|
`)}
|
|
@@ -137,4 +137,4 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
|
|
|
137
137
|
ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
|
|
138
138
|
WHERE parts_fts MATCH ?
|
|
139
139
|
ORDER BY timestamp DESC LIMIT ?`,Q=_.prepare(H);return R?Q.all(M,R,W):Q.all(M,W)}
|
|
140
|
-
export{w as
|
|
140
|
+
export{w as $d,j_ as ae,u_ as be,y as ce,G as de,J as ee,V_ as fe,O_ as ge,N_ as he,Y_ as ie,f_ as je,s as ke,B_ as le,A_ as me,y_ as ne,z_ as oe,t_ as pe,e_ as qe,_E as re};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Rf as a,Sf as b,Tf as c,Uf as d,Vf as e,Wf as f,Xf as g,Yf as h,Zf as i,_f as j}from"./chunk-esk028rd.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-ncsp5n4k.js";import"./chunk-2t6b962t.js";import"./chunk-h25505f0.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-b8a0sphn.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function v(b){switch(b){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}
|
|
2
|
-
export{v as
|
|
2
|
+
export{v as rg};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{La as H}from"./chunk-bzaz3335.js";import"./chunk-sca5q3tt.js";import"./chunk-q265drks.js";import{Ze as $,df as T}from"./chunk-g8hcxgg8.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-ncsp5n4k.js";import"./chunk-2t6b962t.js";import"./chunk-h25505f0.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import{Th as k}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-b8a0sphn.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as gz,t as cz,u as Az,v as Nz,w as Pz}from"./chunk-
|
|
1
|
+
import{s as gz,t as cz,u as Az,v as Nz,w as Pz}from"./chunk-6437f0h4.js";import{x as T}from"./chunk-jekst6kh.js";import{A as Uz,B as Vz,C as wz,D as Kz,y as uz,z as Gz}from"./chunk-jvnf66a0.js";import{K as b,T as Hz,U as Xz,Z as Lz,aa as Bz,ba as jz,ea as Fz,ua as Dz,va as _z,wa as Oz,xa as qz}from"./chunk-hna3c2ck.js";import"./chunk-dabq8kdx.js";import{La as fz}from"./chunk-bzaz3335.js";import{Na as Yz}from"./chunk-fpjhg6ce.js";import{Hb as Qz,Qb as Wz,vb as $z}from"./chunk-pd9d22ss.js";import{$b as f}from"./chunk-sca5q3tt.js";import{Ad as zz,Gd as g,Hd as Jz,Jd as E,Md as Zz,Rd as P,Ud as U,ed as n,od as h,pd as u,qd as s,vd as t,yd as e}from"./chunk-4v2t1xs5.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{ze as pz}from"./chunk-ar8a7kmt.js";import"./chunk-twdfyk78.js";import{Ue as Mz,Ve as kz}from"./chunk-g8hcxgg8.js";import"./chunk-v508x7cg.js";import{ef as c}from"./chunk-ye4wyq1k.js";import{jf as o}from"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import{uf as Iz}from"./chunk-8qp8v96d.js";import"./chunk-ka1915vs.js";import"./chunk-esk028rd.js";import"./chunk-0zzh482s.js";import{mg as Cz}from"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-ncsp5n4k.js";import"./chunk-2t6b962t.js";import{eh as Sz,hh as yz}from"./chunk-h25505f0.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import{Lh as k,Mh as r,Oh as I,Ph as C}from"./chunk-pykxe413.js";import{Th as Ez}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import{ti as S}from"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import{Ai as Tz,Di as hz}from"./chunk-a4dmw23t.js";import"./chunk-b8a0sphn.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import{Zi as a}from"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import{Readable as tz,Writable as ez}from"node:stream";import*as y from"@agentclientprotocol/sdk";import xz from"node:path";import{PROTOCOL_VERSION as nz,RequestError as sz}from"@agentclientprotocol/sdk";import{RequestError as Rz}from"@agentclientprotocol/sdk";import{nanoid as M}from"nanoid";var G=S("Agent");function i(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function vz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:i(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:i("headers"in z?z.headers:void 0)};return null}function lz(z){let Z={};for(let J of z){let Y=vz(J);if(Y)Z[J.name]=Y}return Z}function bz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function iz(z){let Z=Jz(z.metadata);return Z?[{type:"text",text:g(Z)}]:bz(z.content)}function az(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function rz(z){if(!o(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...h("capacity"),resource:z.resource}}function oz(z){if(!(z instanceof Rz)||!z.data||typeof z.data!=="object")return;let Z=z.data;if(!s(Z.taskFailure)||Z.toolExecutionStarted!==!1||!Number.isInteger(Z.toolCallsCount)||Z.toolCallsCount<0||Z.outputStarted!==!1)return;return{taskFailure:Z.taskFailure,toolExecutionStarted:Z.toolExecutionStarted,toolCallsCount:Z.toolCallsCount,outputStarted:Z.outputStarted}}class x{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Kz({maxPendingItems:Gz,maxPendingBytes:Uz,writeTimeoutMs:Vz,signal:J.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await J.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([U.loadSession(this.id,this.cwd),U.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await U.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Fz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await U.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),b.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Wz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?lz(this.options.mcpServers):void 0,J=b.getInstance().getTerminalService(this.id);if(this.runtime=await Lz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,B)=>{let L=await J.execute(W,{cwd:B.cwd,env:B.env,timeout:B.timeoutMs,signal:B.signal,allowLocalFallback:!1,onOutput:(j)=>B.onOutput?.("stdout",j)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await T.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await _z(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=$z.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.requestPendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:B,messageId:L,content:j}=W.properties,F=W.properties.metadata;if(W.type==="team.message.received"&&typeof B==="string"&&typeof L==="string"&&typeof j==="string"&&Xz(F,{messageId:L,teamName:B}))(async()=>{let V=await this.runtime?.enqueueSteering(j,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:F});if(!V?.accepted)return;if(await new Hz(B,a()).markDelivered([L]),V.delivery==="next_turn")this.requestPendingResume()})().catch((V)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,V)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,Q=H?.status==="active"||H?.status==="verifying";if(X||Q)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}})}}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!zz(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of iz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,L,j=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},F=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)j(V);else L=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.session.id,status:"in_progress",title:`Resuming ${F.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${F.source.id} at depth ${F.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,L)j(L);return F}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await T.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:W,onEvent:(F)=>{if(F.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.toolCall.id,status:"in_progress",title:`Review: ${F.toolCall.function.name}`,content:[],kind:this.mapToolKind(F.toolKind)});else if(F.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.toolCall.id,status:F.result.success?"completed":"failed",content:[]})}}),L=await B.completion,j=(await T.list(this.cwd,this.id)).find((F)=>F.start.reviewId===B.reviewId);if(!j)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:L.status,findings:L.findings.length,content:n(j.start,L)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:j})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await Oz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.requestPendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await U.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=qz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let X;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:H.name,description:H.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(b.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,X=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((K)=>K.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Zz(X).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let W=Yz(H);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((K)=>K.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let K=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!K.accepted)throw Error(K.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${K.queued})`),K.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,L=()=>{B.abort(Z.abortSignal?.reason)};if(Z.abortSignal?.aborted)L();else Z.abortSignal?.addEventListener("abort",L,{once:!0});let j=!1,F=!1,V=!1,m,d=new Promise((K)=>{m=K});this.pendingPrompt=B,this.pendingPromptCompletion=d;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Dz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,B.signal)}let K={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Qz(this.agent.chatStream(Y,K,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)F=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)F=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{V=!0;let w=$.toolCall,q=w.function.name;if(q===E)break;let N=this.mapToolKind($.toolKind),D=`Executing ${q}`;if(q==="Task"&&"function"in w)try{let R=JSON.parse(w.function.arguments),_=R.resume_from??R.resume;if(typeof _==="string")D=`Resuming ${String(R.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:D,content:[],kind:N});break}case"tool_progress":{V=!0;let w=$.toolCall;if(w.function.name===E)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{V=!0;let w=$.toolCall;if(w.function.name===E)break;let q=$.result,N=[],D=q.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;N.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))N.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=w.function.name,mz=jz(e(Bz(_,q),t));N.push({type:"content",content:{type:"text",text:mz}})}if(w.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))N.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let R=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:R,content:N});break}case"structured_output":F=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
|
|
2
|
-
export{s as
|
|
2
|
+
export{s as uf,g as vf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
|
|
2
|
-
export{a as
|
|
2
|
+
export{a as Fh,f as Gh,l as Hh,x as Ih,b as Jh,V as Kh};
|