blade-code 0.10.3 → 0.10.5
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-069zpw09.js +6 -0
- package/dist/{chunk-grp43mdb.js → chunk-19kg7yvw.js} +1 -1
- package/dist/{chunk-3wp3h373.js → chunk-1m5r6mp2.js} +1 -1
- package/dist/chunk-1q21sxhx.js +1 -0
- package/dist/{chunk-aa0ffw17.js → chunk-1r6szcrj.js} +1 -1
- package/dist/{chunk-jqwntnp1.js → chunk-1vx4sf1y.js} +1 -1
- package/dist/{chunk-5fxc90rb.js → chunk-1x4fpe47.js} +1 -1
- package/dist/{chunk-p5tpzh6f.js → chunk-2nkd1kjx.js} +1 -1
- package/dist/chunk-417wefq7.js +99 -0
- package/dist/{chunk-xdbg7cn3.js → chunk-51wtvmzn.js} +2 -2
- package/dist/{chunk-c45y8tx1.js → chunk-62881c2s.js} +120 -120
- package/dist/{chunk-eezg6pee.js → chunk-6eragc74.js} +1 -1
- package/dist/{chunk-zq9r0jx3.js → chunk-7jy60gnx.js} +1 -1
- package/dist/{chunk-r4pz99sy.js → chunk-am8dtvff.js} +1 -1
- package/dist/chunk-c5tds5v0.js +9 -0
- package/dist/{chunk-vmg5n0zv.js → chunk-f6mszdsd.js} +1 -1
- package/dist/{chunk-s95rgkd8.js → chunk-fz1vyc15.js} +1 -1
- package/dist/chunk-g6h6h8xr.js +1 -0
- package/dist/chunk-hh85pk77.js +160 -0
- package/dist/{chunk-rcdynprn.js → chunk-njyvrtje.js} +2 -2
- package/dist/{chunk-da1jvzbz.js → chunk-nz78b5c5.js} +1 -1
- package/dist/chunk-r1764q6f.js +1 -0
- package/dist/chunk-r6mwyg3h.js +3 -0
- package/dist/{chunk-bn148dr5.js → chunk-rh7v814a.js} +8 -8
- package/dist/chunk-rzzt21ef.js +22 -0
- package/dist/{chunk-wje6bck2.js → chunk-s645azsm.js} +1 -1
- package/dist/{chunk-7hqbwpt5.js → chunk-sanhjqpd.js} +1 -1
- package/dist/{chunk-1cx96gx1.js → chunk-tjnfhm9v.js} +1 -1
- package/dist/{chunk-8th744ef.js → chunk-v0ygsjry.js} +1 -1
- package/dist/{chunk-bfw2p0x8.js → chunk-vntzy7bc.js} +3 -3
- package/dist/{chunk-vwq9s5nj.js → chunk-vpj0sv73.js} +4 -4
- package/dist/{chunk-9yytfg19.js → chunk-xv0maezy.js} +1 -1
- package/dist/{chunk-7089z4e1.js → chunk-yc53wz4r.js} +1 -1
- package/dist/web/assets/{ChatView-Pqa25Vua.js → ChatView-Y-6k-ayR.js} +2 -2
- package/dist/web/assets/{CodeBlockHighlighter-Dxt-FWJk.js → CodeBlockHighlighter-CFW6qjnA.js} +1 -1
- package/dist/web/assets/{FilePreview-Dj2yppPn.js → FilePreview-CR_XetY0.js} +2 -2
- package/dist/web/assets/{MarkdownRenderer-BI2xpTV2.js → MarkdownRenderer-CVrxJswQ.js} +12 -12
- package/dist/web/assets/{McpModal-COw0BcHJ.js → McpModal-BO-85gll.js} +1 -1
- package/dist/web/assets/SettingsModal-CW87OnxI.js +1 -0
- package/dist/web/assets/{SkillsModal-CTZTu9xg.js → SkillsModal-Q8ZFPhys.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-DPXkV-qb.js → TaskSwitcher-BzH-0QXr.js} +1 -1
- package/dist/web/assets/{TerminalPanel-tpUxwaCh.js → TerminalPanel-DTqvx8yB.js} +1 -1
- package/dist/web/assets/index-B7etZcne.css +1 -0
- package/dist/web/assets/index-ClOgGy-I.js +32 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-1g5qc1qx.js +0 -99
- package/dist/chunk-8thp1nep.js +0 -1
- package/dist/chunk-9p5f3ryf.js +0 -1
- package/dist/chunk-c05t8207.js +0 -22
- package/dist/chunk-mgwny24b.js +0 -160
- package/dist/chunk-n3y9ytvg.js +0 -3
- package/dist/chunk-nxj1638n.js +0 -6
- package/dist/chunk-pnrx3spk.js +0 -9
- package/dist/chunk-r4j5ca1h.js +0 -1
- package/dist/web/assets/SettingsModal-h4AxN730.js +0 -1
- package/dist/web/assets/index-Dep3eEsS.css +0 -1
- package/dist/web/assets/index-bjyn3NHs.js +0 -32
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Rb as W}from"./chunk-
|
|
2
|
+
import{Rb as W}from"./chunk-vntzy7bc.js";import{Ub as F,Vb as M}from"./chunk-drrdzmaa.js";import"./chunk-sanhjqpd.js";import"./chunk-g6h6h8xr.js";import"./chunk-fvhc1yj8.js";import"./chunk-vpj0sv73.js";import"./chunk-qm11hjd3.js";import{md as T}from"./chunk-qda309d9.js";import"./chunk-rh7v814a.js";import"./chunk-tq52pbde.js";import"./chunk-79s052sw.js";import{qe as N,re as B}from"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import"./chunk-1vx4sf1y.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import{Ve as K}from"./chunk-9ffr01c3.js";import C from"node:path";var E=process.argv.slice(2),I=p(E),v=I!==null;if(I!==null)T.setGlobalDebug(I);function p(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 u(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 c(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 m(){if(u(E)){let{getVersion:J}=await import("./chunk-1r6szcrj.js");console.log(J());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=c(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:J}=await import("./chunk-tjnfhm9v.js");J(U.map((Z)=>C.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:J}=await import("./chunk-ccwskwb3.js");await J.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let J=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(J&&!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:J}=await import("./chunk-069zpw09.js");if(await J())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:J}=await import("./chunk-c5tds5v0.js");if(await J())return}if(E.includes("--acp")){let{runAcpIntegration:J}=await import("./chunk-rzzt21ef.js");await J();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{serveCommand:b},{updateCommands:V},{webCommand:P}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-r1764q6f.js"),import("./chunk-1q21sxhx.js"),import("./chunk-njyvrtje.js"),import("./chunk-gb54hc78.js"),import("./chunk-fz1vyc15.js"),import("./chunk-v93hcxe7.js"),import("./chunk-2nkd1kjx.js"),import("./chunk-5twefby5.js"),import("./chunk-nz78b5c5.js")]),x=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(O).command(y).command(S).command(V).command(k).command(P).command(b).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((J,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),v&&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(J)console.error("Error: Invalid arguments:"),console.error(J),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(J)=>{let Z=J._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-4ncbd4k0.js").then(({checkVersionOnStartup:j})=>j()),[{render:A},{createElement:w},{AppWrapper:f}]=await Promise.all([import("ink"),import("react"),import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(J)=>{let Z=J._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-4ncbd4k0.js").then(({checkVersionOnStartup:j})=>j()),[{render:A},{createElement:w},{AppWrapper:f}]=await Promise.all([import("ink"),import("react"),import("./chunk-hh85pk77.js")]),H={...J,initialMessage:L,debug:J.debug,print:Boolean(J.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,A(w(f,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await x.parse()}catch(J){console.error("Error: Parse error:",J),process.exit(1)}}if(K.main==K.module)m().catch(console.error);export{m as main};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{m as Yq,n as Zq,o as $q,p as Gq}from"./chunk-51wtvmzn.js";import{q as Qq}from"./chunk-xv0maezy.js";import{E as i,F as r,G as s,I as F,J as a}from"./chunk-62881c2s.js";import"./chunk-s645azsm.js";import{Aa as l,Da as v}from"./chunk-1m5r6mp2.js";import"./chunk-jza1rsan.js";import{qb as u}from"./chunk-417wefq7.js";import"./chunk-an96c54z.js";import{Jb as n}from"./chunk-6eragc74.js";import{Lb as t,Mb as e,Nb as qq}from"./chunk-19kg7yvw.js";import{Ob as o}from"./chunk-6tx8k249.js";import"./chunk-drrdzmaa.js";import{mc as m}from"./chunk-sanhjqpd.js";import"./chunk-g6h6h8xr.js";import"./chunk-fvhc1yj8.js";import"./chunk-dqvcgwhe.js";import"./chunk-ea7wsges.js";import"./chunk-gxmrakrk.js";import"./chunk-yc53wz4r.js";import"./chunk-am8dtvff.js";import"./chunk-35yktzm1.js";import"./chunk-63ysxybd.js";import"./chunk-vpj0sv73.js";import"./chunk-qm11hjd3.js";import"./chunk-qda309d9.js";import"./chunk-rh7v814a.js";import{be as g,ce as d,ee as q,fe as C,he as j,ie as p}from"./chunk-tq52pbde.js";import"./chunk-79s052sw.js";import{re as x}from"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import"./chunk-1vx4sf1y.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";import mq from"yargs";import{hideBin as uq}from"yargs/helpers";var k=1;function B(Z){return q.Object({event_version:q.Literal(k),...Z})}var Kq=B({type:q.Literal("content_delta"),delta:q.String()}),jq=B({type:q.Literal("thinking_delta"),delta:q.String()}),bq=B({type:q.Literal("thinking"),content:q.String()}),Aq=B({type:q.Literal("stream_end")}),Hq=B({type:q.Literal("content"),content:q.String()}),w=j(["readonly","write","execute"]),Rq=B({type:q.Literal("tool_start"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(w)}),zq=B({type:q.Literal("tool_progress"),tool_name:q.String(),message:q.String(),progress:q.Optional(q.Number()),total:q.Optional(q.Number())}),Mq=B({type:q.Literal("tool_result"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(w),success:q.Optional(q.Boolean()),error_type:q.Optional(q.String()),error_message:q.Optional(q.String())}),Eq=B({type:q.Literal("mcp_catalog_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),Pq=B({type:q.Literal("mcp_content_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),content_kind:j(["resources","resource_templates","prompts"]),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),Nq=B({type:q.Literal("mcp_resource_updated"),revision:q.Integer({minimum:1}),server_name:q.String(),uri:q.String()}),fq=B({type:q.Literal("mcp_connection_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),phase:j(["reconnecting","recovered","failed"]),reason:q.String(),attempt:q.Integer({minimum:0}),max_attempts:q.Integer({minimum:0}),next_retry_at:q.Optional(q.Integer({minimum:0})),error:q.Optional(q.String())}),xq=B({type:q.Literal("mcp_log"),revision:q.Integer({minimum:1}),server_name:q.String(),level:j(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:q.Optional(q.String()),message:q.String(),projected_bytes:q.Integer({minimum:0}),data_sha256:q.String(),truncated:q.Boolean(),details_omitted:q.Boolean(),timestamp:q.Integer({minimum:0}),synthetic:q.Optional(q.Boolean())}),Iq=B({type:q.Literal("mcp_instructions_changed"),revision:q.Integer({minimum:0}),server_name:q.String(),action:j(["added","removed"]),reason:j(["snapshot","connection","disconnection"]),text:q.Optional(q.String()),source_bytes:q.Optional(q.Integer({minimum:0})),projected_bytes:q.Optional(q.Integer({minimum:0})),sha256:q.Optional(q.String()),truncated:q.Optional(q.Boolean()),details_omitted:q.Optional(q.Boolean())}),Lq=B({type:q.Literal("mcp_task_changed"),revision:q.Integer({minimum:0}),task_id:q.String(),server_name:q.String(),tool_name:q.String(),status:j(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:q.Optional(q.String()),created_at:q.Integer({minimum:0}),updated_at:q.Integer({minimum:0}),completed_at:q.Optional(q.Integer({minimum:0})),has_result:q.Boolean(),error:q.Optional(q.String())}),Jq=B({type:q.Literal("project_rules_loaded"),files:q.Array(q.Object({id:q.String(),relative_path:q.String(),source:j(["project","local"]),conditional:q.Boolean(),content_sha256:q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:q.Array(q.String()),blocked_write:q.Boolean()}),Wq=B({type:q.Literal("user_shell_started"),execution_id:q.String(),command:q.String(),auxiliary:q.Boolean()}),Sq=B({type:q.Literal("user_shell_output"),execution_id:q.String(),stream:j(["stdout","stderr"]),chunk:q.String(),stream_truncated:q.Boolean()}),Oq=B({type:q.Literal("user_shell_completed"),execution_id:q.String(),message_id:q.String(),status:j(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:q.Union([q.Integer(),q.Null()]),duration_ms:q.Number({minimum:0}),stdout:q.String(),stderr:q.String(),truncated:q.Boolean(),auxiliary:q.Boolean()}),hq=B({type:q.Literal("phase"),phase:j(["turn","searching","inspecting","target_hit","executing","completed"]),status:j(["ongoing","hit","done"]),message:q.String(),turn:q.Optional(q.Number()),tool_name:q.Optional(q.String()),target:q.Optional(q.String())}),Cq=B({type:q.Literal("tool_detail"),tool_name:q.String(),detail:q.String()}),Fq=B({type:q.Literal("task_update"),tasks:q.Array(F)}),kq=B({type:q.Literal("subagent"),state:j(["spawned","completed"]),session_id:q.String(),subagent_type:q.Optional(q.String()),success:q.Optional(q.Boolean()),summary:q.Optional(q.String()),verification_verdict:q.Optional(j(["pass","fail","partial"])),resumed_from:q.Optional(q.String()),root_agent_id:q.Optional(q.String()),resume_depth:q.Optional(q.Integer({minimum:0}))}),wq=B({type:q.Literal("token_usage"),input_tokens:q.Number(),output_tokens:q.Number(),total_tokens:q.Number(),max_context_tokens:q.Number(),cache_read_tokens:q.Optional(q.Number()),cache_write_tokens:q.Optional(q.Number()),cost_usd:q.Optional(q.Number())}),Tq=B({type:q.Literal("compacting"),state:j(["started","completed"])}),yq=B({type:q.Literal("turn_limit"),turns_count:q.Number(),action:q.Literal("continue")}),cq=B({type:q.Literal("task_session"),session_id:q.String(),project_path:q.String(),source_project_path:q.String(),isolation:j(["local","worktree"]),worktree_branch:q.Optional(q.String()),base_commit:q.Optional(q.String())}),gq=B({type:q.Literal("task_admission"),state:j(["queued","running"]),queue_position:q.Optional(q.Integer({minimum:1})),queue_depth:q.Integer({minimum:0}),in_flight:q.Integer({minimum:0}),max_concurrent_tasks:q.Integer({minimum:1})}),dq=B({type:q.Literal("output"),content:q.String(),exit_code:q.Number()}),pq=B({type:q.Literal("error"),message:q.String()}),GQ=C(q.Union([Kq,jq,bq,Aq,Hq,Rq,zq,Mq,Eq,Pq,Nq,fq,xq,Iq,Lq,Jq,Wq,Sq,Oq,hq,Cq,Fq,kq,wq,Tq,yq,cq,gq,dq,pq]));function T(Z,$){return{event_version:k,type:Z,...$}}function lq(Z){if(Z?.signal)return{signal:Z.signal,dispose:()=>{return}};let $=new AbortController,G=()=>$.abort("interrupt");return process.once("SIGINT",G),process.once("SIGTERM",G),{signal:$.signal,dispose:()=>{process.removeListener("SIGINT",G),process.removeListener("SIGTERM",G)}}}var vq=j(["text","jsonl"]),iq=q.Object({headless:q.Optional(q.Boolean()),message:q.Optional(q.String()),_:q.Optional(q.Array(q.Union([q.String(),q.Number()]))),model:q.Optional(q.String()),systemPrompt:q.Optional(q.String()),appendSystemPrompt:q.Optional(q.String()),maxTurns:q.Optional(q.Refine(q.Integer({maximum:p}),(Z)=>Z===-1||Z>0,()=>"must be -1 or a positive integer")),permissionMode:q.Optional(q.Enum(g)),mcpConfig:q.Optional(q.Array(q.String())),strictMcpConfig:q.Optional(q.Boolean()),sessionId:q.Optional(q.String()),allowedTools:q.Optional(q.Array(q.String())),disallowedTools:q.Optional(q.Array(q.String())),agents:q.Optional(q.String()),continue:q.Optional(q.Boolean()),resume:q.Optional(q.Union([q.String(),q.Boolean()])),forkSession:q.Optional(q.Boolean()),taskIsolation:q.Optional(j(["local","worktree"])),outputFormat:q.Optional(vq)});class Vq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Z){this.openedThinking=Z}hasOpenThinking(){return this.openedThinking}completeStream(){let Z={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Z}}function rq(Z){return Z.issues.map(($)=>`${$.path.join(".")||"options"}: ${$.message}`).join("; ")}function sq(Z){let $=d(iq,Z);if(!$.success)throw Error(`Invalid headless options: ${rq($.error)}`);return $.data}function aq(Z){return Z.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",($)=>$.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("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("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async($)=>{if(!$.headless)return;let G=await QQ($);process.exit(G)})}function _(Z,$=""){Z.write(`${$}
|
|
2
|
+
`)}function oq(Z){return`[task] [${Z.status}] ${Z.subject}`}function nq(){return{requestConfirmation:async(Z)=>Z.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:Z.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function tq(Z){if(!(Z instanceof Error))return"Unknown error";let Q=Z.lastError??Z;if(Q.responseBody)try{let K=JSON.parse(Q.responseBody)?.error?.message;if(K)return Q.statusCode?`${K} (HTTP ${Q.statusCode})`:K}catch{}let Y=Z.message.match(/Last error:\s*(.+)$/);if(Y)return Y[1];return Z.message}function eq(Z){return Z==="jsonl"?"jsonl":"text"}function y(Z,$){let G=(...Q)=>{for(let Y of Q){let U=$[Y];if(typeof U==="string"&&U.trim()!=="")return U}return};switch(Z){case"Read":case"Edit":case"Write":case"UndoEdit":return G("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return G("notebook_path");case"Grep":return G("path","pattern");case"Glob":return G("pattern");case"WebFetch":return G("url");case"WebSearch":return G("query");case"Bash":return G("command","description");case"Task":return G("description");case"LSP":return G("filePath","operation");case"EnterWorktree":return G("name");case"ExitWorktree":return G("action");default:return}}function qQ(Z,$,G,Q){let Y=new Set(["Glob","Grep","WebSearch","LS"]),U=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Z)&&!Q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${$}`,shouldLockTarget:!0};if(Q.targetLocked)return{phase:"executing",status:"hit",message:G?`Working within target: ${$}`:`Executing: ${$}`,shouldLockTarget:!1};if(Y.has(Z))return{phase:"searching",status:"ongoing",message:`Still searching: ${$}`,shouldLockTarget:!1};if(U.has(Z))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${$}`,shouldLockTarget:!1};return{phase:"executing",status:Q.targetLocked?"hit":"ongoing",message:`Executing: ${$}`,shouldLockTarget:!1}}function c(Z,$){let G=(Q,Y)=>{Z.stdout.write(`${JSON.stringify(T(Q,Y))}
|
|
3
|
+
`)};return{contentDelta(Q){if($==="jsonl"){G("content_delta",{delta:Q});return}Z.stdout.write(Q)},thinkingDelta(Q,Y){if($==="jsonl")return G("thinking_delta",{delta:Q}),Y;if(!Y)Z.stderr.write("[thinking] ");return Z.stderr.write(Q),!0},thinking(Q){if($==="jsonl"){G("thinking",{content:Q});return}_(Z.stderr,`[thinking] ${Q}`)},streamEnd(Q,Y){if($==="jsonl"){G("stream_end",{});return}if(Y)Z.stderr.write(`
|
|
4
|
+
`);if(Q)Z.stdout.write(`
|
|
5
|
+
`)},content(Q){if($==="jsonl"){G("content",{content:Q});return}_(Z.stdout,Q)},toolStart(Q,Y,U,K){if($==="jsonl"){G("tool_start",{tool_name:Q,summary:Y,target:U,tool_kind:K});return}_(Z.stderr,`[tool:start] ${Y}`)},toolProgress(Q,Y,U,K){if($==="jsonl"){G("tool_progress",{tool_name:Q,message:Y,progress:U,total:K});return}_(Z.stderr,`[tool:progress] ${Q}: ${Y}`)},toolResult(Q,Y,U,K,A){if($==="jsonl"){G("tool_result",{tool_name:Q,summary:Y,target:U,tool_kind:K,success:A?.success,error_type:A?.errorType,error_message:A?.errorMessage});return}_(Z.stderr,`[tool:result] ${Y}`)},mcpCatalogChanged(Q){if($==="jsonl"){G("mcp_catalog_changed",{revision:Q.revision,server_name:Q.serverName,added:Q.added,removed:Q.removed,updated:Q.updated});return}_(Z.stderr,`[mcp:catalog] r${Q.revision} ${Q.serverName} +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}`)},mcpContentChanged(Q){if($==="jsonl"){G("mcp_content_changed",{revision:Q.revision,server_name:Q.serverName,content_kind:Q.contentKind==="resourceTemplates"?"resource_templates":Q.contentKind,added:Q.added,removed:Q.removed,updated:Q.updated});return}_(Z.stderr,`[mcp:${Q.contentKind}] r${Q.revision} ${Q.serverName} +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}`)},mcpResourceUpdated(Q){if($==="jsonl"){G("mcp_resource_updated",{revision:Q.revision,server_name:Q.serverName,uri:Q.uri});return}_(Z.stderr,`[mcp:resource] r${Q.revision} ${Q.serverName} updated ${Q.uri}`)},mcpConnectionChanged(Q){if($==="jsonl"){G("mcp_connection_changed",{revision:Q.revision,server_name:Q.serverName,phase:Q.phase,reason:Q.reason,attempt:Q.attempt,max_attempts:Q.maxAttempts,...Q.nextRetryAt!==void 0?{next_retry_at:Q.nextRetryAt}:{},...Q.error?{error:Q.error}:{}});return}_(Z.stderr,`[mcp:connection] r${Q.revision} ${Q.serverName} ${Q.phase} ${Q.attempt}/${Q.maxAttempts}`)},mcpLog(Q){if($==="jsonl"){G("mcp_log",{revision:Q.revision,server_name:Q.serverName,level:Q.level,logger:Q.logger,message:Q.message,projected_bytes:Q.projectedBytes,data_sha256:Q.dataSha256,truncated:Q.truncated,details_omitted:Q.detailsOmitted,timestamp:Q.timestamp,synthetic:Q.synthetic});return}_(Z.stderr,`[mcp:log] ${Q.level} ${Q.serverName}${Q.logger?` logger=${Q.logger}`:""}: ${Q.message}`)},mcpInstructionsChanged(Q){if($==="jsonl"){G("mcp_instructions_changed",{revision:Q.revision,server_name:Q.serverName,action:Q.action,reason:Q.reason,text:Q.text,source_bytes:Q.sourceBytes,projected_bytes:Q.projectedBytes,sha256:Q.sha256,truncated:Q.truncated,details_omitted:Q.detailsOmitted});return}_(Z.stderr,`[mcp:instructions] ${Q.action} ${Q.serverName}${Q.truncated?" (truncated)":""}`)},mcpTaskChanged(Q){if($==="jsonl"){G("mcp_task_changed",{revision:Q.revision,task_id:Q.taskId,server_name:Q.serverName,tool_name:Q.toolName,status:Q.status,status_message:Q.statusMessage,created_at:Q.createdAt,updated_at:Q.updatedAt,completed_at:Q.completedAt,has_result:Q.hasResult,error:Q.error});return}_(Z.stderr,`[mcp:task] ${Q.taskId} ${Q.serverName}/${Q.toolName} `+Q.status)},projectRulesLoaded(Q){if($==="jsonl"){G("project_rules_loaded",{files:Q.files.map((Y)=>({id:Y.id,relative_path:Y.relativePath,source:Y.source,conditional:Y.conditional,content_sha256:Y.contentSha256})),trigger_paths:Q.triggerPaths,blocked_write:Q.blockedWrite});return}_(Z.stderr,`[project-rules] loaded ${Q.files.length} file(s)${Q.blockedWrite?" before write":""}`)},userShellStarted(Q,Y,U){if($==="jsonl"){G("user_shell_started",{execution_id:Q,command:Y,auxiliary:U});return}_(Z.stderr,`[user-shell:start] ${Y}`)},userShellOutput(Q,Y,U,K){if($==="jsonl"){G("user_shell_output",{execution_id:Q,stream:Y,chunk:U,stream_truncated:K});return}(Y==="stderr"?Z.stderr:Z.stdout).write(U)},userShellCompleted(Q){if($==="jsonl"){G("user_shell_completed",{execution_id:Q.executionId,message_id:Q.messageId,status:Q.record.status,exit_code:Q.record.exitCode,duration_ms:Q.record.durationMs,stdout:Q.record.stdout,stderr:Q.record.stderr,truncated:Q.record.truncated,auxiliary:Q.auxiliary});return}_(Z.stderr,`[user-shell:${Q.record.status}] exit=${Q.record.exitCode??"null"} ${Q.record.durationMs}ms`)},phase(Q,Y,U,K={}){if($==="jsonl"){G("phase",{phase:Q,status:Y,message:U,turn:K.turn,tool_name:K.toolName,target:K.target});return}_(Z.stderr,`[phase:${Q}] ${U}`)},toolDetail(Q,Y){if($==="jsonl"){G("tool_detail",{tool_name:Q,detail:Y});return}_(Z.stderr,Y)},taskUpdate(Q){if($==="jsonl"){G("task_update",{tasks:Q});return}for(let Y of Q)_(Z.stderr,oq(Y))},subagent(Q){let Y=Q.kind==="subagent_spawned";if($==="jsonl"){G("subagent",{state:Y?"spawned":"completed",session_id:Q.sessionId,subagent_type:Q.type,success:Y?void 0:Q.success,summary:Y?void 0:Q.summary,verification_verdict:Y?void 0:Q.verificationVerdict,resumed_from:Q.resumedFrom,root_agent_id:Q.rootAgentId,resume_depth:Q.resumeDepth});return}_(Z.stderr,`[subagent:${Y?"spawned":"completed"}] ${Q.sessionId}${Q.resumedFrom?` resumed from ${Q.resumedFrom}`:""}`)},tokenUsage(Q){if($==="jsonl"){G("token_usage",{input_tokens:Q.inputTokens,output_tokens:Q.outputTokens,total_tokens:Q.totalTokens,max_context_tokens:Q.maxContextTokens,cache_read_tokens:Q.cacheReadTokens,cache_write_tokens:Q.cacheWriteTokens,cost_usd:Q.costUsd});return}_(Z.stderr,`[tokens] in=${Q.inputTokens} out=${Q.outputTokens} total=${Q.totalTokens} / ${Q.maxContextTokens}`)},compacting(Q){if($==="jsonl"){G("compacting",{state:Q?"started":"completed"});return}_(Z.stderr,Q?"[context] compacting started":"[context] compacting completed")},turnLimit(Q){if($==="jsonl"){G("turn_limit",{turns_count:Q,action:"continue"});return}_(Z.stderr,`[turn-limit] continuing after ${Q} turns`)},taskSession(Q){if($==="jsonl"){G("task_session",{session_id:Q.sessionId,project_path:Q.projectPath,source_project_path:Q.sourceProjectPath,isolation:Q.isolation,worktree_branch:Q.worktreeBranch,base_commit:Q.baseCommit});return}_(Z.stderr,`[task:${Q.isolation}] ${Q.sessionId} ${Q.sourceProjectPath} -> ${Q.projectPath}${Q.worktreeBranch?` (${Q.worktreeBranch})`:""}`)},taskAdmission(Q){if($==="jsonl"){G("task_admission",{state:Q.state,queue_position:Q.queuePosition,queue_depth:Q.queueDepth,in_flight:Q.inFlight,max_concurrent_tasks:Q.maxConcurrentTasks});return}_(Z.stderr,Q.state==="queued"?`[task:queued] position ${Q.queuePosition??1}/${Q.queueDepth} (running ${Q.inFlight}/${Q.maxConcurrentTasks})`:`[task:running] admitted (running ${Q.inFlight}/${Q.maxConcurrentTasks})`)},output(Q,Y=0){if($==="jsonl"){G("output",{content:Q,exit_code:Y});return}_(Y===0?Z.stdout:Z.stderr,Q)},error(Q){if($==="jsonl"){G("error",{message:Q});return}_(Z.stderr,Q)}}}async function QQ(Z,$={stdout:process.stdout,stderr:process.stderr},G){let Q="text",Y=c($,Q),U=new Vq,K={targetLocked:!1},A,E,I=lq(G);try{let D=sq(Z);Q=eq(D.outputFormat),Y=c($,Q),await Yq();let Xq=await Zq(D),H=await $q(Xq);if(H.mode==="output"){if(H.content)Y.output(H.content,H.exitCode??0);return H.exitCode??0}let J=H.content.trimStart().startsWith("!")?H.content.trimStart().slice(1).trim():void 0;if(J!==void 0&&D.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(D.taskIsolation&&(D.continue||D.resume||D.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:R,messages:S,metadata:O}=await Gq({sessionId:D.sessionId,continue:D.continue,resume:D.resume,forkSession:D.forkSession,fallbackSessionPrefix:"headless"}),P=D.permissionMode??O?.permissionMode??"yolo",h=D.model&&D.model!=="inherit"?D.model:m()?.id,b=D.taskIsolation?await Qq.createSessionTask({sessionId:R,prompt:H.content,sourceProjectPath:x(),isolation:D.taskIsolation,dispatch:{version:1,prompt:H.content,sourceProjectPath:x(),isolation:D.taskIsolation,permissionMode:P,...h?{modelId:h}:{}}}):void 0,N=b?.metadata.projectPath??O?.projectPath??x();if(!b)await u.setSessionPermissionMode(R,N,P);if(b)Y.taskSession({sessionId:R,projectPath:N,sourceProjectPath:b.metadata.taskSourceProjectPath??x(),isolation:D.taskIsolation,worktreeBranch:b.metadata.taskWorktreeBranch,baseCommit:b.metadata.taskBaseCommit}),E=v.subscribe((V)=>{if(V.type!=="task.status"||V.sessionId!==R||V.projectPath!==N||!["queued","running"].includes(String(V.properties.taskStatus))||typeof V.properties.taskQueueDepth!=="number"||typeof V.properties.taskInFlight!=="number"||typeof V.properties.taskConcurrencyLimit!=="number")return;Y.taskAdmission({state:V.properties.taskStatus,queuePosition:typeof V.properties.taskQueuePosition==="number"?V.properties.taskQueuePosition:void 0,queueDepth:V.properties.taskQueueDepth,inFlight:V.properties.taskInFlight,maxConcurrentTasks:V.properties.taskConcurrencyLimit})});let Dq={messages:[...S],userId:"cli-user",sessionId:R,workspaceRoot:N,permissionMode:P,signal:I.signal,...b?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:nq()};if(A=await i.create({sessionId:R,workspaceRoot:N,modelId:D.model,permissionMode:P,mcpConfig:D.mcpConfig,strictMcpConfig:D.strictMcpConfig,agents:D.agents?o(D.agents):void 0,...b?.taskWorktree?{taskWorktree:b.taskWorktree}:{},...b?.metadata.taskIsolation?{taskIsolation:b.metadata.taskIsolation}:{},...S.length>0?{sessionStart:{isResume:!0,resumeSessionId:R}}:{}}),J!==void 0){let V=await A.executeUserShellCommand(J,{signal:I.signal,onEvent:(X)=>{if(X.type==="started")Y.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")Y.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated)}});return Y.userShellCompleted(V),V.record.status==="completed"?0:V.record.status==="aborted"?130:V.record.exitCode??1}let Bq=D.maxTurns??A.getConfig().maxTurns,Uq=b?.taskWorktree?[...new Set([...D.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:D.disallowedTools,_q=await a.createWithRuntime(A,{sessionId:R,systemPrompt:D.systemPrompt,appendSystemPrompt:D.appendSystemPrompt,maxTurns:D.maxTurns,modelId:D.model,permissionMode:P,toolWhitelist:D.allowedTools,toolBlacklist:Uq,mcpConfig:D.mcpConfig,strictMcpConfig:D.strictMcpConfig}),W=await l(_q.chatStream(H.content,Dq,{stream:!0,signal:I.signal,maxTurns:D.maxTurns,...Bq===-1?{onTurnLimitReached:async(V)=>{return Y.turnLimit(V.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(V)=>{switch(V.kind){case"content_delta":U.markAssistantContent(),Y.contentDelta(V.delta);break;case"thinking_delta":U.setThinkingOpened(Y.thinkingDelta(V.delta,U.hasOpenThinking()));break;case"stream_end":{let X=U.completeStream();Y.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=V.toolCall;if(!("function"in X))break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let z=JSON.parse(X.function.arguments),M=r(X.function.name,z),f=y(X.function.name,z),L=qQ(X.function.name,M,f,K);if(L.shouldLockTarget)K.targetLocked=!0;Y.phase(L.phase,L.status,L.message,{toolName:X.function.name,target:f}),Y.toolStart(X.function.name,M,f,V.toolKind)}catch{Y.phase(K.targetLocked?"executing":"searching",K.targetLocked?"hit":"ongoing",K.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),Y.toolStart(X.function.name,X.function.name,void 0,V.toolKind)}break}case"tool_progress":{let X=V.toolCall;if(!("function"in X))break;Y.toolProgress(X.function.name,V.update.message,V.update.progress,V.update.total);break}case"tool_result":{let X=V.toolCall;if(!("function"in X))break;let z;try{let f=JSON.parse(X.function.arguments);z=y(X.function.name,f)}catch{z=void 0}let M=s(X.function.name,V.result);if(Y.toolResult(X.function.name,M.summary,z,void 0,{success:V.result.success,errorType:V.result.error?.type,errorMessage:V.result.error?.message}),M.detail)Y.toolDetail(X.function.name,M.detail);break}case"token_usage":Y.tokenUsage(V.usage);break;case"compaction":Y.compacting(V.phase==="start");break;case"task_update":Y.taskUpdate(V.tasks);break;case"mcp_catalog_changed":Y.mcpCatalogChanged(V);break;case"mcp_content_changed":Y.mcpContentChanged(V);break;case"mcp_resource_updated":Y.mcpResourceUpdated(V);break;case"mcp_connection_changed":Y.mcpConnectionChanged(V);break;case"mcp_log":Y.mcpLog(V);break;case"mcp_instructions_changed":Y.mcpInstructionsChanged(V);break;case"mcp_task_changed":Y.mcpTaskChanged(V);break;case"project_rules_loaded":Y.projectRulesLoaded(V);break;case"steering_applied":case"follow_up_started":case"goal_updated":case"goal_continuation_started":break;case"subagent_spawned":case"subagent_completed":Y.subagent(V);break;case"model_fallback":break;case"turn_start":if(V.turn===1)K.targetLocked=!1;Y.phase("turn",K.targetLocked?"hit":"ongoing",`Turn ${V.turn} started`,{turn:V.turn});break;default:{let X=V}}});if(W.metadata?.outputTruncated)Y.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!W.success)return Y.error(`Error: ${W.error?.message??"Agent execution failed"}`),1;return Y.phase("completed","done","Headless run completed"),0}catch(D){if(U.hasOpenThinking()&&Q==="text")$.stderr.write(`
|
|
6
|
+
`);return Y.error(`Error: ${tq(D)}`),1}finally{E?.();try{await A?.dispose()}finally{I.dispose()}}}async function JQ(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:G,"output-format":Q,"system-prompt":Y,"append-system-prompt":U,"max-turns":K,...A}=n,E=mq(uq(process.argv)).scriptName("blade").strict(!1).options(A).middleware([e,t,qq]);return aq(E),await E.parse(),!0}export{QQ as runHeadless,JQ as handleHeadlessMode,iq as HeadlessOptionsSchema};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ob as I}from"./chunk-6tx8k249.js";import{fc as A}from"./chunk-
|
|
1
|
+
import{Ob as I}from"./chunk-6tx8k249.js";import{fc as A}from"./chunk-sanhjqpd.js";import{nd as h}from"./chunk-qda309d9.js";import{$d as k,Rd as f,Vd as T,Wd as w,Xd as M,Yd as P,ae as E}from"./chunk-rh7v814a.js";import{be as c,ce as S,ee as n,he as m,ie as y}from"./chunk-tq52pbde.js";import{pe as O}from"./chunk-epj56s0n.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),r=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),p=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:m(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(r),timeout:n.Optional(r),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(r),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(r),theme:n.Optional(n.String()),uiTheme:n.Optional(m(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(r),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(m(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(m(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(p),ask:n.Optional(p),deny:n.Optional(p)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let l=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${l}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let a=S(B,t);if(!a.success){let s=a.error.issues.map((l)=>`${l.path.join(".")||"settings"}: ${l.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return a.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),a;try{a=await R.readFile(t,"utf8")}catch(s){let l=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${l}`)}return d(a,t)}function b(o,i){if(!i)return;let t=i;for(let[a,s]of _){if(a==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[a]!==void 0)o[s]=t[a]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let a=await k.getInstance().initialize(i),s=E(a,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Za as yJ}from"./chunk-jza1rsan.js";import{$a as d2,_a as y$,qb as C0}from"./chunk-1g5qc1qx.js";import{wc as DJ}from"./chunk-fvhc1yj8.js";import{Bc as p2,xc as qJ,yc as H$,zc as QJ}from"./chunk-dqvcgwhe.js";import{id as U$}from"./chunk-vwq9s5nj.js";import{nd as $$}from"./chunk-qda309d9.js";import{ie as wJ}from"./chunk-tq52pbde.js";import{re as i}from"./chunk-epj56s0n.js";import{Me as R2,Oe as _2}from"./chunk-0n97186m.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function d$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class g${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(d$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!d$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!d$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!d$(J))}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function w2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function D2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function q2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import c$ from"node:path";var AJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),xJ=/^(LD_.+|DYLD_.+|PATH)$/,y2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function x$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],X=Z[2],z=W.match(y2);if(!z)break;let K=z[1];if(!AJ.has(K))break;J=X}return J}function f1($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],X=Z[2],z=W.match(y2);if(!z)break;let K=z[1];if(xJ.test(K))break;J=X}return J}var kJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function A0($){let J=$,Z=!0;while(Z){Z=!1;for(let W of kJ){let X=J.match(W);if(X){J=J.slice(X[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function m$($){let J=[],Z="",W=!1,X=!1,z=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(z){Z+=Y,z=!1;continue}if(Y==="\\"&&!W){Z+=Y,z=!0;continue}if(Y==="'"&&!X){W=!W,Z+=Y;continue}if(Y==='"'&&!W){X=!X,Z+=Y;continue}if(W||X){Z+=Y;continue}if(Y==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Y===">"||Y==="<")return null;if(Y==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Y==="&")return null;if(Y===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Y}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function P2($){let J=!1,Z=!1,W=!1;for(let X=0;X<$.length;X++){let z=$[X];if(W){W=!1;continue}if(z==="\\"&&!J){W=!0;continue}if(z==="'"&&!Z){J=!J;continue}if(z==='"'&&!J){Z=!Z;continue}if(J)continue;if(z==="$"){let K=$[X+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(z==="`")return!0;if(Z)continue;if(z==="|")return!0;if(z===">"||z==="<")return!0;if(z==="{"){let K=$.slice(X);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function u$($){let J=[],Z="",W=!1,X=!1,z=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(z){Z+=Y,z=!1;continue}if(Y==="\\"&&!W){if(z=!0,X){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=Y,z=!1}continue}if(Y==="'"&&!X){W=!W;continue}if(Y==='"'&&!W){X=!X;continue}if(!W&&!X&&/[ \t]/.test(Y)){if(Z)J.push(Z),Z="";continue}Z+=Y}if(Z)J.push(Z);return J}var MJ=new Set(["npm","pnpm","yarn","bun"]),U2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),TJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function RJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function hJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function P$($){let J=x$(hJ($)),Z=m$(J);if(!Z||Z.length!==1||P2(J)||/[\r\n]/.test(J))return!1;let W=u$(J);if(W.length===0||W.some((Y)=>[...TJ].some((Q)=>Y===Q||Y.startsWith(`${Q}=`))))return!1;let[X,z,K]=W;if(MJ.has(X??""))return RJ(z==="run"?K:z)||z==="--test";if((X==="npx"||X==="bunx")&&U2.has(z??""))return!0;if(U2.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function M1($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!c$.isAbsolute($);let Z=c$.isAbsolute($)?c$.resolve($):c$.resolve(J,$);return y$.isWithinWorkspace(Z,J)}var x0=$$("Agent"),CJ=3;function k0($,J,Z){if($!=="length")return{action:"none"};if(J>=CJ)return{action:"truncated"};if(w2(Z)==="stop")return x0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var pJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],dJ=/```[\s\S]{50,}```/,b2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",gJ=2;function M0($,J,Z=!0){if(!$||J>=gJ)return{action:"none"};if(!Z&&dJ.test($))return{action:"retry",prompt:b2};let W=$.slice(-200),X=W.match(/```/g);if(X&&X.length%2!==0)return{action:"none"};if(pJ.some((K)=>K.test(W)))return{action:"retry",prompt:b2};return{action:"none"}}var mJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],O2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},uJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},cJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",iJ="Required verification did not run successfully before the retry limit.",rJ=3;function L2($,J,Z){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&P$(Z.metadata.command)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let W=Z.metadata?.verificationCommands;if(!Array.isArray(W))return;for(let X of W)if(typeof X==="string"&&P$(X))$.add(X)}function T0($,J,Z){if(!$||!mJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(O2).filter((Q)=>O2[Q].test($)),X=[...J],z=W.filter((Q)=>!X.some((D)=>uJ[Q].test(D)));if(W.length>0?z.length===0:X.some(P$))return{action:"none"};if(Z>=rJ)return{action:"fail",message:iJ};let Y=W.length>1&&z.length>0?` Missing successful verification categories: ${z.join(", ")}.`:"";return{action:"retry",prompt:`${cJ}${Y}`}}var lJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],F2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function v2($){return typeof $==="string"&&F2.some((J)=>J.test($))}var nJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],oJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function sJ($){if(typeof $!=="string")return;if(oJ.some((J)=>J.test($)))return"multiple-allowed";return nJ.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=sJ(J);if(Z!==void 0)return Z==="required"}return!1}var aJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",tJ="Required delegation did not complete before the retry limit.",eJ=3;function I2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),X=r$(W),z=!1;if(!X)for(let K of W){if(F2.some((Y)=>Y.test(K)))break;if(lJ.some((Y)=>Y.test(K))){z=!0;break}}if(W.length===0||!X&&!z||J.has("Task"))return{action:"none"};if(Z>=eJ)return{action:"fail",message:tJ};return{action:"retry",prompt:aJ}}var $Z=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],JZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],ZZ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function E2($){return ZZ.reduce((J,Z)=>J.replace(Z," "),$)}function l$($){if(typeof $!=="string")return!1;let J=E2($);return $Z.some((Z)=>Z.test(J))}var WZ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",XZ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",zZ="Required worktree lifecycle did not complete before the retry limit.",KZ=3;function N2($,J,Z){if(!$)return{action:"none"};let W=E2($);if(!l$(W))return{action:"none"};let X=JZ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let z=!J.has("EnterWorktree")?"EnterWorktree":X&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if(Z>=KZ)return{action:"fail",message:zZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?WZ:XZ}}var G2=30000;async function R0($){try{let Z=U$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??i(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,X=new Promise((z)=>{W=setTimeout(()=>z("timeout"),G2)});try{let z=await Promise.race([Z,X]);if(z==="timeout")return x0.warn(`[Loop] Stop hook 超时 (${G2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=z;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return x0.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function YZ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var QZ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function VZ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function BZ($){let J=$;for(let Q of QZ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),X=W&&W[1].length>=6?W[1]:Z;if(X=X.trim().replace(/[\s.。!!??,,;;::-]+$/,""),X.length<=60)return X;let z=X.slice(0,60),K=z.lastIndexOf(" ");return`${(K>36?z.slice(0,K):z).trimEnd()}…`}function S2($){return BZ(VZ($))}import{EventEmitter as HZ}from"events";import f2 from"node:path";function h0($){if(_2($.sessionId),!f2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:f2.resolve($.projectPath)}}function r1($){let J=h0($);return JSON.stringify([J.projectPath,J.sessionId])}class b$ extends HZ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!b$.instance)b$.instance=new b$;return b$.instance}publish($,J,Z,W){let X=h0($);this.emit("event",{sessionId:X.sessionId,projectPath:X.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var A2=b$.getInstance();var X$=$$("Agent"),n$=new Set;async function jZ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(n$.has(Z))return;if(n$.size>=5000)n$.clear();n$.add(Z);try{let W=$.workspaceRoot,X=await C0.findSessionMetadata(Z,W);if(!X)return;if(X.title&&X.title.trim())return;let z=S2(J);if(!z)return;await C0.updateSessionMetadata(Z,X.projectPath,{title:z}),A2.publish({sessionId:Z,projectPath:X.projectPath},"session.updated",{title:z})}catch(W){X$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var p0=`<turn_aborted>
|
|
1
|
+
import{Za as yJ}from"./chunk-jza1rsan.js";import{_a as y$,cb as d2,qb as C0}from"./chunk-417wefq7.js";import{wc as DJ}from"./chunk-fvhc1yj8.js";import{Bc as p2,xc as qJ,yc as H$,zc as QJ}from"./chunk-dqvcgwhe.js";import{id as U$}from"./chunk-vpj0sv73.js";import{nd as $$}from"./chunk-qda309d9.js";import{ie as wJ}from"./chunk-tq52pbde.js";import{re as i}from"./chunk-epj56s0n.js";import{Me as R2,Oe as _2}from"./chunk-0n97186m.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function d$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class g${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(d$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!d$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!d$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!d$(J))}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function w2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function D2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function q2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import c$ from"node:path";var AJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),xJ=/^(LD_.+|DYLD_.+|PATH)$/,y2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function x$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],X=Z[2],z=W.match(y2);if(!z)break;let K=z[1];if(!AJ.has(K))break;J=X}return J}function f1($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],X=Z[2],z=W.match(y2);if(!z)break;let K=z[1];if(xJ.test(K))break;J=X}return J}var kJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function A0($){let J=$,Z=!0;while(Z){Z=!1;for(let W of kJ){let X=J.match(W);if(X){J=J.slice(X[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function m$($){let J=[],Z="",W=!1,X=!1,z=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(z){Z+=Y,z=!1;continue}if(Y==="\\"&&!W){Z+=Y,z=!0;continue}if(Y==="'"&&!X){W=!W,Z+=Y;continue}if(Y==='"'&&!W){X=!X,Z+=Y;continue}if(W||X){Z+=Y;continue}if(Y==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Y===">"||Y==="<")return null;if(Y==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Y==="&")return null;if(Y===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Y}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function P2($){let J=!1,Z=!1,W=!1;for(let X=0;X<$.length;X++){let z=$[X];if(W){W=!1;continue}if(z==="\\"&&!J){W=!0;continue}if(z==="'"&&!Z){J=!J;continue}if(z==='"'&&!J){Z=!Z;continue}if(J)continue;if(z==="$"){let K=$[X+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(z==="`")return!0;if(Z)continue;if(z==="|")return!0;if(z===">"||z==="<")return!0;if(z==="{"){let K=$.slice(X);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function u$($){let J=[],Z="",W=!1,X=!1,z=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(z){Z+=Y,z=!1;continue}if(Y==="\\"&&!W){if(z=!0,X){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=Y,z=!1}continue}if(Y==="'"&&!X){W=!W;continue}if(Y==='"'&&!W){X=!X;continue}if(!W&&!X&&/[ \t]/.test(Y)){if(Z)J.push(Z),Z="";continue}Z+=Y}if(Z)J.push(Z);return J}var MJ=new Set(["npm","pnpm","yarn","bun"]),U2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),TJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function RJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function hJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function P$($){let J=x$(hJ($)),Z=m$(J);if(!Z||Z.length!==1||P2(J)||/[\r\n]/.test(J))return!1;let W=u$(J);if(W.length===0||W.some((Y)=>[...TJ].some((Q)=>Y===Q||Y.startsWith(`${Q}=`))))return!1;let[X,z,K]=W;if(MJ.has(X??""))return RJ(z==="run"?K:z)||z==="--test";if((X==="npx"||X==="bunx")&&U2.has(z??""))return!0;if(U2.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function M1($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!c$.isAbsolute($);let Z=c$.isAbsolute($)?c$.resolve($):c$.resolve(J,$);return y$.isWithinWorkspace(Z,J)}var x0=$$("Agent"),CJ=3;function k0($,J,Z){if($!=="length")return{action:"none"};if(J>=CJ)return{action:"truncated"};if(w2(Z)==="stop")return x0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var pJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],dJ=/```[\s\S]{50,}```/,b2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",gJ=2;function M0($,J,Z=!0){if(!$||J>=gJ)return{action:"none"};if(!Z&&dJ.test($))return{action:"retry",prompt:b2};let W=$.slice(-200),X=W.match(/```/g);if(X&&X.length%2!==0)return{action:"none"};if(pJ.some((K)=>K.test(W)))return{action:"retry",prompt:b2};return{action:"none"}}var mJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],O2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},uJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},cJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",iJ="Required verification did not run successfully before the retry limit.",rJ=3;function L2($,J,Z){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&P$(Z.metadata.command)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let W=Z.metadata?.verificationCommands;if(!Array.isArray(W))return;for(let X of W)if(typeof X==="string"&&P$(X))$.add(X)}function T0($,J,Z){if(!$||!mJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(O2).filter((Q)=>O2[Q].test($)),X=[...J],z=W.filter((Q)=>!X.some((D)=>uJ[Q].test(D)));if(W.length>0?z.length===0:X.some(P$))return{action:"none"};if(Z>=rJ)return{action:"fail",message:iJ};let Y=W.length>1&&z.length>0?` Missing successful verification categories: ${z.join(", ")}.`:"";return{action:"retry",prompt:`${cJ}${Y}`}}var lJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],F2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function v2($){return typeof $==="string"&&F2.some((J)=>J.test($))}var nJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],oJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function sJ($){if(typeof $!=="string")return;if(oJ.some((J)=>J.test($)))return"multiple-allowed";return nJ.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=sJ(J);if(Z!==void 0)return Z==="required"}return!1}var aJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",tJ="Required delegation did not complete before the retry limit.",eJ=3;function I2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),X=r$(W),z=!1;if(!X)for(let K of W){if(F2.some((Y)=>Y.test(K)))break;if(lJ.some((Y)=>Y.test(K))){z=!0;break}}if(W.length===0||!X&&!z||J.has("Task"))return{action:"none"};if(Z>=eJ)return{action:"fail",message:tJ};return{action:"retry",prompt:aJ}}var $Z=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],JZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],ZZ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function E2($){return ZZ.reduce((J,Z)=>J.replace(Z," "),$)}function l$($){if(typeof $!=="string")return!1;let J=E2($);return $Z.some((Z)=>Z.test(J))}var WZ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",XZ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",zZ="Required worktree lifecycle did not complete before the retry limit.",KZ=3;function N2($,J,Z){if(!$)return{action:"none"};let W=E2($);if(!l$(W))return{action:"none"};let X=JZ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let z=!J.has("EnterWorktree")?"EnterWorktree":X&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if(Z>=KZ)return{action:"fail",message:zZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?WZ:XZ}}var G2=30000;async function R0($){try{let Z=U$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??i(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,X=new Promise((z)=>{W=setTimeout(()=>z("timeout"),G2)});try{let z=await Promise.race([Z,X]);if(z==="timeout")return x0.warn(`[Loop] Stop hook 超时 (${G2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=z;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return x0.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function YZ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var QZ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function VZ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function BZ($){let J=$;for(let Q of QZ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),X=W&&W[1].length>=6?W[1]:Z;if(X=X.trim().replace(/[\s.。!!??,,;;::-]+$/,""),X.length<=60)return X;let z=X.slice(0,60),K=z.lastIndexOf(" ");return`${(K>36?z.slice(0,K):z).trimEnd()}…`}function S2($){return BZ(VZ($))}import{EventEmitter as HZ}from"events";import f2 from"node:path";function h0($){if(_2($.sessionId),!f2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:f2.resolve($.projectPath)}}function r1($){let J=h0($);return JSON.stringify([J.projectPath,J.sessionId])}class b$ extends HZ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!b$.instance)b$.instance=new b$;return b$.instance}publish($,J,Z,W){let X=h0($);this.emit("event",{sessionId:X.sessionId,projectPath:X.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var A2=b$.getInstance();var X$=$$("Agent"),n$=new Set;async function jZ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(n$.has(Z))return;if(n$.size>=5000)n$.clear();n$.add(Z);try{let W=$.workspaceRoot,X=await C0.findSessionMetadata(Z,W);if(!X)return;if(X.title&&X.title.trim())return;let z=S2(J);if(!z)return;await C0.updateSessionMetadata(Z,X.projectPath,{title:z}),A2.publish({sessionId:Z,projectPath:X.projectPath},"session.updated",{title:z})}catch(W){X$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var p0=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`;function V$($){return $.executionEngine?.getContextManager()}async function s($,J,Z,W=null,X){try{let z=V$($),K=typeof Z==="string"?Z.trim()!=="":Z.some((Y)=>Y.type==="text"?Y.text.trim()!=="":!0);if(z&&J.sessionId&&K){let Y=await z.saveMessage(J.sessionId,"user",Z,W,X,J.subagentInfo);return jZ(J,Z),Y}}catch(z){X$.warn("[Loop] 保存用户消息失败:",z)}return null}async function h($,J,Z,W,X){try{let z=V$($);if(z&&J.sessionId&&(Z.trim()||X?.trim()))return await z.saveMessage(J.sessionId,"assistant",Z,W,void 0,J.subagentInfo,X)}catch(z){X$.warn("[Loop] 保存助手消息失败:",z)}return null}async function x2($,J,Z){try{let W=V$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",p0,Z,void 0,J.subagentInfo)}catch(W){X$.warn("[Loop] 保存中断边界失败:",W)}return null}async function k2($,J,Z,W,X){try{let z=V$($);if(!z||!J.sessionId||Z.length===0)return null;return await z.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,X,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(z){X$.warn("[Loop] 保存 contextual project rules provenance 失败:",z)}return null}async function d0($,J,Z,W,X){try{let z=V$($);if(z&&J.sessionId)return await z.saveToolUse(J.sessionId,Z,W,X,J.subagentInfo)}catch(z){X$.warn("[Loop] 保存工具调用失败:",z)}return null}async function o$($,J,Z,W,X,z,K,Y,Q){try{let D=V$($);if(D&&J.sessionId)return await D.saveToolResult(J.sessionId,Z,W,X,z,K,J.subagentInfo,Y,Q)}catch(D){X$.warn("[Loop] 保存工具结果失败:",D)}return null}async function s$($,J,Z,W){try{let X=V$($);if(X&&J.sessionId)return await X.saveCompaction(J.sessionId,Z,W,null)}catch(X){X$.warn("[Loop] 保存压缩数据失败:",X)}return null}import{promises as LZ}from"node:fs";import FZ from"node:path";import{nanoid as z$}from"nanoid";import*as R from"node:fs/promises";import*as B$ from"node:path";var M2={enabled:!0,maxIndexLines:200};var wZ="memory",T2="MEMORY.md";class g0{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=R2($);this.memoryDir=B$.join(W,wZ)}this.config={...M2,...J}}async initialize(){if(this.initialized)return;await R.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,T2);try{let J=await R.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),X=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Lb as a,Mb as b,Nb as c}from"./chunk-19kg7yvw.js";import"./chunk-6tx8k249.js";import"./chunk-sanhjqpd.js";import"./chunk-g6h6h8xr.js";import"./chunk-fvhc1yj8.js";import"./chunk-63ysxybd.js";import"./chunk-qda309d9.js";import"./chunk-rh7v814a.js";import"./chunk-tq52pbde.js";import"./chunk-79s052sw.js";import"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import"./chunk-1vx4sf1y.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{De as a,Ee as b,Fe as c,Ge as d,He as e,Ie as f}from"./chunk-
|
|
1
|
+
import{De as a,Ee as b,Fe as c,Ge as d,He as e,Ie as f}from"./chunk-1vx4sf1y.js";import"./chunk-9ffr01c3.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e={name:"blade-code",version:"0.10.
|
|
1
|
+
var e={name:"blade-code",version:"0.10.5",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};function i(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function a(){return`v${e.version}`}function d(){return`v${e.version} © 2025 Blade Code`}
|
|
2
2
|
export{i as De,n as Ee,o as Fe,c as Ge,a as He,d as Ie};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Hc as a,Ic as b,Jc as c}from"./chunk-
|
|
1
|
+
import{Hc as a,Ic as b,Jc as c}from"./chunk-yc53wz4r.js";import"./chunk-rh7v814a.js";import"./chunk-tq52pbde.js";import"./chunk-79s052sw.js";import"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import"./chunk-1vx4sf1y.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as y,b as A,c as C,d as D}from"./chunk-
|
|
1
|
+
import{a as y,b as A,c as C,d as D}from"./chunk-r6mwyg3h.js";import"./chunk-ygx03mdh.js";import"./chunk-15d49qty.js";import"./chunk-xv0maezy.js";import"./chunk-62881c2s.js";import"./chunk-s645azsm.js";import"./chunk-1m5r6mp2.js";import"./chunk-jza1rsan.js";import"./chunk-417wefq7.js";import"./chunk-an96c54z.js";import"./chunk-drrdzmaa.js";import{kc as q}from"./chunk-sanhjqpd.js";import"./chunk-g6h6h8xr.js";import"./chunk-fvhc1yj8.js";import"./chunk-dqvcgwhe.js";import"./chunk-ea7wsges.js";import"./chunk-gxmrakrk.js";import"./chunk-yc53wz4r.js";import"./chunk-am8dtvff.js";import"./chunk-35yktzm1.js";import"./chunk-63ysxybd.js";import"./chunk-vpj0sv73.js";import"./chunk-qm11hjd3.js";import"./chunk-qda309d9.js";import"./chunk-rh7v814a.js";import"./chunk-tq52pbde.js";import"./chunk-79s052sw.js";import"./chunk-epj56s0n.js";import"./chunk-gxzbv67r.js";import"./chunk-bexgcc2d.js";import"./chunk-1vx4sf1y.js";import"./chunk-z906d5tb.js";import"./chunk-948qe2pp.js";import"./chunk-0n97186m.js";import"./chunk-9ffr01c3.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import{Ab as i0,Cb as z0,Fb as d0,Gb as v$,rb as j$,sb as v,tb as l0,ub as S$,vb as c0,wb as p0,xb as n0,yb as o,zb as m$}from"./chunk-an96c54z.js";import{Fc as H0}from"./chunk-gxmrakrk.js";import{ad as L0}from"./chunk-35yktzm1.js";import{jd as N$}from"./chunk-qm11hjd3.js";import{nd as Y0}from"./chunk-qda309d9.js";import{le as f$,me as y$}from"./chunk-79s052sw.js";import{re as Q$}from"./chunk-epj56s0n.js";import{Ae as Q0,xe as Z0}from"./chunk-bexgcc2d.js";import{Ee as l}from"./chunk-1vx4sf1y.js";import{Le as g$,Me as V0,Oe as z,Pe as S,Re as h0,Se as h,Te as G0}from"./chunk-0n97186m.js";import{readdir as C$,readFile as s,rm as _0,stat as D1}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as p$,randomUUID as n$}from"node:crypto";import*as m from"node:fs/promises";import*as X0 from"node:path";var H$=1;function i$($,q){let T=p$("sha256").update(q).digest("hex");return X0.join(V0($),".locks",`${T}.lock`)}function O0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function A0($){try{let q=JSON.parse(await m.readFile($,"utf8"));if(q.version!==H$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function J$($){let q=await A0($);if(q)return q;return await new Promise((T)=>setTimeout(T,10)),A0($)}function d$($){try{return process.kill($,0),!0}catch(q){return O0(q,"EPERM")}}async function Z$($,q){let T;try{return T=await m.open($,"wx",384),await T.writeFile(`${JSON.stringify(q)}
|
|
2
|
+
`,"utf8"),!0}catch(G){if(O0(G,"EEXIST"))return!1;if(T)await m.unlink($).catch(()=>{return});throw G}finally{await T?.close().catch(()=>{return})}}class p 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 n{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=Q$()){let T=i$(q,$),G={version:H$,sessionId:$,ownerId:n$(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await m.mkdir(X0.dirname(T),{recursive:!0,mode:448}),await Z$(T,G))return new n(T,G);let Z=await J$(T);if(Z&&d$(Z.pid))throw new p(Z.pid);if(await m.unlink(T).catch((J)=>{if(!O0(J,"ENOENT"))throw J}),await Z$(T,G))return new n(T,G);throw new p((await J$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await A0(this.filePath))?.ownerId!==this.record.ownerId)return;await m.unlink(this.filePath).catch((q)=>{if(!O0(q,"ENOENT"))throw q})}}var E0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function r$($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function o$($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function a$($){return{code:$,...E0[$]}}function L$($){return a$(o$(r$($)))}function w0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in E0))return!1;let T=E0[q.code];return q.message===T.message&&q.retryable===T.retryable}import{promises as $0,realpathSync as s$}from"node:fs";import K0 from"node:path";import*as d from"fs/promises";import*as x from"path";var B$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class i extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class b0{static normalize($,q){let T=x.isAbsolute($)?$:x.resolve(q,$),G=x.normalize(T),Z=x.normalize(q);if(!this.isWithinWorkspace(G,Z))throw new i(`Path outside workspace: ${$} (resolved to ${G}, workspace: ${Z})`,"PATH_OUTSIDE_WORKSPACE");return G}static checkRestricted($){let q=$.split(x.sep);for(let T of B$)if(q.includes(T))throw new i(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new i(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let T=this.normalize($,q);this.checkRestricted(T);try{await d.access(T)}catch(G){throw new i(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,q){try{let T=await d.realpath($),G=await d.realpath(q);if(!this.isWithinWorkspace(T,G))throw new i(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof i)throw T;return $}}static getRelativePath($,q){return x.relative(q,$)}static isWithinWorkspace($,q){let T=x.resolve($),G=x.resolve(q),Z=x.relative(G,T);return Z===""||Z!==".."&&!Z.startsWith(`..${x.sep}`)&&!x.isAbsolute(Z)}static async isWithinWorkspaceResolved($,q){let T=x.resolve(q),G=x.isAbsolute($)?x.resolve($):x.resolve(T,$);if(!this.isWithinWorkspace(G,T))return!1;let Z;try{Z=await d.realpath(T)}catch{return!1}let J=G;while(!0){try{let Q=await d.realpath(J);return this.isWithinWorkspace(Q,Z)}catch(Q){let L=Q.code;if(L!=="ENOENT"&&L!=="ENOTDIR")return!1}let H=x.dirname(J);if(H===J)return!1;J=H}}static isRestricted($){let q=$.split(x.sep);return B$.some((T)=>q.includes(T))}}var q0=Y0("Tool");class u{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!u.instance)u.instance=new u;return u.instance}async recordFileRead($,q){try{let T=await $0.stat($),G={filePath:K0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(G),await this.recordAliases($,G.filePath),q0.debug(`记录文件读取: ${$}`)}catch(T){q0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,q,T="edit"){try{let G=await $0.stat($),Z={filePath:K0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:T};this.setRecord(Z),await this.recordAliases($,Z.filePath),q0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(G){q0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${$}`,G)}}hasFileBeenRead($,q){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return!1;return q?T.has(q):T.size>0}async checkFileModification($,q){let T=this.getFileRecord($,q);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let G=await $0.stat($);if(Math.abs(G.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${G.mtime.toISOString()})`};return{modified:!1}}catch(G){let Z=G;if(Z.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${Z.message}`}}}async checkExternalModification($,q){let T=this.getFileRecord($,q);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let G=await $0.stat($);if(G.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${G.mtime.toISOString()})`};return{isExternal:!1}}catch(G){let Z=G;if(Z.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return q0.warn(`检查文件外部修改失败: ${$}`,G),{isExternal:!1,message:`无法检查文件状态: ${Z.message}`}}}getFileRecord($,q){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(q)return T.get(q);return[...T.values()].sort((G,Z)=>Z.accessTime-G.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let T=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(T),this.removeAliases(T);return}let G=this.accessedFiles.get(T);if(G?.delete(q),G?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[T,G]of this.accessedFiles.entries()){if(q&&!b0.isWithinWorkspace(T,q))continue;if(G.delete($),G.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){u.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(K0.resolve($),q);let T=await $0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,q)}resolveTrackedPath($){let q=K0.resolve($);if(this.accessedFiles.has(q))return q;let T=this.pathAliases.get(q);if(T)return T;try{let G=s$.native(q);return this.pathAliases.get(G)??G}catch{return q}}removeAliases($){for(let[q,T]of this.pathAliases)if(T===$)this.pathAliases.delete(q)}}import*as T0 from"node:crypto";import{promises as K}from"node:fs";import*as F from"node:path";import k0 from"write-file-atomic";var O$="missing";class U0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(z($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!F.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?F.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=G0();this.snapshotDir=F.join(q,"file-history",this.sessionId),this.manifestPath=F.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await K.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=G0(),q=await K.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=T0.createHash("sha256").update(q).digest("hex").slice(0,24),G=F.join($,"file-history",this.sessionId),Z=F.join($,"file-history","workspaces",T,this.sessionId),J=F.join(Z,"manifest.json");try{await K.access(J)}catch{await this.migrateLegacySnapshotDir(G,Z,q)}this.snapshotDir=Z,this.manifestPath=J}async migrateLegacySnapshotDir($,q,T){let G;try{G=JSON.parse(await K.readFile(F.join($,"manifest.json"),"utf8"))}catch{return}if(G.schemaVersion!==1||!Array.isArray(G.snapshots)||!G.snapshots.every((Z)=>this.isWithinWorkspace(Z.filePath,T)))return;await K.mkdir(F.dirname(q),{recursive:!0,mode:493});try{await K.rename($,q)}catch(Z){let J=Z.code;if(J!=="ENOENT"&&J!=="EEXIST"&&J!=="ENOTEMPTY")throw Z}}isWithinWorkspace($,q){if(!F.isAbsolute($))return!1;let T=F.relative(q,F.resolve($));return T===""||T!==".."&&!T.startsWith(`..${F.sep}`)&&!F.isAbsolute(T)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity($),G=!0;try{await K.access(T)}catch{G=!1}let Z=this.trackedFileBackups.get(T),J=Z?Z.version+1:1,H=this.generateFileHash(T,J),Q=this.getSnapshotPath(H,J),L=new Date;if(G){let B=await K.readFile(T);await K.writeFile(Q,B)}let O={backupFileName:H,version:J,backupTime:L};return this.trackedFileBackups.set(T,O),this.snapshots.push({messageId:q,backupFileName:H,timestamp:L,filePath:T,version:J,existedBefore:G}),await this.cleanupOldSnapshots(T),await this.persistManifest(),O}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let T=await this.resolveFileIdentity($),G=this.snapshots.find((Z)=>Z.filePath===T&&Z.backupFileName===q.backupFileName&&Z.version===q.version);if(!G)throw Error(`未找到待完成的快照: ${T}`);G.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let T=await this.resolveFileIdentity($),G=this.snapshots.find((Z)=>Z.filePath===T&&Z.backupFileName===q.backupFileName&&Z.version===q.version);if(!G)return;this.removeSnapshot(G),await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),T=this.snapshots.slice().reverse().find((J)=>J.filePath===q&&J.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let Z=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let J=await K.readFile(Z);await K.mkdir(F.dirname(q),{recursive:!0}),await K.writeFile(q,J)}else await K.rm(q,{force:!0});return this.removeSnapshot(T),await K.rm(Z,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,q){let T=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((J)=>J.messageId===q&&J.filePath===T);if(!G)throw Error(`未找到快照: messageId=${q}, filePath=${T}`);let Z=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let J=await K.readFile(Z);await K.mkdir(F.dirname(T),{recursive:!0}),await K.writeFile(T,J)}else await K.rm(T,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((T)=>T.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((T)=>T.filePath),snapshotCount:q.reduce((T,G)=>T+G.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let Z of q){let J,H=!0;try{J=await K.readFile(Z.filePath)}catch(L){if(L.code!=="ENOENT")throw L;H=!1}if((J?T0.createHash("sha256").update(J).digest("hex"):O$)!==Z.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${Z.filePath}`);if(T.set(Z.filePath,{existed:H,content:J}),Z.target.existedBefore)await K.access(this.getSnapshotPath(Z.target.backupFileName,Z.target.version))}let G=[...this.snapshots];try{for(let J of q)if(J.target.existedBefore){let H=await K.readFile(this.getSnapshotPath(J.target.backupFileName,J.target.version));await K.mkdir(F.dirname(J.filePath),{recursive:!0}),await k0(J.filePath,H)}else await K.rm(J.filePath,{force:!0});let Z=new Set(q.flatMap((J)=>J.selected));this.snapshots=this.snapshots.filter((J)=>!Z.has(J)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...Z].map((J)=>K.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return})))}catch(Z){this.snapshots=G,this.rebuildTrackedFileBackups();let J=[];for(let[H,Q]of T)try{if(Q.existed&&Q.content)await k0(H,Q.content);else await K.rm(H,{force:!0})}catch(L){J.push(L)}if(J.length>0)throw AggregateError([Z,...J],"快照回退失败且无法完整恢复回退前状态");throw Z}return{files:q.map((Z)=>Z.filePath),snapshotCount:q.reduce((Z,J)=>Z+J.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),T=new Set(q.flatMap((Z)=>Z.selected));if(T.size===0)return{files:[],snapshotCount:0};let G=[...this.snapshots];this.snapshots=this.snapshots.filter((Z)=>!T.has(Z)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(Z){throw this.snapshots=G,this.rebuildTrackedFileBackups(),Z}return await Promise.all([...T].map((Z)=>K.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return}))),{files:q.map((Z)=>Z.filePath),snapshotCount:T.size}}buildRewindPlan($){let q=new Set($),T=this.snapshots.filter((J)=>J.postEditHash!==void 0),G=T.filter((J)=>q.has(J.messageId));return[...new Set(G.map((J)=>J.filePath))].sort().map((J)=>{let H=T.filter((B)=>B.filePath===J),Q=H.filter((B)=>q.has(B.messageId)),L=H.indexOf(Q[0]),O=H.slice(L);if(O.length!==Q.length||O.some((B)=>!q.has(B.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${J}`);return{filePath:J,selected:Q,target:Q[0],latest:Q.at(-1)}})}async loadManifest(){try{let $=await K.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await K.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await k0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let T=this.snapshots.filter((G)=>G.filePath===$).slice(0,-this.maxSnapshots);for(let G of T)await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),this.removeSnapshot(G)}async cleanup($=0){let q=this.snapshots.slice().sort((G,Z)=>Z.timestamp.getTime()-G.timestamp.getTime()),T=new Set(q.slice(0,$));for(let G of this.snapshots)if(!T.has(G))await K.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return F.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=F.resolve($),T=[],G=q;while(!0){try{let J=await K.realpath(G);return F.join(J,...T.reverse())}catch(J){let H=J.code;if(H!=="ENOENT"&&H!=="ENOTDIR")throw J}let Z=F.dirname(G);if(Z===G)return q;T.push(F.basename(G)),G=Z}}async hashFile($){try{let q=await K.readFile($);return T0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return O$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let T=T0.createHash("md5");return T.update(`${$}:${q}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as V1}from"node:crypto";import x$ from"node:path";import{StringDecoder as T1}from"node:string_decoder";function e$($,q){let T=q;while(T<$.length&&($[T]&192)===128)T+=1;return T}class g0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let T=e$($,q);this.chunks[0]=$.subarray(T),this.retainedBytes-=T,this.omittedBytes+=T}}}var N0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},r={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},V$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},$1={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},q1=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:N0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:N0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:r,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:V$},{pattern:/^git\s+(status|branch|remote)/i,config:r},{pattern:/^git\s+(log|diff|show)/i,config:V$},{pattern:/^(ls|dir|tree)\s+/i,config:r,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:r,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:r,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:N0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:N0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:r,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:r,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class f0{static getConfigForCommand($){for(let{pattern:q,config:T,summaryTemplate:G}of q1)if(q.test($))return{config:T,summaryTemplate:G};return{config:$1}}static truncate($,q){let{config:T,summaryTemplate:G}=this.getConfigForCommand(q);return this.truncateWithConfig($,T,G)}static truncateWithConfig($,q,T){let G=$.length,Z=$.split(`
|
|
3
|
+
`),J=Z.length;if(J<=q.maxLines&&G<=q.maxChars)return{content:$,truncated:!1,originalLines:J,originalChars:G};let H=Z.slice(0,q.keepHead),Q=Z.slice(-q.keepTail),L=J-q.keepHead-q.keepTail,O=H.join(`
|
|
4
|
+
`);if(O+=`
|
|
5
|
+
|
|
6
|
+
... (${L} lines truncated, showing first ${q.keepHead} and last ${q.keepTail} of ${J} total) ...
|
|
7
|
+
|
|
8
|
+
`,O+=Q.join(`
|
|
9
|
+
`),O.length>q.maxChars){let X=Math.floor(q.maxChars/2)-50,Y=O.slice(0,X),U=O.slice(-X);O=`${Y}
|
|
10
|
+
|
|
11
|
+
... (content truncated to ${q.maxChars} chars) ...
|
|
12
|
+
|
|
13
|
+
${U}`}let B=q.summarize&&T?T(J,G):void 0;if(B)O+=`
|
|
14
|
+
|
|
15
|
+
[Summary: ${B}]`;return{content:O,truncated:!0,originalLines:J,originalChars:G,summary:B}}static truncateForLLM($,q,T){let G=this.truncate($,T),Z=this.truncate(q,T),J;if(G.truncated||Z.truncated){let H=[];if(G.truncated)H.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
|
|
16
|
+
`).length} lines`);if(Z.truncated)H.push(`stderr: ${Z.originalLines} lines -> ${Z.content.split(`
|
|
17
|
+
`).length} lines`);J=`Output truncated: ${H.join(", ")}`}return{stdout:G.content,stderr:Z.content,truncationInfo:J}}static shouldTruncate($,q){let{config:T}=this.getConfigForCommand(q);return $.split(`
|
|
18
|
+
`).length>T.maxLines||$.length>T.maxChars}static getStats($){return{lines:$.split(`
|
|
19
|
+
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var X$=32768,G1=1048576,J1=65536,Z1=3600000,K$=4096,Q1=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class y0{stream;executionId;onEvent;output=new g0(G1/2);decoder=new T1("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor($,q,T){this.stream=$;this.executionId=q;this.onEvent=T}append($){let q=Buffer.isBuffer($)?$:Buffer.from($);if(q.length===0)return;if(this.totalBytes+=q.length,this.sniffBytes<K$){let G=q.subarray(0,Math.min(q.length,K$-this.sniffBytes));this.sniffChunks.push(G),this.sniffBytes+=G.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let T=Y$(this.decoder.write(q));this.output.append(T),this.emit(T)}finish(){if(this.binary)return;let $=Y$(this.decoder.end());this.output.append($),this.emit($)}snapshot(){let $=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:$.content,omittedBytes:$.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit($){if(!$||!this.onEvent||this.streamTruncated)return;let q=J1-this.streamedBytes;if(q<=0){this.streamTruncated=!0;return}let T=H1($,q);if(this.streamedBytes+=Buffer.byteLength(T),T.length<$.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:T,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function Y$($){return $.replace(Q1,"")}function H1($,q){let T=Buffer.from($);if(T.length<=q)return $;let G=q;while(G>0&&(T[G]&192)===128)G-=1;return T.subarray(0,G).toString("utf8")}function U$($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function L1($){let q=$.trim();if(!q)throw Error("User shell command cannot be empty");if(q.length>X$)throw Error(`User shell command exceeds ${X$} characters`);if(q.includes("\x00"))throw Error("User shell command contains a null byte");return q}function B1(){return{execute($,q){return new Promise((T)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",Z=process.platform==="win32"?["/d","/s","/c",$]:["-l","-c",$],{child:J,processTree:H}=N$(G,Z,{cwd:q.cwd,env:q.env,stdio:["ignore","pipe","pipe"]}),Q="",L="",O=!1,B=!1,X=!1,Y,U=()=>{return Y??=H.terminate(),Y},R=setTimeout(()=>{O=!0,U()},q.timeoutMs),M=()=>{B=!0,U()};if(q.signal.addEventListener("abort",M,{once:!0}),q.signal.aborted)M();J.stdout?.on("data",(_)=>{q.onOutput?.("stdout",_)}),J.stderr?.on("data",(_)=>{q.onOutput?.("stderr",_)});let E=async(_)=>{if(X)return;if(X=!0,clearTimeout(R),q.signal.removeEventListener("abort",M),O||B)await U();T({..._,stdout:"",stderr:"",timedOut:O,aborted:B})};J.once("error",(_)=>{E({exitCode:null,error:_.message})}),J.once("close",(_)=>{E({exitCode:_})})})}}}async function V4($,q){let T=L1($),G=q.timeoutMs??Z1,Z=new y0("stdout",q.executionId,q.onEvent),J=new y0("stderr",q.executionId,q.onEvent),H=Date.now();await q.onEvent?.({type:"started",executionId:q.executionId,command:T});let Q,L=!1,O=!1;try{Q=await(q.executor??B1()).execute(T,{cwd:q.cwd,env:q.env,timeoutMs:G,signal:q.signal,onOutput:(M,E)=>{if(M==="stdout")L=!0;else O=!0;(M==="stdout"?Z:J).append(E)}})}catch(M){Q={exitCode:null,stdout:"",stderr:"",error:M instanceof Error?M.message:String(M)}}if(!L)Z.append(Q.stdout);if(!O)J.append(Q.stderr);Z.finish(),J.finish(),await Promise.all([Z.flushEvents(),J.flushEvents()]);let B=Z.snapshot(),X=J.snapshot(),Y=f0.truncateForLLM(B.content.trim(),X.content.trim(),T),U=Q.aborted||q.signal.aborted?"aborted":Q.timedOut?"timed_out":Q.error?"spawn_error":Q.exitCode===0?"completed":"failed",R={version:1,command:T,status:U,exitCode:Q.exitCode,durationMs:Math.max(0,Date.now()-H),stdout:Y.stdout,stderr:Q.error?[Y.stderr,Q.error].filter(Boolean).join(`
|
|
20
|
+
`):Y.stderr,stdoutOmittedBytes:B.omittedBytes,stderrOmittedBytes:X.omittedBytes,binaryOutput:B.binary||X.binary,truncated:Boolean(Y.truncationInfo)||B.omittedBytes>0||X.omittedBytes>0};return await q.onEvent?.({type:"completed",executionId:q.executionId,record:R}),R}function X4($){let q=[$.stdout?`stdout:
|
|
21
|
+
${$.stdout}`:"",$.stderr?`stderr:
|
|
22
|
+
${$.stderr}`:""].filter(Boolean).join(`
|
|
23
|
+
`);return["<user_shell_command>",`<command>${U$($.command)}</command>`,"<result>",`Status: ${$.status}`,`Exit code: ${$.exitCode??"null"}`,`Duration: ${($.durationMs/1000).toFixed(3)} seconds`,`Output:
|
|
24
|
+
${U$(q||"(no output)")}`,"</result>","</user_shell_command>"].join(`
|
|
25
|
+
`)}function F$($){let q=[$.stdout,$.stderr?`stderr:
|
|
26
|
+
${$.stderr}`:""].filter(Boolean).join(`
|
|
27
|
+
`);return[`! ${$.command}`,q||"(no output)"].join(`
|
|
28
|
+
`)}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(q.version!==1||typeof q.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String(q.status))||q.exitCode!==null&&typeof q.exitCode!=="number"||typeof q.durationMs!=="number"||typeof q.stdout!=="string"||typeof q.stderr!=="string"||typeof q.stdoutOmittedBytes!=="number"||typeof q.stderrOmittedBytes!=="number"||typeof q.binaryOutput!=="boolean"||typeof q.truncated!=="boolean")return;return q}function F0($){if(!$||typeof $!=="object"||Array.isArray($))return;return O1($.userShellCommand)}var W0=16777216,W$=65536,W4=1048576,X1=8,x0=200,K1=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,Y1=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,U1=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,N1=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),F1=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function f($,q){return $.count+=1,q}function W1($){return K1.test($.replace(/[A-Z]/g,(q)=>`_${q.toLowerCase()}`))}function x1($){return[...$].filter((q)=>{if(q===`
|
|
29
|
+
`||q==="\r"||q==="\t")return!0;let T=q.codePointAt(0)??0;if(T<32||T===127)return!1;if(T>=57344&&T<=63743)return!1;if(T>=983040&&T<=1048573)return!1;if(T>=1048576&&T<=1114109)return!1;if(T>=917504&&T<=917631)return!1;return!/[\p{Cf}\p{Cn}]/u.test(q)}).join("")}function k($,q){let T=$.normalize("NFKC"),G=T.replace(N1,"");if(G!==T)q.count+=1;T=G,T=T.replace(F1,()=>f(q,"[redacted-private-key]")),T=T.replace(/\bBearer\s+[^\s"'`]+/gi,()=>f(q,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>f(q,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>f(q,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(J,H,Q)=>`${H}${Q}${f(q,"[redacted]")}`);let Z=x1(T);if(Z!==T)q.count+=1;return Z.replace(/\r\n?/g,`
|
|
30
|
+
`)}function _$($,q,T){if(/^data:[^;,]+;base64,/i.test($))return f(T,"[binary omitted]");let G=k($,T),Z=x$.resolve(q);for(let J of[Z,Z.startsWith("/private/")?Z.slice(8):`/private${Z}`])G=G.replaceAll(J,".");return G=G.replace(Y1,(J)=>J.startsWith("./")?J:f(T,"[host-path]")),G=G.replace(U1,()=>f(T,"[host-path]")),G=G.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(J)=>{try{let H=new URL(J);if(H.username||H.password||H.search||H.hash)T.count+=1;return H.username="",H.password="",H.search="",H.hash="",H.toString()}catch{return f(T,"[redacted-url]")}}),G}function m0($,q,T,G=0,Z){if(Z&&W1(Z))return f(T,"[redacted]");if(G>=X1)return f(T,"[depth limit]");if(typeof $==="string")return _$($,q,T);if($===null||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return $;if(Array.isArray($)){let J=$.slice(0,x0).map((H)=>m0(H,q,T,G+1));if($.length>J.length)J.push(f(T,`[${$.length-J.length} items omitted]`));return J}if($&&typeof $==="object"){let J={},H=Object.entries($);for(let[Q,L]of H.slice(0,x0))J[k(Q,T)]=m0(L,q,T,G+1,Q);if(H.length>x0)J["[entries omitted]"]=H.length-x0;return J}return String($)}function _1($,q){let T=Buffer.from($,"utf8");if(T.length<=q)return $;let G=T.subarray(0,q).toString("utf8");while(Buffer.byteLength(G,"utf8")>q)G=G.slice(0,-1);return G}function z1($,q,T){let G=JSON.stringify(m0($,q,T),null,2);if(Buffer.byteLength(G,"utf8")<=W$)return G;T.count+=1;let Z=`
|
|
31
|
+
... [activity truncated]`;return _1(G,W$-Buffer.byteLength(Z))+Z}function v0($,q=""){let T=Math.max(2,...[...$.matchAll(/`+/g)].map((Z)=>Z[0].length)),G="`".repeat(T+1);return`${G}${q}
|
|
32
|
+
${$}
|
|
33
|
+
${G}`}function j0($){return $.replace(/\s+/g," ").trim()}function C1($){let q=new Map,T=new Map,G=new Map,Z=0;for(let J of o($)){if(J.type==="message_created"){let B=T.get(J.data.messageId);if(B)B.role=J.data.role,B.metadata=J.data.metadata,q.set(J.data.messageId,B),T.delete(J.data.messageId);else if(!q.has(J.data.messageId))q.set(J.data.messageId,{order:Z++,role:J.data.role,parts:[],metadata:J.data.metadata});continue}if(J.type!=="part_created"&&J.type!=="part_updated")continue;let H=q.get(J.data.messageId)??T.get(J.data.messageId);if(!H)H={order:Z++,role:"activity",parts:[]},T.set(J.data.messageId,H);let Q=`${J.data.messageId}\x00${J.data.partType}\x00${J.data.partId}`,L=G.get(Q);if(L){L.event=J;continue}let O={order:Z++,event:J};G.set(Q,O),H.parts.push(O)}return[...q.values(),...T.values()].sort((J,H)=>J.order-H.order)}function S0($,q,T,G){return`## Activity: ${$}
|
|
34
|
+
|
|
35
|
+
${v0(z1(q,T.projectPath,G),"json")}`}function z$($,q,T={}){let G={count:0},Z=T.includeReasoning===!0,J=[],H=0,Q=0,L=0;for(let E of C1($)){let _=F0(E.metadata);if(_){let C=k(_.command,G),D=k([_.stdout,_.stderr?`stderr:
|
|
36
|
+
${_.stderr}`:""].filter(Boolean).join(`
|
|
37
|
+
`)||"(no output)",G);J.push(`## User shell command
|
|
38
|
+
|
|
39
|
+
${v0(`$ ${C}
|
|
40
|
+
${D}`,"console")}`),H+=1;continue}let a=[],A=[],g=[],P=Number.POSITIVE_INFINITY;for(let C of E.parts.sort((D,w)=>D.order-w.order)){let{partType:D,payload:w}=C.event.data;if(D==="text"){let N=w.text;if(typeof N==="string"&&N.trim())a.push(k(N,G)),P=Math.min(P,C.order)}else if(D==="image"){let N=w.mimeType;A.push(typeof N==="string"?`[Image: ${k(N,G)}]`:"[Image]"),P=Math.min(P,C.order)}else if(D==="reasoning"&&Z){let N=w.text;if(typeof N==="string"&&N.trim())g.push({order:C.order,markdown:`## Reasoning
|
|
41
|
+
|
|
42
|
+
${k(N,G).trim()}`}),L+=1}else if(D==="tool_call"){let N=w,c=typeof N.toolName==="string"?k(N.toolName,G):"unknown";g.push({order:C.order,markdown:S0(`${c} call`,N.input??{},q,G)}),Q+=1}else if(D==="tool_result"){let N=w,c=typeof N.toolName==="string"?k(N.toolName,G):"unknown";g.push({order:C.order,markdown:S0(`${c} result`,typeof N.error==="string"?{error:N.error}:{output:N.output??null},q,G)}),Q+=1}else if(D==="summary"){let N=w.text;if(typeof N==="string"&&N.trim())g.push({order:C.order,markdown:`## Summary
|
|
43
|
+
|
|
44
|
+
${k(N,G).trim()}`})}else if(D==="subtask_ref")g.push({order:C.order,markdown:S0("Subagent",w,q,G)}),Q+=1;else if(D==="diff"||D==="patch"){let N=typeof w==="string"?w:JSON.stringify(w,null,2);g.push({order:C.order,markdown:`## File changes
|
|
45
|
+
|
|
46
|
+
${v0(_$(N,q.projectPath,G),"diff")}`}),Q+=1}}if((E.role==="user"||E.role==="assistant")&&(a.length>0||A.length>0))g.push({order:P,markdown:`## ${E.role==="user"?"User":"Assistant"}
|
|
47
|
+
|
|
48
|
+
${[...a,...A].join(`
|
|
49
|
+
|
|
50
|
+
`).trim()}`}),H+=1;J.push(...g.sort((C,D)=>C.order-D.order).map((C)=>C.markdown))}if(J.length===0)throw Error("No conversation content to export");let O=`${J.join(`
|
|
51
|
+
|
|
52
|
+
`)}
|
|
53
|
+
`,B=Buffer.byteLength(O,"utf8");if(B>W0)throw Error(`Session export exceeds ${W0} bytes`);let X=V1("sha256").update(O).digest("hex"),Y=x$.basename(q.taskSourceProjectPath??q.projectPath),U=q.selectedModelId??q.taskModelId,M=["# Blade conversation","",`- Session: \`${q.sessionId}\``,...q.title?[`- Title: ${j0(k(q.title,G))}`]:[],`- Project: \`${j0(k(Y,G))}\``,...U?[`- Model: \`${j0(k(U,G))}\``]:[],...q.permissionMode?[`- Permission mode: ${q.permissionMode}`]:[],`- Created: ${q.firstMessageTime}`,`- Updated: ${q.lastMessageTime}`,`- State: ${q.archivedAt?"archived":"active"}`,`- Reasoning: ${Z?"included":"omitted"}`,...q.reasoningEffort?[`- Reasoning effort: ${q.reasoningEffort}`]:[],...q.serviceTier?[`- Service tier: ${q.serviceTier}`]:[],...q.responseVerbosity?[`- Response verbosity: ${q.responseVerbosity}`]:[],...q.communicationStyle?[`- Communication style: ${q.communicationStyle}`]:[],...q.communicationStyleDigest?[`- Communication style SHA-256: \`${q.communicationStyleDigest}\``]:[],...q.projectInstructionsDigest?[`- Project instructions SHA-256: \`${q.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${X}\``,`- Content bytes: ${B}`,`- Redactions: ${G.count}`,"","---",""].join(`
|
|
54
|
+
`)+`
|
|
55
|
+
`+O;if(Buffer.byteLength(M,"utf8")>W0)throw Error(`Session export exceeds ${W0} bytes`);return{filename:`blade-session-${q.sessionId.slice(0,12)}.md`,markdown:M,contentSha256:X,contentBytes:B,messageCount:H,activityCount:Q,reasoningIncluded:Z,reasoningCount:L,redactionCount:G.count}}var I0=Y0("Service"),D$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),r0=new Set(["local","worktree"]),M1=new Set(["default","autoEdit","yolo","plan"]),R1=new Set(["applied","discarded","conflicted"]);class o0 extends Error{}function M$($){try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}}function R$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((G)=>typeof q[G]!=="string"||!q[G])||typeof q.sourceHadChanges!=="boolean"||q.sourceStateFingerprint!==void 0&&(typeof q.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test(q.sourceStateFingerprint)))return;return q}function A$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(!R1.has(String(q.status))||typeof q.updatedAt!=="string"||!Number.isFinite(Date.parse(q.updatedAt))||q.sourceCommit!==void 0&&(typeof q.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test(q.sourceCommit))||q.changedFiles!==void 0&&(typeof q.changedFiles!=="number"||!Number.isInteger(q.changedFiles)||q.changedFiles<0)||q.message!==void 0&&(typeof q.message!=="string"||!q.message.trim()||q.message.length>500))return;return{status:q.status,updatedAt:q.updatedAt,...typeof q.sourceCommit==="string"?{sourceCommit:q.sourceCommit}:{},...typeof q.changedFiles==="number"?{changedFiles:q.changedFiles}:{},...typeof q.message==="string"?{message:q.message}:{}}}function E$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["changedFiles","additions","deletions","commits"].some((G)=>typeof q[G]!=="number"||!Number.isInteger(q[G])||q[G]<0))return;return q}function w$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(q.version!==1||typeof q.prompt!=="string"||!q.prompt.trim()||q.prompt.length>32000||typeof q.sourceProjectPath!=="string"||!V.isAbsolute(q.sourceProjectPath)||!r0.has(q.isolation)||!C0(q.permissionMode)||q.title!==void 0&&(typeof q.title!=="string"||!q.title.trim()||q.title.length>200)||q.modelId!==void 0&&(typeof q.modelId!=="string"||!q.modelId.trim()||q.modelId.length>500)||q.reasoningEffort!==void 0&&!H0(q.reasoningEffort)||q.serviceTier!==void 0&&!Q0(q.serviceTier)||q.responseVerbosity!==void 0&&!Z0(q.responseVerbosity)||q.communicationStyle!==void 0&&!L0(q.communicationStyle)||q.communicationStyleDigest!==void 0&&(typeof q.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.communicationStyleDigest))||q.projectInstructionsDigest!==void 0&&(typeof q.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.projectInstructionsDigest)))return;let T;if(q.attachments!==void 0){if(!Array.isArray(q.attachments)||q.attachments.length>f$)return;let G=0;for(let Z of q.attachments){if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let J=Z;if(!["file","image","url"].includes(String(J.type)))return;for(let H of["path","url","content","mimeType","name"])if(J[H]!==void 0&&typeof J[H]!=="string")return;G+=typeof J.content==="string"?Buffer.byteLength(J.content):0}if(G>y$)return;T=q.attachments.map((Z)=>{let J=Z;return{type:J.type,...J.path!==void 0?{path:J.path}:{},...J.url!==void 0?{url:J.url}:{},...J.content!==void 0?{content:J.content}:{},...J.mimeType!==void 0?{mimeType:J.mimeType}:{},...J.name!==void 0?{name:J.name}:{}}})}return{version:1,prompt:q.prompt,...typeof q.title==="string"?{title:q.title}:{},sourceProjectPath:V.resolve(q.sourceProjectPath),isolation:q.isolation,permissionMode:q.permissionMode,...typeof q.modelId==="string"?{modelId:q.modelId}:{},...H0(q.reasoningEffort)?{reasoningEffort:q.reasoningEffort}:{},...Q0(q.serviceTier)?{serviceTier:q.serviceTier}:{},...Z0(q.responseVerbosity)?{responseVerbosity:q.responseVerbosity}:{},...L0(q.communicationStyle)?{communicationStyle:q.communicationStyle}:{},...typeof q.communicationStyleDigest==="string"?{communicationStyleDigest:q.communicationStyleDigest}:{},...typeof q.projectInstructionsDigest==="string"?{projectInstructionsDigest:q.projectInstructionsDigest}:{},...T?{attachments:T}:{}}}function C0($){return typeof $==="string"&&M1.has($)}function b$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(typeof q.sessionId!=="string"||!q.sessionId||typeof q.projectPath!=="string"||!V.isAbsolute(q.projectPath))return;return{sessionId:q.sessionId,projectPath:V.resolve(q.projectPath)}}var I$={stat($){return D1($,{bigint:!0})},readFile($){return s($,"utf-8")}},J0=I$;function u4($){J0=$}function h4(){J0=I$}class P$ extends Error{constructor($){super(`Session has no durable creation record: ${$}`);this.name="SessionMissingCreationError"}}class e extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor($,q){super($===q?`Session is archived: ${$}`:`Session is archived by ancestor ${q}: ${$}`);this.sessionId=$;this.archivedBySessionId=q;this.name="SessionArchivedError"}}class I extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor($){super($);this.name="SessionArchiveConflictError"}}function P0($,q){return`${$}\x00${q}`}function u$($){return typeof $==="string"&&$.length<=64&&Number.isFinite(Date.parse($))}function A1($){let q=new Map($.map((T)=>[P0(T.projectPath,T.sessionId),T]));return $.map((T)=>{let G=T,Z=new Set;while(G){let L=P0(G.projectPath,G.sessionId);if(Z.has(L))break;if(Z.add(L),u$(G.archivedAt))return{...T,archivedAt:G.archivedAt,archivedBySessionId:G.sessionId};G=G.parentId?q.get(P0(G.projectPath,G.parentId)):void 0}let{archivedAt:J,archivedBySessionId:H,...Q}=T;return Q})}function u0($,q){let T=A1($);if(q===null)return T;return T.filter((G)=>Boolean(G.archivedAt)===q)}class W{static toUISafeMessages($){let q=Date.now(),T=$.length,G=[];return $.forEach((Z,J)=>{if(Z.role!=="user"&&Z.role!=="assistant")return;let H;if(typeof Z.content==="string")H=Z.content;else if(Array.isArray(Z.content))H=Z.content.map((X)=>X.type==="text"?X.text:"[Image]").join("");else H="";let Q=H.trim();if(!Q)return;let L=F0(Z.metadata),O=L?F$(L):Q,B=G[G.length-1];if(B&&B.role===Z.role&&B.content===O)return;G.push({id:`restored-${q}-${J}`,role:Z.role,content:O,timestamp:q-(T-J)*1000,metadata:Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0})}),G}static async listSessionPage($={}){let q=c0($),T=await this.listSessionPageFromProjection(q);if(T)return T;let Z=(await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,q.cursor?5000:0,q.archived)).sort(p0),J=n0(Z,q);return{sessions:J.sessions.map((H)=>this.toPublicMetadata(H)),nextCursor:J.nextCursor}}static async listSessionPageFromProjection($){let q=S$($);try{let T=await z0();if(!T)return null;await d0(T,this.projectionDeriver(),$.cursor?5000:0);let G=[],Z=[];if($.cwd)G.push("s.project_path = ?"),Z.push($.cwd);if(!$.includeSubagents)G.push("s.is_subagent = 0");if(G.push($.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),q){G.push(`(
|
|
56
|
+
s.last_message_time < ?
|
|
57
|
+
OR (
|
|
58
|
+
s.last_message_time = ?
|
|
59
|
+
AND (
|
|
60
|
+
s.project_sort_key > ?
|
|
61
|
+
OR (s.project_sort_key = ? AND s.session_sort_key > ?)
|
|
62
|
+
)
|
|
63
|
+
)
|
|
64
|
+
)`);let L=l0(q.projectPath);Z.push(q.lastMessageTime,q.lastMessageTime,L,L,l0(q.sessionId))}let H=T.prepare(`WITH RECURSIVE archive_members(
|
|
65
|
+
project_path, session_id, archive_root_id, effective_archived_at, depth
|
|
66
|
+
) AS (
|
|
67
|
+
SELECT project_path, session_id, session_id, archived_at, 0
|
|
68
|
+
FROM sessions
|
|
69
|
+
WHERE archived_at IS NOT NULL
|
|
70
|
+
UNION ALL
|
|
71
|
+
SELECT child.project_path, child.session_id, parent.archive_root_id,
|
|
72
|
+
parent.effective_archived_at, parent.depth + 1
|
|
73
|
+
FROM sessions child
|
|
74
|
+
JOIN archive_members parent
|
|
75
|
+
ON child.project_path = parent.project_path
|
|
76
|
+
AND child.parent_id = parent.session_id
|
|
77
|
+
WHERE parent.depth < 128
|
|
78
|
+
),
|
|
79
|
+
ranked_archive AS (
|
|
80
|
+
SELECT project_path, session_id, archive_root_id,
|
|
81
|
+
effective_archived_at,
|
|
82
|
+
ROW_NUMBER() OVER (
|
|
83
|
+
PARTITION BY project_path, session_id
|
|
84
|
+
ORDER BY depth ASC, archive_root_id ASC
|
|
85
|
+
) AS rank
|
|
86
|
+
FROM archive_members
|
|
87
|
+
)
|
|
88
|
+
SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
|
|
89
|
+
FROM sessions s
|
|
90
|
+
LEFT JOIN ranked_archive a
|
|
91
|
+
ON a.project_path = s.project_path
|
|
92
|
+
AND a.session_id = s.session_id
|
|
93
|
+
AND a.rank = 1
|
|
94
|
+
${G.length>0?`WHERE ${G.join(" AND ")}`:""}
|
|
95
|
+
ORDER BY s.last_message_time DESC,
|
|
96
|
+
s.project_sort_key ASC,
|
|
97
|
+
s.session_sort_key ASC
|
|
98
|
+
LIMIT ?`).all(...Z,$.limit+1).map((L)=>{let O=JSON.parse(L.metadata_json);if(L.archive_root_id&&L.effective_archived_at)return{...O,archivedAt:L.effective_archived_at,archivedBySessionId:L.archive_root_id};let{archivedAt:B,archivedBySessionId:X,...Y}=O;return Y}),Q=n0(H,$);return{sessions:Q.sessions.map((L)=>this.toPublicMetadata(L)),nextCursor:Q.nextCursor}}catch{return null}}static async listSessions($={}){let q=c0($),T=await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,0,q.archived),G=new Set;return T.sort(p0).flatMap((Z)=>{let J=`${Z.projectPath}\x00${Z.sessionId}`;if(G.has(J))return[];return G.add(J),[this.toPublicMetadata(Z)]})}static async findSessionMetadata($,q){if(z($),q!==void 0){if(!V.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=V.resolve(q),Z=this.getSessionFilePath(G,$);try{let J=await this.readStoredSessionMetadata(Z,$,G);if(J.projectPath!==G)return;if(!J.parentId||J.archivedAt)return this.toPublicMetadata(u0([J],null)[0]??J);let H=await this.scanStoredSessions(G,!0,0,null);return this.toPublicMetadata(H.find((Q)=>Q.sessionId===$)??J)}catch(J){if(J.code==="ENOENT")return;throw J}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).filter((G)=>G.sessionId===$);if(T.length===0)return;if(T.length>1)throw Error(`Ambiguous session ID: ${$}`);return this.toPublicMetadata(T[0])}static async loadSession($,q){try{if(q){if(!V.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=V.resolve(q),Z=this.getSessionFilePath(G,$);try{return await this.loadSessionFromFile(Z,$,G)}catch(J){if(J.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw J}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((G)=>G.sessionId===$);if(!T)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(T.filePath,$)}catch(T){throw I0.error(`[SessionService] 加载会话失败 (${$}):`,T),T}}static async exportSessionMarkdown($,q,T={}){z($);let G=this.resolveCatalogWorkspace(q),Z=S(G,$),J;try{J=await this.readStableSessionSnapshot(Z,$)}catch(L){throw this.sanitizeStoredSessionError(L,$)}let H=this.projectMetadataFromEntries(J,$,G,Z);if(H.projectPath!==G)throw Error(`Session export workspace mismatch: ${$}`);let Q=H.archivedAt;if(!Q&&H.parentId)Q=(await this.findArchivedAncestor(H.parentId,G))?.archivedAt;return z$(J,{...H,archivedAt:Q},T)}static async listRewindCheckpoints($,q){z($);let T=this.resolveCatalogWorkspace(q),G=S(T,$),Z=await this.readStableSessionSnapshot(G,$);this.validateSessionWorkspace(Z,$,T);let J=new U0({sessionId:$,workspaceRoot:T});await J.initialize();let H=m$(Z),Q=[];for(let L of H){let O=i0(Z,L.messageId),B=await J.previewRewind(O.snapshotMessageIds);Q.push({...L,fileCount:B.files.length})}return Q}static async rewindSession($,q,T){z($);let G=this.resolveCatalogWorkspace(q);await this.assertSessionWritable($,G);let Z=S(G,$),J=new v(Z),H;try{await J.appendValidatedAsync(async(Q)=>{this.validateSessionWorkspace(Q,$,G);let L=i0(Q,T.targetMessageId),O=new U0({sessionId:$,workspaceRoot:G});await O.initialize();let B=await O.previewRewind(L.snapshotMessageIds),X=T.mode==="conversation"?await O.commitSnapshots(L.snapshotMessageIds):await O.rewindSnapshots(L.snapshotMessageIds),Y=new Date().toISOString(),U={id:j(),sessionId:$,timestamp:Y,type:"session_rewound",cwd:G,gitBranch:h(G),version:l(),data:{rewindId:j(),targetMessageId:T.targetMessageId,mode:T.mode,restoredFiles:T.mode==="conversation"?[]:X.files,createdAt:Y}},R=o([...Q,U]);return H={checkpoint:{...L.checkpoint,fileCount:B.files.length},mode:T.mode,removedTurns:L.removedTurns,restoredFiles:U.data.restoredFiles,messages:this.convertJSONLToMessages(R)},U})}catch(Q){throw this.sanitizeStoredSessionError(Q,$)}if(!H)throw Error(`Session rewind did not produce a result: ${$}`);for(let Q of H.restoredFiles)u.getInstance().clearFileRecord(Q);return H}static async forkSession($,q){z($);let T=q.newSessionId??`fork-${Date.now()}-${j(8)}`;z(T);let G=this.resolveForkWorkspace(q.sourceProjectPath),Z=this.resolveForkWorkspace(q.targetProjectPath);if(G!==Z)throw Error("Session forks must stay in the source workspace");let J=S(G,$),H=await this.readStableSessionSnapshot(J,$),Q=this.getSessionCreatedEntry(H,$);if(Q.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!V.isAbsolute(Q.cwd)||V.resolve(Q.cwd)!==G)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let L=this.projectMetadataFromEntries(H,$,G,J);if(L.archivedAt)throw new e($,$);if(L.parentId){let b=await this.findArchivedAncestor(L.parentId,G);if(b)throw new e($,b.sessionId)}let O=o(H),B=new Date().toISOString(),X=Q.data.rootId||$,Y=h(Z),U=l(),{status:R,taskStatus:M,taskStatusReason:E,taskFailure:_,taskStartedAt:a,taskCompletedAt:A,taskOwnerPid:g,taskPromptSummary:P,taskDispatch:C,taskModelId:D,taskRetriedFrom:w,taskDelivery:N,taskIsolation:c,taskSourceProjectPath:a0,taskWorktree:t0,taskDiffStat:s0,taskQueuePosition:e0,taskQueueDepth:$$,taskConcurrencyLimit:q$,...D0}=Q.data,M0={id:j(),sessionId:T,timestamp:B,type:"session_created",cwd:Z,gitBranch:Y,version:U,data:{...D0,sessionId:T,rootId:X,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:B,taskIsolation:"local",taskSourceProjectPath:Z,createdAt:B,updatedAt:B}},B0=O.filter((b)=>b.type!=="session_created"&&b.type!=="inbox_acknowledged").map((b)=>{let R0={...b,id:j(),sessionId:T,cwd:Z,gitBranch:Y,version:U};if(b.type==="session_updated"){let{status:l$,taskStatus:G$,taskStatusReason:E1,taskFailure:w1,taskStartedAt:b1,taskCompletedAt:k1,taskOwnerPid:g1,taskPromptSummary:f1,taskDispatch:y1,taskModelId:j1,taskRetriedFrom:S1,taskDelivery:m1,taskIsolation:v1,taskSourceProjectPath:I1,taskWorktree:P1,taskDiffStat:u1,taskQueuePosition:h1,taskQueueDepth:l1,taskConcurrencyLimit:c1,...c$}=b.data;return{...R0,type:"session_updated",data:{...c$,sessionId:T,rootId:X,parentId:$,relationType:"fork"}}}if(b.type==="message_created"){let{inboxMessageId:l$,...G$}=b.data;return{...R0,type:"message_created",data:G$}}return R0}),y={id:j(),sessionId:T,timestamp:B,type:"session_updated",cwd:Z,gitBranch:Y,version:U,data:{sessionId:T,rootId:X,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:B,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:Z,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:B}},t=[M0,...B0,y],T$=S(Z,T);try{await new v(T$).createExclusive(t)}catch(b){if(b.code==="EEXIST")throw Error(`Fork session already exists: ${T}`,{cause:b});throw b}let h$=this.projectMetadataFromEntries(t,T,Z,T$);return{sessionId:T,parentSessionId:$,projectPath:Z,messages:this.convertJSONLToMessages(t),metadata:this.toPublicMetadata(h$)}}static async deleteSession($,q){if(z($),q){if(!V.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=V.resolve(q),Z=this.getSessionFilePath(G,$),J=new v(Z),H;try{H=await J.deleteValidated((Q)=>{return this.projectMetadataFromEntries(Q,$,G,Z).projectPath===G})}catch(Q){if(!this.isCorruptSessionJSONLError(Q))throw Q;H=await J.delete()}if(!H)return 0;return await _0(V.join(V.dirname(Z),`${$}.inbox.json`),{force:!0}),await _0(h0(G,$),{force:!0}),await this.removeFromProjection($,G),1}let T=(await this.scanStoredSessions(void 0,!0)).filter((G)=>G.sessionId===$);if(T.length===0)return 0;return await Promise.all(T.map(async(G)=>{await new v(G.filePath).delete(),await _0(V.join(V.dirname(G.filePath),`${G.sessionId}.inbox.json`),{force:!0}),await _0(h0(G.projectPath,G.sessionId),{force:!0}),await this.removeFromProjection(G.sessionId,G.projectPath)})),T.length}static async removeFromProjection($,q){try{let T=await z0();if(T)v$(T,$,q)}catch{}}static validateTaskMetadataUpdate($,q){if($.taskPromptSummary!==void 0&&$.taskPromptSummary!==null&&(!$.taskPromptSummary.trim()||$.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if($.taskFailure!==void 0&&$.taskFailure!==null&&!w0($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!w$($.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&&!C0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!H0($.reasoningEffort))throw Error("Invalid session reasoning effort");if($.serviceTier!==void 0&&$.serviceTier!==null&&!Q0($.serviceTier))throw Error("Invalid session service tier");if($.responseVerbosity!==void 0&&$.responseVerbosity!==null&&!Z0($.responseVerbosity))throw Error("Invalid session response verbosity");if($.communicationStyle!==void 0&&$.communicationStyle!==null&&!L0($.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&&!b$($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!A$($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!r0.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!V.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let T=R$($.taskWorktree);if(!T||T.sessionId!==q||![T.repositoryRoot,T.originalWorkspaceRoot,T.worktreeRoot,T.workspaceRoot].every((G)=>V.isAbsolute(G)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!E$($.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($,q,T={}){z($),W.validateTaskMetadataUpdate(T,$);let G=W.resolveCatalogWorkspace(q);if(T.taskWorktree&&V.resolve(T.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let Z=new Date().toISOString(),J={id:j(),sessionId:$,timestamp:Z,type:"session_created",cwd:G,gitBranch:h(G),version:l(),data:{sessionId:$,rootId:$,...T.title!==void 0?{title:T.title}:{},taskStatus:T.taskStatus??"queued",...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},createdAt:Z,updatedAt:Z}},H=W.getSessionFilePath(G,$);return await new v(H).createExclusive([J]),W.toPublicMetadata(W.projectMetadataFromEntries([J],$,G,H))}static async assertSessionWritable($,q){let T=await this.findSessionMetadata($,q);if(!T)throw Error(`Session not found: ${$}`);if(T.archivedAt)throw new e($,T.archivedBySessionId??$);return T}static async findArchivedAncestor($,q){let T=new Set,G=$;while(G){if(T.has(G))throw Error("Session lineage contains a cycle");T.add(G),z(G);let Z=S(q,G),J;try{J=await s(Z,"utf8")}catch(Q){if(Q.code==="ENOENT")return;throw Q}let H=this.projectMetadataFromEntries(this.parseStoredSession(J,G),G,q,Z);if(H.projectPath!==q)throw Error("Session lineage escapes the requested workspace");if(H.archivedAt)return{sessionId:H.sessionId,archivedAt:H.archivedAt};G=H.parentId}return}static async listSessionArchiveMembers($,q){z($);let T=this.resolveCatalogWorkspace(q),G=await this.scanStoredSessions(T,!0,0,null);if(!G.some((H)=>H.sessionId===$))throw Error(`Session not found: ${$}`);let Z=new Set([$]),J=!0;while(J){J=!1;for(let H of G)if(H.parentId&&Z.has(H.parentId)&&!Z.has(H.sessionId))Z.add(H.sessionId),J=!0}return G.filter((H)=>Z.has(H.sessionId)).sort((H,Q)=>H.sessionId.localeCompare(Q.sessionId)).map((H)=>this.toPublicMetadata(H))}static async archiveSession($,q){z($);let T=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,T);if(!G)throw Error(`Session not found: ${$}`);if(G.archivedAt)return G;let Z=await this.listSessionArchiveMembers($,T),J=Z.find((Q)=>Q.taskStatus==="queued"||Q.taskStatus==="running");if(J)throw new I(`Stop session ${J.sessionId} before archiving this session tree`);let H=[];try{for(let B of Z)H.push(await n.acquire(B.sessionId,T));let Q=S(T,$),L=new v(Q),O=[];return await L.appendValidated((B)=>{let X=this.projectMetadataFromEntries(B,$,T,Q);if(X.archivedAt)throw new I(`Session archive state changed concurrently: ${$}`);if(X.taskStatus==="queued"||X.taskStatus==="running")throw new I(`Stop session ${$} before archiving it`);let Y=new Date().toISOString(),U={id:j(),sessionId:$,timestamp:Y,type:"session_updated",cwd:T,gitBranch:h(T),version:l(),data:{sessionId:$,archivedAt:Y,updatedAt:Y}};return O=[...B,U],U}),this.toPublicMetadata({...this.projectMetadataFromEntries(O,$,T,Q),archivedBySessionId:$})}catch(Q){if(Q instanceof I)throw Q;if(Q instanceof p)throw new I(Q.message);throw this.sanitizeStoredSessionError(Q,$)}finally{for(let Q of H.reverse())await Q.release()}}static async unarchiveSession($,q){z($);let T=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,T);if(!G)throw Error(`Session not found: ${$}`);if(!G.archivedAt)return G;if(G.archivedBySessionId&&G.archivedBySessionId!==$)throw new I(`Unarchive ancestor ${G.archivedBySessionId} to restore session ${$}`);let Z;try{Z=await n.acquire($,T);let J=S(T,$),H=new v(J),Q=[];return await H.appendValidated((L)=>{if(!this.projectMetadataFromEntries(L,$,T,J).archivedAt)throw new I(`Session archive state changed concurrently: ${$}`);let B=new Date().toISOString(),X={id:j(),sessionId:$,timestamp:B,type:"session_updated",cwd:T,gitBranch:h(T),version:l(),data:{sessionId:$,archivedAt:null,updatedAt:B}};return Q=[...L,X],X}),this.toPublicMetadata(this.projectMetadataFromEntries(Q,$,T,J))}catch(J){if(J instanceof I)throw J;if(J instanceof p)throw new I(J.message);throw this.sanitizeStoredSessionError(J,$)}finally{await Z?.release()}}static async updateSessionMetadata($,q,T){if(z($),W.validateTaskMetadataUpdate(T,$),T.taskStatus!==void 0&&!D$.has(T.taskStatus))throw Error(`Invalid session task status: ${String(T.taskStatus)}`);if(T.taskOwnerPid!==void 0&&T.taskOwnerPid!==null&&(!Number.isInteger(T.taskOwnerPid)||T.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let G=W.resolveCatalogWorkspace(q);if(T.taskWorktree&&V.resolve(T.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let Z=W.getSessionFilePath(G,$),J=new v(Z),H=[];try{await J.appendValidatedAsync(async(Q)=>{let L=W.getSessionCreatedEntry(Q,$);if(L.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!V.isAbsolute(L.cwd)||V.resolve(L.cwd)!==G)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let O=W.projectMetadataFromEntries(Q,$,G,Z);if(O.archivedAt)throw new e($,$);if(O.parentId){let Y=await W.findArchivedAncestor(O.parentId,G);if(Y)throw new e($,Y.sessionId)}let B=new Date().toISOString(),X={id:j(),sessionId:$,timestamp:B,type:"session_updated",cwd:G,gitBranch:h(G),version:l(),data:{sessionId:$,...T.title!==void 0?{title:T.title}:{},...T.taskStatus!==void 0?{taskStatus:T.taskStatus}:{},...T.taskStatusReason!==void 0?{taskStatusReason:T.taskStatusReason}:{},...T.taskFailure!==void 0?{taskFailure:T.taskFailure}:{},...T.taskStartedAt!==void 0?{taskStartedAt:T.taskStartedAt}:{},...T.taskCompletedAt!==void 0?{taskCompletedAt:T.taskCompletedAt}:{},...T.taskOwnerPid!==void 0?{taskOwnerPid:T.taskOwnerPid}:{},...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskDelivery!==void 0?{taskDelivery:T.taskDelivery}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.taskDiffStat!==void 0?{taskDiffStat:T.taskDiffStat}:{},...T.taskQueuePosition!==void 0?{taskQueuePosition:T.taskQueuePosition}:{},...T.taskQueueDepth!==void 0?{taskQueueDepth:T.taskQueueDepth}:{},...T.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:T.taskConcurrencyLimit}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},updatedAt:B}};return H=[...Q,X],X})}catch(Q){throw W.sanitizeStoredSessionError(Q,$)}return W.toPublicMetadata(W.projectMetadataFromEntries(H,$,G,Z))}static async setSessionPermissionMode($,q,T){if(z($),!C0(T))throw Error("Invalid session permission mode");let G=W.resolveCatalogWorkspace(q),Z=await W.findSessionMetadata($,G);if(Z?.permissionMode===T)return Z;if(Z)return W.updateSessionMetadata($,G,{permissionMode:T});try{return await W.createSessionMetadata($,G,{taskStatus:"completed",permissionMode:T})}catch(J){if(J.code!=="EEXIST")throw J;return W.updateSessionMetadata($,G,{permissionMode:T})}}static async findSessionTaskWorktree($,q){z($);let T=W.resolveCatalogWorkspace(q),G=W.getSessionFilePath(T,$);try{return(await W.readStoredSessionMetadata(G,$,T)).taskWorktree}catch(Z){if(Z.code==="ENOENT")return;throw W.sanitizeStoredSessionError(Z,$)}}static async findSessionTaskDispatch($,q){z($);let T=W.resolveCatalogWorkspace(q),G=W.getSessionFilePath(T,$);try{return(await W.readStoredSessionMetadata(G,$,T)).taskDispatch}catch(Z){if(Z.code==="ENOENT")return;throw W.sanitizeStoredSessionError(Z,$)}}static async loadSessionFromFile($,q,T){let G=await s($,"utf-8"),Z=this.parseStoredSession(G,q);if(T!==void 0){if(this.projectMetadataFromEntries(Z,q,T,$).projectPath!==T)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToMessages(Z)}static convertJSONLToMessages($){let q=[],T=new Map,G=new Map,Z=new Map,J=new Map,H=new Map;for(let Q of o($)){if(Q.type==="message_created"){let L=Q.data.role==="assistant"&&Q.data.parentMessageId?Z.get(Q.data.parentMessageId):void 0,O=L??{role:Q.data.role,content:"",...Q.data.metadata||Q.data.inboxMessageId?{metadata:{...Q.data.metadata&&typeof Q.data.metadata==="object"&&!Array.isArray(Q.data.metadata)?Q.data.metadata:{},...Q.data.inboxMessageId?{inboxMessageId:Q.data.inboxMessageId}:{}}}:{}};if(T.set(Q.data.messageId,O),G.set(Q.data.messageId,[]),!L)q.push(O)}if(Q.type==="part_created"){if(Q.data.partType==="reasoning"){let L=T.get(Q.data.messageId);if(L){let O=Q.data.payload;L.reasoningContent=(L.reasoningContent??"")+(O.text??"")}}if(Q.data.partType==="text"){let L=T.get(Q.data.messageId);if(L){let O=Q.data.payload,B=G.get(Q.data.messageId);if(B)B.push({type:"text",text:O.text??""}),L.content=k$(B);else L.content=O.text??""}}if(Q.data.partType==="image"){let L=T.get(Q.data.messageId);if(L){let O=Q.data.payload,B=G.get(Q.data.messageId);if(B&&O.dataUrl)B.push({type:"image_url",image_url:{url:O.dataUrl}}),L.content=k$(B)}}if(Q.data.partType==="tool_call"){let L=T.get(Q.data.messageId);if(L?.role!=="assistant"){if(L=Z.get(Q.data.messageId),!L)L={role:"assistant",content:"",tool_calls:[]},Z.set(Q.data.messageId,L),q.push(L)}if(L.role==="assistant"){let O=Q.data.payload,B=O.toolCallId??Q.data.partId;J.set(Q.data.partId,B),H.set(B,L),L.tool_calls??=[],L.tool_calls.push({id:B,type:"function",function:{name:O.toolName??"unknown",arguments:JSON.stringify(O.input??{})}})}}if(Q.data.partType==="tool_result"){let L=Q.data.payload,O=typeof L.error==="string"?`Error: ${L.error}`:typeof L.output==="string"?L.output:JSON.stringify(L.output??""),B=L;q.push({role:"tool",content:O,tool_call_id:J.get(Q.data.messageId)??L.toolCallId,name:L.toolName,metadata:B})}if(Q.data.partType==="summary"){let L=Q.data.payload,O=Q.data.payload;q.push({role:"system",content:L.text??"",metadata:O})}if(Q.data.partType==="subtask_ref"){let L=T.get(Q.data.messageId)??H.get(Q.data.messageId);if(L){let O=Q.data.payload,B=L.metadata??{};L.metadata={...B,subtaskRef:O}}}}}return q}static projectionDeriver(){return($,q,T)=>{try{let G=S(T,q);return this.projectMetadataFromEntries($,q,T,G)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection($,q,T=0,G=!1){try{let Z=await z0();if(!Z)return null;await d0(Z,this.projectionDeriver(),T);let J=$?Z.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all($):Z.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),H=[];for(let Q of J){if(!q&&Q.is_subagent===1)continue;try{let L=JSON.parse(Q.metadata_json);if($!==void 0&&L.projectPath!==$)continue;H.push(L)}catch{}}return u0(H,G)}catch{return null}}static async scanStoredSessions($,q=!1,T=0,G=!1){let Z=$?V.resolve($):void 0,J=await this.scanStoredSessionsFromProjection(Z,q,T,G);if(J)return J;let H=Z?[{storagePath:V0(Z),projectPath:Z}]:await this.listAllProjectStorageDirectories(),Q=[];for(let L of H){let O;try{O=await C$(L.storagePath)}catch(B){if(B.code==="ENOENT")continue;throw B}for(let B of O){if(!B.endsWith(".jsonl"))continue;let X=B.slice(0,-6),Y=V.join(L.storagePath,B);try{let U=await this.readStoredSessionMetadata(Y,X,L.projectPath);if(Z!==void 0&&U.projectPath!==Z){I0.warn(`[SessionService] Skipping out-of-scope session transcript: ${X}`);continue}if(!q&&U.relationType==="subagent")continue;Q.push(U)}catch(U){let R=U.code;if(R==="ENOENT")continue;if(R)throw U;I0.warn(`[SessionService] Skipping invalid session transcript: ${X}`)}}}return u0(Q,G)}static async listAllProjectStorageDirectories(){let $=V.join(G0(),"projects"),q;try{q=await C$($,{withFileTypes:!0,encoding:"utf8"})}catch(T){if(T.code==="ENOENT")return[];throw T}return q.filter((T)=>T.isDirectory()).map((T)=>({storagePath:V.join($,T.name),projectPath:g$(T.name)}))}static async readStoredSessionMetadata($,q,T){let G=await s($,"utf-8"),Z=this.parseStoredSession(G,q);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(Z,q,T,$))}static async reconcileInterruptedTask($){let q=$.taskOwnerPid;if($.taskStatus!=="running"||q===void 0||M$(q))return $;let T;try{T=await n.acquire($.sessionId,$.projectPath)}catch(J){if(!(J instanceof p))throw J;let H=await s($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(H,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let G=new v($.filePath),Z;try{try{await G.appendValidated((J)=>{let H=this.projectMetadataFromEntries(J,$.sessionId,$.projectPath,$.filePath);if(H.taskStatus!=="running"||H.taskOwnerPid!==q||M$(q))throw new o0;let Q=new Date().toISOString(),L={id:j(),sessionId:$.sessionId,timestamp:Q,type:"session_updated",cwd:$.projectPath,gitBranch:h($.projectPath),version:l(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:Q,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:Q}};return Z=[...J,L],L})}catch(J){if(!(J instanceof o0))throw J}if(!Z){let J=await s($.filePath,"utf-8");Z=this.parseStoredSession(J,$.sessionId)}return this.projectMetadataFromEntries(Z,$.sessionId,$.projectPath,$.filePath)}finally{await T.release()}}static projectMetadataFromEntries($,q,T,G){if($.length===0)throw Error(`Empty session transcript: ${q}`);let Z=this.getSessionCreatedEntry($,q),J=$.reduce((y,t)=>t.type==="session_updated"?{...y,...t.data}:y,{...Z.data}),H=o($),Q=H.filter((y)=>y.type==="message_created"&&["user","assistant"].includes(y.data.role)).length,L=H.some((y)=>y.type==="part_created"&&y.data.partType==="tool_result"&&typeof y.data.payload.error==="string"),B=(D$.has(J.taskStatus)?J.taskStatus:void 0)??(L?"failed":"completed"),X=typeof J.taskOwnerPid==="number"&&Number.isInteger(J.taskOwnerPid)&&J.taskOwnerPid>0?J.taskOwnerPid:void 0,Y=r0.has(J.taskIsolation)?J.taskIsolation:void 0,U=typeof J.taskSourceProjectPath==="string"&&V.isAbsolute(J.taskSourceProjectPath)?V.resolve(J.taskSourceProjectPath):void 0,R=Z.cwd;if(R!==void 0&&!V.isAbsolute(R))throw Error(`Session catalog cwd must be absolute: ${q}`);let M=R===void 0?T:V.resolve(R),E=R$(J.taskWorktree),_=E?.sessionId===q&&V.resolve(E.workspaceRoot)===M?E:void 0,a=E$(J.taskDiffStat),A=w$(J.taskDispatch),g=typeof J.taskModelId==="string"&&J.taskModelId.trim()?J.taskModelId:A?.modelId,P=typeof J.selectedModelId==="string"&&J.selectedModelId.trim()?J.selectedModelId:g,C=C0(J.permissionMode)?J.permissionMode:A?.permissionMode,D=H0(J.reasoningEffort)?J.reasoningEffort:A?.reasoningEffort,w=Q0(J.serviceTier)?J.serviceTier:A?.serviceTier,N=Z0(J.responseVerbosity)?J.responseVerbosity:A?.responseVerbosity,c=L0(J.communicationStyle)?J.communicationStyle:A?.communicationStyle,a0=Object.hasOwn(J,"communicationStyleDigest")?typeof J.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(J.communicationStyleDigest)?J.communicationStyleDigest:void 0:c===A?.communicationStyle?A?.communicationStyleDigest:void 0,t0=Object.hasOwn(J,"projectInstructionsDigest")?typeof J.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(J.projectInstructionsDigest)?J.projectInstructionsDigest:void 0:A?.projectInstructionsDigest,s0=u$(J.archivedAt)?J.archivedAt:void 0,e0=b$(J.taskRetriedFrom),$$=A$(J.taskDelivery),q$=typeof J.taskQueuePosition==="number"&&Number.isInteger(J.taskQueuePosition)&&J.taskQueuePosition>0?J.taskQueuePosition:void 0,D0=typeof J.taskQueueDepth==="number"&&Number.isInteger(J.taskQueueDepth)&&J.taskQueueDepth>=0?J.taskQueueDepth:void 0,M0=typeof J.taskConcurrencyLimit==="number"&&Number.isInteger(J.taskConcurrencyLimit)&&J.taskConcurrencyLimit>0?J.taskConcurrencyLimit:void 0,B0=w0(J.taskFailure)?J.taskFailure:B==="failed"&&typeof J.taskStatusReason==="string"?L$(J.taskStatusReason):void 0;return{sessionId:q,projectPath:M,gitBranch:Z.gitBranch,rootId:J.rootId||q,parentId:J.parentId,relationType:J.relationType,resumedFrom:J.resumedFrom,rootAgentId:J.rootAgentId,resumeDepth:J.resumeDepth,title:J.title,agentType:J.agentType,model:J.model,selectedModelId:P,permissionMode:C,reasoningEffort:D,serviceTier:w,responseVerbosity:N,communicationStyle:c,communicationStyleDigest:a0,projectInstructionsDigest:t0,taskStatus:B,taskStatusReason:B0?.message??(typeof J.taskStatusReason==="string"?J.taskStatusReason:void 0),taskFailure:B0,taskStartedAt:typeof J.taskStartedAt==="string"?J.taskStartedAt:void 0,taskCompletedAt:typeof J.taskCompletedAt==="string"?J.taskCompletedAt:void 0,taskPromptSummary:typeof J.taskPromptSummary==="string"?J.taskPromptSummary:void 0,taskModelId:g,taskRetryAvailable:A!==void 0,taskRetriedFrom:e0,taskDelivery:$$,taskIsolation:Y,taskSourceProjectPath:U,taskWorktreePath:_?.worktreeRoot,taskWorktreeBranch:_?.branch,taskBaseCommit:_?.baseCommit,taskDiffStat:a,taskQueuePosition:q$,taskQueueDepth:D0,taskConcurrencyLimit:M0,archivedAt:s0,taskOwnerPid:X,taskWorktree:_,taskDispatch:A,messageCount:Q,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:L||B==="failed",filePath:G}}static toPublicMetadata($){let{filePath:q,taskOwnerPid:T,taskWorktree:G,taskDispatch:Z,...J}=$;return J}static getSessionFilePath($,q){return S($,q)}static getSessionCreatedEntry($,q){let T=$.find((G)=>G.type==="session_created");if(!T)throw new P$(q);return T}static resolveCatalogWorkspace($){if(!V.isAbsolute($))throw Error("Session catalog cwd must be absolute");return V.resolve($)}static validateSessionWorkspace($,q,T){let G=this.getSessionCreatedEntry($,q);if(G.data.sessionId!==q)throw Error(`Session creation record sessionId mismatch: ${q}`);if(!V.isAbsolute(G.cwd)||V.resolve(G.cwd)!==T)throw Error(`Session creation record cwd mismatch: ${q}`)}static resolveForkWorkspace($){if(!V.isAbsolute($))throw Error("Fork workspace paths must be absolute");return V.resolve($)}static parseStoredSession($,q){return j$($,`session ${q}`)}static isCorruptSessionJSONLError($){return $ instanceof Error&&$.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError($,q){if(!this.isCorruptSessionJSONLError($)||!($ instanceof Error))return $;let T=$.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${q}${T?` at line ${T}`:""}`,{cause:$.cause})}static async readStableSessionSnapshot($,q,T=3){for(let G=0;G<T;G+=1){let Z=await J0.stat($),J=await J0.readFile($),H=this.parseStoredSession(J,q),Q=await J0.stat($);if(Z.size===Q.size&&Z.mtimeNs===Q.mtimeNs&&Z.dev===Q.dev&&Z.ino===Q.ino)return H}throw Error("Session changed while creating fork; retry the operation")}}function k$($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
|
|
99
|
+
export{b0 as _a,p as $a,n as ab,L$ as bb,u as cb,U0 as db,g0 as eb,f0 as fb,V4 as gb,X4 as hb,F$ as ib,F0 as jb,W4 as kb,u4 as lb,h4 as mb,P$ as nb,e as ob,I as pb,W as qb};
|