blade-code 0.10.40 → 0.10.41

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 (91) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-zwt7f9ab.js → chunk-01jt0mpr.js} +1 -1
  3. package/dist/{chunk-zfn7w33a.js → chunk-0hqsdbkr.js} +1 -1
  4. package/dist/chunk-1j2sf8mc.js +1 -0
  5. package/dist/chunk-1kwm2m6t.js +1 -0
  6. package/dist/{chunk-8jexqfqg.js → chunk-22h5kh4z.js} +1 -1
  7. package/dist/{chunk-vtb0m80j.js → chunk-27w2k6t7.js} +1 -1
  8. package/dist/{chunk-x6c6yqpx.js → chunk-2bm55evt.js} +2 -2
  9. package/dist/{chunk-mc42kjv9.js → chunk-358zaryv.js} +2 -2
  10. package/dist/{chunk-qggnvzkc.js → chunk-3p32k12g.js} +1 -1
  11. package/dist/chunk-4ekrbk2w.js +2 -0
  12. package/dist/{chunk-4wk9cc2b.js → chunk-4mdy9d43.js} +1 -1
  13. package/dist/{chunk-ew5dmar1.js → chunk-5sbewyjn.js} +2 -2
  14. package/dist/chunk-5w8edqbt.js +1 -0
  15. package/dist/{chunk-p504jme7.js → chunk-5ygv33qe.js} +2 -2
  16. package/dist/{chunk-h188kz0p.js → chunk-5zf8204m.js} +1 -1
  17. package/dist/{chunk-3w64mkc3.js → chunk-62jaf7ej.js} +2 -2
  18. package/dist/chunk-6a3c496e.js +1 -0
  19. package/dist/{chunk-vs7tcyse.js → chunk-6dma8han.js} +2 -2
  20. package/dist/chunk-6fe9kq17.js +1 -0
  21. package/dist/{chunk-1hea2ad2.js → chunk-8xfzbv9v.js} +1 -1
  22. package/dist/{chunk-ts3pgkmz.js → chunk-9neq5xrb.js} +2 -2
  23. package/dist/{chunk-74jd1hcs.js → chunk-adgx9vd7.js} +2 -2
  24. package/dist/chunk-asnzpfzh.js +10 -0
  25. package/dist/chunk-atdeg922.js +2 -0
  26. package/dist/{chunk-93jx06kq.js → chunk-b5b8fb9y.js} +1 -1
  27. package/dist/{chunk-3azdwanx.js → chunk-bdxaz350.js} +1 -1
  28. package/dist/{chunk-hpqhk0jf.js → chunk-bw7fgs2n.js} +1 -1
  29. package/dist/{chunk-dhsdn91x.js → chunk-ck8sw2zp.js} +1 -1
  30. package/dist/chunk-d61673v7.js +5 -0
  31. package/dist/{chunk-ydz6bvs1.js → chunk-djr17h80.js} +1 -1
  32. package/dist/{chunk-nxc705wc.js → chunk-dp9xzsja.js} +1 -1
  33. package/dist/{chunk-xtfy56qh.js → chunk-eg5sz4bw.js} +1 -1
  34. package/dist/{chunk-ckfc7j7m.js → chunk-ens8nsge.js} +1 -1
  35. package/dist/{chunk-keart8yy.js → chunk-f4bx2n1y.js} +3 -3
  36. package/dist/chunk-f7y4m3y0.js +1 -0
  37. package/dist/chunk-fnz5g9ac.js +1 -0
  38. package/dist/{chunk-3rjmkaey.js → chunk-fxw1q5j5.js} +1 -1
  39. package/dist/{chunk-fk8jf873.js → chunk-fz55cnws.js} +2 -2
  40. package/dist/{chunk-6360fg4j.js → chunk-g9re8v25.js} +1 -1
  41. package/dist/{chunk-a7pvtxvz.js → chunk-gbbnjzy8.js} +1 -1
  42. package/dist/{chunk-4p8sp6p3.js → chunk-hjkdc185.js} +1 -1
  43. package/dist/chunk-kjn0yaqw.js +1 -0
  44. package/dist/chunk-m883e8d4.js +1 -0
  45. package/dist/chunk-mx5s93np.js +6 -0
  46. package/dist/{chunk-hq18c6r9.js → chunk-n0ebpwxd.js} +1 -1
  47. package/dist/chunk-nhzdkxnx.js +2 -0
  48. package/dist/{chunk-03bzxkdg.js → chunk-npgt73cg.js} +1 -1
  49. package/dist/{chunk-dhcm8958.js → chunk-nsawkccy.js} +1 -1
  50. package/dist/chunk-p54vmne8.js +1 -0
  51. package/dist/{chunk-zv9jxwdp.js → chunk-q87nwpsb.js} +1 -1
  52. package/dist/chunk-qy9qkvwe.js +1 -0
  53. package/dist/chunk-s8f8amvg.js +1 -0
  54. package/dist/{chunk-k2hzhw9f.js → chunk-sfbprf9r.js} +1 -1
  55. package/dist/{chunk-np8f17zg.js → chunk-t80e2bms.js} +1 -1
  56. package/dist/{chunk-v11r4ahz.js → chunk-tsskar00.js} +1 -1
  57. package/dist/{chunk-34cexc50.js → chunk-v80xem15.js} +1 -1
  58. package/dist/chunk-w07gb3h0.js +6 -0
  59. package/dist/{chunk-rs43m9d9.js → chunk-w1vcjwbx.js} +3 -3
  60. package/dist/{chunk-4dq8rbq2.js → chunk-wk0vpgwk.js} +198 -198
  61. package/dist/{chunk-9wxj0gxa.js → chunk-wvc6bx0t.js} +1 -1
  62. package/dist/{chunk-8kqnezvc.js → chunk-x04xb9g3.js} +1 -1
  63. package/dist/chunk-x5s68axq.js +44 -0
  64. package/dist/{chunk-rb1fv7en.js → chunk-xs7w13na.js} +1 -1
  65. package/dist/{chunk-0evyrnx0.js → chunk-y30kw6gj.js} +1 -1
  66. package/dist/{chunk-0s11h8yd.js → chunk-yhw0pvyt.js} +2 -2
  67. package/dist/{chunk-2fgmsnh6.js → chunk-yxwargqc.js} +1 -1
  68. package/dist/chunk-z15h0370.js +1 -0
  69. package/dist/{chunk-7qj2tbew.js → chunk-zracmha2.js} +1 -1
  70. package/package.json +1 -1
  71. package/dist/chunk-0442z8f4.js +0 -1
  72. package/dist/chunk-2b4h0nb5.js +0 -1
  73. package/dist/chunk-3nj2f0q9.js +0 -2
  74. package/dist/chunk-9dxkfqxg.js +0 -10
  75. package/dist/chunk-bqpqh6re.js +0 -2
  76. package/dist/chunk-fa1gxd12.js +0 -1
  77. package/dist/chunk-h7bat4ws.js +0 -1
  78. package/dist/chunk-h9620q2d.js +0 -1
  79. package/dist/chunk-kpr5nqh2.js +0 -5
  80. package/dist/chunk-nzyc8z6k.js +0 -6
  81. package/dist/chunk-px491bge.js +0 -1
  82. package/dist/chunk-r01spp7a.js +0 -1
  83. package/dist/chunk-s3nz9qx8.js +0 -1
  84. package/dist/chunk-thstqcg3.js +0 -2
  85. package/dist/chunk-v53vv0e9.js +0 -6
  86. package/dist/chunk-v85q852a.js +0 -44
  87. package/dist/chunk-vtdg5cb1.js +0 -1
  88. package/dist/chunk-vv0vk8bp.js +0 -1
  89. package/dist/chunk-w69qkark.js +0 -1
  90. package/dist/chunk-xpmr9bf7.js +0 -1
  91. package/dist/chunk-y10jqqyg.js +0 -1
@@ -0,0 +1 @@
1
+ import{Ag as a,Bg as b,Cg as c,Dg as d,Eg as e,Fg as f}from"./chunk-358zaryv.js";import"./chunk-22h5kh4z.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,4 +1,4 @@
1
- import{re as L1,se as Z0,te as G1}from"./chunk-hq18c6r9.js";import{xe as $O,ye as HO}from"./chunk-zwt7f9ab.js";import{Be as Y1}from"./chunk-ckfc7j7m.js";import{Ce as B0,Ee as M0}from"./chunk-keart8yy.js";import{nf as V0,of as o1,yf as S0}from"./chunk-v85q852a.js";import{Bf as u,Df as W,Gf as R1}from"./chunk-93jx06kq.js";import{Nf as b}from"./chunk-6360fg4j.js";import{ig as h,jg as z}from"./chunk-fk8jf873.js";import{wg as p0}from"./chunk-mc42kjv9.js";import{Bg as w}from"./chunk-ew5dmar1.js";import J1 from"node:path";import Y$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import zO from"yaml";var u$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function c$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
1
+ import{se as L1,te as Z0,ue as G1}from"./chunk-n0ebpwxd.js";import{ye as $O,ze as HO}from"./chunk-01jt0mpr.js";import{Ce as Y1}from"./chunk-ens8nsge.js";import{De as B0,Fe as M0}from"./chunk-f4bx2n1y.js";import{of as V0,pf as o1,zf as S0}from"./chunk-x5s68axq.js";import{Cf as u,Ef as W,Hf as R1}from"./chunk-b5b8fb9y.js";import{Of as b}from"./chunk-g9re8v25.js";import{ng as h,og as z}from"./chunk-fz55cnws.js";import{Bg as p0}from"./chunk-358zaryv.js";import{Gg as w}from"./chunk-5sbewyjn.js";import J1 from"node:path";import Y$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import zO from"yaml";var u$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function c$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -707,4 +707,4 @@ ${q.join(`
707
707
  </${Q}>`:"";return{content:J,files:[...O],references:O.map(k$),triggerPaths:[...$],contentBytes:Buffer.byteLength(J,"utf8"),provenanceSha256:_0(O.map((K)=>`${K.id}:${K.contentSha256}`).join(`
708
708
  `))}}function WO(O,$){let Q=$,q=[];for(let Z=O.length-1;Z>=0;Z-=1){let J=O[Z];if(!J)continue;let K=Buffer.byteLength(J.content,"utf8");if(K>Q)continue;q.push(J),Q-=K}return q.reverse()}class d{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=O1(O),this.definitions=Object.freeze([...$].sort(Q1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=_0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
709
709
  `))}static empty(O){return new d(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new d(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=T$){if(this.definitions.length===0)return $0([],[],"project-instructions");let Q=this.relativeSourcePath(O),q=this.definitions.filter((Z)=>!Z.conditional&&$1(Z.scopeDirectory,Q));return $0(WO(q,$),[],"project-instructions")}contextualRules(O,$,Q,q=C$){if(this.definitions.length===0)return $0([],[],"contextual-project-instructions");let Z=this.relativeSourcePath(O),J=[...new Set($.map((G)=>q1(B.relative(this.projectRoot,O1(G)))).filter(Z1))].sort(),K=new Map;for(let G of J)for(let L of this.definitions){if(Q.has(L.id))continue;if(!$1(L.scopeDirectory,G))continue;if(L.conditional){let Y=B.posix.relative(L.scopeDirectory||".",G);if(!L.patterns?.some((V)=>XO(V,{dot:!0})(Y)))continue}else if($1(L.scopeDirectory,Z))continue;K.set(L.id,L)}let X=WO([...K.values()].sort(Q1),q);return $0(X,J,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let q=this.byId.get(Q.id);if(!q||q.contentSha256!==Q.contentSha256||q.relativePath!==Q.relativePath||q.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return q});return $0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(Q1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=q1(B.relative(this.projectRoot,O1(O)));if($&&!Z1($))throw Error("Project instruction source is outside the catalog root");return $}}async function P$(O,$){let Q=await m.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>ZO)throw Error(`Project rule exceeds ${ZO} bytes`);let q=await m.realpath($),Z=q1(B.relative(O,q));if(!Z1(Z))throw Error("Project rule escapes its repository root");let J=await m.readFile(q,"utf8");if(LO(J))throw Error("Project rule contains hidden control characters");let K=w$(J),X=K.content.trim();if(!X)throw Error("Project rule content must not be empty");let G=f$(K.data.paths),L=h$(Z),Y=_0(JSON.stringify({relativePath:Z,patterns:G??[],content:X}));return{id:`${L.source}:${_0(Z).slice(0,20)}`,relativePath:Z,source:L.source,kind:L.kind,scopeDirectory:L.scopeDirectory,priority:L.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:X,contentSha256:Y}}async function YO(O,$){let Q=E$(O);if(!$.projectTrusted)return d.empty(Q);let q=await m.realpath(Q),Z=_$.stream([...y$],{cwd:q,absolute:!0,dot:!0,deep:D$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...v$]}),J=[];for await(let L of Z)if(J.push(L.toString()),J.length>qO)throw Error(`Project rule catalog exceeds ${qO} files`);J.sort();let K=new Set(J.filter((L)=>B.basename(L)==="AGENTS.override.md").map((L)=>B.dirname(L))),X=[],G=0;for(let L of J){if(B.basename(L)==="AGENTS.md"&&K.has(B.dirname(L)))continue;try{let Y=await P$(q,L);if(G+=Buffer.byteLength(Y.content,"utf8"),G>JO)throw Error(`Project rule catalog exceeds ${JO} bytes`);X.push(Y)}catch(Y){R$.warn(`[ProjectRules] Ignoring rule: ${Y instanceof Error?Y.message:String(Y)}`)}}return new d(q,X)}var Q0=new Map,FO=[];async function p$(O){let $=await w.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await e0(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function d$(O){let $={...O};for(let Q of Object.values(B0))$[Q]=(O[Q]??[]).map((q)=>({...q,matcher:q.matcher?{...q.matcher}:void 0,hooks:q.hooks.map((Z)=>({...Z}))}));return $}function f2(O){FO=[...new Set(O.map(($)=>J1.resolve($)))]}async function h2(O,$={}){let Q=J1.resolve(O),q=Q0.get(Q);if(!q)q=(async()=>{let J=await w.getInstance().getStatus(Q),K=i(Q),X=P({cwd:Q}),G=T.getInstance(Q),L=z0(Q);if(K.getAllNames().length===0)K.loadFromStandardLocations(J.state==="trusted");await Promise.all([X.initialize(),G.isInitialized()?void 0:G.initialize(Q),L.isInitialized()?void 0:L.initialize(Q,[...$.cliPluginDirs??FO])]),x0(Q),await a0(Q);let Y=await e0(Q,{projectTrusted:J.state==="trusted",plugins:L.getActive()}),V=await YO(Q,{projectTrusted:J.state==="trusted"});return{workspaceRoot:Q,subagents:K,skills:X,commands:G,plugins:L,communicationStyles:Y,projectRules:V}})().catch((J)=>{throw Q0.delete(Q),J}),Q0.set(Q,q);let Z=await q;if($.reconcilePlugins)x0(Q),await a0(Q),await p$(Z);return Z}function k2(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:J1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??HO.snapshot(),projectRules:O.projectRules?.snapshot()??d.empty($),hooks:d$("hooks"in O&&O.hooks?O.hooks:M0.getInstance().getConfig($))}}function P2(){for(let O of Q0.keys())x0(O);Q0.clear(),v.resetInstances(),k.resetInstance(),T.resetInstance(),f.resetInstance()}
710
- export{u$ as Wd,c$ as Xd,W1 as Yd,i$ as Zd,t$ as _d,i as $d,H4 as ae,U1 as be,P as ce,DO as de,T as ee,o0 as fe,j0 as ge,f as he,z0 as ie,a0 as je,x0 as ke,d as le,p$ as me,f2 as ne,h2 as oe,k2 as pe,P2 as qe};
710
+ export{u$ as Xd,c$ as Yd,W1 as Zd,i$ as _d,t$ as $d,i as ae,H4 as be,U1 as ce,P as de,DO as ee,T as fe,o0 as ge,j0 as he,f as ie,z0 as je,a0 as ke,x0 as le,d as me,p$ as ne,f2 as oe,h2 as pe,k2 as qe,P2 as re};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-sfbprf9r.js";import"./chunk-358zaryv.js";import"./chunk-22h5kh4z.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,4 +1,4 @@
1
- import{ra as H}from"./chunk-9wxj0gxa.js";import"./chunk-5cgyevqj.js";import"./chunk-qgez5vw6.js";import{Fd as T,zd as $}from"./chunk-vtb0m80j.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-keart8yy.js";import"./chunk-v11r4ahz.js";import"./chunk-v85q852a.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as k}from"./chunk-6360fg4j.js";import"./chunk-bqpqh6re.js";import"./chunk-fk8jf873.js";import"./chunk-p504jme7.js";import"./chunk-8kqnezvc.js";import"./chunk-mc42kjv9.js";import"./chunk-ew5dmar1.js";import"./chunk-03bzxkdg.js";import"./chunk-ts3pgkmz.js";import"./chunk-8jexqfqg.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ra as H}from"./chunk-wvc6bx0t.js";import"./chunk-5cgyevqj.js";import"./chunk-qgez5vw6.js";import{Fd as T,zd as $}from"./chunk-27w2k6t7.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-f4bx2n1y.js";import"./chunk-tsskar00.js";import"./chunk-x5s68axq.js";import"./chunk-gbbnjzy8.js";import"./chunk-b5b8fb9y.js";import"./chunk-atdeg922.js";import{Of as k}from"./chunk-g9re8v25.js";import"./chunk-nhzdkxnx.js";import"./chunk-fz55cnws.js";import"./chunk-5ygv33qe.js";import"./chunk-x04xb9g3.js";import"./chunk-358zaryv.js";import"./chunk-5sbewyjn.js";import"./chunk-npgt73cg.js";import"./chunk-9neq5xrb.js";import"./chunk-22h5kh4z.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -1,2 +1,2 @@
1
- import{Ng as F}from"./chunk-8jexqfqg.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
2
- export{M as Dg,z as Eg,J as Fg,A as Gg,N as Hg,O as Ig,Q as Jg,T as Kg,E as Lg,U as Mg};
1
+ import{Sg as F}from"./chunk-22h5kh4z.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
2
+ export{M as Ig,z as Jg,J as Kg,A as Lg,N as Mg,O as Ng,Q as Og,T as Pg,E as Qg,U as Rg};
@@ -1,4 +1,4 @@
1
- import{Eb as HJ}from"./chunk-5cgyevqj.js";import{Fb as l0,Mb as O6,Nb as U6,Ob as $2,Pb as J2,Wb as H6,cc as C$,mc as y0,oc as G2,pc as X1,qc as O2,xc as f$}from"./chunk-7qj2tbew.js";import{Cc as t,Fc as D6,Gc as O0}from"./chunk-3azdwanx.js";import{Gd as T6}from"./chunk-atsw605q.js";import{Hd as ZJ,Id as C0,Jd as a6,Kd as WJ,Ld as q2,Nd as Y6}from"./chunk-kpr5nqh2.js";import{re as v0,se as A0,ve as YJ}from"./chunk-hq18c6r9.js";import{Ee as Z$}from"./chunk-keart8yy.js";import{Nf as a}from"./chunk-6360fg4j.js";import{ig as G0}from"./chunk-fk8jf873.js";import{wg as G6}from"./chunk-mc42kjv9.js";import{Eg as H$,Gg as a2,Hg as z0,Ig as K1,Kg as L6,Mg as q6}from"./chunk-ts3pgkmz.js";import{Ng as _8}from"./chunk-8jexqfqg.js";function $$($){return $.role==="system"&&Array.isArray($.content)}function e0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find($$);if(this._contextualSystemMessages=$.messages.filter(e0),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)=>!$$(W)&&!e0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!e0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter($$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!$$(J)&&!e0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(e0),this._history=$.filter((J)=>!$$(J)&&!e0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function x2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function h2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var wJ=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"]),LJ=/^(LD_.+|DYLD_.+|PATH)$/,R2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function S$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(!wJ.has(K))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(LJ.test(K))break;J=Y}return J}var qJ=[/^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 I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of qJ){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 s$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){Z+=X,H=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function C2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let H=$[Y];if(W){W=!1;continue}if(H==="\\"&&!J){W=!0;continue}if(H==="'"&&!Z){J=!J;continue}if(H==='"'&&!J){Z=!Z;continue}if(J)continue;if(H==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(H==="`")return!0;if(Z)continue;if(H==="|")return!0;if(H===">"||H==="<")return!0;if(H==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function A$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){if(H=!0,Y){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,H=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var GJ=new Set(["npm","pnpm","yarn","bun"]),I2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),OJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function UJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function yJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function FJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=A$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let H=Y[1];if(!H||H==="-")return;let K=i0.isAbsolute(H)?i0.resolve(H):i0.resolve(Z,H);if(!l0.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function J$($,J){let Z=S$(yJ($)),W=s$(Z);if(!W||C2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:FJ(Z,W,J);if(!Y)return!1;let H=A$(Y);if(H.length===0||H.some((z)=>[...OJ].some((j)=>z===j||z.startsWith(`${j}=`))))return!1;let[K,X,Q]=H;if(GJ.has(K??""))return UJ(X==="run"?Q:X)||X==="--test";if((K==="npx"||K==="bunx")&&I2.has(X??""))return!0;if(I2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=G0("Agent"),_J=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=_J)return{action:"truncated"};if(x2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var bJ=[/:\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],NJ=/```[\s\S]{50,}```/,v2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",PJ=2;function g1($,J,Z=!0){if(!$||J>=PJ)return{action:"none"};if(!Z&&NJ.test($))return{action:"retry",prompt:v2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(bJ.some((K)=>K.test(W)))return{action:"retry",prompt:v2};return{action:"none"}}var SJ=[/\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}(?:测试|单测|集成测试|检查|构建)/],p2={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},AJ={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},EJ="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.",fJ="Required verification did not run successfully before the retry limit.",TJ=3;function m2($,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&&J$(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 H of Y)if(typeof H==="string"&&J$(H,W))$.add(H)}function m1($,J,Z){if(!$||!SJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(p2).filter((Q)=>p2[Q].test($)),Y=[...J],H=W.filter((Q)=>!Y.some((z)=>AJ[Q].test(z)));if(W.length>0?H.length===0:Y.some((Q)=>J$(Q)))return{action:"none"};if(Z>=TJ)return{action:"fail",message:fJ};let X=W.length>1&&H.length>0?` Missing successful verification categories: ${H.join(", ")}.`:"";return{action:"retry",prompt:`${EJ}${X}`}}var kJ=[/\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|子代理|子智能体)/],u2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function d2($){return typeof $==="string"&&u2.some((J)=>J.test($))}var xJ=[/\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|子代理)/],MJ=[/\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 hJ($){if(typeof $!=="string")return;if(MJ.some((J)=>J.test($)))return"multiple-allowed";return xJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=hJ(J);if(Z!==void 0)return Z==="required"}return!1}var RJ="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.",CJ="Required delegation did not complete before the retry limit.",IJ=3;function c2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),H=!1;if(!Y)for(let K of W){if(u2.some((X)=>X.test(K)))break;if(kJ.some((X)=>X.test(K))){H=!0;break}}if(W.length===0||!Y&&!H||J.has("Task"))return{action:"none"};if(Z>=IJ)return{action:"fail",message:CJ};return{action:"retry",prompt:RJ}}var vJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],pJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],gJ=[/\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 i2($){return gJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=i2($);return vJ.some((Z)=>Z.test(J))}var mJ="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.",uJ="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.",dJ="Required worktree lifecycle did not complete before the retry limit.",cJ=3;function l2($,J,Z){if(!$)return{action:"none"};let W=i2($);if(!$1(W))return{action:"none"};let Y=pJ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let H=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!H)return{action:"none"};if(Z>=cJ)return{action:"fail",message:dJ};return{action:"retry",tool:H,prompt:H==="EnterWorktree"?mJ:uJ}}var g2=30000;async function u1($){try{let Z=Z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((H)=>{W=setTimeout(()=>H("timeout"),g2)});try{let H=await Promise.race([Z,Y]);if(H==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=H;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function iJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var lJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function rJ($){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 nJ($){let J=$;for(let Q of lJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let H=Y.slice(0,60),K=H.lastIndexOf(" ");return`${(K>36?H.slice(0,K):H).trimEnd()}…`}function r2($){return nJ(rJ($))}import{EventEmitter as oJ}from"events";import n2 from"node:path";function d1($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return o2($)===o2(J)}class W$ extends oJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}publish($,J,Z,W){let Y=d1($);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 E$=W$.getInstance();var M0=G0("Agent"),J1=new Set;async function aJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let H=r2(J);if(!H)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:H}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:H})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
1
+ import{Eb as HJ}from"./chunk-5cgyevqj.js";import{Fb as l0,Mb as O6,Nb as U6,Ob as $2,Pb as J2,Wb as H6,cc as C$,mc as y0,oc as G2,pc as X1,qc as O2,xc as f$}from"./chunk-zracmha2.js";import{Cc as t,Fc as D6,Gc as O0}from"./chunk-bdxaz350.js";import{Gd as T6}from"./chunk-atsw605q.js";import{Hd as ZJ,Id as C0,Jd as a6,Ld as WJ,Md as q2,Od as Y6}from"./chunk-d61673v7.js";import{se as v0,te as A0,we as YJ}from"./chunk-n0ebpwxd.js";import{Fe as Z$}from"./chunk-f4bx2n1y.js";import{Of as a}from"./chunk-g9re8v25.js";import{ng as G0}from"./chunk-fz55cnws.js";import{Bg as G6}from"./chunk-358zaryv.js";import{Jg as H$,Lg as a2,Mg as z0,Ng as K1,Pg as L6,Rg as q6}from"./chunk-9neq5xrb.js";import{Sg as _8}from"./chunk-22h5kh4z.js";function $$($){return $.role==="system"&&Array.isArray($.content)}function e0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find($$);if(this._contextualSystemMessages=$.messages.filter(e0),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)=>!$$(W)&&!e0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!e0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter($$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!$$(J)&&!e0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(e0),this._history=$.filter((J)=>!$$(J)&&!e0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function x2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function M2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function h2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var wJ=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"]),LJ=/^(LD_.+|DYLD_.+|PATH)$/,R2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function S$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(!wJ.has(K))break;J=Y}return J}function m4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],H=W.match(R2);if(!H)break;let K=H[1];if(LJ.test(K))break;J=Y}return J}var qJ=[/^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 I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of qJ){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 s$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){Z+=X,H=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function C2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let H=$[Y];if(W){W=!1;continue}if(H==="\\"&&!J){W=!0;continue}if(H==="'"&&!Z){J=!J;continue}if(H==='"'&&!J){Z=!Z;continue}if(J)continue;if(H==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(H==="`")return!0;if(Z)continue;if(H==="|")return!0;if(H===">"||H==="<")return!0;if(H==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function A$($){let J=[],Z="",W=!1,Y=!1,H=!1;for(let K=0;K<$.length;K++){let X=$[K];if(H){Z+=X,H=!1;continue}if(X==="\\"&&!W){if(H=!0,Y){let Q=$[K+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,H=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var GJ=new Set(["npm","pnpm","yarn","bun"]),I2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),OJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function UJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function yJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function FJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=A$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let H=Y[1];if(!H||H==="-")return;let K=i0.isAbsolute(H)?i0.resolve(H):i0.resolve(Z,H);if(!l0.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function J$($,J){let Z=S$(yJ($)),W=s$(Z);if(!W||C2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:FJ(Z,W,J);if(!Y)return!1;let H=A$(Y);if(H.length===0||H.some((z)=>[...OJ].some((j)=>z===j||z.startsWith(`${j}=`))))return!1;let[K,X,Q]=H;if(GJ.has(K??""))return UJ(X==="run"?Q:X)||X==="--test";if((K==="npx"||K==="bunx")&&I2.has(X??""))return!0;if(I2.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function l4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=G0("Agent"),_J=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=_J)return{action:"truncated"};if(x2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var bJ=[/:\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],NJ=/```[\s\S]{50,}```/,v2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",PJ=2;function g1($,J,Z=!0){if(!$||J>=PJ)return{action:"none"};if(!Z&&NJ.test($))return{action:"retry",prompt:v2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(bJ.some((K)=>K.test(W)))return{action:"retry",prompt:v2};return{action:"none"}}var SJ=[/\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}(?:测试|单测|集成测试|检查|构建)/],p2={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},AJ={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},EJ="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.",fJ="Required verification did not run successfully before the retry limit.",TJ=3;function m2($,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&&J$(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 H of Y)if(typeof H==="string"&&J$(H,W))$.add(H)}function m1($,J,Z){if(!$||!SJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(p2).filter((Q)=>p2[Q].test($)),Y=[...J],H=W.filter((Q)=>!Y.some((z)=>AJ[Q].test(z)));if(W.length>0?H.length===0:Y.some((Q)=>J$(Q)))return{action:"none"};if(Z>=TJ)return{action:"fail",message:fJ};let X=W.length>1&&H.length>0?` Missing successful verification categories: ${H.join(", ")}.`:"";return{action:"retry",prompt:`${EJ}${X}`}}var kJ=[/\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|子代理|子智能体)/],u2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function d2($){return typeof $==="string"&&u2.some((J)=>J.test($))}var xJ=[/\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|子代理)/],MJ=[/\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 hJ($){if(typeof $!=="string")return;if(MJ.some((J)=>J.test($)))return"multiple-allowed";return xJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=hJ(J);if(Z!==void 0)return Z==="required"}return!1}var RJ="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.",CJ="Required delegation did not complete before the retry limit.",IJ=3;function c2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),H=!1;if(!Y)for(let K of W){if(u2.some((X)=>X.test(K)))break;if(kJ.some((X)=>X.test(K))){H=!0;break}}if(W.length===0||!Y&&!H||J.has("Task"))return{action:"none"};if(Z>=IJ)return{action:"fail",message:CJ};return{action:"retry",prompt:RJ}}var vJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],pJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],gJ=[/\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 i2($){return gJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=i2($);return vJ.some((Z)=>Z.test(J))}var mJ="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.",uJ="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.",dJ="Required worktree lifecycle did not complete before the retry limit.",cJ=3;function l2($,J,Z){if(!$)return{action:"none"};let W=i2($);if(!$1(W))return{action:"none"};let Y=pJ.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let H=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!H)return{action:"none"};if(Z>=cJ)return{action:"fail",message:dJ};return{action:"retry",tool:H,prompt:H==="EnterWorktree"?mJ:uJ}}var g2=30000;async function u1($){try{let Z=Z$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((H)=>{W=setTimeout(()=>H("timeout"),g2)});try{let H=await Promise.race([Z,Y]);if(H==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${g2}ms),按 shouldStop: true 处理`),{action:"stop"};let K=H;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function iJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var lJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function rJ($){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 nJ($){let J=$;for(let Q of lJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let H=Y.slice(0,60),K=H.lastIndexOf(" ");return`${(K>36?H.slice(0,K):H).trimEnd()}…`}function r2($){return nJ(rJ($))}import{EventEmitter as oJ}from"events";import n2 from"node:path";function d1($){if(a2($.sessionId),!n2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:n2.resolve($.projectPath)}}function o2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function Y5($,J){return o2($)===o2(J)}class W$ extends oJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!W$.instance)W$.instance=new W$;return W$.instance}publish($,J,Z,W){let Y=d1($);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 E$=W$.getInstance();var M0=G0("Agent"),J1=new Set;async function aJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let H=r2(J);if(!H)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:H}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:H})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<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>`,r0="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",s2="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class Y$ 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 n0($){return $.executionEngine?.getContextManager()}async function K0($,J,Z,W=null,Y,H={}){let K=H.required??$.executionEngine!==void 0;try{let X=n0($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let z=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)aJ(J,Z);return z}if(K&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(M0.warn("[Loop] 保存用户消息失败:",X),K)throw new Y$("user_message",{cause:X})}return null}async function g($,J,Z,W,Y,H,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=n0($),z=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&z){let j=await Q.saveMessage(J.sessionId,"assistant",Z,W,H,J.subagentInfo,Y);if(X&&!j)throw Error("Durable assistant-message commit returned no identity");return j}if(X&&J.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(M0.warn("[Loop] 保存助手消息失败:",Q),X)throw new Y$("assistant_message",{cause:Q})}return null}async function t2($,J,Z){try{let W=n0($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",c1,Z,void 0,J.subagentInfo)}catch(W){M0.warn("[Loop] 保存中断边界失败:",W)}return null}async function e2($,J,Z,W,Y){try{let H=n0($);if(!H||!J.sessionId||Z.length===0)return null;return await H.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(H){M0.warn("[Loop] 保存 contextual project rules provenance 失败:",H)}return null}async function i1($,J,Z,W,Y,H={}){try{let K=n0($);if(K&&J.sessionId){let X=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo);if(H.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(H.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(M0.warn("[Loop] 保存工具调用失败:",K),H.required)throw K}return null}async function Z1($,J,Z,W,Y,H,K,X,Q,z={}){try{let j=n0($);if(j&&J.sessionId){let q=await j.saveToolResult(J.sessionId,Z,W,Y,H,K,J.subagentInfo,X,Q);if(z.required&&!q)throw Error("Durable tool-result commit returned no identity");return q}if(z.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(j){if(M0.warn("[Loop] 保存工具结果失败:",j),z.required)throw j}return null}async function T$($,J,Z,W,Y={}){try{let H=n0($);if(H&&J.sessionId){let K=await H.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(H){if(M0.warn("[Loop] 保存压缩数据失败:",H),Y.required)throw H}return null}import{createHash as y4}from"node:crypto";import{promises as K8}from"node:fs";import X8 from"node:path";import{nanoid as R0}from"nanoid";import*as i from"node:fs/promises";import*as o0 from"node:path";var $6={enabled:!0,maxIndexLines:200};var sJ="memory",J6="MEMORY.md";class l1{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=H$($);this.memoryDir=o0.join(W,sJ)}this.config={...$6,...J}}async initialize(){if(this.initialized)return;await i.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=o0.join(this.memoryDir,J6);try{let J=await i.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -118,7 +118,7 @@ Full output saved to: ${X}`}catch{return`${J}
118
118
 
119
119
  ${Y}`}}import{Mutex as M8}from"async-mutex";import{nanoid as h8}from"nanoid";import*as w0 from"node:fs/promises";import*as j6 from"node:path";import{Mutex as G8}from"async-mutex";import O8 from"write-file-atomic";var H1=1,M$=8388608;function V6($,J){let Z={version:H1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
120
120
  `}function s1($,J){return $ instanceof Error&&"code"in $&&$.code===J}function U8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function y8($,J,Z){let W;try{W=JSON.parse($)}catch(H){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:H})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==H1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((H)=>{if(!H||typeof H!=="object"||!("id"in H)||typeof H.id!=="string"||!("content"in H)||!U8(H.content)||!("queuedAt"in H)||typeof H.queuedAt!=="number"||"persisted"in H&&typeof H.persisted!=="boolean"||"origin"in H&&H.origin!=="user"&&H.origin!=="background_subagent"||"metadata"in H&&(H.metadata===null||typeof H.metadata!=="object"||Array.isArray(H.metadata))||"outputSchema"in H&&H.outputSchema!==void 0&&(!H.outputSchema||typeof H.outputSchema!=="object"||Array.isArray(H.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let K="outputSchema"in H&&H.outputSchema!==void 0?X1(H.outputSchema).schema:void 0;return{id:H.id,content:H.content,queuedAt:H.queuedAt,..."persisted"in H&&H.persisted===!0?{persisted:!0}:{},..."origin"in H&&H.origin?{origin:H.origin}:{},..."metadata"in H&&H.metadata?{metadata:JSON.parse(JSON.stringify(H.metadata))}:{},...K?{outputSchema:K}:{}}});return{version:H1,sessionId:Z,messages:Y}}function F8($){return new Set($.flatMap((J)=>J.type==="inbox_acknowledged"?J.data.messageIds:[]))}class Q1{workspaceRoot;sessionId;filePath;mutex=new G8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new Q1($,J,K1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=V6(this.sessionId,Z);if(Buffer.byteLength(W)>M$)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:H1,sessionId:this.sessionId,messages:[]};try{if((await w0.stat(this.filePath)).size>M$)throw Error(`Steering inbox exceeds ${M$} bytes: ${this.filePath}`);await w0.chmod(this.filePath,384),$=y8(await w0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!s1(Y,"ENOENT"))throw Y}let J=z0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=F8(D6(await w0.readFile(J,"utf8"),J))}catch(Y){if(!s1(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await w0.mkdir(j6.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await w0.unlink(this.filePath).catch((W)=>{if(!s1(W,"ENOENT"))throw W});return}let Z=J??V6(this.sessionId,$);if(Buffer.byteLength(Z)>M$)throw Error(`Steering inbox exceeds ${M$} bytes: ${this.filePath}`);await O8(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as U0 from"node:fs/promises";import*as y6 from"node:path";import{nanoid as s}from"nanoid";class a0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new O0(z0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=a0.instances.get(Z);if(!W)W=new a0($,J),a0.instances.set(Z,W);return W}static release($,J){a0.instances.delete(`${J}\x00${$}`)}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);E$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($)}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z)await $.onCommitted(W)}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}E$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function Q$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class S0 extends Error{}var b8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.",N8=20,P8=1e4,S8=1e5,A8=2592000000,w6=128,E8=1e6;function f8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>w6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>E8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>w6||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function F6($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,H=Y.turnId,K=Y.inputMessageIds,X=Y.turnsCount,Q=Y.toolCallsCount,z=Y.durationMs,j=Array.isArray(K)?K.filter((V)=>typeof V==="string"&&V.length>0&&V.length<=128):[];if(typeof H!=="string"||H.length===0||H.length>128||J!==void 0&&H!==J||!Array.isArray(K)||K.length>N8||j.length!==K.length||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>P8||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>S8||typeof z!=="number"||!Number.isSafeInteger(z)||z<0||z>A8)return;let q;if("goalFinalization"in Y){if(q=f8(Y.goalFinalization),!q)return}return{turnId:H,inputMessageIds:[...new Set(j)],turnsCount:X,toolCallsCount:Q,durationMs:z,...q?{goalFinalization:q}:{}}}function T8($,J){let Z=t($),W=Z.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(W<0)return;for(let Y=Z.length-1;Y>W;Y--){let H=Z[Y];if(H?.type!=="message_created")continue;let K=F6(H,J);if(K)return K}return}function k8($){let J=t($);for(let Z=J.length-1;Z>=0;Z--){let W=J[Z];if(W?.type!=="message_created")continue;let Y=F6(W);if(!Y?.goalFinalization)continue;if(!J.slice(0,Z).some((K)=>K.type==="turn_started"&&K.data.turnId===Y.turnId))continue;return{turnId:Y.turnId,finalization:Y}}return}function t1($,J){let Z=t($),W=J?Z.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J):-1;if(J&&W<0)return{all:[],orphaned:[]};let Y=new Map,H=new Set,K=new Set;for(let Q of Z.slice(W+1)){if(Q.type==="interaction_requested"){K.add(Q.data.toolCallId);continue}if(Q.type!=="part_created")continue;let z=Q.data.payload&&typeof Q.data.payload==="object"&&!Array.isArray(Q.data.payload)?Q.data.payload:{},j=typeof z.toolCallId==="string"?z.toolCallId:Q.data.partId;if(Q.data.partType==="tool_call")Y.set(j,{toolCallId:j,messageId:Q.data.messageId,toolName:typeof z.toolName==="string"?z.toolName:"unknown",input:z.input??null});else if(Q.data.partType==="tool_result")H.add(j),H.add(Q.data.partId),H.add(Q.data.messageId)}let X=[...Y.values()];return{all:X,orphaned:X.filter((Q)=>!H.has(Q.toolCallId)&&!K.has(Q.toolCallId))}}class I0{projectPath;maxSessions;version;constructor($=a(),J=100,Z=G6()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:s(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:L6(this.projectPath),version:this.version,data:Z}}log($){return a0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=z0(this.projectPath,$);if((await new O0(Z).readAll()).length>0)return;let H=new Date().toISOString(),K={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:H,updatedAt:H},X=this.createEvent("session_created",$,K);await this.log($).commit(X)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=O6;return J}async initialize(){try{let $=H$(this.projectPath);await U0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,H,K){try{await this.ensureSessionCreated($,H);let X=new Date().toISOString(),Q=s(),z={messageId:Q,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},j=this.createEvent("message_created",$,z),q=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:"reasoning",payload:{text:K},createdAt:X})]:[],V=typeof Z==="string"?[this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:"text",payload:{text:Z},createdAt:X})]:Z.map((D)=>this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:D.type==="text"?"text":"image",payload:D.type==="text"?{text:D.text}:{mimeType:x8(D.image_url.url)??"image/png",dataUrl:D.image_url.url},createdAt:X}));return await this.log($).commitBatch([j,...q,...V]),Q}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=Y.some((V)=>V.type==="inbox_acknowledged"&&V.data.messageIds.includes(J.inboxMessageId)),K=Y.find((V)=>V.type==="message_created"&&V.data.inboxMessageId===J.inboxMessageId),X=Y.findLast((V)=>{if(V.type!=="part_created"||V.data.partType!=="tool_call"||!V.data.payload||typeof V.data.payload!=="object"||Array.isArray(V.data.payload))return!1;let D=V.data.payload;if(D.toolName!=="Task"||!D.input||typeof D.input!=="object"||Array.isArray(D.input))return!1;let b=D.input,T=b.resume_from??b.resume;return b.run_in_background===!0&&b.subagent_session_id===J.childSessionId&&b.description===J.subagentRef.subagentDescription&&(b.subagent_type===void 0||b.subagent_type===J.subagentRef.subagentType)&&(b.resume_from===void 0||b.resume===void 0||b.resume_from===b.resume)&&(T===void 0?J.subagentRef.subagentResumedFrom===void 0:T===J.subagentRef.subagentResumedFrom)});if(!X)return Z={eligible:!1,acknowledged:H,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(H)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];let Q=Y.find((V)=>V.type==="part_created"&&V.data.partType==="subtask_ref"&&V.data.payload!==null&&typeof V.data.payload==="object"&&!Array.isArray(V.data.payload)&&V.data.payload.childSessionId===J.childSessionId&&V.data.payload.status===J.subagentRef.subagentStatus);if(K&&Q)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let z=new Date().toISOString(),j=K?.data.messageId??s(),q=[];if(!K){let V={messageId:j,role:"user",inboxMessageId:J.inboxMessageId,createdAt:z,metadata:JSON.parse(JSON.stringify(J.metadata))};q.push(this.createEvent("message_created",$,V)),q.push(this.createEvent("part_created",$,{partId:s(),messageId:j,partType:"text",payload:{text:J.content},createdAt:z}))}if(!Q){let V=Y.findLast((b)=>b.type==="part_created"&&b.data.partType==="subtask_ref"&&b.data.messageId===X.data.messageId&&b.data.payload!==null&&typeof b.data.payload==="object"&&!Array.isArray(b.data.payload)&&b.data.payload.childSessionId===J.childSessionId),D=V?.data.payload&&typeof V.data.payload==="object"&&!Array.isArray(V.data.payload)?V.data.payload:void 0;q.push(this.createEvent("part_created",$,{partId:s(),messageId:X.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof D?.startedAt==="string"?D.startedAt:z,finishedAt:z},createdAt:z}))}return Z={eligible:!0,acknowledged:!1,persisted:q.length>0,messageId:j},q}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=t(Z);if(W.some((H)=>H.type==="turn_started"&&H.data.turnId===J.turnId))throw new S0;let Y=Q$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof S0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=new Set(Y.flatMap((z)=>z.type==="inbox_acknowledged"?z.data.messageIds:[])),K=[...new Set(Z)].filter((z)=>!H.has(z)),X=Y.findLast((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===J.turnId);if(X){if(X.type==="turn_aborted"||K.length===0)throw new S0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let Q=Q$(Y).active;if(!Q||Q.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof S0))throw W}}async saveTurnAbort($,J){await this.saveTurnTerminal($,"turn_aborted",J)}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=t(J),W=Q$(Z).active;return W?t1(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=t(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let H=Y.input;return H.run_in_background===!0&&typeof H.subagent_session_id==="string"?[H.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=t(W),H=Q$(Y).active,K=t1(Y);if(!H&&K.orphaned.length===0)throw new S0;let X=H?T8(Y,H.turnId):void 0;if(H&&X&&K.orphaned.length===0){Z={turnId:H.turnId,outcome:"completed",finalization:X};let V=new Set(Y.flatMap((T)=>T.type==="inbox_acknowledged"?T.data.messageIds:[])),D=X.inputMessageIds.filter((T)=>!V.has(T)),b=new Date().toISOString();return[...D.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:D,acknowledgedAt:b})]:[],this.createEvent("turn_completed",$,{turnId:H.turnId,completedAt:b,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs})]}Z=H?{turnId:H.turnId,outcome:"aborted"}:void 0;let Q=H?t1(Y,H.turnId).all.length:0,z=new Date().toISOString(),j=H?Date.parse(H.startedAt):Number.NaN,q=K.orphaned.flatMap((V)=>{let D=J.adoptedToolResults?.get(V.toolCallId),b=D?.toolCallId===V.toolCallId&&D.toolName===V.toolName?D:void 0,T=this.createEvent("part_created",$,{partId:V.toolCallId,messageId:b?V.messageId:V.toolCallId,partType:"tool_result",payload:b?{toolCallId:V.toolCallId,toolName:V.toolName,output:b.output,error:b.error??null,...b.metadata===void 0?{}:{metadata:b.metadata}}:{toolCallId:V.toolCallId,toolName:V.toolName,output:null,error:b8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:z});if(!b?.subagentRef)return[T];let A=b.subagentRef;return[T,this.createEvent("part_created",$,{partId:s(),messageId:V.messageId,partType:"subtask_ref",payload:{childSessionId:A.subagentSessionId,agentType:A.subagentType,description:A.subagentDescription??"",status:A.subagentStatus,summary:A.subagentSummary??"",resumedFrom:A.subagentResumedFrom??null,rootAgentId:A.subagentRootId??A.subagentSessionId,resumeDepth:A.subagentResumeDepth??0,verificationVerdict:A.verificationVerdict??null,startedAt:z,finishedAt:z},createdAt:z})]});return H?[...q,this.createEvent("turn_aborted",$,{turnId:H.turnId,cause:"process_restart",abortedAt:z,turnsCount:0,toolCallsCount:Q,durationMs:Number.isFinite(j)?Math.max(0,Date.now()-j):0})]:q})}catch(W){if(!(W instanceof S0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?k8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="interaction_requested"&&H.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((H)=>H.type==="interaction_responded"&&H.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="interaction_responded"&&H.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((H)=>H.type==="interaction_recovered"&&H.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((H)=>H.type==="review_started"&&H.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((H)=>H.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===H.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((H)=>H.type==="review_started"&&H.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((H)=>H.type==="review_completed"&&H.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y){try{await this.ensureSessionCreated($,Y);let H=new Date().toISOString(),K=W??s(),X=[];if(!W){let j={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:H};X.push(this.createEvent("message_created",$,j))}let Q=s(),z={partId:Q,messageId:K,partType:"tool_call",payload:{toolCallId:Q,toolName:J,input:Z},createdAt:H};if(X.push(this.createEvent("part_created",$,z)),J==="Task"&&Z&&typeof Z==="object"){let j=Z,q=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,V=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(q&&V){let D={partId:s(),messageId:K,partType:"subtask_ref",payload:{childSessionId:q,agentType:V,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:H},createdAt:H};X.push(this.createEvent("part_created",$,D))}}return await this.log($).commitBatch(X),Q}catch(H){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,H),H}}async saveToolResult($,J,Z,W,Y=null,H,K,X,Q){try{await this.ensureSessionCreated($,K);let z=new Date().toISOString(),j=Y??s();return await this.log($).commitValidatedBatch((q)=>{let V=X?.subagentStatus==="running"?t(q).findLast((k)=>k.type==="part_created"&&k.data.partType==="subtask_ref"&&k.data.payload!==null&&typeof k.data.payload==="object"&&!Array.isArray(k.data.payload)&&k.data.payload.childSessionId===X.subagentSessionId&&(k.data.payload.status==="completed"||k.data.payload.status==="failed"||k.data.payload.status==="cancelled")):void 0,D=V?.data.payload,b=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},T=D?{...b,subagentSessionId:D.childSessionId,subagentType:D.agentType,description:D.description,subagentStatus:D.status,subagentSummary:D.summary,subagentResumedFrom:D.resumedFrom,subagentRootId:D.rootAgentId,subagentResumeDepth:D.resumeDepth,verificationVerdict:D.verificationVerdict}:Q,A=[];if(!Y){let k={messageId:j,role:"assistant",parentMessageId:void 0,createdAt:z};A.push(this.createEvent("message_created",$,k))}let x={partId:J,messageId:j,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:H??null,...T===void 0?{}:{metadata:T}},createdAt:z};if(A.push(this.createEvent("part_created",$,x)),X&&!V){let k=X.subagentStatus==="running"?null:z,W0={partId:s(),messageId:j,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:z,finishedAt:k},createdAt:z};A.push(this.createEvent("part_created",$,W0))}return A}),J}catch(z){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,z),z}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),H=s(),K={messageId:H,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(Z),Q={partId:s(),messageId:H,partType:"summary",payload:{text:J,metadata:X,...Z.replacementMessages?{replacementMessages:U6(Z.replacementMessages)}:{}},createdAt:Y},z=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,Q)];return await this.log($).commitBatch(z),H}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=z0(this.projectPath,$),W=await new O0(J).readAll();return W.length>0?t(W):null}catch{return null}}async loadSession($){try{let J=z0(this.projectPath,$),Z=new O0(J),W=t(await Z.readAll());if(W.length===0)return null;let Y=W.find((H)=>H.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=z0(this.projectPath,$),Z=new O0(J),W=t(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let Q of W){if(Q.type==="message_created")Y.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let z=Y.get(Q.data.messageId);if(z){let j=Q.data.payload;z.content=j.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let z=Y.get(Q.data.messageId);if(z)z.content=z.content?`${z.content}
121
- [Image]`:"[Image]"}}let H=Array.from(Y.values()),K=W[W.length-1],X=new Date(K.timestamp).getTime();return{messages:H,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=H$(this.projectPath);return(await U0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=z0(this.projectPath,$),Z=new O0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let H=t(Y),K=Y[Y.length-1],X=H.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=z0(this.projectPath,$);await new O0(J).delete(),await U0.unlink(K1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-hpqhk0jf.js"),H=await W();if(H)Y(H,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,H)=>H.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,J,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let Y=t(W);if(Y.some((X)=>(X.type==="turn_completed"||X.type==="turn_aborted")&&X.data.turnId===Z.turnId))throw new S0;let K=Q$(Y).active;if(!K||K.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return J==="turn_completed"?this.createEvent("turn_completed",$,Z):this.createEvent("turn_aborted",$,Z)})}catch(W){if(!(W instanceof S0))throw W}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=z0(this.projectPath,Z),H=await new O0(W).getStats();J+=H.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=H$(this.projectPath);await U0.mkdir($,{recursive:!0,mode:493});let J=y6.join($,".health-check");return await U0.writeFile(J,"test","utf-8"),await U0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return q6()}}function x8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var _6=131072,b6=new Map;function e1($,J){let Z=`${$}\x00${J}`,W=b6.get(Z);if(!W)W=new M8,b6.set(Z,W);return W}function Z2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>_6)throw Error(`${J} exceeds ${_6} bytes`);return JSON.parse(Z)}function N6($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function R8($,J){return JSON.stringify($)===JSON.stringify(J)}function C8($,J){if($.request.interactionType!=="elicitation")return Z2(J,"Interaction response");return Z2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function P6($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function I8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function v8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
121
+ [Image]`:"[Image]"}}let H=Array.from(Y.values()),K=W[W.length-1],X=new Date(K.timestamp).getTime();return{messages:H,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=H$(this.projectPath);return(await U0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=z0(this.projectPath,$),Z=new O0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let H=t(Y),K=Y[Y.length-1],X=H.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=z0(this.projectPath,$);await new O0(J).delete(),await U0.unlink(K1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-bw7fgs2n.js"),H=await W();if(H)Y(H,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,H)=>H.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,J,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let Y=t(W);if(Y.some((X)=>(X.type==="turn_completed"||X.type==="turn_aborted")&&X.data.turnId===Z.turnId))throw new S0;let K=Q$(Y).active;if(!K||K.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return J==="turn_completed"?this.createEvent("turn_completed",$,Z):this.createEvent("turn_aborted",$,Z)})}catch(W){if(!(W instanceof S0))throw W}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=z0(this.projectPath,Z),H=await new O0(W).getStats();J+=H.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=H$(this.projectPath);await U0.mkdir($,{recursive:!0,mode:493});let J=y6.join($,".health-check");return await U0.writeFile(J,"test","utf-8"),await U0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return q6()}}function x8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var _6=131072,b6=new Map;function e1($,J){let Z=`${$}\x00${J}`,W=b6.get(Z);if(!W)W=new M8,b6.set(Z,W);return W}function Z2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>_6)throw Error(`${J} exceeds ${_6} bytes`);return JSON.parse(Z)}function N6($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function R8($,J){return JSON.stringify($)===JSON.stringify(J)}function C8($,J){if($.request.interactionType!=="elicitation")return Z2(J,"Interaction response");return Z2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function P6($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function I8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function v8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
122
122
  `)}function p8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=v8(J);return{toolOutput:`User answers:
123
123
  ${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
124
124
  ${K}
@@ -0,0 +1,10 @@
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-w1vcjwbx.js";import"./chunk-t80e2bms.js";import"./chunk-5zf8204m.js";import"./chunk-yxwargqc.js";import"./chunk-nsawkccy.js";import"./chunk-wk0vpgwk.js";import"./chunk-wvc6bx0t.js";import"./chunk-v80xem15.js";import"./chunk-adgx9vd7.js";import"./chunk-5cgyevqj.js";import"./chunk-zracmha2.js";import"./chunk-qgez5vw6.js";import"./chunk-bdxaz350.js";import{$c as R}from"./chunk-hjkdc185.js";import"./chunk-y30kw6gj.js";import{vd as Q}from"./chunk-27w2k6t7.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-d61673v7.js";import"./chunk-4ekrbk2w.js";import"./chunk-fxw1q5j5.js";import"./chunk-yhw0pvyt.js";import"./chunk-6dma8han.js";import"./chunk-n0ebpwxd.js";import"./chunk-01jt0mpr.js";import"./chunk-ens8nsge.js";import"./chunk-f4bx2n1y.js";import"./chunk-tsskar00.js";import"./chunk-x5s68axq.js";import"./chunk-gbbnjzy8.js";import"./chunk-b5b8fb9y.js";import"./chunk-atdeg922.js";import"./chunk-g9re8v25.js";import"./chunk-nhzdkxnx.js";import"./chunk-fz55cnws.js";import"./chunk-5ygv33qe.js";import"./chunk-x04xb9g3.js";import{Bg as M}from"./chunk-358zaryv.js";import"./chunk-5sbewyjn.js";import"./chunk-npgt73cg.js";import"./chunk-9neq5xrb.js";import"./chunk-22h5kh4z.js";import m from"chalk";import K from"open";var A=`
2
+ ____ _ _
3
+ | __ )| | __ _ __| | ___
4
+ | _ \\| |/ _\` |/ _\` |/ _ \\
5
+ | |_) | | (_| | (_| | __/
6
+ |____/|_|\\__,_|\\__,_|\\___|
7
+ `,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
8
+ `));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
9
+ `)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
10
+ `));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as If,T as Jf,A as Kf};
@@ -1,2 +1,2 @@
1
1
  import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
2
- export{a as Bf,f as Cf,l as Df,x as Ef,b as Ff,V as Gf};
2
+ export{a as Cf,f as Df,l as Ef,x as Ff,b as Gf,V as Hf};
@@ -1,4 +1,4 @@
1
- import{ig as i}from"./chunk-fk8jf873.js";import{Dg as o,Fg as C,Hg as L,Lg as j,Mg as n}from"./chunk-ts3pgkmz.js";import{Ng as I}from"./chunk-8jexqfqg.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
1
+ import{ng as i}from"./chunk-fz55cnws.js";import{Ig as o,Kg as C,Mg as L,Qg as j,Rg as n}from"./chunk-9neq5xrb.js";import{Sg as I}from"./chunk-22h5kh4z.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
2
2
  `),W=!_.endsWith(`
3
3
  `),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
4
4
  `)}
@@ -1 +1 @@
1
- import{Mc as a,Nc as b,Oc as c,Pc as d,Qc as e,Rc as f,Sc as g,Tc as h}from"./chunk-3azdwanx.js";import"./chunk-fk8jf873.js";import"./chunk-ts3pgkmz.js";import"./chunk-8jexqfqg.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
1
+ import{Mc as a,Nc as b,Oc as c,Pc as d,Qc as e,Rc as f,Sc as g,Tc as h}from"./chunk-bdxaz350.js";import"./chunk-fz55cnws.js";import"./chunk-9neq5xrb.js";import"./chunk-22h5kh4z.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
@@ -1,2 +1,2 @@
1
- import{wg as d,yg as h}from"./chunk-mc42kjv9.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},"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{Bg as d,Dg as h}from"./chunk-358zaryv.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},"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 Uc,w as Vc};
@@ -0,0 +1,5 @@
1
+ import{$f as Uf,Sf as ax,Tf as uf,Uf as cf,Vf as ox,Wf as kf,Yf as Sf,_f as Kf,ag as hf,bg as Qf,dg as Df,eg as bf,gg as B}from"./chunk-nhzdkxnx.js";import{ng as t}from"./chunk-fz55cnws.js";import{rg as ef,tg as Zf}from"./chunk-5ygv33qe.js";import{wg as wx}from"./chunk-x04xb9g3.js";var P_={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},sf=(f)=>P_[f]||{};var E_=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function Gf(f){return typeof f==="string"&&E_.has(f)}function P0(f){if(!f.aborted)return;if(Gf(f.reason))return f.reason;return"user-cancel"}function h0(f){if(Gf(f))return!0;if(!(f instanceof Error))return!1;if(f.name==="AbortError")return!0;if(f instanceof DOMException&&f.name==="AbortError")return!0;if(f.message.includes("aborted"))return!0;return!1}function af(...f){let x=f.filter(Boolean);if(x.length===0)return new AbortController().signal;if(x.length===1)return x[0];let _=AbortSignal;if(typeof _.any==="function")return _.any(x);for(let P of x)if(P.aborted)return P;let M=new AbortController,T=new Map;for(let P of x){let D=()=>{M.abort(P.reason);for(let[U,E]of T)U.removeEventListener("abort",E)};T.set(P,D)}for(let[P,D]of T)P.addEventListener("abort",D,{once:!0});return M.signal}function r(f,x,_){let M=_?.throwOnAbort??!1;if(x?.aborted){if(M)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((T,P)=>{let D,U=setTimeout(()=>{if(x&&D)x.removeEventListener("abort",D);T()},f);if(x)D=()=>{if(clearTimeout(U),M)P(new DOMException("Aborted","AbortError"));else T()},x.addEventListener("abort",D,{once:!0})})}var U_=t("Chat"),h_={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Yf(f){if(typeof f==="string")return f;return f.filter((x)=>x.type==="text").map((x)=>x.text).join(`
2
+ `)}function D_(f){if(!f)return{};try{let x=JSON.parse(f);return x&&typeof x==="object"&&!Array.isArray(x)?x:{}}catch{return U_.warn("[PiAIChatService] Invalid historical tool arguments",{value:f}),{}}}function R_(f){let x=f.match(/^data:([^;,]+);base64,(.+)$/s);return x?{mimeType:x[1],data:x[2]}:void 0}async function V_(f,x){let _=R_(f);if(_)return{type:"image",..._};if(!/^https?:\/\//i.test(f))return{type:"text",text:`[Unsupported image source: ${f}]`};let M=await fetch(f,{signal:x});if(!M.ok)throw Error(`Failed to load image ${f}: HTTP ${M.status}`);return{type:"image",mimeType:M.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await M.arrayBuffer()).toString("base64")}}async function df(f,x,_,M,T){let P=f.filter((E)=>E.role==="system").map((E)=>Yf(E.content)).filter(Boolean).join(`
3
+
4
+ `),D=[];for(let E of f){if(E.role==="system")continue;if(E.role==="user"){let V=x.input.includes("image"),A=typeof E.content==="string"?E.content:await Promise.all(E.content.map((R)=>R.type==="text"?Promise.resolve({type:"text",text:R.text}):V?V_(R.image_url.url,M):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));D.push({role:"user",content:A,timestamp:Date.now()});continue}if(E.role==="assistant"){let V=[];if(E.reasoningContent?.trim())V.push({type:"thinking",thinking:E.reasoningContent});let A=Yf(E.content);if(A)V.push({type:"text",text:A});for(let R of E.tool_calls??[]){if(!("function"in R))continue;V.push({type:"toolCall",id:R.id,name:R.function.name,arguments:D_(R.function.arguments)})}D.push({role:"assistant",content:V,api:x.api,provider:x.provider,model:x.id,usage:h_,stopReason:E.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}D.push({role:"toolResult",toolCallId:E.tool_call_id??"",toolName:E.name??"unknown",content:[{type:"text",text:Yf(E.content)}],isError:!1,timestamp:Date.now()})}let U=_?.filter((E)=>!T||E.name===T).map((E)=>({name:E.name,description:E.description,parameters:E.parameters,constrainedSampling:E.constrainedSampling}));return{...P?{systemPrompt:P}:{},messages:D,...U?.length?{tools:U}:{}}}function rf(f){let x=[];for(let _=0;_<f.length;_++){let M=f[_];if(M.role==="tool")continue;let T=M.role==="assistant"&&M.tool_calls?.length?M.tool_calls:void 0;if(!T){x.push(M);continue}let P=[],D=_+1;while(D<f.length&&f[D].role==="tool")P.push(f[D++]);let U=new Set(T.map((A)=>A.id)),E=P.filter((A)=>A.tool_call_id&&U.has(A.tool_call_id)),V=new Set(E.map((A)=>A.tool_call_id));if(U.size===T.length&&E.length===U.size&&V.size===U.size)x.push(M,...E);_=D-1}return x}function nf(f){return f.some((x)=>x.role==="assistant"&&Boolean(x.tool_calls?.length)&&!x.reasoningContent?.trim())}function fx(f,x){return{...f,...x.baseUrl?{baseUrl:ef(f.api,x.baseUrl)}:{},...x.maxOutputTokens?{maxTokens:x.maxOutputTokens}:{}}}function Cf(f){let x=f.modelCatalog??Zf();return{models:x.models,model:fx(x.getModel(f.provider,f.model),f)}}function xx(f,x){let _=f.modelCatalog??Zf();return fx(_.getModel(x.provider,x.model),f)}import{randomBytes as W_}from"node:crypto";import{createHmac as j_}from"node:crypto";function z_(f){try{let x=new URL(f);if(x.hash="",x.hostname=x.hostname.toLowerCase(),x.searchParams.sort(),x.pathname!=="/")x.pathname=x.pathname.replace(/\/+$/,"");return x.toString()}catch{return f.trim().replace(/\/+$/,"")}}function H_(f){if(!f)return[];return Object.entries(f).map(([x,_])=>[x.trim().toLowerCase(),_.trim()]).sort(([x],[_])=>x.localeCompare(_))}function Af(f,x,_){let M=JSON.stringify([f.provider.trim(),String(f.api).trim(),z_(f.baseUrl),f.model.trim(),f.serviceTier?.trim()??"",f.apiVersion?.trim()??"",f.apiKey??"",H_(f.customHeaders),_]);return j_("sha256",Buffer.from(x)).update(M).digest("hex")}var $_=60000,X_=4,G_=0.8;var Ef=300000,Jf=600000;var _x=128,Mx=256,Y_=1800000,Pf=50;class n extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(f){super(`Provider circuit open; retry after ${f.retryAfterMs??0}ms`);this.circuit=f;this.name="ProviderCircuitOpenError"}}function Nf(f){return f instanceof n||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_CIRCUIT_OPEN"}function l(f,x){return f!==void 0&&Number.isSafeInteger(f)&&f>0?f:x}function Z_(f,x){return f!==void 0&&Number.isFinite(f)&&f>0&&f<=1?f:x}function C_(f,x){return Af(f,x,{providerCircuitOpenDurationMs:f.openDurationMs})}function i(f){let x=0;for(let _ of f)if(_.failure)x++;return x}function Tx(f){return f!==void 0&&Number.isInteger(f)&&f>=100&&f<=599?f:void 0}function Ax(f){if(f===void 0||!Number.isFinite(f)||f<0)return;return Math.min(Math.ceil(f),Sf)}class Ex{#A=new Map;#U=new WeakMap;#f;#x;#M;#_;constructor(f={}){this.#f=f.processSecret?new Uint8Array(f.processSecret):W_(32),this.#x=f.now??(()=>performance.now()),this.#M=f.wallNow??f.now??Date.now,this.#_={maxEntries:Math.min(l(f.maxEntries,_x),_x),maxWindowEntries:Math.min(l(f.maxWindowEntries,Mx),Mx),windowMs:l(f.windowMs,$_),minSamples:l(f.minSamples,X_),errorRateThreshold:Z_(f.errorRateThreshold,G_),idleTtlMs:l(f.idleTtlMs,Y_)}}get size(){return this.#A.size}get(f){if(f.openDurationMs===0)return this.#P();let x=this.#x();this.#X(x);let _=C_(f,this.#f),M=this.#A.get(_);if(M)return M.lastTouchedAt=x,this.#T(M,f.probeLeaseMs);if(this.#A.size>=this.#_.maxEntries)this.#Z();if(this.#A.size>=this.#_.maxEntries)return this.#P();let T={key:_,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:f.openDurationMs,effectiveOpenDurationMs:f.openDurationMs,lastTouchedAt:x,detached:!1};return this.#A.set(_,T),this.#T(T,f.probeLeaseMs)}#T(f,x){let _=this,M=Math.max(Ef,Math.min(l(x,Ef),Jf));return{preflight:()=>_.#V(f),check:()=>_.#j(f,M),recordSuccess:(T)=>_.#W(T,"success"),recordFailure:(T,P)=>_.#W(T,"failure",P),recordNeutral:(T)=>_.#W(T,"neutral"),abandon:(T)=>_.#Y(T),snapshot:()=>_.#G(f)}}#P(){let f=this;return{preflight:()=>({eligible:!0}),check:()=>{let x=Object.freeze({kind:"noop"});return f.#U.set(x,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:x}},recordSuccess:(x)=>f.#E(x),recordFailure:(x)=>f.#E(x),recordNeutral:(x)=>f.#E(x),abandon:(x)=>f.#Y(x),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#E(f){let x=this.#U.get(f);if(x?.kind==="noop")x.settled=!0;return}#V(f){let x=this.#x();if(f.detached)return{eligible:!0};if(f.lastTouchedAt=x,this.#$(f,x),f.state==="closed")return{eligible:!0};if(f.state==="open"){let M=f.nextProbeAt??x;return x<M?this.#h(f,M-x):{eligible:!0}}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&x>=f.probeLeaseExpiresAt)return{eligible:!0};let _=Math.max(1,(f.probeLeaseExpiresAt??x+Pf)-x);return this.#h(f,Math.min(Pf,_))}#h(f,x){let{allowed:_,...M}=this.#H(f,x);return{eligible:!1,...M}}#j(f,x){let _=this.#x();if(f.detached)return this.#P().check();if(f.lastTouchedAt=_,this.#$(f,_),f.state==="closed")return this.#D(f,"regular");if(f.state==="open"){let T=f.nextProbeAt??_;if(_<T)return this.#H(f,T-_);f.state="half_open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0}if(f.probeLeaseId===void 0||f.probeLeaseExpiresAt!==void 0&&_>=f.probeLeaseExpiresAt)return this.#z(f,_,x);let M=Math.max(1,(f.probeLeaseExpiresAt??_+Pf)-_);return this.#H(f,Math.min(Pf,M))}#D(f,x,_){let M=Object.freeze({kind:x});return this.#U.set(M,{entry:f,generation:f.generation,attemptId:f.nextAttemptId++,kind:x,..._!==void 0?{probeLeaseId:_}:{},settled:!1}),{allowed:!0,probe:x==="probe",token:M}}#z(f,x,_){let M=f.nextProbeLeaseId++;f.probeLeaseId=M,f.probeLeaseExpiresAt=x+_,f.lastTouchedAt=x;let T=this.#D(f,"probe",M),P=f.lastFailure??{reason:"server_error"};return{...T,reason:P.reason,...P.statusCode!==void 0?{statusCode:P.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:i(f.samples)}}#H(f,x){let _=f.lastFailure??{reason:"server_error"};return{allowed:!1,state:f.state==="open"?"open":"half_open",reason:_.reason,..._.statusCode!==void 0?{statusCode:_.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(x)),nextProbeAt:this.#M()+Math.max(0,Math.ceil(x)),openDurationMs:f.effectiveOpenDurationMs,sampleCount:f.samples.length,failureCount:i(f.samples)}}#W(f,x,_){let M=this.#U.get(f);if(!M||M.settled)return;if(M.settled=!0,M.kind==="noop"||!M.entry)return;let T=M.entry;if(T.detached||M.generation!==T.generation||M.kind==="regular"&&T.state!=="closed"||M.kind==="probe"&&(T.state!=="half_open"||M.probeLeaseId!==T.probeLeaseId))return;let P=this.#x();if(T.lastTouchedAt=P,M.kind==="probe"){if(x==="failure"&&_)return this.#R(T,_,P,"reopened");return this.#k(T)}if(x==="neutral")return;if(this.#S(T,x==="failure",P),x!=="failure"||!_)return;let D=i(T.samples),U=T.samples.length===0?0:D/T.samples.length;if(T.samples.length>=this.#_.minSamples&&U>=this.#_.errorRateThreshold)return this.#R(T,_,P,"opened");return}#R(f,x,_,M){let T={reason:x.reason,...Tx(x.statusCode)!==void 0?{statusCode:Tx(x.statusCode)}:{},...Ax(x.retryAfterMs)!==void 0?{retryAfterMs:Ax(x.retryAfterMs)}:{}},P=T.retryAfterMs??0,D=Math.max(f.configuredOpenDurationMs,P);return f.state="open",f.generation++,f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.effectiveOpenDurationMs=D,f.nextProbeAt=_+D,f.lastFailure=T,{phase:M,reason:T.reason,...T.statusCode!==void 0?{statusCode:T.statusCode}:{},retryAfterMs:D,nextProbeAt:this.#M()+D,openDurationMs:D,sampleCount:f.samples.length,failureCount:i(f.samples)}}#k(f){let x=f.lastFailure??{reason:"server_error"};return f.state="closed",f.generation++,f.samples=[],f.probeLeaseId=void 0,f.probeLeaseExpiresAt=void 0,f.nextProbeAt=void 0,f.effectiveOpenDurationMs=f.configuredOpenDurationMs,{phase:"closed",reason:x.reason,...x.statusCode!==void 0?{statusCode:x.statusCode}:{},openDurationMs:f.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#Y(f){let x=this.#U.get(f);if(!x||x.settled)return!1;if(x.settled=!0,x.kind==="noop")return!0;let _=x.entry;if(!_||_.detached||x.kind!=="probe"||x.generation!==_.generation||x.probeLeaseId!==_.probeLeaseId)return!1;return _.probeLeaseId=void 0,_.probeLeaseExpiresAt=void 0,_.lastTouchedAt=this.#x(),!0}#S(f,x,_){if(this.#$(f,_),f.samples.length>=this.#_.maxWindowEntries)f.samples.shift();f.samples.push({at:_,failure:x})}#$(f,x){let _=x-this.#_.windowMs,M=0;while(M<f.samples.length&&f.samples[M].at<_)M++;if(M>0)f.samples.splice(0,M)}#G(f){if(!f.detached)this.#$(f,this.#x());return{state:f.state,sampleCount:f.samples.length,failureCount:i(f.samples),...f.nextProbeAt!==void 0?{nextProbeAt:f.nextProbeAt}:{},noop:!1,detached:f.detached}}#X(f){for(let[x,_]of this.#A)if(_.state==="closed"&&f-_.lastTouchedAt>this.#_.idleTtlMs)this.#C(x,_)}#Z(){let f;for(let x of this.#A.values())if(x.state==="closed"&&(!f||x.lastTouchedAt<f.lastTouchedAt))f=x;if(f)this.#C(f.key,f)}#C(f,x){x.detached=!0,this.#A.delete(f)}}var Px;function Ux(){return Px??=new Ex,Px}import{randomBytes as k_}from"node:crypto";var hx=16,Dx=128,Rx=32,Vx=3,jx=16,zx=96,Hx=24,Wx=12,$x=16,Xx=4,Gx=4,Yx=67108864,Zx=33554432,Cx=12,kx=2,Sx=2,Jx=1,Qx=15000,Nx=30000;class e extends Error{reason;scope;requestClass;resource;inFlight;limit;queued;maxWaitMs;code="PROVIDER_ADMISSION_BUSY";retryable;constructor(f,x,_,M,T,P,D,U){super(f==="queue_full"?`Provider request admission ${x} ${M} queue is full`:f==="wait_timeout"?`Provider request admission timed out waiting for ${x} capacity`:"Provider request admission scheduler is closed");this.reason=f;this.scope=x;this.requestClass=_;this.resource=M;this.inFlight=T;this.limit=P;this.queued=D;this.maxWaitMs=U;this.name="ProviderAdmissionError",this.retryable=f!=="closed"}}function ff(f){return f instanceof e||f!==null&&typeof f==="object"&&"code"in f&&f.code==="PROVIDER_ADMISSION_BUSY"}function Z(f,x,_){if(f===void 0||!Number.isSafeInteger(f)||f<=0)return x;return Math.min(f,_)}function S_(f){let x=Z(f.globalMaxInFlight,hx,hx),_=Z(f.globalMaxPending,Dx,Dx),M=Z(f.domainMaxPending,Rx,Rx),T=Math.min(Z(f.ownerMaxInFlight,Vx,Vx),x),P=Math.min(Z(f.ownerMaxPending,jx,jx),_),D=Math.min(Z(f.nonForegroundGlobalMaxPending,Math.min(zx,Math.max(1,Math.floor(_*3/4))),zx),_),U=Math.min(Z(f.nonForegroundDomainMaxPending,Math.min(Hx,Math.max(1,Math.floor(M*3/4))),Hx),M),E=Math.min(Z(f.nonForegroundOwnerMaxPending,Math.min(Wx,Math.max(1,Math.floor(P*3/4))),Wx),P),V=Math.min(Z(f.internalGlobalMaxPending,Math.min($x,Math.max(1,Math.floor(_/8))),$x),D),A=Math.min(Z(f.internalDomainMaxPending,Math.min(Xx,Math.max(1,Math.floor(M/8))),Xx),U),R=Math.min(Z(f.internalOwnerMaxPending,Math.min(Gx,Math.max(1,Math.floor(P/4))),Gx),E),j=Z(f.globalMaxPendingBytes,B,B),z=Math.min(Z(f.domainMaxPendingBytes,Yx,Yx),j),Q=Math.min(Z(f.ownerMaxPendingBytes,Zx,Zx),j),b=Math.min(Z(f.nonForegroundGlobalMaxInFlight,Math.min(Cx,x),Cx),x),u=Math.min(Z(f.nonForegroundOwnerMaxInFlight,Math.min(kx,T),kx),T),Vf=Math.min(Z(f.internalGlobalMaxInFlight,Math.min(Sx,x),Sx),x),xf=Z(f.internalDomainMaxInFlight,Jx,Jx),jf=Z(f.agingMs,Nx,Nx);return{globalMaxInFlight:x,globalMaxPending:_,domainMaxPending:M,ownerMaxInFlight:T,ownerMaxPending:P,nonForegroundGlobalMaxPending:D,nonForegroundDomainMaxPending:U,nonForegroundOwnerMaxPending:E,internalGlobalMaxPending:V,internalDomainMaxPending:A,internalOwnerMaxPending:R,globalMaxPendingBytes:j,domainMaxPendingBytes:z,ownerMaxPendingBytes:Q,nonForegroundGlobalMaxInFlight:b,nonForegroundOwnerMaxInFlight:u,internalGlobalMaxInFlight:Vf,internalDomainMaxInFlight:xf,agingMs:jf}}function Ox(f,x){if(!f.trim())throw Error(`${x} must not be blank`)}function J_(f){if(Ox(f.sessionId,"sessionId"),Ox(f.ownerId,"ownerId"),!Number.isSafeInteger(f.scope.maxConcurrent)||f.scope.maxConcurrent<Uf||f.scope.maxConcurrent>hf)throw Error(`maxConcurrent must be between ${Uf} and ${hf}`);if(!Number.isSafeInteger(f.scope.maxPendingBytes)||f.scope.maxPendingBytes<=0||f.scope.maxPendingBytes>B)throw Error(`maxPendingBytes must be between 1 and ${B}`);if(!Number.isSafeInteger(f.pendingBytes)||f.pendingBytes<=0||f.pendingBytes>B+1)throw Error(`pendingBytes must be between 1 and ${B+1}`);if(!Number.isSafeInteger(f.maxWaitMs)||f.maxWaitMs<0||f.maxWaitMs>Df)throw Error(`maxWaitMs must be 0-${Df}`)}function Of(f,x){if(x!==void 0)return x;if(f?.reason!==void 0)return f.reason;return new DOMException("Provider request admission cancelled","AbortError")}function N_(f,x){return Af(f,x,{providerRequestConcurrency:f.maxConcurrent,providerRequestPendingBytes:f.maxPendingBytes})}class bx{#A;#U;#f;#x=[];#M=new Map;#_=new Map;#T=0;#P=0;#E=0;#V=0;#h=0;#j=0;#D=0;#z=0;#H=1;#W=0;#R=!1;constructor(f={}){this.#A=f.processSecret?new Uint8Array(f.processSecret):k_(32),this.#U=f.now??(()=>performance.now()),this.#f=S_(f)}admit(f){if(J_(f),this.#R)throw this.#O("closed",f,{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight},this.#x.length);if(f.signal?.aborted)throw Of(f.signal);let x=N_(f.scope,this.#A),_=this.#M.get(x),M=this.#_.get(f.ownerId),T=_??this.#S(f.scope.maxConcurrent),P=M??this.#$();if(this.#x.length===0&&this.#G(T,P,f.requestClass)){if(!_)this.#M.set(x,T);if(!M)this.#_.set(f.ownerId,P),this.#H++;let j=this.#Z(x,f.ownerId,f.requestClass),z=this.#v(f,0);return{ready:Promise.resolve(j),getSnapshot:()=>({...z}),cancel:()=>{z={...z}}}}let D=this.#k(f,T,P);if(D)throw this.#O("queue_full",f,D,this.#x.length);let U=this.#X(T,P,f.requestClass);if(f.maxWaitMs===0)throw this.#O("wait_timeout",f,U,this.#x.length);if(!_)this.#M.set(x,T);if(!M)this.#_.set(f.ownerId,P),this.#H++;let E,V,A=new Promise((j,z)=>{E=j,V=z});A.catch(()=>{return});let R={domainKey:x,sessionId:f.sessionId,ownerId:f.ownerId,requestClass:f.requestClass,maxWaitMs:f.maxWaitMs,pendingBytes:f.pendingBytes,enqueuedAt:this.#U(),signal:f.signal,resolve:E,reject:V,settled:!1,admitted:!1};if(f.signal)R.abortListener=()=>this.#K(R,Of(f.signal)),f.signal.addEventListener("abort",R.abortListener,{once:!0});return R.timer=setTimeout(()=>this.#B(R),f.maxWaitMs),R.timer.unref?.(),this.#x.push(R),this.#Y(T,P,R),this.#J(),{ready:A,getSnapshot:()=>this.#F(R),cancel:(j)=>this.#K(R,Of(f.signal,j))}}close(){if(this.#R)return;this.#R=!0;for(let f of[...this.#x]){let x=this.#M.get(f.domainKey),_=this.#_.get(f.ownerId),M=x&&_?this.#X(x,_,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};this.#N(f,new e("closed",M.scope,f.requestClass,M.resource,M.inFlight,M.limit,this.#x.length,f.maxWaitMs))}}getStats(){return{inFlight:this.#T,queued:this.#x.length,pendingBytes:this.#j,nonForegroundInFlight:this.#P,internalInFlight:this.#E,nonForegroundQueued:this.#V,internalQueued:this.#h,nonForegroundPendingBytes:this.#D,internalPendingBytes:this.#z,domainCount:this.#M.size,ownerCount:this.#_.size,closed:this.#R}}#k(f,x,_){let M=(A,R,j)=>R>=j?{scope:A,resource:"pending_count",inFlight:R,limit:j}:void 0;if(f.requestClass==="internal"){let A=M("class",this.#h,this.#f.internalGlobalMaxPending)??M("class",_.internalQueued,this.#f.internalOwnerMaxPending)??M("class",x.internalQueued,this.#f.internalDomainMaxPending);if(A)return A}if(f.requestClass!=="foreground"){let A=M("class",this.#V,this.#f.nonForegroundGlobalMaxPending)??M("class",_.nonForegroundQueued,this.#f.nonForegroundOwnerMaxPending)??M("class",x.nonForegroundQueued,this.#f.nonForegroundDomainMaxPending);if(A)return A}let T=M("global",this.#x.length,this.#f.globalMaxPending)??M("owner",_.queued,this.#f.ownerMaxPending)??M("domain",x.queued,this.#f.domainMaxPending);if(T)return T;let P=Math.min(f.scope.maxPendingBytes,this.#f.globalMaxPendingBytes),D=Math.min(P,this.#f.domainMaxPendingBytes),U=Math.min(P,this.#f.ownerMaxPendingBytes),E=(A,R)=>f.pendingBytes>R-A,V=(A)=>{if(A==="owner")return{scope:A,resource:"pending_bytes",inFlight:_.inFlight,limit:this.#f.ownerMaxInFlight};if(A==="domain")return{scope:A,resource:"pending_bytes",inFlight:x.inFlight,limit:x.maxConcurrent};return{scope:A,resource:"pending_bytes",inFlight:this.#T,limit:this.#f.globalMaxInFlight}};if(f.requestClass==="internal"){let A=Math.max(1,Math.floor(P/8)),R=Math.max(1,Math.floor(D/4)),j=Math.max(1,Math.floor(U/4));if(E(this.#z,A)||E(_.internalPendingBytes,j)||E(x.internalPendingBytes,R))return V("class")}if(f.requestClass!=="foreground"){let A=Math.max(1,Math.floor(P*3/4)),R=Math.max(1,Math.floor(D*3/4)),j=Math.max(1,Math.floor(U/2));if(E(this.#D,A)||E(_.nonForegroundPendingBytes,j)||E(x.nonForegroundPendingBytes,R))return V("class")}if(E(this.#j,P))return V("global");if(E(_.pendingBytes,U))return V("owner");if(E(x.pendingBytes,D))return V("domain");return}#Y(f,x,_){if(f.queued++,x.queued++,this.#j+=_.pendingBytes,f.pendingBytes+=_.pendingBytes,x.pendingBytes+=_.pendingBytes,_.requestClass!=="foreground")this.#V++,f.nonForegroundQueued++,x.nonForegroundQueued++,this.#D+=_.pendingBytes,f.nonForegroundPendingBytes+=_.pendingBytes,x.nonForegroundPendingBytes+=_.pendingBytes;if(_.requestClass==="internal")this.#h++,f.internalQueued++,x.internalQueued++,this.#z+=_.pendingBytes,f.internalPendingBytes+=_.pendingBytes,x.internalPendingBytes+=_.pendingBytes}#S(f){return{maxConcurrent:f,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#$(){return{order:this.#H,inFlight:0,nonForegroundInFlight:0,internalInFlight:0,queued:0,nonForegroundQueued:0,internalQueued:0,pendingBytes:0,nonForegroundPendingBytes:0,internalPendingBytes:0}}#G(f,x,_){if(this.#T>=this.#f.globalMaxInFlight)return!1;if(f.inFlight>=f.maxConcurrent)return!1;if(x.inFlight>=this.#f.ownerMaxInFlight)return!1;if(_==="foreground")return!0;if(this.#P>=this.#f.nonForegroundGlobalMaxInFlight)return!1;if(x.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return!1;let M=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=M)return!1;if(_!=="internal")return!0;return this.#E<this.#f.internalGlobalMaxInFlight&&f.internalInFlight<this.#f.internalDomainMaxInFlight}#X(f,x,_){if(x.inFlight>=this.#f.ownerMaxInFlight)return{scope:"owner",resource:"stream",inFlight:x.inFlight,limit:this.#f.ownerMaxInFlight};if(_!=="foreground"&&x.nonForegroundInFlight>=this.#f.nonForegroundOwnerMaxInFlight)return{scope:"class",resource:"stream",inFlight:x.nonForegroundInFlight,limit:this.#f.nonForegroundOwnerMaxInFlight};if(f.inFlight>=f.maxConcurrent)return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent};if(_!=="foreground"){let M=Math.max(1,f.maxConcurrent-1);if(f.nonForegroundInFlight>=M)return{scope:"class",resource:"stream",inFlight:f.nonForegroundInFlight,limit:M}}if(_==="internal"&&f.internalInFlight>=this.#f.internalDomainMaxInFlight)return{scope:"class",resource:"stream",inFlight:f.internalInFlight,limit:this.#f.internalDomainMaxInFlight};if(this.#T>=this.#f.globalMaxInFlight)return{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};if(_!=="foreground"&&this.#P>=this.#f.nonForegroundGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#P,limit:this.#f.nonForegroundGlobalMaxInFlight};if(_==="internal"&&this.#E>=this.#f.internalGlobalMaxInFlight)return{scope:"class",resource:"stream",inFlight:this.#E,limit:this.#f.internalGlobalMaxInFlight};return{scope:"domain",resource:"stream",inFlight:f.inFlight,limit:f.maxConcurrent}}#Z(f,x,_){let M=this.#M.get(f),T=this.#_.get(x);if(!M||!T)throw Error("Provider admission accounting state is unavailable");if(this.#T++,M.inFlight++,T.inFlight++,_!=="foreground")this.#P++,M.nonForegroundInFlight++,T.nonForegroundInFlight++;if(_==="internal")this.#E++,M.internalInFlight++,T.internalInFlight++;let P=!1;return{release:()=>{if(P)return;P=!0,this.#C(f,x,_)}}}#C(f,x,_){let M=this.#M.get(f),T=this.#_.get(x);if(this.#T=Math.max(0,this.#T-1),M)M.inFlight=Math.max(0,M.inFlight-1);if(T)T.inFlight=Math.max(0,T.inFlight-1);if(_!=="foreground"){if(this.#P=Math.max(0,this.#P-1),M)M.nonForegroundInFlight=Math.max(0,M.nonForegroundInFlight-1);if(T)T.nonForegroundInFlight=Math.max(0,T.nonForegroundInFlight-1)}if(_==="internal"){if(this.#E=Math.max(0,this.#E-1),M)M.internalInFlight=Math.max(0,M.internalInFlight-1);if(T)T.internalInFlight=Math.max(0,T.internalInFlight-1)}this.#b(f,x),this.#J()}#J(){if(this.#R)return;while(this.#x.length>0){let f=this.#U(),x=new Map;for(let[U,E]of this.#x.entries()){let V=this.#M.get(E.domainKey),A=this.#_.get(E.ownerId);if(V===void 0||A===void 0||!this.#G(V,A,E.requestClass))continue;let R=this.#L(E,f),j=x.get(E.ownerId);if(!j||R<j.rank||R===j.rank&&U<j.index)x.set(E.ownerId,{pending:E,rank:R,index:U})}let _=[...x.values()].filter(({pending:U})=>{let E=this.#M.get(U.domainKey),V=this.#_.get(U.ownerId);return E!==void 0&&V!==void 0&&this.#G(E,V,U.requestClass)}).map(({pending:U,rank:E})=>({pending:U,rank:E,order:this.#_.get(U.ownerId).order}));if(_.length===0)return;let M=Math.min(..._.map((U)=>U.rank)),T=_.filter((U)=>U.rank===M),D=T.filter((U)=>U.order>this.#W).sort((U,E)=>U.order-E.order)[0]??T.sort((U,E)=>U.order-E.order)[0];this.#I(D.pending,D.order)}}#L(f,x){let _=f.requestClass==="foreground"?0:f.requestClass==="background"?1:2,M=Math.floor(Math.max(0,x-f.enqueuedAt)/this.#f.agingMs);return Math.max(0,_-M)}#I(f,x){if(!this.#Q(f,!1))return;f.settled=!0,f.admitted=!0,this.#W=x;let _=this.#Z(f.domainKey,f.ownerId,f.requestClass);f.permit=_,f.resolve(_)}#B(f){let x=this.#M.get(f.domainKey),_=this.#_.get(f.ownerId),M=x&&_?this.#X(x,_,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};this.#N(f,new e("wait_timeout",M.scope,f.requestClass,M.resource,M.inFlight,M.limit,this.#x.length,f.maxWaitMs))}#K(f,x){this.#N(f,x)}#N(f,x){if(!this.#Q(f))return;f.settled=!0,f.reject(x),this.#J()}#Q(f,x=!0){if(f.settled||f.admitted)return!1;let _=this.#x.indexOf(f);if(_<0)return!1;this.#x.splice(_,1);let M=this.#M.get(f.domainKey),T=this.#_.get(f.ownerId);if(M&&T)this.#u(M,T,f);if(this.#c(f),x)this.#b(f.domainKey,f.ownerId);return!0}#u(f,x,_){if(f.queued=Math.max(0,f.queued-1),x.queued=Math.max(0,x.queued-1),this.#j=Math.max(0,this.#j-_.pendingBytes),f.pendingBytes=Math.max(0,f.pendingBytes-_.pendingBytes),x.pendingBytes=Math.max(0,x.pendingBytes-_.pendingBytes),_.requestClass!=="foreground")this.#V=Math.max(0,this.#V-1),f.nonForegroundQueued=Math.max(0,f.nonForegroundQueued-1),x.nonForegroundQueued=Math.max(0,x.nonForegroundQueued-1),this.#D=Math.max(0,this.#D-_.pendingBytes),f.nonForegroundPendingBytes=Math.max(0,f.nonForegroundPendingBytes-_.pendingBytes),x.nonForegroundPendingBytes=Math.max(0,x.nonForegroundPendingBytes-_.pendingBytes);if(_.requestClass==="internal")this.#h=Math.max(0,this.#h-1),f.internalQueued=Math.max(0,f.internalQueued-1),x.internalQueued=Math.max(0,x.internalQueued-1),this.#z=Math.max(0,this.#z-_.pendingBytes),f.internalPendingBytes=Math.max(0,f.internalPendingBytes-_.pendingBytes),x.internalPendingBytes=Math.max(0,x.internalPendingBytes-_.pendingBytes)}#c(f){if(f.timer)clearTimeout(f.timer);if(f.timer=void 0,f.signal&&f.abortListener)f.signal.removeEventListener("abort",f.abortListener);f.abortListener=void 0,f.signal=void 0}#b(f,x){let _=this.#M.get(f);if(_&&_.inFlight===0&&_.queued===0)this.#M.delete(f);let M=this.#_.get(x);if(M&&M.inFlight===0&&M.queued===0)this.#_.delete(x)}#F(f){let x=Math.max(0,Math.floor(this.#U()-f.enqueuedAt));if(f.admitted)return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#x.length,inFlight:this.#T,limit:this.#f.globalMaxInFlight,waitMs:x,maxWaitMs:f.maxWaitMs};let _=this.#M.get(f.domainKey),M=this.#_.get(f.ownerId),T=_&&M?this.#X(_,M,f.requestClass):{scope:"global",resource:"stream",inFlight:this.#T,limit:this.#f.globalMaxInFlight};return{state:"queued",requestClass:f.requestClass,resource:T.resource,scope:T.scope,reason:"capacity",queuePosition:this.#w(f,T.scope),queueDepth:this.#x.length,inFlight:T.inFlight,limit:T.limit,waitMs:x,maxWaitMs:f.maxWaitMs}}#v(f,x){return{state:"admitted",requestClass:f.requestClass,resource:"stream",scope:"domain",queuePosition:0,queueDepth:this.#x.length,inFlight:this.#T,limit:this.#f.globalMaxInFlight,waitMs:x,maxWaitMs:f.maxWaitMs}}#w(f,x){let _=this.#x.filter((M)=>{switch(x){case"owner":return M.ownerId===f.ownerId;case"domain":return M.domainKey===f.domainKey;case"class":return M.requestClass===f.requestClass;case"global":return!0}});return Math.max(1,_.indexOf(f)+1)}#O(f,x,_,M){return new e(f,_.scope,x.requestClass,_.resource,_.inFlight,_.limit,M,x.maxWaitMs)}}var Kx;function Lx(){return Kx??=new bx,Kx}var O_=1e5,K_=4,Q_=4,Ix=8,b_=16,v=32,L_=8;function I_(f,x={}){let _=x.maxBytes??B,M=x.maxNodes??O_;if(!Number.isSafeInteger(_)||_<=0||_>=Number.MAX_SAFE_INTEGER)throw Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(M)||M<=0)throw Error("maxNodes must be a positive safe integer");let T=new WeakSet,P=0,D=0,U=!1,E=(A)=>{if(U||A<=0)return;if(!Number.isSafeInteger(A)||A>_-P){P=_+1,U=!0;return}P+=A},V=(A)=>{if(U)return;if(D+=1,D>M){E(_+1);return}if(A===null){E(K_);return}switch(typeof A){case"string":E(Buffer.byteLength(A,"utf8"));return;case"number":case"bigint":E(Ix);return;case"boolean":E(Q_);return;case"undefined":case"function":case"symbol":return;case"object":break}if(T.has(A))return;if(T.add(A),ArrayBuffer.isView(A)){E(v+A.byteLength);return}if(A instanceof ArrayBuffer){E(v+A.byteLength);return}if(A instanceof Date){E(v+Ix);return}if(A instanceof RegExp){E(v+Buffer.byteLength(A.source,"utf8"));return}if(A instanceof Map){E(v);for(let[R,j]of A)if(V(R),V(j),U)return;return}if(A instanceof Set){E(v);for(let R of A)if(V(R),U)return;return}if(A instanceof WeakMap||A instanceof WeakSet){E(v);return}if(Array.isArray(A)){E(b_);for(let R of A)if(V(R),U)return;return}E(v);for(let R of Reflect.ownKeys(A)){if(typeof R!=="string")continue;let j=Object.getOwnPropertyDescriptor(A,R);if(!j?.enumerable||!("value"in j))continue;if(E(L_+Buffer.byteLength(R,"utf8")),V(j.value),U)return}};return V(f),P}function Bx(f){return I_([f.messages,f.context,f.tools,f.requestOptions],{maxBytes:B})}var ux=new WeakSet;class y extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(f,x){super(`Provider recovery budget exhausted after ${f}ms`);this.budgetMs=f;this.elapsedMs=x;this.name="ProviderRecoveryBudgetExceededError"}}var B_=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],u_=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],c_=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function cx(f){return(f instanceof Error?f.message:String(f)).toLowerCase()}function F_(f){let x=cx(f);return u_.some((_)=>x.includes(_))}function Lf(f){if(f!==null&&typeof f==="object")ux.add(f)}function w0(f){return f!==null&&typeof f==="object"&&ux.has(f)}function v_(f){return f!==null&&typeof f==="object"&&"code"in f?f.code:void 0}function w_(f){if(f===null||typeof f!=="object")return;let x=f;for(let _ of["status","statusCode"]){let M=x[_];if(typeof M==="number"&&Number.isInteger(M))return M}return}function q_(f){let x=f.match(/^(?:error:\s*)?(\d{3})\b/),_=f.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),M=Number(x?.[1]??_?.[1]);return Number.isInteger(M)?M:void 0}function g(f,x){let _=cx(f),M=v_(f);if(M==="STREAM_IDLE_TIMEOUT"||M==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||f instanceof Error&&f.name==="AbortError"||_.includes("request aborted")||_==="aborted")return{retryable:!1};if(B_.some((P)=>_.includes(P))||F_(f))return{retryable:!1};if(x?.shouldRetry==="false")return{retryable:!1,statusCode:x.statusCode};let T=x?.statusCode??w_(f)??q_(_);if(x?.shouldRetry==="true")return{retryable:!0,reason:T===429?"rate_limit":T===408||T===409?"timeout":"server_error",statusCode:T};if(T===429)return{retryable:!0,reason:"rate_limit",statusCode:T};if(T===408||T===409)return{retryable:!0,reason:"timeout",statusCode:T};if(T!==void 0&&T>=500&&T<=599)return{retryable:!0,reason:"server_error",statusCode:T};if(M==="PROVIDER_STREAM_CLOSED"||_.includes("stream closed before completion")||_.includes("ended without")||_.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:T};if(c_.some((P)=>_.includes(P)))return{retryable:!0,reason:"transport",statusCode:T};if(_.includes("timeout")||_.includes("timed out")||_.includes("temporarily unavailable")||_.includes("upstream_error")||_.includes("overloaded")||_.includes("rate limit")||_.includes("too many requests")||_.includes("service unavailable")||_.includes("server error")||_.includes("internal error")||_.includes("please retry")||_.includes("try your request again"))return{retryable:!0,reason:_.includes("rate")||_.includes("too many")?"rate_limit":_.includes("timeout")||_.includes("timed out")?"timeout":"server_error",statusCode:T};return{retryable:!1,statusCode:T}}function If(f,x){if(!f)return;if(f.retryAfterMs!==void 0){let T=Number.parseFloat(f.retryAfterMs);if(Number.isFinite(T))return Math.max(0,T)}if(f.retryAfter===void 0)return;let _=Number.parseFloat(f.retryAfter);if(Number.isFinite(_))return Math.max(0,_*1000);let M=Date.parse(f.retryAfter);return Number.isFinite(M)?Math.max(0,M-x):void 0}function Fx(f,x,_={}){let M=_.now??Date.now(),T=_.maxDelayMs??60000,P=If(x,M);if(P!==void 0)return Math.min(Math.ceil(P),T);let D=Math.max(0,f-1),U=_.maxExponentialDelayMs??8000,E=Math.min(500*2**D,U),V=Math.max(0,Math.min(1,_.random??Math.random())),A=E*(0.75+V*0.25);return Math.min(Math.round(A),T)}function qx(f,x){let _=f.onPayload;f.onPayload=async(M,T)=>{let P=_?await _(M,T):M;return x(P===void 0?M:P,T)}}function p_(f){if(!f.reasoningEnabled)return;return f.reasoningEffort??f.reasoningLevel??"high"}function m_(f){switch(f){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function t_(f,x,_,M){let T=M?void 0:p_(_);if(!T){if(x.api==="anthropic-messages")f.thinkingEnabled=!1;if(x.api==="google-generative-ai"||x.api==="google-vertex")f.thinking={enabled:!1};return}switch(x.api){case"anthropic-messages":f.thinkingEnabled=!0,f.effort=T;break;case"google-generative-ai":case"google-vertex":f.thinking={enabled:!0,level:m_(T)};break;case"mistral-conversations":f.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":f.reasoning=T;break;default:f.reasoningEffort=T}}function l_(f,x,_){if(!_)return;switch(x){case"anthropic-messages":case"bedrock-converse-stream":f.toolChoice={type:"tool",name:_};break;case"openai-completions":case"mistral-conversations":case"pi-messages":f.toolChoice={type:"function",function:{name:_}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":f.toolChoice={type:"function",name:_};break;case"google-generative-ai":case"google-vertex":f.toolChoice="any";break}}function y_(f,x,_){let M=_.serviceTier;if(!M)return;if(x.api==="openai-responses"||x.api==="openai-codex-responses"||x.api==="azure-openai-responses"){f.serviceTier=M;return}if(x.api!=="openai-completions"&&!(x.api==="anthropic-messages"&&M==="fast"))return;qx(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;return x.api==="anthropic-messages"?{...T,speed:"fast"}:{...T,service_tier:M}})}function g_(f,x,_){let M=_.responseVerbosity;if(!M)return;if(wx(x,M),x.api==="openai-codex-responses"){f.textVerbosity=M;return}qx(f,(T)=>{if(!T||typeof T!=="object"||Array.isArray(T))return T;if(x.api==="openai-completions")return{...T,verbosity:M};let P="text"in T&&T.text&&typeof T.text==="object"&&!Array.isArray(T.text)?T.text:{};return{...T,text:{...P,verbosity:M}}})}function px(f,x,_,M,T=!1){let P={apiKey:f.apiKey,headers:f.customHeaders,signal:_,temperature:M?.temperature??f.temperature??0,maxTokens:M?.maxOutputTokens??f.maxOutputTokens,timeoutMs:f.timeout,maxRetries:0,cacheRetention:f.enablePromptCaching?"short":"none"};if(t_(P,x,f,T),l_(P,x.api,M?.toolChoice?.toolName),y_(P,x,f),g_(P,x,f),x.api==="azure-openai-responses")P.azureBaseUrl=f.baseUrl,P.azureApiVersion=f.apiVersion,P.azureDeploymentName=x.id;return P}function vx(f,x){let _=x.get("x-should-retry");return{statusCode:f,...x.get("retry-after")!==null?{retryAfter:x.get("retry-after")??void 0}:{},...x.get("retry-after-ms")!==null?{retryAfterMs:x.get("retry-after-ms")??void 0}:{},..._==="true"||_==="false"?{shouldRetry:_}:{}}}var s_=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function mx(f,x,_){let M=f.onResponse;if(f.onResponse=async(P,D)=>{let U=new Headers(P.headers);_(vx(P.status,U)),await M?.(P,D)},!s_.has(x.api)||typeof globalThis.fetch!=="function")return;let T=typeof f.fetch==="function"?f.fetch:globalThis.fetch.bind(globalThis);f.fetch=async(P,D)=>{let U=await T(P,D);return _(vx(U.status,U.headers)),U}}function tx(f){return{promptTokens:f.input+f.cacheRead+f.cacheWrite,completionTokens:f.output,totalTokens:f.totalTokens,costUsd:f.cost.total,...f.reasoning!==void 0?{reasoningTokens:f.reasoning}:{},...f.cacheWrite>0?{cacheCreationInputTokens:f.cacheWrite}:{},...f.cacheRead>0?{cacheReadInputTokens:f.cacheRead}:{}}}var Rf=300000,a_=30000;class lx extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(f){super(`Provider stream idle timeout after ${f}ms without an event`);this.timeoutMs=f;this.name="StreamIdleTimeoutError"}}class yx extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function Bf(f){return f.reason instanceof Error?f.reason:new DOMException("Aborted","AbortError")}function o_(f){return f.idleTimeoutMs&&f.idleTimeoutMs>0?f.idleTimeoutMs:Rf}function d_(f,x){if(x===0)return;let _=x!==void 0&&x>0?x:a_;return Math.max(1,Math.min(_,Math.floor(f/2)))}function r_(f,x,_){if(_?.aborted)return Promise.reject(Bf(_));return new Promise((M,T)=>{let P=!1,D=()=>{clearTimeout(A),_?.removeEventListener("abort",V)},U=(R)=>{if(P)return;P=!0,D(),M(R)},E=(R)=>{if(P)return;P=!0,D(),T(R instanceof Error?R:Error(String(R)))},V=()=>{if(_)E(Bf(_))},A=setTimeout(()=>U({kind:"timer"}),Math.max(0,x));if(_?.addEventListener("abort",V,{once:!0}),_?.aborted){V();return}f.then((R)=>U({kind:"next",result:R}),E)})}async function*i_(f,x,_){let M=o_(x),T=d_(M,x.stallWarningMs);if(x.signal?.aborted)throw Bf(x.signal);let P=Date.now(),D=Promise.resolve().then(()=>f.next()),U;for(;;){let V=await r_(D,(U?M:T??M)-(Date.now()-P),x.signal);if(V.kind==="next"){if(U)yield{...U,phase:"recovered",durationMs:Math.max(U.durationMs,Date.now()-P)};return V.result}if(!U&&T!==void 0){_.stallCount++,U={phase:"detected",stallCount:_.stallCount,durationMs:T,warningAfterMs:T,timeoutMs:M,outputStarted:_.outputStarted},yield U;continue}let A=new lx(M);throw x.abort?.(A),A}}async function*gx(f,x,_,M,T={}){let D=f.stream(x,_,M)[Symbol.asyncIterator](),U=0,E=!1,V={stallCount:0,outputStarted:!1};try{while(!0){let A=i_(D,T,V),R=await A.next();while(!R.done)yield{providerStall:R.value},R=await A.next();let j=R.value;if(j.done)throw new yx;let z=j.value;switch(z.type){case"text_delta":V.outputStarted=!0,yield{content:z.delta};break;case"thinking_delta":V.outputStarted=!0,yield{reasoningContent:z.delta};break;case"toolcall_end":V.outputStarted=!0,yield{toolCalls:[{index:U++,id:z.toolCall.id,type:"function",function:{name:z.toolCall.name,arguments:JSON.stringify(z.toolCall.arguments)}}]};break;case"done":E=!0,yield{finishReason:z.reason,usage:tx(z.message.usage)};return;case"error":throw Error(z.error.errorMessage??`Request ${z.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!E)Promise.resolve(D.return?.()).catch(()=>{return})}}var sx=t("Chat"),n_=1;function e_(f){return Boolean(f&&f.role==="user"&&Array.isArray(f.content)&&f.content.some((x)=>x.type==="image_url"))}function f0(f,x){let _=g(f,x);if(!_.retryable||!_.reason)return;let M=_.statusCode;switch(_.reason){case"rate_limit":if(M!==429)return;break;case"server_error":if(M===void 0||M<500||M>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let T=If(x,Date.now());return{reason:_.reason,...M!==void 0?{statusCode:M}:{},...T!==void 0?{retryAfterMs:T}:{}}}function x0(f){return f!==null&&typeof f==="object"&&"code"in f&&f.code==="STREAM_IDLE_TIMEOUT"}class Ff{config;models;model;admissionFallbackOwnerId=`pi-service-${process.pid}-${n_++}`;constructor(f){let x=Cf(f);this.config={...f,maxContextTokens:x.model.contextWindow,maxOutputTokens:f.maxOutputTokens??x.model.maxTokens},this.models=x.models,this.model=x.model,sx.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(f,x,_,M){let T="",P="",D=[],U,E;for await(let V of this.streamChat(f,x,_,M)){T+=V.content??"",P+=V.reasoningContent??"";for(let A of V.toolCalls??[])if(A.id&&A.type==="function"&&A.function?.name)D.push(A);U=V.usage??U,E=V.finishReason??E}return{content:T,...P?{reasoningContent:P}:{},...D.length>0?{toolCalls:D}:{},usage:U,finishReason:E}}async*streamChat(f,x,_,M){let T=M?.toolChoice?.toolName;if(T&&!x?.some((h)=>h.name===T))throw Error(`Required tool is unavailable: ${T}`);let P=rf(f);if(P.some((h)=>e_(h))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let D=Boolean(T)||nf(P),U=await df(P,this.model,x,_,T),E=Bx({messages:P,context:U,tools:x,requestOptions:M}),V=M?.providerRecovery;if(V&&!ox(V.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let A=V?.mode==="bounded_foreground"&&V.budgetMs>0?{budgetMs:V.budgetMs,startedAt:void 0}:void 0,R=A?"bounded_foreground":"standard",j=this.config.maxRetries??2,z=this.config.maxRetries??(A?ax:2),Q=A!==void 0&&this.config.maxRetries===void 0,b=0,u,Vf=this.config.providerCircuitRegistry??Ux(),xf=this.config.providerCircuitBreakerOpenMs??kf,jf=Math.max(Ef,Math.min(this.config.streamIdleTimeout??Rf,Jf)),dx=this.config.providerRequestAdmissionScheduler??Lx(),rx=this.config.providerRequestConcurrency??Kf,vf=this.config.providerRequestAdmissionMs??Qf,ix=this.config.providerRequestPendingBytes??bf,zf=M?.providerAdmission??{sessionId:this.admissionFallbackOwnerId,ownerId:this.admissionFallbackOwnerId,requestClass:"internal"},nx=(h)=>Vf.get({provider:h.provider,api:h.api,baseUrl:h.baseUrl??this.config.baseUrl??"",model:h.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,openDurationMs:xf,probeLeaseMs:jf}),ex=(h)=>({provider:h.provider,api:h.api,baseUrl:h.baseUrl??this.config.baseUrl??"",model:h.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,maxConcurrent:rx,maxPendingBytes:ix}),Y=(h=Date.now())=>{if(!A)return;let H=A.startedAt===void 0?0:Math.min(A.budgetMs,Math.max(0,h-A.startedAt));return{recoveryBudgetMs:A.budgetMs,recoveryElapsedMs:H,recoveryRemainingMs:Math.max(0,A.budgetMs-H)}},F=()=>({mode:R,...Y()??{}}),wf=()=>{if(A&&A.startedAt===void 0)A.startedAt=Date.now()},w=()=>{let h=Y();return new y(A?.budgetMs??0,h?.recoveryElapsedMs??0)},s=()=>!Q||b<z+1,Hf=(h,H)=>{let{state:k,...X}=H;return{phase:h,...X,...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}},qf=(h)=>({phase:"rejected",requestClass:h.requestClass,resource:h.resource,scope:h.scope,reason:h.reason,queuePosition:0,queueDepth:Math.max(0,h.queued),inFlight:Math.max(0,h.inFlight),limit:Math.max(0,h.limit),waitMs:h.reason==="wait_timeout"?h.maxWaitMs:0,maxWaitMs:h.maxWaitMs,...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}),f_=async function*(h){let H=Y()?.recoveryRemainingMs,k=H!==void 0&&A?.startedAt!==void 0?Math.min(vf,H):vf,X;try{X=dx.admit({scope:ex(h),sessionId:zf.sessionId,ownerId:zf.ownerId,requestClass:zf.requestClass,maxWaitMs:k,pendingBytes:E,signal:_})}catch(W){if(ff(W)){if(W.reason==="wait_timeout"&&A?.startedAt!==void 0&&(Y()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:qf(W)}}throw W}let I=X.getSnapshot();if(I.state==="admitted")return await X.ready;yield{providerAdmission:Hf("queued",I)};let c=X.ready.then((W)=>({kind:"ready",permit:W}),(W)=>({kind:"error",error:W}));while(!0){let W=X.getSnapshot(),J=Math.max(1,Math.min(Qx,Math.max(1,k-W.waitMs))),N,S=new Promise((q)=>{N=setTimeout(()=>q({kind:"heartbeat"}),J),N.unref?.()}),O=await Promise.race([c,S]);if(N)clearTimeout(N);if(O.kind==="heartbeat"){yield{providerAdmission:Hf("queued",X.getSnapshot())};continue}if(O.kind==="error"){if(ff(O.error)){if(O.error.reason==="wait_timeout"&&A?.startedAt!==void 0&&(Y()?.recoveryRemainingMs??0)<=0)throw w();yield{providerAdmission:qf(O.error)}}throw O.error}return yield{providerAdmission:Hf("admitted",X.getSnapshot())},O.permit}},x_=(h)=>{if(!s())throw w();if(Q)b++;u=void 0;let H=new AbortController,k=_?af(_,H.signal):H.signal,X;if(A?.startedAt!==void 0){let W=Y()?.recoveryRemainingMs??0;if(W<=0)throw w();let J=new y(A.budgetMs,A.budgetMs);X=setTimeout(()=>H.abort(J),W),X.unref?.()}let I=px(this.config,h,k,M,D);mx(I,h,(W)=>{u=W});let c=gx(this.models,h,U,I,{idleTimeoutMs:this.config.streamIdleTimeout??Rf,signal:k,abort:(W)=>H.abort(W)});return async function*(){try{yield*c}finally{if(X)clearTimeout(X)}}()},pf=this,m=(h)=>({phase:h.phase,reason:h.reason,...h.statusCode!==void 0?{statusCode:h.statusCode}:{},...h.retryAfterMs!==void 0?{retryAfterMs:h.retryAfterMs}:{},...h.nextProbeAt!==void 0?{nextProbeAt:h.nextProbeAt}:{},openDurationMs:h.openDurationMs,sampleCount:h.sampleCount,failureCount:h.failureCount,...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}),mf=(h,H)=>({phase:h,reason:H.reason,...H.statusCode!==void 0?{statusCode:H.statusCode}:{},retryAfterMs:H.retryAfterMs,...H.nextProbeAt!==void 0?{nextProbeAt:H.nextProbeAt}:{},openDurationMs:H.openDurationMs,sampleCount:H.sampleCount,failureCount:H.failureCount,...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}),__=(h)=>({phase:"probe",reason:h.reason??"server_error",...h.statusCode!==void 0?{statusCode:h.statusCode}:{},openDurationMs:h.openDurationMs??xf,...h.sampleCount!==void 0?{sampleCount:h.sampleCount}:{},...h.failureCount!==void 0?{failureCount:h.failureCount}:{},...Y()?{recoveryRemainingMs:Y()?.recoveryRemainingMs}:{}}),Wf=(h,H,k)=>({providerRetry:{phase:"exhausted",attempt:h,maxRetries:z,reason:H,...k!==void 0?{statusCode:k}:{},...F(),exhaustedBy:"recovery_budget"}}),tf=async function*(h,H,k,X){let I,c=!1,W,J,N=nx(h);for(let S=0;S<=k;S++){if(!s())break;let O,q;while(!O){let $=N.preflight();while(!$.eligible){if(W=$.reason,J=$.statusCode,!A||!X){let L=mf("rejected",$);throw yield{providerCircuit:L},new n(L)}wf();let G=Y()?.recoveryRemainingMs??0;if(G<=0){let L=w();throw yield Wf(Q?Math.max(0,b-1):S,$.reason,$.statusCode),L}yield{providerCircuit:mf("waiting",$)};let p=Math.min(Math.max(1,$.retryAfterMs),uf,G);if(await r(p,_,{throwOnAbort:!0}),(Y()?.recoveryRemainingMs??0)<=0){let L=w();throw yield Wf(Q?Math.max(0,b-1):S,$.reason,$.statusCode),L}$=N.preflight()}try{q=yield*f_(h)}catch(K){if(K instanceof y)yield Wf(Q?Math.max(0,b-1):S,W??"timeout",J);throw K}let C=N.check();if(C.allowed)O=C;else q.release(),q=void 0}let a=O.token;if(O.probe)yield{providerCircuit:__(O)};try{let $=!1,C=!1;for await(let K of x_(h)){if(K.providerStall){yield K;continue}let G=Q?b-1:S;if(G>0&&W&&!$)$=!0,yield{providerRetry:{phase:"recovered",attempt:G,maxRetries:z,reason:W,...J!==void 0?{statusCode:J}:{},...F()}};if(!C){C=!0;let p=N.recordSuccess(a);if(p)yield{providerCircuit:m(p)}}c=!0,H(),yield K}if(!C){let K=N.recordSuccess(a);if(K)yield{providerCircuit:m(K)}}return}catch($){if(q?.release(),I=$,pf.logIdleTimeout($,c,h),await pf.handleAbort(_),$ instanceof y){if(c)throw Lf($),$;throw yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,b-1):S,maxRetries:z,reason:W??"timeout",...J!==void 0?{statusCode:J}:{},...F(),exhaustedBy:"recovery_budget"}},$}let C=g($,u);if(c)throw Lf($),$;let K=f0($,u),G=K?N.recordFailure(a,K):u&&!x0($)?N.recordNeutral(a):void 0;if(G)yield{providerCircuit:m(G)};if(!C.retryable||!C.reason){if(S>0&&W)yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,b-1):S,maxRetries:z,reason:W,...J!==void 0?{statusCode:J}:{},...F()}};throw $}W=C.reason,J=C.statusCode;let p=S<k&&s();if(G&&G.phase!=="closed"&&p&&(!A||!X)){let L={...m(G),phase:"rejected"};throw yield{providerCircuit:L},new n(L)}if(p){wf();let L=Q?b:S+1,T_=Fx(L,u,A?{maxDelayMs:cf,maxExponentialDelayMs:cf}:void 0),yf=G&&G.phase!=="closed"?G.retryAfterMs??0:0;if(A&&yf>0&&G)yield{providerCircuit:{...m(G),phase:"waiting"}};let A_=Y(),Xf=Math.max(T_,yf),o=A?Math.min(Xf,A_?.recoveryRemainingMs??Xf):Xf,Mf={attempt:L,maxRetries:z,reason:C.reason,...C.statusCode!==void 0?{statusCode:C.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...Mf,delayMs:o,nextRetryAt:Date.now()+o,...F()}},A){let d=o;while(d>0){let gf=Math.min(d,uf);if(await r(gf,_,{throwOnAbort:!0}),d-=gf,(Y()?.recoveryRemainingMs??0)<=0){let Tf=w();throw yield{providerRetry:{phase:"exhausted",...Mf,...F(),exhaustedBy:"recovery_budget"}},Tf}if(d>0){if(G&&G.phase!=="closed"&&G.nextProbeAt!==void 0){let Tf=Math.max(0,G.nextProbeAt-Date.now());if(Tf>0)yield{providerCircuit:{...m(G),phase:"waiting",retryAfterMs:Tf}}}yield{providerRetry:{phase:"waiting",...Mf,delayMs:o,nextRetryAt:Date.now()+d,...F()}}}}}else await r(o,_,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...Mf,...F()}}}else yield{providerRetry:{phase:"exhausted",attempt:Q?Math.max(0,b-1):S,maxRetries:z,reason:C.reason,...C.statusCode!==void 0?{statusCode:C.statusCode}:{},...F(),...A&&(X||!s())?{exhaustedBy:"attempt_limit"}:{}}}}finally{N.abandon(a),q?.release()}}throw I},$f,lf=!1,_f=this.config.fallbackModels??[],M_=A&&_f.length>0?Math.min(j,z):z;try{for await(let h of tf(this.model,()=>{lf=!0},M_,_f.length===0))yield h;return}catch(h){if($f=h,lf||!ff(h)&&!Nf(h)&&!g(h,u).retryable)throw h}for(let[h,H]of _f.entries()){if(!s())break;yield{modelFallback:!0};let k=!1;try{let X=xx(this.config,H),I=h===_f.length-1,c=A&&!I?Math.min(j,z):z;for await(let W of tf(X,()=>{k=!0},c,I))yield W;return}catch(X){if($f=X,k||!ff(X)&&!Nf(X)&&!g(X,u).retryable)throw X}}throw $f}async handleAbort(f){if(f?.aborted)await r(0,f,{throwOnAbort:!0})}logIdleTimeout(f,x,_){if(f===null||typeof f!=="object"||!("code"in f)||f.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in f)||typeof f.timeoutMs!=="number")return;sx.warn("[PiAIChatService] Provider stream idle timeout",{provider:_.provider,model:_.id,timeoutMs:f.timeoutMs,replayBoundaryCrossed:x})}getConfig(){return{...this.config}}updateConfig(f){let x={...this.config,...f},_=Cf(x);this.config={...x,maxContextTokens:_.model.contextWindow,maxOutputTokens:x.maxOutputTokens??_.model.maxTokens},this.models=_.models,this.model=_.model}}var _0=t("Service");async function EM(f){let x=f;if(x.provider){let _=sf(x.provider);if(Object.keys(_).length>0)x={...x,customHeaders:{..._,...x.customHeaders}},_0.debug(`Injected ${x.provider} specific headers:`,Object.keys(_))}return M0(x)}function M0(f){return new Ff(f)}
5
+ export{P0 as Hd,h0 as Id,af as Jd,ff as Kd,F_ as Ld,w0 as Md,Ff as Nd,EM as Od};
@@ -1,4 +1,4 @@
1
- import{b as iJ,c as nJ,d as tJ}from"./chunk-k2hzhw9f.js";import{j as XJ,k as GJ}from"./chunk-np8f17zg.js";import{s as x8}from"./chunk-2fgmsnh6.js";import{B as UY,D as e2,E as o2,F as q6,L as j1,N as D4,O as V4,S as Z8,T as PJ,U as RJ,X as yJ,Y as MJ,ba as T6,ca as k6,da as OY,ea as l4,ga as d4,ia as B6,z as L6}from"./chunk-4dq8rbq2.js";import{ma as j9,na as h9,oa as E9,ra as qY}from"./chunk-9wxj0gxa.js";import"./chunk-34cexc50.js";import{Ua as t4,Va as s4,ib as e4,rb as l2}from"./chunk-74jd1hcs.js";import{Ab as K8}from"./chunk-5cgyevqj.js";import{Tb as r4,Yb as S4,bc as v4,ic as E4,jc as u2,kc as g4,mc as j8,uc as Y8,xc as P0}from"./chunk-7qj2tbew.js";import"./chunk-qgez5vw6.js";import"./chunk-3azdwanx.js";import{Zc as aJ}from"./chunk-qggnvzkc.js";import{$c as u8,_c as q8,bd as T1}from"./chunk-4p8sp6p3.js";import"./chunk-0evyrnx0.js";import{Fd as m0,fd as I$,gd as r0,hd as Q$,id as MQ,jd as D$,kd as h8,ld as Z9,md as dQ,nd as t9,od as X9,pd as f$,qd as $1,rd as GY,sd as a0,td as rJ,ud as R2,vd as X8,yd as x4}from"./chunk-vtb0m80j.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-kpr5nqh2.js";import{Qd as rQ}from"./chunk-3nj2f0q9.js";import"./chunk-3rjmkaey.js";import"./chunk-0s11h8yd.js";import{$d as M6,ce as hJ,ie as AJ,oe as KY}from"./chunk-vs7tcyse.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import{Ce as TQ,Ee as O1}from"./chunk-keart8yy.js";import"./chunk-v11r4ahz.js";import{nf as ZY,yf as bJ,zf as XY}from"./chunk-v85q852a.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import{Hf as V$,If as E8,Jf as kQ}from"./chunk-thstqcg3.js";import{Nf as l0}from"./chunk-6360fg4j.js";import"./chunk-bqpqh6re.js";import{fg as YY,ig as e1}from"./chunk-fk8jf873.js";import{kg as JJ,lg as YJ,og as h1}from"./chunk-p504jme7.js";import"./chunk-8kqnezvc.js";import{Ag as r9}from"./chunk-mc42kjv9.js";import{Bg as $4}from"./chunk-ew5dmar1.js";import"./chunk-03bzxkdg.js";import"./chunk-ts3pgkmz.js";import{Ng as IQ}from"./chunk-8jexqfqg.js";import{useMemoizedFn as D2}from"ahooks";import{useEffect as xX,useState as V2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as jX,useRef as f2}from"react";import{useShallow as _Y}from"zustand/react/shallow";import{useStore as zY}from"zustand";function n($){return zY(f$,$)}var NY=[],S$=()=>n(($)=>$.session.sessionId),I1=()=>n(($)=>$.session.workspaceRoot),Q4=()=>n(($)=>$.session.messages),J4=()=>n(($)=>$.session.clearCount),Y4=()=>n(($)=>$.session.isCompacting),Z4=()=>n(($)=>$.session.tokenUsage.estimatedCostUsd),X4=()=>n(($)=>$.session.providerCircuit),G4=()=>n(($)=>$.session.providerAdmission),K4=()=>n(($)=>$.session.providerRetry),q4=()=>n(($)=>$.session.providerStall),U4=()=>n(($)=>$.session.actionStationarity),n1=()=>n(($)=>$.session.actions),O4=()=>n(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),z4=()=>n(($)=>$.app.initializationStatus),_4=()=>n(($)=>$.app.initializationError),y8=()=>n(($)=>$.app.activeModal),N4=()=>n(($)=>$.app.tasks),F4=()=>n(($)=>$.app.modelEditorTarget),H4=()=>n(($)=>$.app.sessionSelectorData),W4=()=>n(($)=>$.app.awaitingSecondCtrlC),t1=()=>n(($)=>$.app.actions),M8=()=>n(($)=>$.app.initializationStatus==="ready"),L4=()=>n(($)=>$.app.tasks.length>0),v$=()=>n(($)=>$.config.config?.permissionMode||"default"),B4=()=>n(($)=>$.config.config?.models??NY),C8=()=>n(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),I8=()=>n(($)=>$.config.config?.currentModelId),A0=()=>n(($)=>{return r0.getTheme()}),w4=()=>n(($)=>$.config.config?.codeTheme??"default"),e0=()=>n(($)=>$.focus.currentFocus),b4=()=>n(($)=>$.focus.actions),s1=()=>n(($)=>$.command.isProcessing),A4=()=>n(($)=>$.command.actions),T8=()=>n(($)=>$.command.pendingCommands),P4=()=>n(($)=>$.command.recoveredSteeringCount),k8=()=>n(($)=>$.app.thinkingModeEnabled),f8=()=>n(($)=>$.app.reasoningEffort),S8=()=>n(($)=>$.app.serviceTier),v8=()=>n(($)=>$.app.responseVerbosity),D8=()=>n(($)=>$.app.communicationStyle),R4=()=>n(($)=>$.session.currentThinkingContent),y4=()=>n(($)=>$.session.thinkingExpanded),M4=()=>n(($)=>$.session.currentStreamingMessageId),C4=()=>n(_Y(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),I4=()=>n(($)=>$.session.finalizingStreamingMessageId),T4=()=>n(($)=>$.session.historyExpanded),k4=()=>n(($)=>$.session.expandedMessageCount);import{useMemoizedFn as h$}from"ahooks";import{useEffect as d8,useRef as n4}from"react";function FY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let G=JSON.parse(J.responseBody)?.error?.message;if(G){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${G}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function HY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function WY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function V8($){let Q=HY($),Y=WY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=FY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as LY,mkdirSync as BY,writeFileSync as wY}from"node:fs";import bY from"node:os";import E2 from"node:path";var f4=null;function AY(){let $=process.env.BLADE_STORAGE_ROOT||E2.join(bY.homedir(),".blade");return E2.join($,"logs","stream-debug.log")}function PY($){if(f4===$)return;let Q=E2.dirname($);BY(Q,{recursive:!0,mode:493}),wY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{b as iJ,c as nJ,d as tJ}from"./chunk-sfbprf9r.js";import{j as XJ,k as GJ}from"./chunk-t80e2bms.js";import{s as x8}from"./chunk-yxwargqc.js";import{B as UY,D as e2,E as o2,F as q6,L as j1,N as D4,O as V4,S as Z8,T as PJ,U as RJ,X as yJ,Y as MJ,ba as T6,ca as k6,da as OY,ea as l4,ga as d4,ia as B6,z as L6}from"./chunk-wk0vpgwk.js";import{ma as j9,na as h9,oa as E9,ra as qY}from"./chunk-wvc6bx0t.js";import"./chunk-v80xem15.js";import{Ua as t4,Va as s4,ib as e4,rb as l2}from"./chunk-adgx9vd7.js";import{Ab as K8}from"./chunk-5cgyevqj.js";import{Tb as r4,Yb as S4,bc as v4,ic as E4,jc as u2,kc as g4,mc as j8,uc as Y8,xc as P0}from"./chunk-zracmha2.js";import"./chunk-qgez5vw6.js";import"./chunk-bdxaz350.js";import{Zc as aJ}from"./chunk-3p32k12g.js";import{$c as u8,_c as q8,bd as T1}from"./chunk-hjkdc185.js";import"./chunk-y30kw6gj.js";import{Fd as m0,fd as I$,gd as r0,hd as Q$,id as MQ,jd as D$,kd as h8,ld as Z9,md as dQ,nd as t9,od as X9,pd as f$,qd as $1,rd as GY,sd as a0,td as rJ,ud as R2,vd as X8,yd as x4}from"./chunk-27w2k6t7.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-d61673v7.js";import{Rd as rQ}from"./chunk-4ekrbk2w.js";import"./chunk-fxw1q5j5.js";import"./chunk-yhw0pvyt.js";import{ae as M6,de as hJ,je as AJ,pe as KY}from"./chunk-6dma8han.js";import"./chunk-n0ebpwxd.js";import"./chunk-01jt0mpr.js";import"./chunk-ens8nsge.js";import{De as TQ,Fe as O1}from"./chunk-f4bx2n1y.js";import"./chunk-tsskar00.js";import{Af as XY,of as ZY,zf as bJ}from"./chunk-x5s68axq.js";import"./chunk-gbbnjzy8.js";import"./chunk-b5b8fb9y.js";import{If as V$,Jf as E8,Kf as kQ}from"./chunk-atdeg922.js";import{Of as l0}from"./chunk-g9re8v25.js";import"./chunk-nhzdkxnx.js";import{kg as YY,ng as e1}from"./chunk-fz55cnws.js";import{pg as JJ,qg as YJ,tg as h1}from"./chunk-5ygv33qe.js";import"./chunk-x04xb9g3.js";import{Fg as r9}from"./chunk-358zaryv.js";import{Gg as $4}from"./chunk-5sbewyjn.js";import"./chunk-npgt73cg.js";import"./chunk-9neq5xrb.js";import{Sg as IQ}from"./chunk-22h5kh4z.js";import{useMemoizedFn as D2}from"ahooks";import{useEffect as xX,useState as V2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as jX,useRef as f2}from"react";import{useShallow as _Y}from"zustand/react/shallow";import{useStore as zY}from"zustand";function n($){return zY(f$,$)}var NY=[],S$=()=>n(($)=>$.session.sessionId),I1=()=>n(($)=>$.session.workspaceRoot),Q4=()=>n(($)=>$.session.messages),J4=()=>n(($)=>$.session.clearCount),Y4=()=>n(($)=>$.session.isCompacting),Z4=()=>n(($)=>$.session.tokenUsage.estimatedCostUsd),X4=()=>n(($)=>$.session.providerCircuit),G4=()=>n(($)=>$.session.providerAdmission),K4=()=>n(($)=>$.session.providerRetry),q4=()=>n(($)=>$.session.providerStall),U4=()=>n(($)=>$.session.actionStationarity),n1=()=>n(($)=>$.session.actions),O4=()=>n(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),z4=()=>n(($)=>$.app.initializationStatus),_4=()=>n(($)=>$.app.initializationError),y8=()=>n(($)=>$.app.activeModal),N4=()=>n(($)=>$.app.tasks),F4=()=>n(($)=>$.app.modelEditorTarget),H4=()=>n(($)=>$.app.sessionSelectorData),W4=()=>n(($)=>$.app.awaitingSecondCtrlC),t1=()=>n(($)=>$.app.actions),M8=()=>n(($)=>$.app.initializationStatus==="ready"),L4=()=>n(($)=>$.app.tasks.length>0),v$=()=>n(($)=>$.config.config?.permissionMode||"default"),B4=()=>n(($)=>$.config.config?.models??NY),C8=()=>n(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),I8=()=>n(($)=>$.config.config?.currentModelId),A0=()=>n(($)=>{return r0.getTheme()}),w4=()=>n(($)=>$.config.config?.codeTheme??"default"),e0=()=>n(($)=>$.focus.currentFocus),b4=()=>n(($)=>$.focus.actions),s1=()=>n(($)=>$.command.isProcessing),A4=()=>n(($)=>$.command.actions),T8=()=>n(($)=>$.command.pendingCommands),P4=()=>n(($)=>$.command.recoveredSteeringCount),k8=()=>n(($)=>$.app.thinkingModeEnabled),f8=()=>n(($)=>$.app.reasoningEffort),S8=()=>n(($)=>$.app.serviceTier),v8=()=>n(($)=>$.app.responseVerbosity),D8=()=>n(($)=>$.app.communicationStyle),R4=()=>n(($)=>$.session.currentThinkingContent),y4=()=>n(($)=>$.session.thinkingExpanded),M4=()=>n(($)=>$.session.currentStreamingMessageId),C4=()=>n(_Y(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),I4=()=>n(($)=>$.session.finalizingStreamingMessageId),T4=()=>n(($)=>$.session.historyExpanded),k4=()=>n(($)=>$.session.expandedMessageCount);import{useMemoizedFn as h$}from"ahooks";import{useEffect as d8,useRef as n4}from"react";function FY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let G=JSON.parse(J.responseBody)?.error?.message;if(G){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${G}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function HY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function WY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function V8($){let Q=HY($),Y=WY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=FY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as LY,mkdirSync as BY,writeFileSync as wY}from"node:fs";import bY from"node:os";import E2 from"node:path";var f4=null;function AY(){let $=process.env.BLADE_STORAGE_ROOT||E2.join(bY.homedir(),".blade");return E2.join($,"logs","stream-debug.log")}function PY($){if(f4===$)return;let Q=E2.dirname($);BY(Q,{recursive:!0,mode:493}),wY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),f4=$}function g2($,Q,Y){try{let J=AY();PY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",G=`[${Z}] [${$}] ${Q}${X}
3
3
  `;LY(J,G)}catch{}}var J8=e1("UI");function j4($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,g2("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),J8.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),g2("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),G=$.getStreamingMessageId();if(G){if(Z)D$(G,Z);h8(G)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===j8)break;if(J8.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),G=D4(Z.function.name,X);$.sessionActions.addToolMessage(G,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:G,params:X})}catch(X){J8.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===j8)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",G=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(G,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:G,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===j8)break;J8.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=v4(V4(Z.function.name,J.result),S4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":J8.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -1 +1 @@
1
- import"./chunk-8jexqfqg.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
1
+ import"./chunk-22h5kh4z.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};