blade-code 0.10.110 → 0.10.112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-eaymmgvz.js → chunk-19szcewf.js} +1 -1
  3. package/dist/{chunk-r44ecdvt.js → chunk-1cxpjdbn.js} +1 -1
  4. package/dist/{chunk-tsbyhb62.js → chunk-2h37sdgt.js} +1 -1
  5. package/dist/{chunk-5770csfs.js → chunk-34xpxqjf.js} +94 -94
  6. package/dist/{chunk-vp4ksbts.js → chunk-3hejvrgx.js} +1 -1
  7. package/dist/chunk-3vn6hcmp.js +1 -0
  8. package/dist/{chunk-5gpavd2c.js → chunk-4m0q8n44.js} +1 -1
  9. package/dist/{chunk-xhz2a9a0.js → chunk-68gvb58c.js} +1 -1
  10. package/dist/{chunk-t3tw0zfx.js → chunk-6nnanm6g.js} +1 -1
  11. package/dist/{chunk-k45w6w2h.js → chunk-6wn33cv8.js} +1 -1
  12. package/dist/{chunk-sehfcsn1.js → chunk-904zjkaa.js} +1 -1
  13. package/dist/{chunk-y2489d6k.js → chunk-b0ffv012.js} +1 -1
  14. package/dist/{chunk-cawf90zq.js → chunk-bqykmq8f.js} +1 -1
  15. package/dist/{chunk-j45tttb8.js → chunk-cbemfmm9.js} +1 -1
  16. package/dist/{chunk-57phmavh.js → chunk-dr63cmxq.js} +1 -1
  17. package/dist/{chunk-aj0gttng.js → chunk-e95q62pq.js} +2 -2
  18. package/dist/{chunk-mbqtt6qh.js → chunk-eg4yn1wb.js} +1 -1
  19. package/dist/{chunk-7fkvpysw.js → chunk-fhdrx7e9.js} +1 -1
  20. package/dist/{chunk-chqb1gpn.js → chunk-hw9138p5.js} +1 -1
  21. package/dist/{chunk-7egvtv3n.js → chunk-j5satx4j.js} +1 -1
  22. package/dist/{chunk-m12xmaga.js → chunk-kbqvdsv8.js} +1 -1
  23. package/dist/{chunk-2qhq6gcy.js → chunk-kk2knxx8.js} +1 -1
  24. package/dist/{chunk-fr9n7n42.js → chunk-m25nn7m6.js} +1 -1
  25. package/dist/{chunk-07wfs7ng.js → chunk-mwfbt6eg.js} +1 -1
  26. package/dist/{chunk-9zp4m6p8.js → chunk-nz1kj4b2.js} +1 -1
  27. package/dist/{chunk-5frzn7px.js → chunk-nzj1gfz9.js} +1 -1
  28. package/dist/{chunk-556e469e.js → chunk-pq8bncc1.js} +1 -1
  29. package/dist/{chunk-t88z3r2s.js → chunk-qxsacwcs.js} +2 -2
  30. package/dist/{chunk-a843n3ed.js → chunk-th6mczcw.js} +1 -1
  31. package/dist/{chunk-cr5chpr4.js → chunk-tw7xf4gp.js} +1 -1
  32. package/dist/{chunk-tseehebs.js → chunk-x2r1rncz.js} +1 -1
  33. package/dist/{chunk-j5w2c7w4.js → chunk-x4m7ffgq.js} +1 -1
  34. package/dist/{chunk-ahk6m7m7.js → chunk-x7zbsjh3.js} +1 -1
  35. package/dist/{chunk-awvnwb43.js → chunk-z2d7yqvc.js} +1 -1
  36. package/dist/{chunk-0hmhmvhc.js → chunk-zck02rpy.js} +1 -1
  37. package/dist/chunk-zcxd6ha7.js +1 -0
  38. package/dist/{chunk-g7my2fd3.js → chunk-ztv7pe6s.js} +1 -1
  39. package/dist/web/assets/{ChatView-BRMfjCD8.js → ChatView-DCHnicTP.js} +4 -4
  40. package/dist/web/assets/{CodeBlockHighlighter-fHhPow2L.js → CodeBlockHighlighter-0VOa5Mes.js} +1 -1
  41. package/dist/web/assets/{FilePreview-Cb3TjUx0.js → FilePreview-C_3KHzzj.js} +1 -1
  42. package/dist/web/assets/{KanbanBoard-NteHVue_.js → KanbanBoard-D_NTkUnD.js} +1 -1
  43. package/dist/web/assets/{MarkdownRenderer-BzjqGZva.js → MarkdownRenderer-3g4TPTeI.js} +3 -3
  44. package/dist/web/assets/{SettingsModal-BLUWzdTK.js → SettingsModal-3GMy6V-E.js} +1 -1
  45. package/dist/web/assets/{TaskSwitcher-AOProHdA.js → TaskSwitcher-eCdxu5Eo.js} +1 -1
  46. package/dist/web/assets/{TerminalPanel-L8CgcAVz.js → TerminalPanel-9q9Trmv9.js} +1 -1
  47. package/dist/web/assets/{arrow-left-_61S23rO.js → arrow-left-03GxbYI7.js} +1 -1
  48. package/dist/web/assets/{calendar-clock-DPMvTHvJ.js → calendar-clock-8W4ostX1.js} +1 -1
  49. package/dist/web/assets/{chevrons-up-down-Cpc-UgQI.js → chevrons-up-down-BboZzEAk.js} +1 -1
  50. package/dist/web/assets/{clock-3-CymPvPeM.js → clock-3-aXgeptZP.js} +1 -1
  51. package/dist/web/assets/{external-link-BL14LL_z.js → external-link-UkIIC2ds.js} +1 -1
  52. package/dist/web/assets/{folder-Cw4Tq-mf.js → folder-BOCc5dv2.js} +1 -1
  53. package/dist/web/assets/{index-BmEou5PG.js → index-DaiT-mmo.js} +15 -15
  54. package/dist/web/assets/{pause-DTcf5LF5.js → pause-DVIT6IIr.js} +1 -1
  55. package/dist/web/assets/{play-CCnbLmur.js → play-DsdF5dji.js} +1 -1
  56. package/dist/web/assets/{teamService-DbtZQ8_1.js → teamService-BliaDj1Z.js} +1 -1
  57. package/dist/web/index.html +1 -1
  58. package/package.json +1 -1
  59. package/dist/chunk-564571zs.js +0 -1
  60. package/dist/chunk-znh7k7b7.js +0 -1
@@ -1 +1 @@
1
- import{Ab as c,Eb as d,Fb as e,Gb as f,Hb as g,Ib as h,Jb as i,Kb as j,Lb as k,Sb as l,Tb as m,Ub as n,Vb as o,Xb as p,Yb as q,Zb as r,xb as a,yb as b}from"./chunk-t88z3r2s.js";import"./chunk-cnhw5mqv.js";import"./chunk-5frzn7px.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-hv6hrsnk.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-ahk6m7m7.js";import"./chunk-eyb9psbc.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-vp4ksbts.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
1
+ import{Ab as c,Eb as d,Fb as e,Gb as f,Hb as g,Ib as h,Jb as i,Kb as j,Lb as k,Sb as l,Tb as m,Ub as n,Vb as o,Xb as p,Yb as q,Zb as r,xb as a,yb as b}from"./chunk-qxsacwcs.js";import"./chunk-cnhw5mqv.js";import"./chunk-nzj1gfz9.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-hv6hrsnk.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-x7zbsjh3.js";import"./chunk-eyb9psbc.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-3hejvrgx.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,4 +1,4 @@
1
- import{m as c,n as v,o as d,p as m,q as l,r as a}from"./chunk-j5w2c7w4.js";import{Y as O,da as S}from"./chunk-5770csfs.js";import"./chunk-ypbnczjp.js";import"./chunk-2qhq6gcy.js";import"./chunk-23v8c9b8.js";import{Gb as M,Pb as E}from"./chunk-t88z3r2s.js";import"./chunk-cnhw5mqv.js";import{Fd as h,Td as f}from"./chunk-5frzn7px.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{re as I}from"./chunk-tseehebs.js";import{te as y,ue as R,ve as g}from"./chunk-a843n3ed.js";import{we as C}from"./chunk-bksfg23m.js";import"./chunk-ng96f4xd.js";import{Te as w}from"./chunk-xhz2a9a0.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-y2489d6k.js";import"./chunk-9zp4m6p8.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-ahk6m7m7.js";import"./chunk-eyb9psbc.js";import"./chunk-cawf90zq.js";import{Ch as A}from"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import{Sh as P}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-vp4ksbts.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as c,n as v,o as d,p as m,q as l,r as a}from"./chunk-x4m7ffgq.js";import{Y as O,da as S}from"./chunk-34xpxqjf.js";import"./chunk-ypbnczjp.js";import"./chunk-kk2knxx8.js";import"./chunk-23v8c9b8.js";import{Gb as M,Pb as E}from"./chunk-qxsacwcs.js";import"./chunk-cnhw5mqv.js";import{Fd as h,Td as f}from"./chunk-nzj1gfz9.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{re as I}from"./chunk-x2r1rncz.js";import{te as y,ue as R,ve as g}from"./chunk-th6mczcw.js";import{we as C}from"./chunk-bksfg23m.js";import"./chunk-ng96f4xd.js";import{Te as w}from"./chunk-68gvb58c.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-b0ffv012.js";import"./chunk-nz1kj4b2.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-x7zbsjh3.js";import"./chunk-eyb9psbc.js";import"./chunk-bqykmq8f.js";import{Ch as A}from"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import{Sh as P}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-3hejvrgx.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace 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"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1,4 +1,4 @@
1
- import{$f as L0,_f as b1,ag as z1,fg as N0}from"./chunk-cqqmkwvn.js";import{mg as jO,ng as wO}from"./chunk-9g64g1np.js";import{qg as A1}from"./chunk-935v0gpc.js";import{rg as b0,tg as J0}from"./chunk-ahk6m7m7.js";import{Ah as I0,vh as S0,wh as GO}from"./chunk-cawf90zq.js";import{Eh as u,Gh as L,Jh as c1}from"./chunk-6k5k40p8.js";import{Sh as M}from"./chunk-ecd727xh.js";import{si as k,ti as S}from"./chunk-dvv28pkc.js";import{Gi as u0}from"./chunk-vp4ksbts.js";import{Ni as N}from"./chunk-vbwvsgs1.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
1
+ import{$f as L0,_f as b1,ag as z1,fg as N0}from"./chunk-cqqmkwvn.js";import{mg as jO,ng as wO}from"./chunk-9g64g1np.js";import{qg as A1}from"./chunk-935v0gpc.js";import{rg as b0,tg as J0}from"./chunk-x7zbsjh3.js";import{Ah as I0,vh as S0,wh as GO}from"./chunk-bqykmq8f.js";import{Eh as u,Gh as L,Jh as c1}from"./chunk-6k5k40p8.js";import{Sh as M}from"./chunk-ecd727xh.js";import{si as k,ti as S}from"./chunk-dvv28pkc.js";import{Gi as u0}from"./chunk-3hejvrgx.js";import{Ni as N}from"./chunk-vbwvsgs1.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
2
2
  ${J.map((K)=>`- ${K}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4
 
@@ -1,4 +1,4 @@
1
- import{$d as F$,_d as n,ae as h_,be as D$,ce as j,de as c_,ee as f$,fe as n_,ge as z$,he as l_,ie as p_,ke as d0,ne as i_,oe as x$}from"./chunk-qdv0n8yt.js";import{tf as D0}from"./chunk-hv6hrsnk.js";import{lg as f0}from"./chunk-9g64g1np.js";import{xg as a1}from"./chunk-eyb9psbc.js";import{Kh as K$,Lh as M$,Mh as B0,Nh as g0,Oh as W0}from"./chunk-p3m1jyg5.js";import{Sh as B1}from"./chunk-ecd727xh.js";import{si as h0}from"./chunk-dvv28pkc.js";import{Ci as F0,zi as M0}from"./chunk-z52s82k7.js";import{Gi as a}from"./chunk-vp4ksbts.js";import{Qi as q$,Ri as Q0,Si as A$,Ti as x,Ui as u,Wi as A0,Xi as t,Yi as k}from"./chunk-rkdxqx8m.js";import{readdir as v_,readFile as T0,rm as G0,stat as o0}from"node:fs/promises";import*as Y from"node:path";import{nanoid as P}from"nanoid";import{createHash as u$,randomUUID as h$}from"node:crypto";import*as h from"node:fs/promises";import*as b0 from"node:path";import{execFileSync as j$}from"node:child_process";import{createHash as y$}from"node:crypto";import{readFileSync as I$}from"node:fs";var m$=/^[a-f0-9]{64}$/;function O1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&m$.test($.fingerprint)}var T1={readFile:(_)=>I$(_,"utf8"),execFile:(_,$)=>j$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},v$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function X_(_,$){return{platform:_,fingerprint:y$("sha256").update(`${_}\x00${$}`).digest("hex")}}function P$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let T=R.slice(O+2).split(/\s+/)[19];if(!T||!/^\d+$/.test(T))throw Error("Missing process start ticks");return T}function x0(_,$=process.platform,R=T1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return X_($,P$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?X_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,X=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return X?X_($,X):void 0}}catch{return}return}function X1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function j2(_,$,R=T1,O=v$){if(!Number.isInteger(_)||_<=1)return!1;let X=x0(_,$.platform,R);if(X)return X.fingerprint===$.fingerprint;return!O(_)}var C1=1;function c$(_,$){let R=u$("sha256").update($).digest("hex");return b0.join(Q0(_),".locks",`${R}.lock`)}function w0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==C1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!O1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function L1(_){let $=await L_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),L_(_)}function n$(_){try{return process.kill(_,0),!0}catch($){return w0($,"EPERM")}}async function W1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
1
+ import{$d as F$,_d as n,ae as h_,be as D$,ce as j,de as c_,ee as f$,fe as n_,ge as z$,he as l_,ie as p_,ke as d0,ne as i_,oe as x$}from"./chunk-qdv0n8yt.js";import{tf as D0}from"./chunk-hv6hrsnk.js";import{lg as f0}from"./chunk-9g64g1np.js";import{xg as a1}from"./chunk-eyb9psbc.js";import{Kh as K$,Lh as M$,Mh as B0,Nh as g0,Oh as W0}from"./chunk-p3m1jyg5.js";import{Sh as B1}from"./chunk-ecd727xh.js";import{si as h0}from"./chunk-dvv28pkc.js";import{Ci as F0,zi as M0}from"./chunk-z52s82k7.js";import{Gi as a}from"./chunk-3hejvrgx.js";import{Qi as q$,Ri as Q0,Si as A$,Ti as x,Ui as u,Wi as A0,Xi as t,Yi as k}from"./chunk-rkdxqx8m.js";import{readdir as v_,readFile as T0,rm as G0,stat as o0}from"node:fs/promises";import*as Y from"node:path";import{nanoid as P}from"nanoid";import{createHash as u$,randomUUID as h$}from"node:crypto";import*as h from"node:fs/promises";import*as b0 from"node:path";import{execFileSync as j$}from"node:child_process";import{createHash as y$}from"node:crypto";import{readFileSync as I$}from"node:fs";var m$=/^[a-f0-9]{64}$/;function O1(_){if(!_||typeof _!=="object")return!1;let $=_;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&m$.test($.fingerprint)}var T1={readFile:(_)=>I$(_,"utf8"),execFile:(_,$)=>j$(_,$,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},v$=(_)=>{try{return process.kill(_,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function X_(_,$){return{platform:_,fingerprint:y$("sha256").update(`${_}\x00${$}`).digest("hex")}}function P$(_,$){let R=$.readFile(`/proc/${_}/stat`).trim(),O=R.lastIndexOf(")");if(O<0)throw Error("Invalid /proc process stat");let T=R.slice(O+2).split(/\s+/)[19];if(!T||!/^\d+$/.test(T))throw Error("Missing process start ticks");return T}function x0(_,$=process.platform,R=T1){if(!Number.isInteger(_)||_<=1)return;try{if($==="linux")return X_($,P$(_,R));if($==="darwin"){let O=R.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return O?X_($,O):void 0}if($==="win32"){let O=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,X=R.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",O]).trim();return X?X_($,X):void 0}}catch{return}return}function X1(_,$){return x0(_,$.platform)?.fingerprint===$.fingerprint}function j2(_,$,R=T1,O=v$){if(!Number.isInteger(_)||_<=1)return!1;let X=x0(_,$.platform,R);if(X)return X.fingerprint===$.fingerprint;return!O(_)}var C1=1;function c$(_,$){let R=u$("sha256").update($).digest("hex");return b0.join(Q0(_),".locks",`${R}.lock`)}function w0(_,$){return _ instanceof Error&&"code"in _&&_.code===$}async function L_(_){try{let $=JSON.parse(await h.readFile(_,"utf8"));if($.version!==C1||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!O1($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function L1(_){let $=await L_(_);if($)return $;return await new Promise((R)=>setTimeout(R,10)),L_(_)}function n$(_){try{return process.kill(_,0),!0}catch($){return w0($,"EPERM")}}async function W1(_,$){let R;try{return R=await h.open(_,"wx",384),await R.writeFile(`${JSON.stringify($)}
2
2
  `,"utf8"),!0}catch(O){if(w0(O,"EEXIST"))return!1;if(R)await h.unlink(_).catch(()=>{return});throw O}finally{await R?.close().catch(()=>{return})}}class d extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class o{filePath;record;released=!1;constructor(_,$){this.filePath=_;this.record=$}static async acquire(_,$=B1()){let R=c$($,_),O={version:C1,sessionId:_,ownerId:h$(),pid:process.pid,processIdentity:x0(process.pid),acquiredAt:new Date().toISOString()};if(await h.mkdir(b0.dirname(R),{recursive:!0,mode:448}),await W1(R,O))return new o(R,O);let X=await L1(R);if(X&&n$(X.pid)&&(!X.processIdentity||X1(X.pid,X.processIdentity)))throw new d(X.pid);if(await h.unlink(R).catch((T)=>{if(!w0(T,"ENOENT"))throw T}),await W1(R,O))return new o(R,O);throw new d((await L1(R))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await L_(this.filePath))?.ownerId!==this.record.ownerId)return;await h.unlink(this.filePath).catch(($)=>{if(!w0($,"ENOENT"))throw $})}}import{createHash as k0}from"node:crypto";import{constants as s,promises as c}from"node:fs";import i from"node:path";import{Mutex as l$}from"async-mutex";var G1=128,V1=67108864,p$=24576,E1=65536,B_=1,H1=/^[a-f0-9]{64}$/,i$=/^[a-f0-9]{64}\.txt$/,U1=64,d$=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),j0=`
3
3
 
4
4
  ...[middle omitted; read the private prompt artifact for the complete request]...
@@ -1,2 +1,2 @@
1
- import{Gi as S}from"./chunk-vp4ksbts.js";import{_i as f}from"./chunk-tf7ezqew.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{Gi as S}from"./chunk-3hejvrgx.js";import{_i as f}from"./chunk-tf7ezqew.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as h,u as i,g as j,C as k,V as l};
@@ -1,4 +1,4 @@
1
- import{cc as M4}from"./chunk-cnhw5mqv.js";import{$c as c2,Id as u0,Kd as K6,Ld as h1,Md as Q6,Td as o$,Wc as vJ,Yc as IJ,Zc as uJ,_c as m2,ec as X$,fd as gJ,gd as T4,hd as R4,id as I2,jd as k1,kd as h4,ld as x4,md as S1,qd as DJ,yd as K1}from"./chunk-5frzn7px.js";import{Yd as S4}from"./chunk-53h87fmt.js";import{_d as H0,be as bJ,ce as v0}from"./chunk-qdv0n8yt.js";import{df as eJ}from"./chunk-pshyn3yy.js";import{ef as b4,ff as i0,gf as f4,hf as zJ,kf as E1,lf as V6,mf as BJ,nf as jJ,pf as UJ}from"./chunk-q2exry0f.js";import{$f as r0,_f as J$,cg as E4,gg as H4}from"./chunk-cqqmkwvn.js";import{tg as N$}from"./chunk-ahk6m7m7.js";import{Dh as nJ}from"./chunk-4w4wjm49.js";import{Sh as X0}from"./chunk-ecd727xh.js";import{si as k0}from"./chunk-dvv28pkc.js";import{Gi as CJ}from"./chunk-vp4ksbts.js";import{Ri as b$,Ti as r6,Ui as P0,Vi as R1,Xi as hJ,Yi as xJ,Zi as kJ}from"./chunk-rkdxqx8m.js";import{_i as L8}from"./chunk-tf7ezqew.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class A1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(f$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(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)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function b6($){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 E6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function S6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var c4=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"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!c4.has(K))break;J=Y}return J}function uZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(l4.test(K))break;J=Y}return J}var i4=[/^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 D2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of i4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var r4=new Set(["npm","pnpm","yarn","bun"]),R6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),n4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),o4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function a4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function h6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function s4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function t4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function e4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function $5($){let J=h6($.replace(o4,"").trim()),Z=t4(J);if(!Z)return;if(Z.length===0)return x6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=h6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!e4(V))return;return x6(Y)}function x6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=$5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:s4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...n4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(r4.has(Q??""))return a4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&R6.has(X??""))return!0;if(R6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function cZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var w2=k0("Agent"),J5=3;function q2($,J,Z){if($!=="length")return{action:"none"};if(J>=J5)return{action:"truncated"};if(b6(Z)==="stop")return w2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var Z5=[/:\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],W5=/```[\s\S]{50,}```/,k6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Y5=2;function G2($,J,Z=!0){if(!$||J>=Y5)return{action:"none"};if(!Z&&W5.test($))return{action:"retry",prompt:k6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(Z5.some((K)=>K.test(W)))return{action:"retry",prompt:k6};return{action:"none"}}var V5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],C6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},K5={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},Q5="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.",X5="Required verification did not run successfully before the retry limit.",H5=3;function I6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function F2($,J,Z){if(!$||!V5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>K5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=H5)return{action:"fail",message:X5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${Q5}${Q}`}}var z5=[/\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|子代理|子智能体)/],u6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function g6($){return typeof $==="string"&&u6.some((J)=>J.test($))}var B5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],j5=[/\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 U5($){if(typeof $!=="string")return;if(j5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=U5(J);if(Z!==void 0)return Z==="required"}return!1}var D5="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.",w5="Required delegation did not complete before the retry limit.",q5=3;function p6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(u6.some((Q)=>Q.test(K)))break;if(z5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};return{action:"retry",prompt:D5}}var G5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],F5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],L5=[/\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 d6($){return L5.reduce((J,Z)=>J.replace(Z," "),$)}function N1($){if(typeof $!=="string")return!1;let J=d6($);return G5.some((Z)=>Z.test(J))}var O5="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.",f5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",A5="Required worktree lifecycle did not complete before the retry limit.",y5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=d6($);if(!N1(W))return{action:"none"};let Y=F5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=y5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?O5:f5}}var v6=30000;async function L2($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??X0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),v6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return w2.warn(`[Loop] Stop hook 超时 (${v6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return w2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var P5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function _5($){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 b5($){let J=$;for(let X of P5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function c6($){return b5(_5($))}import{EventEmitter as E5}from"events";import l6 from"node:path";function O2($){if(r6($.sessionId),!l6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l6.resolve($.projectPath)}}function i6($){let J=O2($);return JSON.stringify([J.projectPath,J.sessionId])}function Z3($,J){return i6($)===i6(J)}class P$ extends E5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=O2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var n$=P$.getInstance();var t0=k0("Agent"),P1=new Set;async function S5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=c6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var f2=`<turn_aborted>
1
+ import{cc as M4}from"./chunk-cnhw5mqv.js";import{$c as c2,Id as u0,Kd as K6,Ld as h1,Md as Q6,Td as o$,Wc as vJ,Yc as IJ,Zc as uJ,_c as m2,ec as X$,fd as gJ,gd as T4,hd as R4,id as I2,jd as k1,kd as h4,ld as x4,md as S1,qd as DJ,yd as K1}from"./chunk-nzj1gfz9.js";import{Yd as S4}from"./chunk-53h87fmt.js";import{_d as H0,be as bJ,ce as v0}from"./chunk-qdv0n8yt.js";import{df as eJ}from"./chunk-pshyn3yy.js";import{ef as b4,ff as i0,gf as f4,hf as zJ,kf as E1,lf as V6,mf as BJ,nf as jJ,pf as UJ}from"./chunk-q2exry0f.js";import{$f as r0,_f as J$,cg as E4,gg as H4}from"./chunk-cqqmkwvn.js";import{tg as N$}from"./chunk-x7zbsjh3.js";import{Dh as nJ}from"./chunk-4w4wjm49.js";import{Sh as X0}from"./chunk-ecd727xh.js";import{si as k0}from"./chunk-dvv28pkc.js";import{Gi as CJ}from"./chunk-3hejvrgx.js";import{Ri as b$,Ti as r6,Ui as P0,Vi as R1,Xi as hJ,Yi as xJ,Zi as kJ}from"./chunk-rkdxqx8m.js";import{_i as L8}from"./chunk-tf7ezqew.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class A1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(f$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(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)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function b6($){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 E6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function S6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var c4=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"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!c4.has(K))break;J=Y}return J}function uZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(l4.test(K))break;J=Y}return J}var i4=[/^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 D2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of i4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var r4=new Set(["npm","pnpm","yarn","bun"]),R6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),n4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),o4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function a4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function h6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function s4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function t4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function e4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function $5($){let J=h6($.replace(o4,"").trim()),Z=t4(J);if(!Z)return;if(Z.length===0)return x6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=h6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!e4(V))return;return x6(Y)}function x6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=$5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:s4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...n4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(r4.has(Q??""))return a4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&R6.has(X??""))return!0;if(R6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function cZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var w2=k0("Agent"),J5=3;function q2($,J,Z){if($!=="length")return{action:"none"};if(J>=J5)return{action:"truncated"};if(b6(Z)==="stop")return w2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var Z5=[/:\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],W5=/```[\s\S]{50,}```/,k6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Y5=2;function G2($,J,Z=!0){if(!$||J>=Y5)return{action:"none"};if(!Z&&W5.test($))return{action:"retry",prompt:k6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(Z5.some((K)=>K.test(W)))return{action:"retry",prompt:k6};return{action:"none"}}var V5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],C6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},K5={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},Q5="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.",X5="Required verification did not run successfully before the retry limit.",H5=3;function I6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function F2($,J,Z){if(!$||!V5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>K5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=H5)return{action:"fail",message:X5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${Q5}${Q}`}}var z5=[/\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|子代理|子智能体)/],u6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function g6($){return typeof $==="string"&&u6.some((J)=>J.test($))}var B5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],j5=[/\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 U5($){if(typeof $!=="string")return;if(j5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=U5(J);if(Z!==void 0)return Z==="required"}return!1}var D5="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.",w5="Required delegation did not complete before the retry limit.",q5=3;function p6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(u6.some((Q)=>Q.test(K)))break;if(z5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};return{action:"retry",prompt:D5}}var G5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],F5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],L5=[/\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 d6($){return L5.reduce((J,Z)=>J.replace(Z," "),$)}function N1($){if(typeof $!=="string")return!1;let J=d6($);return G5.some((Z)=>Z.test(J))}var O5="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.",f5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",A5="Required worktree lifecycle did not complete before the retry limit.",y5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=d6($);if(!N1(W))return{action:"none"};let Y=F5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=y5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?O5:f5}}var v6=30000;async function L2($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??X0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),v6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return w2.warn(`[Loop] Stop hook 超时 (${v6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return w2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var P5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function _5($){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 b5($){let J=$;for(let X of P5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function c6($){return b5(_5($))}import{EventEmitter as E5}from"events";import l6 from"node:path";function O2($){if(r6($.sessionId),!l6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l6.resolve($.projectPath)}}function i6($){let J=O2($);return JSON.stringify([J.projectPath,J.sessionId])}function Z3($,J){return i6($)===i6(J)}class P$ extends E5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=O2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var n$=P$.getInstance();var t0=k0("Agent"),P1=new Set;async function S5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=c6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var f2=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",n6="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class _$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)S5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new _$("user_message",{cause:Q})}return null}async function C0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let B=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!B)throw Error("Durable assistant-message commit returned no identity");return B}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new _$("assistant_message",{cause:X})}return null}async function o6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",f2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function a6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function A2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function _1($,J,Z,W,Y,V,K,Q,X,H={}){try{let B=z$($);if(B&&J.sessionId){let j=await B.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(B){if(t0.warn("[Loop] 保存工具结果失败:",B),H.required)throw B}return null}async function a$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function D0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,B=await C0(J,Z,Y,H,V);if(B)H=B;if(Q!==void 0){let j={role:"user",content:Q};if(X)j.metadata=X;W.appendControl("user",j);let z=await l0(J,Z,j.content,H,X);if(z)H=z}return H}import{createHash as X6}from"node:crypto";import{promises as l5}from"node:fs";import i5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var s6={enabled:!0,maxIndexLines:200};var M5="memory",t6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=b$($);this.memoryDir=B$.join(W,M5)}this.config={...s6,...J}}async initialize(){if(this.initialized)return;await J0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,t6);try{let J=await J0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -160,7 +160,7 @@ ${C.reason}
160
160
 
161
161
  <system-reminder>
162
162
  Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
163
- </system-reminder>`;X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:R});continue}let O0=await W?.turnSteering?.drainOrSeal();if(O0&&O0.messages.length>0){await m$("Goal completion evidence invalidated by new user steering"),Z0=void 0,o0=!1,c0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let R=await C0($,Z,G.content||"",X,G.reasoningContent);if(R)X=R;yield{kind:"steering_applied",...await q1(O0.messages),delivery:"current_turn"};continue}let Y0=B4({requested:b0,taskAvailable:N().some((R)=>R.name==="Task"),mutationRevision:q$,verificationRevision:v$,verificationVerdict:q0,verificationFeedback:w$,verificationStallCount:u$,retryCount:H1});if(Y0.action==="retry"){if(H1++,d0=Y0.requireVerificationTask,d0)p0="Task";X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:Y0.prompt});continue}if(Y0.action==="fail")return X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),{success:!1,error:{type:"goal_verification_failed",message:Y0.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};let I=!1,y=!1;if(b0){if(!W?.goalLifecycle||q0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};y=!0}let a=j6(),n=a?.finalMessage??G.content??"",U0=a?.persistenceMetadata,O;if(y){let R=m0?.completionVerification;if(m0?.status!=="verifying"||m0.goalId!==I$||R?.status!=="pass"||R.attempt!==B1||typeof R.verifierSessionId!=="string"||R.verifierSessionId!==E0||typeof R.evidenceSha256!=="string"||R.evidenceSha256!==x0)throw Error("Goal completion lost its persisted verification receipt before finalization");O={goalId:m0.goalId,verificationAttempt:R.attempt,verifierSessionId:R.verifierSessionId,evidenceSha256:R.evidenceSha256,goalUpdatedAt:m0.updatedAt}}let f0=await K0(O),G0=U0||f0?{...U0,...f0?{turnFinalization:f0}:{}}:void 0;q.appendAssistant({role:"assistant",content:n,...G0?{metadata:x$(G0)}:{}});let Q0=await C0($,Z,n,X,U0?void 0:G.reasoningContent,G0);if(Q0)X=Q0;if(y&&W?.goalLifecycle){let R=await W.goalLifecycle.finalizeCompletion();b0=!1,I=!0,yield{kind:"goal_updated",goal:R}}if(a)yield a.event;return{success:!0,finalMessage:n,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,toolSuccessRate:Q.length>0?Q.filter((R)=>R.success).length/Q.length:void 0,totalToolFailures:b.totalFailures||void 0,...I?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...E0?{goalVerifierSessionId:E0}:{},...x0?{goalVerificationEvidenceSha256:x0}:{}}:{},...B6?{outputTruncated:!0}:{},...a?.resultMetadata}}}if(G.finishReason!=="length")n0=0;q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls});{let w=await C0($,Z,G.content||"",X,G.reasoningContent);if(w)X=w}if(W?.signal?.aborted)return B(K,Q.length,W.signal);let O1=G.toolCalls.filter((w)=>w.type==="function"),B2;if(s0?.hasTools()){l.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${O1.length} 个工具结果`);let w=s0;for(let D of w.getQueuedToolCalls()){let A=j.get(D.function.name)?.kind;yield{kind:"tool_start",toolCall:D,toolKind:A}}B2=(async()=>{let D=[];for await(let P of w.getRemainingResults())D.push(P);return D})()}else{let w=new Map,D=new Y1;for(let E of O1){let f=D.admit();if(f){w.set(E.id,f);continue}let p=Q1(E.function.arguments),C=p===null?void 0:w6(E.function.name,p);if(C){w.set(E.id,C);continue}let Y0=j.get(E.function.name)?.kind;yield{kind:"tool_start",toolCall:E,toolKind:Y0}}let P=Promise.resolve(),A=(E,f,p)=>{let C=P.then(()=>A2($,Z,E,f,X,{required:$.executionEngine!==void 0,providerToolCallId:p}));return P=C.then(()=>{return},()=>{return}),C},c=async(E)=>{let f=null;try{let p=w.get(E.id);if(p)return{toolCall:E,result:p,toolUseUuid:null};let C=Q1(E.function.arguments);if(C===null)return{toolCall:E,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${E.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};V1(E.function.name,C);try{f=await A(E.function.name,C,E.id)}catch(I){return{toolCall:E,result:{success:!1,llmContent:H$,error:{type:"execution_error",message:H$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:I instanceof Error?I:Error(String(I))}}if(E.function.name==="ExitWorktree"&&j0.has("EnterWorktree")&&!j0.has("ExitWorktree")&&F2($2,t1,0).action!=="none"){let I="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:E,result:{success:!1,llmContent:I,error:{type:"validation_error",message:I},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:f}}let Y0=await G6(E.function.name,C,{sessionId:Z.sessionId,taskListId:Z.taskListId,goalTaskListId:Z.goalTaskListId,userId:Z.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:H2,workspaceRoot:Z.workspaceRoot||X0(),environment:$.config.env,worktreeIsolationRequired:w1,worktreeActive:j0.has("EnterWorktree")&&!j0.has("ExitWorktree"),subagentType:Z.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:Z.sessionId?z0.createConfirmationHandler(Z.confirmationHandler,{sessionId:Z.sessionId,projectPath:Z.workspaceRoot||X0(),toolCallId:f??E.id,toolName:E.function.name}):Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager,onProgress:(I)=>{Y$.push({toolCall:E,update:{message:I.slice(0,1000)}})},onProgressUpdate:(I)=>{Y$.push({toolCall:E,update:I})}});return{toolCall:E,result:Y0,toolUseUuid:f}}catch(p){return l.error(`Tool execution failed for ${E.function.name}:`,p),{toolCall:E,result:{success:!1,llmContent:"",error:{type:"execution_error",message:p instanceof Error?p.message:"Unknown error"},metadata:void 0},toolUseUuid:f,error:p instanceof Error?p:Error("Unknown error")}}};B2=Promise.all(O1.map(c))}let f1,N6,P6=!1,j2=!1,p4=B2.then((w)=>{f1=w},(w)=>{P6=!0,N6=w}).finally(()=>{j2=!0,Y$.close()});while(!j2||Y$.hasPending){let w=Y$.shift()??(j2?void 0:await Y$.next());if(w)yield{kind:"tool_progress",toolCall:w.toolCall,update:w.update}}if(await p4,P6)throw N6;if(!f1)throw Error("Tool execution completed without results");let d4=new k2;for(let{toolCall:w,result:D,toolUseUuid:P}of f1){let A=w;if(Q.push(D),D.metadata?.abortedBeforeLaunch){let y=D.error?.message??"任务已被用户中止";if(P)try{let a=await _1($,Z,P,A.function.name,null,P,y,void 0,void 0,{required:$.executionEngine!==void 0});if(a)X=a}catch{return _4(K,Q.length,V)}return q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:`Error: ${y}`}),B(K,Q.length,W?.signal)}{let y=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,n=((Q0)=>Q0==="running"||Q0==="completed"||Q0==="failed"||Q0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",U0=y?.verificationVerdict==="pass"||y?.verificationVerdict==="fail"||y?.verificationVerdict==="partial"?y.verificationVerdict:void 0,O=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:A.function.name,subagentDescription:typeof y.description==="string"?y.description:void 0,subagentStatus:n,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0,subagentResumedFrom:typeof y.subagentResumedFrom==="string"?y.subagentResumedFrom:void 0,subagentRootId:typeof y.subagentRootId==="string"?y.subagentRootId:void 0,subagentResumeDepth:typeof y.subagentResumeDepth==="number"?y.subagentResumeDepth:void 0,verificationVerdict:U0}:void 0,f0=y?(()=>{let{oldContent:Q0,newContent:R,...T0}=y;return x$(T0)})():void 0;if(y?.durableToolUseFailed!==!0&&(P!==null||$.executionEngine===void 0))try{let Q0=await _1($,Z,P??A.id,A.function.name,D.success?x$(D.llmContent):null,P,D.success?void 0:D.error?.message,O,f0,{required:$.executionEngine!==void 0});if(Q0)X=Q0}catch{return _4(K,Q.length,V)}}yield{kind:"tool_result",toolCall:A,result:D};let c=await W6(A,D,$,Z);if(c){if(yield c,!Z.taskListId&&W?.goalLifecycle?.refreshFrontier){let y=await W.goalLifecycle.refreshFrontier();if(y?.ok)yield{kind:"goal_frontier_updated",goal:y.goal,frontier:y.frontier,tasks:y.tasks};else if(y){if(y.goal)yield{kind:"goal_updated",goal:y.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:y.error.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}let E,f=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,p=A.function.name==="Task"&&f?{subagentSessionId:f.subagentSessionId,subagentType:f.subagentType,subagentStatus:f.subagentStatus,subagentSummary:f.subagentSummary,subagentResumedFrom:f.subagentResumedFrom,subagentRootId:f.subagentRootId,subagentResumeDepth:f.subagentResumeDepth,verificationVerdict:f.verificationVerdict,verificationFeedback:f.verificationFeedback}:void 0;if(D.success){if(J4(b,A.function.name),f?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");b0=!0;let O=typeof f.goalCompletionAttempt==="number"?f.goalCompletionAttempt:void 0,f0=typeof f.goalCompletionRequestedAt==="string"?f.goalCompletionRequestedAt:void 0,G0=typeof f.goalId==="string"?f.goalId:void 0;if(z4({goalId:I$,attempt:B1,requestedAt:s1},{goalId:G0,attempt:O,requestedAt:f0}))H1=0,v$=-1,q0=void 0,E0=void 0,w$=void 0,U1=void 0,x0=void 0,m0=void 0;B1=O??B1,s1=f0??s1,I$=G0??I$,j1=typeof f.goalObjective==="string"?f.goalObjective:j1;let R=await W?.goalLifecycle?.getSnapshot();if(R)u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}else if(A.function.name==="UpdateGoal"&&f?.goalStatus==="blocked"){b0=!1,d0=!1,C$=!1,z1=!1,q0=void 0,v$=-1,E0=void 0,w$=void 0,U1=void 0,u$=void 0,x0=void 0,m0=void 0;let O=await W?.goalLifecycle?.getSnapshot();if(O)yield{kind:"goal_updated",goal:O}}let y=G4(d$,A.function.name,D,Z.workspaceRoot);if(y.length>0){if(Z0=void 0,o0=!1,c0=0,q$++,p$=-1,a0=void 0,X1=0,b0){H1=0,await m$("Goal completion evidence invalidated by a workspace mutation");let O=await W?.goalLifecycle?.getSnapshot();if(O)u$=O.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:O}}if(W?.goalLifecycle?.clearFrontierStall)yield{kind:"goal_updated",goal:await W.goalLifecycle.clearFrontierStall()}}let a=typeof f?.subagentType==="string"?f.subagentType:typeof f?.subagent_type==="string"?f.subagent_type:void 0,n=a===r0,U0=A.function.name==="Task"&&f?.verificationAgentBuiltin===!0&&(a===J$||n)&&(f?.subagentStatus==="completed"||f?.status==="completed");if(U0){if(a0=(f?.verificationVerdict==="pass"||f?.verificationVerdict==="fail"||f?.verificationVerdict==="partial"?f.verificationVerdict:void 0)??w4(typeof D.llmContent==="string"?D.llmContent:f?.subagentSummary&&typeof f.subagentSummary==="string"?f.subagentSummary:void 0),p$=q$,z1&&n){z1=!1,q0=a0,v$=q$,E0=typeof f?.subagentSessionId==="string"?f.subagentSessionId:void 0;let f0=typeof D.llmContent==="string"?D.llmContent.slice(0,4000):typeof f?.subagentSummary==="string"?f.subagentSummary:void 0,G0=typeof f?.verificationFeedback==="string"&&f.verificationFeedback.trim()?f.verificationFeedback.trim():void 0;if(w$=q0?G0??`Independent verifier returned ${q0.toUpperCase()}.`:void 0,U1=q0!=="pass"&&G0?X6("sha256").update(G0,"utf8").digest("hex"):void 0,q0&&W?.goalLifecycle){let Q0=JSON.stringify({goalId:I$,objective:j1,mutationRevision:q$,verdict:q0,verifierSessionId:E0,evidence:f0});x0=X6("sha256").update(Q0).digest("hex");let R=await W.goalLifecycle.recordVerification({verdict:q0,verifierSessionId:E0,summary:w$,evidenceSha256:x0,feedbackSha256:U1});m0=R,u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}}}if(y.length>0||U0)E={...y.length>0?{modifiedFiles:y}:{},...U0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...a0?{verificationVerdict:a0}:{}}:{}};if(A.function.name==="EnterWorktree"&&D.metadata?.workspaceTransition==="enter")j0.add("EnterWorktree"),j0.delete("ExitWorktree");else if(A.function.name==="ExitWorktree"&&D.metadata?.workspaceTransition==="exit"&&j0.has("EnterWorktree"))j0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(A.function.name))j0.add(A.function.name);if(A.function.name==="Task"&&D.metadata?.isolation==="worktree")j0.add("TaskWorktree");I6(t1,A.function.name,D,Z.workspaceRoot)}else Z4(b,A.function.name);let C=D.success?D.llmContent||"":yZ(A.function.name,D.error);if(!D.success){let y=W4(b,A.function.name);if(y&&typeof C==="string")C=`${C}
163
+ </system-reminder>`;X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:R});continue}let O0=await W?.turnSteering?.drainOrSeal();if(O0&&O0.messages.length>0){await m$("Goal completion evidence invalidated by new user steering"),Z0=void 0,o0=!1,c0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let R=await C0($,Z,G.content||"",X,G.reasoningContent);if(R)X=R;yield{kind:"steering_applied",...await q1(O0.messages),delivery:"current_turn"};continue}let Y0=B4({requested:b0,taskAvailable:N().some((R)=>R.name==="Task"),mutationRevision:q$,verificationRevision:v$,verificationVerdict:q0,verificationFeedback:w$,verificationStallCount:u$,retryCount:H1});if(Y0.action==="retry"){if(H1++,d0=Y0.requireVerificationTask,d0)p0="Task";X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:Y0.prompt});continue}if(Y0.action==="fail")return X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),{success:!1,error:{type:"goal_verification_failed",message:Y0.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};let I=!1,y=!1;if(b0){if(!W?.goalLifecycle||q0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};y=!0}let a=j6(),n=a?.finalMessage??G.content??"",U0=a?.persistenceMetadata,O;if(y){let R=m0?.completionVerification;if(m0?.status!=="verifying"||m0.goalId!==I$||R?.status!=="pass"||R.attempt!==B1||typeof R.verifierSessionId!=="string"||R.verifierSessionId!==E0||typeof R.evidenceSha256!=="string"||R.evidenceSha256!==x0)throw Error("Goal completion lost its persisted verification receipt before finalization");O={goalId:m0.goalId,verificationAttempt:R.attempt,verifierSessionId:R.verifierSessionId,evidenceSha256:R.evidenceSha256,goalUpdatedAt:m0.updatedAt}}let f0=await K0(O),G0=U0||f0?{...U0,...f0?{turnFinalization:f0}:{}}:void 0;q.appendAssistant({role:"assistant",content:n,...G0?{metadata:x$(G0)}:{}});let Q0=await C0($,Z,n,X,U0?void 0:G.reasoningContent,G0);if(Q0)X=Q0;if(y&&W?.goalLifecycle){let R=await W.goalLifecycle.finalizeCompletion();b0=!1,I=!0,yield{kind:"goal_updated",goal:R}}if(a)yield a.event;return{success:!0,finalMessage:n,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,toolSuccessRate:Q.length>0?Q.filter((R)=>R.success).length/Q.length:void 0,totalToolFailures:b.totalFailures||void 0,...I?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...E0?{goalVerifierSessionId:E0}:{},...x0?{goalVerificationEvidenceSha256:x0}:{}}:{},...B6?{outputTruncated:!0}:{},...a?.resultMetadata}}}if(G.finishReason!=="length")n0=0;q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls});{let w=await C0($,Z,G.content||"",X,G.reasoningContent);if(w)X=w}if(W?.signal?.aborted)return B(K,Q.length,W.signal);let O1=G.toolCalls.filter((w)=>w.type==="function"),B2;if(s0?.hasTools()){l.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${O1.length} 个工具结果`);let w=s0;for(let D of w.getQueuedToolCalls()){let A=j.get(D.function.name)?.kind;yield{kind:"tool_start",toolCall:D,toolKind:A}}B2=(async()=>{let D=[];for await(let P of w.getRemainingResults())D.push(P);return D})()}else{let w=new Map,D=new Y1;for(let E of O1){let f=D.admit();if(f){w.set(E.id,f);continue}let p=Q1(E.function.arguments),C=p===null?void 0:w6(E.function.name,p);if(C){w.set(E.id,C);continue}let Y0=j.get(E.function.name)?.kind;yield{kind:"tool_start",toolCall:E,toolKind:Y0}}let P=Promise.resolve(),A=(E,f,p)=>{let C=P.then(()=>A2($,Z,E,f,X,{required:$.executionEngine!==void 0,providerToolCallId:p}));return P=C.then(()=>{return},()=>{return}),C},c=async(E)=>{let f=null;try{let p=w.get(E.id);if(p)return{toolCall:E,result:p,toolUseUuid:null};let C=Q1(E.function.arguments);if(C===null)return{toolCall:E,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${E.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};V1(E.function.name,C);try{f=await A(E.function.name,C,E.id)}catch(I){return{toolCall:E,result:{success:!1,llmContent:H$,error:{type:"execution_error",message:H$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:I instanceof Error?I:Error(String(I))}}if(E.function.name==="ExitWorktree"&&j0.has("EnterWorktree")&&!j0.has("ExitWorktree")&&F2($2,t1,0).action!=="none"){let I="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:E,result:{success:!1,llmContent:I,error:{type:"validation_error",message:I},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:f}}let Y0=await G6(E.function.name,C,{sessionId:Z.sessionId,taskListId:Z.taskListId,goalTaskListId:Z.goalTaskListId,userId:Z.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:H2,workspaceRoot:Z.workspaceRoot||X0(),environment:$.config.env,worktreeIsolationRequired:w1,worktreeActive:j0.has("EnterWorktree")&&!j0.has("ExitWorktree"),subagentType:Z.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:Z.sessionId?z0.createConfirmationHandler(Z.confirmationHandler,{sessionId:Z.sessionId,projectPath:Z.workspaceRoot||X0(),toolCallId:f??E.id,toolName:E.function.name}):Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager,onProgress:(I)=>{Y$.push({toolCall:E,update:{message:I.slice(0,1000)}})},onProgressUpdate:(I)=>{Y$.push({toolCall:E,update:I})}});return{toolCall:E,result:Y0,toolUseUuid:f}}catch(p){return l.error(`Tool execution failed for ${E.function.name}:`,p),{toolCall:E,result:{success:!1,llmContent:"",error:{type:"execution_error",message:p instanceof Error?p.message:"Unknown error"},metadata:void 0},toolUseUuid:f,error:p instanceof Error?p:Error("Unknown error")}}};B2=Promise.all(O1.map(c))}let f1,N6,P6=!1,j2=!1,p4=B2.then((w)=>{f1=w},(w)=>{P6=!0,N6=w}).finally(()=>{j2=!0,Y$.close()});while(!j2||Y$.hasPending){let w=Y$.shift()??(j2?void 0:await Y$.next());if(w)yield{kind:"tool_progress",toolCall:w.toolCall,update:w.update}}if(await p4,P6)throw N6;if(!f1)throw Error("Tool execution completed without results");let d4=new k2;for(let{toolCall:w,result:D,toolUseUuid:P}of f1){let A=w;if(Q.push(D),D.metadata?.abortedBeforeLaunch){let y=D.error?.message??"任务已被用户中止";if(P)try{let a=await _1($,Z,P,A.function.name,null,P,y,void 0,void 0,{required:$.executionEngine!==void 0});if(a)X=a}catch{return _4(K,Q.length,V)}return q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:`Error: ${y}`}),B(K,Q.length,W?.signal)}{let y=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,n=((Q0)=>Q0==="running"||Q0==="completed"||Q0==="failed"||Q0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",U0=y?.verificationVerdict==="pass"||y?.verificationVerdict==="fail"||y?.verificationVerdict==="partial"?y.verificationVerdict:void 0,O=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:A.function.name,subagentDescription:typeof y.description==="string"?y.description:void 0,subagentStatus:n,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0,subagentResumedFrom:typeof y.subagentResumedFrom==="string"?y.subagentResumedFrom:void 0,subagentRootId:typeof y.subagentRootId==="string"?y.subagentRootId:void 0,subagentResumeDepth:typeof y.subagentResumeDepth==="number"?y.subagentResumeDepth:void 0,verificationVerdict:U0}:void 0,f0=y?(()=>{let{oldContent:Q0,newContent:R,...T0}=y;return x$(T0)})():void 0;if(y?.durableToolUseFailed!==!0&&(P!==null||$.executionEngine===void 0))try{let Q0=await _1($,Z,P??A.id,A.function.name,D.success?x$(D.llmContent):null,P,D.success?void 0:D.error?.message,O,f0,{required:$.executionEngine!==void 0});if(Q0)X=Q0}catch{return _4(K,Q.length,V)}}yield{kind:"tool_result",toolCall:A,result:D};let c=await W6(A,D,$,Z);if(c){if(yield c,!Z.taskListId&&W?.goalLifecycle?.refreshFrontier){let y=await W.goalLifecycle.refreshFrontier();if(y?.ok)yield{kind:"goal_frontier_updated",goal:y.goal,frontier:y.frontier,tasks:y.tasks};else if(y){if(y.goal)yield{kind:"goal_updated",goal:y.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:y.error.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}let E,f=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,p=A.function.name==="Task"&&f?{subagentSessionId:f.subagentSessionId,subagentType:f.subagentType,subagentStatus:f.subagentStatus,subagentSummary:f.subagentSummary,subagentResumedFrom:f.subagentResumedFrom,subagentRootId:f.subagentRootId,subagentResumeDepth:f.subagentResumeDepth,verificationVerdict:f.verificationVerdict,verificationFeedback:f.verificationFeedback}:void 0;if(D.success){if(J4(b,A.function.name),f?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");b0=!0;let O=typeof f.goalCompletionAttempt==="number"?f.goalCompletionAttempt:void 0,f0=typeof f.goalCompletionRequestedAt==="string"?f.goalCompletionRequestedAt:void 0,G0=typeof f.goalId==="string"?f.goalId:void 0;if(z4({goalId:I$,attempt:B1,requestedAt:s1},{goalId:G0,attempt:O,requestedAt:f0}))H1=0,v$=-1,q0=void 0,E0=void 0,w$=void 0,U1=void 0,x0=void 0,m0=void 0;B1=O??B1,s1=f0??s1,I$=G0??I$,j1=typeof f.goalObjective==="string"?f.goalObjective:j1;let R=await W?.goalLifecycle?.getSnapshot();if(R)u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}else if(A.function.name==="UpdateGoal"&&f?.goalStatus==="blocked"){b0=!1,d0=!1,C$=!1,z1=!1,q0=void 0,v$=-1,E0=void 0,w$=void 0,U1=void 0,u$=void 0,x0=void 0,m0=void 0;let O=await W?.goalLifecycle?.getSnapshot();if(O)yield{kind:"goal_updated",goal:O}}let y=G4(d$,A.function.name,D,Z.workspaceRoot);if(y.length>0){if(Z0=void 0,o0=!1,c0=0,q$++,p$=-1,a0=void 0,X1=0,b0){H1=0,await m$("Goal completion evidence invalidated by a workspace mutation");let O=await W?.goalLifecycle?.getSnapshot();if(O)u$=O.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:O}}if(W?.goalLifecycle?.clearFrontierStall){let O=await W.goalLifecycle.clearFrontierStall();if(O)yield{kind:"goal_updated",goal:O}}}let a=typeof f?.subagentType==="string"?f.subagentType:typeof f?.subagent_type==="string"?f.subagent_type:void 0,n=a===r0,U0=A.function.name==="Task"&&f?.verificationAgentBuiltin===!0&&(a===J$||n)&&(f?.subagentStatus==="completed"||f?.status==="completed");if(U0){if(a0=(f?.verificationVerdict==="pass"||f?.verificationVerdict==="fail"||f?.verificationVerdict==="partial"?f.verificationVerdict:void 0)??w4(typeof D.llmContent==="string"?D.llmContent:f?.subagentSummary&&typeof f.subagentSummary==="string"?f.subagentSummary:void 0),p$=q$,z1&&n){z1=!1,q0=a0,v$=q$,E0=typeof f?.subagentSessionId==="string"?f.subagentSessionId:void 0;let f0=typeof D.llmContent==="string"?D.llmContent.slice(0,4000):typeof f?.subagentSummary==="string"?f.subagentSummary:void 0,G0=typeof f?.verificationFeedback==="string"&&f.verificationFeedback.trim()?f.verificationFeedback.trim():void 0;if(w$=q0?G0??`Independent verifier returned ${q0.toUpperCase()}.`:void 0,U1=q0!=="pass"&&G0?X6("sha256").update(G0,"utf8").digest("hex"):void 0,q0&&W?.goalLifecycle){let Q0=JSON.stringify({goalId:I$,objective:j1,mutationRevision:q$,verdict:q0,verifierSessionId:E0,evidence:f0});x0=X6("sha256").update(Q0).digest("hex");let R=await W.goalLifecycle.recordVerification({verdict:q0,verifierSessionId:E0,summary:w$,evidenceSha256:x0,feedbackSha256:U1});m0=R,u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}}}if(y.length>0||U0)E={...y.length>0?{modifiedFiles:y}:{},...U0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...a0?{verificationVerdict:a0}:{}}:{}};if(A.function.name==="EnterWorktree"&&D.metadata?.workspaceTransition==="enter")j0.add("EnterWorktree"),j0.delete("ExitWorktree");else if(A.function.name==="ExitWorktree"&&D.metadata?.workspaceTransition==="exit"&&j0.has("EnterWorktree"))j0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(A.function.name))j0.add(A.function.name);if(A.function.name==="Task"&&D.metadata?.isolation==="worktree")j0.add("TaskWorktree");I6(t1,A.function.name,D,Z.workspaceRoot)}else Z4(b,A.function.name);let C=D.success?D.llmContent||"":yZ(A.function.name,D.error);if(!D.success){let y=W4(b,A.function.name);if(y&&typeof C==="string")C=`${C}
164
164
 
165
165
  ${y}`}if(typeof C==="object"&&C!==null)C=JSON.stringify(C,null,2);if(typeof C==="string")C=NJ(C,A.function.name,{messageBudget:d4});let O0=typeof C==="string"?C:JSON.stringify(C);if(q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:S4(D,O0),...A.function.name==="Task"||E?{metadata:x$({toolCallId:A.id,toolName:A.function.name,error:D.success?null:D.error?.message??null,...p?{metadata:p}:{},...E?{independentVerification:E}:{}})}:{}}),f?.durableToolUseFailed===!0)return{success:!1,error:{type:"tool_persistence_failed",message:H$,details:D.error},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let Y0=Q1(A.function.arguments)??{},I=q6(A.function.name,Y0,D);if(I&&I.files.length>0){for(let n of I.references)_.add(n.id);let y={role:"system",content:I.content,metadata:x$({contextualProjectRules:!0,ruleReferences:I.references,triggerPaths:I.triggerPaths})};q.appendContextualProjectInstructions(y);let a=await a6($,Z,I.references,I.triggerPaths,X);if(a)X=a;yield{kind:"project_rules_loaded",files:I.files.map((n)=>({id:n.id,relativePath:n.relativePath,source:n.source,conditional:n.conditional,contentSha256:n.contentSha256})),triggerPaths:I.triggerPaths,blockedWrite:D.metadata?.contextualProjectRulesRequired===!0}}if(A.function.name===u0&&D.metadata?.structuredOutputRetryExhausted===!0)return{success:!1,error:{type:"structured_output_failed",message:D.error?.message??"Structured output validation retry budget was exhausted."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,structuredOutputSchemaDigest:U?.schemaDigest}};if(W?.signal?.aborted)return B(K,Q.length,W.signal);if(D.metadata?.shouldExitLoop){let y=typeof D.llmContent==="string"?D.llmContent:"循环已退出";return{success:D.success,finalMessage:y,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,shouldExitLoop:!0,targetMode:D.metadata?.targetMode,planContent:typeof D.metadata?.planContent==="string"?D.metadata.planContent:void 0}}}}let V$=n2(M,O1,f1.map(({result:w})=>w));if(V$){if(yield{kind:"action_stationarity",...V$},V$.phase==="halted")return{success:!1,error:{type:"loop_detected",message:`Stopped after ${V$.runLength} repeated ${V$.toolName} calls without observable progress.`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}};if(V$.phase==="detected"){let w={role:"user",content:`
166
166
 
@@ -1,4 +1,4 @@
1
- import{we as s}from"./chunk-bksfg23m.js";import{Pe as o}from"./chunk-xhz2a9a0.js";import{$g as y,Ah as l,Bh as n,ah as D,ch as N,eh as j,fh as F,hh as R,lh as E,mh as _,nh as f,oh as C,qh as S,rh as m,vh as c}from"./chunk-cawf90zq.js";import{Ch as Y}from"./chunk-4w4wjm49.js";import{Eh as x,Gh as k,Jh as Z}from"./chunk-6k5k40p8.js";import{Qh as X}from"./chunk-ecd727xh.js";import{$h as P,Uh as h,Vh as A,ai as T,ci as $,di as U,ei as G,gi as L,hi as M,ji as O,ki as I}from"./chunk-x05zyqzf.js";import{si as d}from"./chunk-dvv28pkc.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{we as s}from"./chunk-bksfg23m.js";import{Pe as o}from"./chunk-68gvb58c.js";import{$g as y,Ah as l,Bh as n,ah as D,ch as N,eh as j,fh as F,hh as R,lh as E,mh as _,nh as f,oh as C,qh as S,rh as m,vh as c}from"./chunk-bqykmq8f.js";import{Ch as Y}from"./chunk-4w4wjm49.js";import{Eh as x,Gh as k,Jh as Z}from"./chunk-6k5k40p8.js";import{Qh as X}from"./chunk-ecd727xh.js";import{$h as P,Uh as h,Vh as A,ai as T,ci as $,di as U,ei as G,gi as L,hi as M,ji as O,ki as I}from"./chunk-x05zyqzf.js";import{si as d}from"./chunk-dvv28pkc.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1,4 +1,4 @@
1
- import{Pe as N}from"./chunk-xhz2a9a0.js";import{tg as $}from"./chunk-ahk6m7m7.js";import{Sh as _}from"./chunk-ecd727xh.js";import{qi as Y,si as Z}from"./chunk-dvv28pkc.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Pe as N}from"./chunk-68gvb58c.js";import{tg as $}from"./chunk-x7zbsjh3.js";import{Sh as _}from"./chunk-ecd727xh.js";import{qi as Y,si as Z}from"./chunk-dvv28pkc.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as xe,y as ye,j as ze,C as Ae};
@@ -1,2 +1,2 @@
1
- import{Gi as d,Ii as h}from"./chunk-vp4ksbts.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{Gi as d,Ii as h}from"./chunk-3hejvrgx.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as re,w as se};
@@ -1,4 +1,4 @@
1
- import{ta as F,va as L}from"./chunk-5770csfs.js";import{Jd as $,Ld as B,Td as Q}from"./chunk-5frzn7px.js";import{Vf as y}from"./chunk-9zp4m6p8.js";import{Sh as V}from"./chunk-ecd727xh.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{ta as F,va as L}from"./chunk-34xpxqjf.js";import{Jd as $,Ld as B,Td as Q}from"./chunk-nzj1gfz9.js";import{Vf as y}from"./chunk-nz1kj4b2.js";import{Sh as V}from"./chunk-ecd727xh.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as m,I as n,M as o,R as p,_ as q,C as r};
@@ -25,7 +25,7 @@ import{xg as YO}from"./chunk-eyb9psbc.js";import{Eh as qO,Gh as S,Jh as y}from".
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-7fkvpysw.js"),{createChatServiceAsync:W}=await import("./chunk-wyw17nfy.js"),{resolveModelConfig:J}=await import("./chunk-25ps9fxw.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-tsbyhb62.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-fhdrx7e9.js"),{createChatServiceAsync:W}=await import("./chunk-wyw17nfy.js"),{resolveModelConfig:J}=await import("./chunk-25ps9fxw.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-2h37sdgt.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -1 +1 @@
1
- import{h as o}from"./chunk-556e469e.js";import"./chunk-vp4ksbts.js";import"./chunk-tf7ezqew.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{h as o}from"./chunk-pq8bncc1.js";import"./chunk-3hejvrgx.js";import"./chunk-tf7ezqew.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1 +1 @@
1
- import{te as a,ue as b,ve as c}from"./chunk-a843n3ed.js";import"./chunk-bksfg23m.js";import"./chunk-xhz2a9a0.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-935v0gpc.js";import"./chunk-cawf90zq.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-vp4ksbts.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{te as a,ue as b,ve as c}from"./chunk-th6mczcw.js";import"./chunk-bksfg23m.js";import"./chunk-68gvb58c.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-935v0gpc.js";import"./chunk-bqykmq8f.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-3hejvrgx.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -0,0 +1 @@
1
+ import{h as a,i as b,j as c,k as d,l as e}from"./chunk-pq8bncc1.js";import"./chunk-3hejvrgx.js";import"./chunk-tf7ezqew.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};