blade-code 0.10.41 → 0.10.42

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 (106) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-t80e2bms.js → chunk-020hgyg7.js} +1 -1
  3. package/dist/{chunk-fxw1q5j5.js → chunk-0jsy9eav.js} +1 -1
  4. package/dist/{chunk-5sbewyjn.js → chunk-0qf7h4n2.js} +2 -2
  5. package/dist/{chunk-b5b8fb9y.js → chunk-18wnstzp.js} +1 -1
  6. package/dist/chunk-1e9866ye.js +5 -0
  7. package/dist/{chunk-q87nwpsb.js → chunk-1whfdz08.js} +1 -1
  8. package/dist/{chunk-bdxaz350.js → chunk-1yjzj2d0.js} +2 -2
  9. package/dist/{chunk-y30kw6gj.js → chunk-3v2sgvzt.js} +2 -2
  10. package/dist/{chunk-eg5sz4bw.js → chunk-3xx2ebr7.js} +1 -1
  11. package/dist/{chunk-nhzdkxnx.js → chunk-4k37vmxh.js} +1 -1
  12. package/dist/{chunk-xs7w13na.js → chunk-4rmdfme3.js} +1 -1
  13. package/dist/chunk-5hbm5e24.js +44 -0
  14. package/dist/{chunk-gbbnjzy8.js → chunk-5zr3w30g.js} +1 -1
  15. package/dist/{chunk-ens8nsge.js → chunk-6d0hphtd.js} +1 -1
  16. package/dist/chunk-74sxsd1h.js +1 -0
  17. package/dist/chunk-78jy2kby.js +1 -0
  18. package/dist/{chunk-djr17h80.js → chunk-7gjb405q.js} +1 -1
  19. package/dist/{chunk-atsw605q.js → chunk-7pmpm5yq.js} +1 -1
  20. package/dist/chunk-7qd6xqjs.js +1 -0
  21. package/dist/{chunk-adgx9vd7.js → chunk-8b2bpfnt.js} +3 -3
  22. package/dist/{chunk-6dma8han.js → chunk-8csfb83y.js} +2 -2
  23. package/dist/chunk-8wg7g98v.js +10 -0
  24. package/dist/{chunk-5zf8204m.js → chunk-anwm8rp3.js} +1 -1
  25. package/dist/{chunk-yxwargqc.js → chunk-brwdd5kp.js} +1 -1
  26. package/dist/chunk-c53hc8ze.js +1 -0
  27. package/dist/{chunk-yhw0pvyt.js → chunk-d2fce0vk.js} +2 -2
  28. package/dist/chunk-dgs04r04.js +2 -0
  29. package/dist/{chunk-dp9xzsja.js → chunk-dr4et3gj.js} +1 -1
  30. package/dist/{chunk-qgez5vw6.js → chunk-dx7xefys.js} +1 -1
  31. package/dist/{chunk-5ygv33qe.js → chunk-ecw74d2s.js} +2 -2
  32. package/dist/{chunk-w07gb3h0.js → chunk-ex21hxqf.js} +1 -1
  33. package/dist/{chunk-tsskar00.js → chunk-f542fh7g.js} +1 -1
  34. package/dist/{chunk-0hqsdbkr.js → chunk-f90ybvrs.js} +1 -1
  35. package/dist/{chunk-2bm55evt.js → chunk-fye8eghq.js} +2 -2
  36. package/dist/chunk-h9fkttf1.js +2 -0
  37. package/dist/chunk-hkmgrdxc.js +1 -0
  38. package/dist/{chunk-01jt0mpr.js → chunk-hypq4t4z.js} +1 -1
  39. package/dist/{chunk-8xfzbv9v.js → chunk-jf6mkx0j.js} +1 -1
  40. package/dist/{chunk-g9re8v25.js → chunk-jv9zg1fw.js} +1 -1
  41. package/dist/{chunk-wvc6bx0t.js → chunk-jz2gkqdt.js} +2 -2
  42. package/dist/chunk-katrmbxc.js +1 -0
  43. package/dist/{chunk-4ekrbk2w.js → chunk-kfv4mdcm.js} +2 -2
  44. package/dist/{chunk-9neq5xrb.js → chunk-m3dvta6k.js} +2 -2
  45. package/dist/chunk-m4ya7qqd.js +1 -0
  46. package/dist/{chunk-22h5kh4z.js → chunk-m8s208g3.js} +1 -1
  47. package/dist/{chunk-27w2k6t7.js → chunk-mp637mb6.js} +2 -2
  48. package/dist/{chunk-npgt73cg.js → chunk-mpymjr7j.js} +1 -1
  49. package/dist/{chunk-f4bx2n1y.js → chunk-mt7fn8cv.js} +3 -3
  50. package/dist/chunk-n6c6k87j.js +1 -0
  51. package/dist/{chunk-x04xb9g3.js → chunk-pm9kt54d.js} +1 -1
  52. package/dist/chunk-ppxn94za.js +1 -0
  53. package/dist/{chunk-hjkdc185.js → chunk-q6n6rqzs.js} +2 -2
  54. package/dist/{chunk-4mdy9d43.js → chunk-qb49rm5q.js} +1 -1
  55. package/dist/chunk-rf7hdke7.js +1 -0
  56. package/dist/chunk-rjjjgcw4.js +1 -0
  57. package/dist/{chunk-wk0vpgwk.js → chunk-sw3p1ygn.js} +396 -396
  58. package/dist/{chunk-fz55cnws.js → chunk-t2mc97k7.js} +2 -2
  59. package/dist/{chunk-5cgyevqj.js → chunk-te95z52n.js} +1 -1
  60. package/dist/{chunk-n0ebpwxd.js → chunk-vc32qrmq.js} +1 -1
  61. package/dist/chunk-vsaqjbm2.js +6 -0
  62. package/dist/{chunk-nsawkccy.js → chunk-wcxsm922.js} +1 -1
  63. package/dist/chunk-wm944thh.js +111 -0
  64. package/dist/chunk-wn23bvs0.js +1 -0
  65. package/dist/{chunk-62jaf7ej.js → chunk-wtczk025.js} +1 -1
  66. package/dist/{chunk-ck8sw2zp.js → chunk-xkg84094.js} +2 -2
  67. package/dist/{chunk-3p32k12g.js → chunk-y75y911b.js} +2 -2
  68. package/dist/chunk-yatvtpft.js +1 -0
  69. package/dist/{chunk-358zaryv.js → chunk-yqxyy3w2.js} +2 -2
  70. package/dist/{chunk-sfbprf9r.js → chunk-z60w7p8a.js} +1 -1
  71. package/dist/chunk-za6zyd82.js +8 -0
  72. package/dist/chunk-zhrc510s.js +1 -0
  73. package/dist/web/assets/{ChatView-BP89vdT_.js → ChatView-DBgMoUrW.js} +2 -2
  74. package/dist/web/assets/{CodeBlockHighlighter-UnjC3KVk.js → CodeBlockHighlighter-DLFQUVD6.js} +1 -1
  75. package/dist/web/assets/{FilePreview-D0BiZowf.js → FilePreview--1qHdJP_.js} +1 -1
  76. package/dist/web/assets/{MarkdownRenderer-CPu_rkPT.js → MarkdownRenderer-DcVHyjtl.js} +3 -3
  77. package/dist/web/assets/{SettingsModal-CM9pcJas.js → SettingsModal-BM6SPUXW.js} +1 -1
  78. package/dist/web/assets/{TaskSwitcher-BOCm7kPO.js → TaskSwitcher-B5VYY_QG.js} +1 -1
  79. package/dist/web/assets/{TerminalPanel-CUZ4slSS.js → TerminalPanel-XWA1jGs8.js} +1 -1
  80. package/dist/web/assets/index-B8y5_J0i.js +11 -0
  81. package/dist/web/assets/{session-events-109FkhOM.js → session-events-DJh6SZcl.js} +5 -5
  82. package/dist/web/index.html +2 -2
  83. package/package.json +1 -1
  84. package/dist/chunk-1j2sf8mc.js +0 -1
  85. package/dist/chunk-1kwm2m6t.js +0 -1
  86. package/dist/chunk-5w8edqbt.js +0 -1
  87. package/dist/chunk-6a3c496e.js +0 -1
  88. package/dist/chunk-6fe9kq17.js +0 -1
  89. package/dist/chunk-asnzpfzh.js +0 -10
  90. package/dist/chunk-atdeg922.js +0 -2
  91. package/dist/chunk-bw7fgs2n.js +0 -1
  92. package/dist/chunk-d61673v7.js +0 -5
  93. package/dist/chunk-f7y4m3y0.js +0 -1
  94. package/dist/chunk-fnz5g9ac.js +0 -1
  95. package/dist/chunk-kjn0yaqw.js +0 -1
  96. package/dist/chunk-m883e8d4.js +0 -1
  97. package/dist/chunk-mx5s93np.js +0 -6
  98. package/dist/chunk-p54vmne8.js +0 -1
  99. package/dist/chunk-qy9qkvwe.js +0 -1
  100. package/dist/chunk-s8f8amvg.js +0 -1
  101. package/dist/chunk-v80xem15.js +0 -2
  102. package/dist/chunk-w1vcjwbx.js +0 -8
  103. package/dist/chunk-x5s68axq.js +0 -44
  104. package/dist/chunk-z15h0370.js +0 -1
  105. package/dist/chunk-zracmha2.js +0 -111
  106. package/dist/web/assets/index-CthLsVgC.js +0 -11
@@ -0,0 +1 @@
1
+ import{pe as a,qe as b,re as c,se as d,te as e}from"./chunk-8csfb83y.js";import"./chunk-vc32qrmq.js";import"./chunk-hypq4t4z.js";import"./chunk-6d0hphtd.js";import"./chunk-mt7fn8cv.js";import"./chunk-f542fh7g.js";import"./chunk-5hbm5e24.js";import"./chunk-5zr3w30g.js";import"./chunk-18wnstzp.js";import"./chunk-dgs04r04.js";import"./chunk-jv9zg1fw.js";import"./chunk-4k37vmxh.js";import"./chunk-t2mc97k7.js";import"./chunk-ecw74d2s.js";import"./chunk-pm9kt54d.js";import"./chunk-yqxyy3w2.js";import"./chunk-0qf7h4n2.js";import"./chunk-mpymjr7j.js";import"./chunk-m3dvta6k.js";import"./chunk-m8s208g3.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
@@ -0,0 +1 @@
1
+ import{Vc as a,Wc as b}from"./chunk-xkg84094.js";import"./chunk-yqxyy3w2.js";import"./chunk-m8s208g3.js";export{a as globalOptions,b as cliConfig};
@@ -1,4 +1,4 @@
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()} ===
1
+ import{b as iJ,c as nJ,d as tJ}from"./chunk-z60w7p8a.js";import{j as XJ,k as GJ}from"./chunk-020hgyg7.js";import{s as x8}from"./chunk-brwdd5kp.js";import{B as UY,D as e2,E as o2,F as q6,L as j1,N as D4,O as V4,T as Z8,U as PJ,V as RJ,Y as yJ,Z as MJ,ca as T6,da as k6,ea as OY,fa as l4,ha as d4,ja as B6,z as L6}from"./chunk-sw3p1ygn.js";import{na as j9,oa as h9,pa as E9,sa as qY}from"./chunk-jz2gkqdt.js";import"./chunk-h9fkttf1.js";import{Va as t4,Wa as s4,jb as e4,sb as l2}from"./chunk-8b2bpfnt.js";import{Bb as K8}from"./chunk-te95z52n.js";import{Ub as r4,Zb as S4,cc as v4,jc as E4,kc as u2,lc as g4,nc as j8,vc as Y8,yc as P0}from"./chunk-wm944thh.js";import"./chunk-dx7xefys.js";import"./chunk-1yjzj2d0.js";import{_c as aJ}from"./chunk-y75y911b.js";import{$c as q8,ad as u8,cd as T1}from"./chunk-q6n6rqzs.js";import"./chunk-3v2sgvzt.js";import{Gd as m0,gd as I$,hd as r0,id as Q$,jd as MQ,kd as D$,ld as h8,md as Z9,nd as dQ,od as t9,pd as X9,qd as f$,rd as $1,sd as GY,td as a0,ud as rJ,vd as R2,wd as X8,zd as x4}from"./chunk-mp637mb6.js";import"./chunk-v508x7cg.js";import"./chunk-7pmpm5yq.js";import"./chunk-1e9866ye.js";import{Td as rQ}from"./chunk-kfv4mdcm.js";import"./chunk-0jsy9eav.js";import"./chunk-d2fce0vk.js";import{ce as M6,fe as hJ,le as AJ,re as KY}from"./chunk-8csfb83y.js";import"./chunk-vc32qrmq.js";import"./chunk-hypq4t4z.js";import"./chunk-6d0hphtd.js";import{Fe as TQ,He as O1}from"./chunk-mt7fn8cv.js";import"./chunk-f542fh7g.js";import{Af as ZY,Ff as bJ,Gf as XY}from"./chunk-5hbm5e24.js";import"./chunk-5zr3w30g.js";import"./chunk-18wnstzp.js";import{Of as V$,Pf as E8,Qf as kQ}from"./chunk-dgs04r04.js";import{Uf as l0}from"./chunk-jv9zg1fw.js";import"./chunk-4k37vmxh.js";import{qg as YY,tg as e1}from"./chunk-t2mc97k7.js";import{vg as JJ,wg as YJ,zg as h1}from"./chunk-ecw74d2s.js";import"./chunk-pm9kt54d.js";import{Lg as r9}from"./chunk-yqxyy3w2.js";import{Mg as $4}from"./chunk-0qf7h4n2.js";import"./chunk-mpymjr7j.js";import"./chunk-m3dvta6k.js";import{Yg as IQ}from"./chunk-m8s208g3.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,2 +1,2 @@
1
1
  import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
2
- export{B as Gd};
2
+ export{B as Hd};
@@ -0,0 +1 @@
1
+ import{sc as a,tc as b,uc as c,vc as d,wc as e,xc as f,yc as g}from"./chunk-wm944thh.js";import"./chunk-dx7xefys.js";import"./chunk-1yjzj2d0.js";import"./chunk-0jsy9eav.js";import"./chunk-hypq4t4z.js";import"./chunk-f542fh7g.js";import"./chunk-dgs04r04.js";import"./chunk-jv9zg1fw.js";import"./chunk-t2mc97k7.js";import"./chunk-pm9kt54d.js";import"./chunk-yqxyy3w2.js";import"./chunk-m3dvta6k.js";import"./chunk-m8s208g3.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1,4 +1,4 @@
1
- import{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>
1
+ import{Fb as HJ}from"./chunk-te95z52n.js";import{Gb as l0,Nb as O6,Ob as U6,Pb as $2,Qb as J2,Xb as H6,dc as C$,nc as y0,pc as G2,qc as X1,rc as O2,yc as f$}from"./chunk-wm944thh.js";import{Dc as t,Gc as D6,Hc as O0}from"./chunk-1yjzj2d0.js";import{Hd as T6}from"./chunk-7pmpm5yq.js";import{Id as ZJ,Jd as C0,Kd as a6,Nd as WJ,Od as q2,Qd as Y6}from"./chunk-1e9866ye.js";import{ue as v0,ve as A0,ye as YJ}from"./chunk-vc32qrmq.js";import{He as Z$}from"./chunk-mt7fn8cv.js";import{Uf as a}from"./chunk-jv9zg1fw.js";import{tg as G0}from"./chunk-t2mc97k7.js";import{Hg as G6}from"./chunk-yqxyy3w2.js";import{Pg as H$,Rg as a2,Sg as z0,Tg as K1,Vg as L6,Xg as q6}from"./chunk-m3dvta6k.js";import{Yg as _8}from"./chunk-m8s208g3.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-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(`
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-n6c6k87j.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}
@@ -201,4 +201,4 @@ ${E}`}if(typeof M==="object"&&M!==null)M=JSON.stringify(M,null,2);if(typeof M===
201
201
  ${f6(c0)}
202
202
  </system-reminder>`,metadata:C$};G.appendControl("user",L);let B=await K0($,Z,L.content,Q,C$);if(B)Q=B}}if(W?.signal?.aborted)return j(K,X.length,W.signal);if(K>=j$&&(XJ||R)){if(I.info(`Warning: 达到轮次上限 ${j$} 轮`),W?.onTurnLimitReached){let L=await W.onTurnLimitReached({turnsCount:K});if(L?.continue){G.writeback();let B="failed",P,_,c;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let N=$.chatService.getConfig(),y=await K$.compact(Z.messages,{trigger:"auto",modelName:N.model,modelProvider:N.provider,maxContextTokens:N.maxContextTokens??0,apiKey:N.apiKey,baseURL:N.baseUrl,actualPreTokens:O1,signal:W?.signal,activeTask:j0,workspaceRoot:Z.workspaceRoot||a(),sessionId:Z.sessionId});if(y.usage)yield{kind:"token_usage",usage:G1(y.usage,N.maxContextTokens??0)};let S={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
203
203
 
204
- Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},M=[...y.compactedMessages,S];P=y.success?"llm":"fallback",_=y.preTokens,c=y.postTokens,await T$($,Z,y.summary,{trigger:"auto",reason:"turn_limit",strategy:P,preTokens:y.preTokens,postTokens:y.postTokens,filesIncluded:y.filesIncluded,replacementMessages:M},{required:$.executionEngine!==void 0}),Z.messages=M,G.replaceHistory(Z.messages),B=y.success?"completed":"fallback"}catch(N){throw I.error("[Loop] 轮次上限压缩失败,停止继续执行:",N),N}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:B,strategy:P,preTokens:_,postTokens:c}}K=0;continue}return{success:!0,finalMessage:L?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}return{success:!1,error:{type:"max_turns_exceeded",message:R?`子代理已达到轮次上限 (${j$} 轮)。`:`已达到轮次上限 (${j$} 轮)。`},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}}}catch(O){if(O instanceof Y$)try{let U=Z.sessionId?await f$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):B0;G.restoreDurableHistory(U)}catch(U){I.error("[Loop] Failed to reload durable context after message commit failure:",U),G.restoreDurableHistory(B0)}throw O}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((O)=>{let U=O.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});G.writeback()}}catch(q){if(C0(q))return j(K,X.length,W?.signal);if(q instanceof Y$)return{success:!1,error:{type:"message_persistence_failed",message:q.message},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}};let V=f4(q);return I.error(`API 调用失败: ${V}`),{success:!1,error:{type:"api_error",message:V,details:q},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}}}finally{if(z)Z.messages.push({role:"system",content:c1}),await t2($,Z,Q)}}export{l1 as Ma,S$ as Na,m4 as Oa,I1 as Pa,s$ as Qa,Q$ as Ra,d1 as Sa,o2 as Ta,Y5 as Ua,E$ as Va,a0 as Wa,I0 as Xa,yJ as Ya,J$ as Za,l4 as _a,p1 as $a,g1 as ab,m2 as bb,u1 as cb,c6 as db,i6 as eb,r6 as fb,$$ as gb,a$ as hb,iJ as ib,K0 as jb,g as kb,i1 as lb,Z1 as mb,T$ as nb,h0 as ob,K$ as pb,Q1 as qb,e as rb,q1 as sb,s6 as tb,t6 as ub,e6 as vb,U4 as wb,w2 as xb,KJ as yb,C4 as zb};
204
+ Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},M=[...y.compactedMessages,S];P=y.success?"llm":"fallback",_=y.preTokens,c=y.postTokens,await T$($,Z,y.summary,{trigger:"auto",reason:"turn_limit",strategy:P,preTokens:y.preTokens,postTokens:y.postTokens,filesIncluded:y.filesIncluded,replacementMessages:M},{required:$.executionEngine!==void 0}),Z.messages=M,G.replaceHistory(Z.messages),B=y.success?"completed":"fallback"}catch(N){throw I.error("[Loop] 轮次上限压缩失败,停止继续执行:",N),N}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:B,strategy:P,preTokens:_,postTokens:c}}K=0;continue}return{success:!0,finalMessage:L?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}return{success:!1,error:{type:"max_turns_exceeded",message:R?`子代理已达到轮次上限 (${j$} 轮)。`:`已达到轮次上限 (${j$} 轮)。`},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H,tokensUsed:n}}}}}catch(O){if(O instanceof Y$)try{let U=Z.sessionId?await f$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):B0;G.restoreDurableHistory(U)}catch(U){I.error("[Loop] Failed to reload durable context after message commit failure:",U),G.restoreDurableHistory(B0)}throw O}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((O)=>{let U=O.metadata;return U!==null&&typeof U==="object"&&!Array.isArray(U)&&U.transientGoalContinuation===!0});G.writeback()}}catch(q){if(C0(q))return j(K,X.length,W?.signal);if(q instanceof Y$)return{success:!1,error:{type:"message_persistence_failed",message:q.message},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}};let V=f4(q);return I.error(`API 调用失败: ${V}`),{success:!1,error:{type:"api_error",message:V,details:q},metadata:{turnsCount:K,toolCallsCount:X.length,duration:Date.now()-H}}}finally{if(z)Z.messages.push({role:"system",content:c1}),await t2($,Z,Q)}}export{l1 as Na,S$ as Oa,m4 as Pa,I1 as Qa,s$ as Ra,Q$ as Sa,d1 as Ta,o2 as Ua,Y5 as Va,E$ as Wa,a0 as Xa,I0 as Ya,yJ as Za,J$ as _a,l4 as $a,p1 as ab,g1 as bb,m2 as cb,u1 as db,c6 as eb,i6 as fb,r6 as gb,$$ as hb,a$ as ib,iJ as jb,K0 as kb,g as lb,i1 as mb,Z1 as nb,T$ as ob,h0 as pb,K$ as qb,Q1 as rb,e as sb,q1 as tb,s6 as ub,t6 as vb,e6 as wb,U4 as xb,w2 as yb,KJ as zb,C4 as Ab};
@@ -1,4 +1,4 @@
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
1
+ import{ue as L1,ve as Z0,we as G1}from"./chunk-vc32qrmq.js";import{Ae as $O,Be as HO}from"./chunk-hypq4t4z.js";import{Ee as Y1}from"./chunk-6d0hphtd.js";import{Fe as B0,He as M0}from"./chunk-mt7fn8cv.js";import{Af as V0,Bf as o1,Ff as S0}from"./chunk-5hbm5e24.js";import{If as u,Kf as W,Nf as R1}from"./chunk-18wnstzp.js";import{Uf as b}from"./chunk-jv9zg1fw.js";import{tg as h,ug as z}from"./chunk-t2mc97k7.js";import{Hg as p0}from"./chunk-yqxyy3w2.js";import{Mg as w}from"./chunk-0qf7h4n2.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 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};
710
+ export{u$ as Zd,c$ as _d,W1 as $d,i$ as ae,t$ as be,i as ce,H4 as de,U1 as ee,P as fe,DO as ge,T as he,o0 as ie,j0 as je,f as ke,z0 as le,a0 as me,x0 as ne,d as oe,p$ as pe,f2 as qe,h2 as re,k2 as se,P2 as te};
@@ -0,0 +1,10 @@
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-za6zyd82.js";import"./chunk-020hgyg7.js";import"./chunk-anwm8rp3.js";import"./chunk-brwdd5kp.js";import"./chunk-wcxsm922.js";import"./chunk-sw3p1ygn.js";import"./chunk-jz2gkqdt.js";import"./chunk-h9fkttf1.js";import"./chunk-8b2bpfnt.js";import"./chunk-te95z52n.js";import"./chunk-wm944thh.js";import"./chunk-dx7xefys.js";import"./chunk-1yjzj2d0.js";import{ad as R}from"./chunk-q6n6rqzs.js";import"./chunk-3v2sgvzt.js";import{wd as Q}from"./chunk-mp637mb6.js";import"./chunk-v508x7cg.js";import"./chunk-7pmpm5yq.js";import"./chunk-1e9866ye.js";import"./chunk-kfv4mdcm.js";import"./chunk-0jsy9eav.js";import"./chunk-d2fce0vk.js";import"./chunk-8csfb83y.js";import"./chunk-vc32qrmq.js";import"./chunk-hypq4t4z.js";import"./chunk-6d0hphtd.js";import"./chunk-mt7fn8cv.js";import"./chunk-f542fh7g.js";import"./chunk-5hbm5e24.js";import"./chunk-5zr3w30g.js";import"./chunk-18wnstzp.js";import"./chunk-dgs04r04.js";import"./chunk-jv9zg1fw.js";import"./chunk-4k37vmxh.js";import"./chunk-t2mc97k7.js";import"./chunk-ecw74d2s.js";import"./chunk-pm9kt54d.js";import{Hg as M}from"./chunk-yqxyy3w2.js";import"./chunk-0qf7h4n2.js";import"./chunk-mpymjr7j.js";import"./chunk-m3dvta6k.js";import"./chunk-m8s208g3.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};
@@ -1,3 +1,3 @@
1
- import{Pg as $,Qg as F}from"./chunk-9neq5xrb.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
1
+ import{Vg as $,Wg as F}from"./chunk-m3dvta6k.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
2
2
  `,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
3
3
  export{_ as l};
@@ -1,4 +1,4 @@
1
- import{M as P}from"./chunk-wk0vpgwk.js";import{Xa as K}from"./chunk-adgx9vd7.js";import{Qb as G,Rb as N,Sb as S,Tb as O,Ub as s,xc as B}from"./chunk-zracmha2.js";import{Gc as j}from"./chunk-bdxaz350.js";import{Gd as q}from"./chunk-atsw605q.js";import{Zd as v}from"./chunk-6dma8han.js";import{Mg as z}from"./chunk-9neq5xrb.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{M as P}from"./chunk-sw3p1ygn.js";import{Ya as K}from"./chunk-8b2bpfnt.js";import{Rb as G,Sb as N,Tb as S,Ub as O,Vb as s,yc as B}from"./chunk-wm944thh.js";import{Hc as j}from"./chunk-1yjzj2d0.js";import{Hd as q}from"./chunk-7pmpm5yq.js";import{$d as v}from"./chunk-8csfb83y.js";import{Sg as z}from"./chunk-m3dvta6k.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -0,0 +1 @@
1
+ import{f as a,g as i,h as l,i as m}from"./chunk-za6zyd82.js";import"./chunk-020hgyg7.js";import"./chunk-anwm8rp3.js";import"./chunk-brwdd5kp.js";import"./chunk-wcxsm922.js";import"./chunk-sw3p1ygn.js";import"./chunk-jz2gkqdt.js";import"./chunk-h9fkttf1.js";import"./chunk-8b2bpfnt.js";import"./chunk-te95z52n.js";import"./chunk-wm944thh.js";import"./chunk-dx7xefys.js";import"./chunk-1yjzj2d0.js";import{ad as n}from"./chunk-q6n6rqzs.js";import"./chunk-3v2sgvzt.js";import{wd as s}from"./chunk-mp637mb6.js";import"./chunk-v508x7cg.js";import"./chunk-7pmpm5yq.js";import"./chunk-1e9866ye.js";import"./chunk-kfv4mdcm.js";import"./chunk-0jsy9eav.js";import"./chunk-d2fce0vk.js";import"./chunk-8csfb83y.js";import"./chunk-vc32qrmq.js";import"./chunk-hypq4t4z.js";import"./chunk-6d0hphtd.js";import"./chunk-mt7fn8cv.js";import"./chunk-f542fh7g.js";import"./chunk-5hbm5e24.js";import"./chunk-5zr3w30g.js";import"./chunk-18wnstzp.js";import"./chunk-dgs04r04.js";import"./chunk-jv9zg1fw.js";import"./chunk-4k37vmxh.js";import"./chunk-t2mc97k7.js";import"./chunk-ecw74d2s.js";import"./chunk-pm9kt54d.js";import"./chunk-yqxyy3w2.js";import"./chunk-0qf7h4n2.js";import"./chunk-mpymjr7j.js";import"./chunk-m3dvta6k.js";import"./chunk-m8s208g3.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,2 +1,2 @@
1
- import{zf as F}from"./chunk-x5s68axq.js";import{sg as D,tg as E}from"./chunk-5ygv33qe.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
- export{H as Ud,Q as Vd,T as Wd};
1
+ import{Ff as F}from"./chunk-5hbm5e24.js";import{yg as D,zg as E}from"./chunk-ecw74d2s.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
+ export{H as Wd,Q as Xd,T as Yd};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as Of,T as Pf,A as Qf};
@@ -1 +1 @@
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};
1
+ import"./chunk-m8s208g3.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,2 +1,2 @@
1
1
  var f;((c)=>{c.ReadOnly="readonly";c.Write="write";c.Execute="execute"})(f||={});function g(b){return b!==void 0&&typeof b.pattern==="string"&&typeof b.search_path==="string"}function h(b){return b!==void 0&&b.kind==="edit"&&typeof b.matches_found==="number"}function j(b){return b==="readonly"}
2
- export{f as yc,g as zc,h as Ac,j as Bc};
2
+ export{f as zc,g as Ac,h as Bc,j as Cc};
@@ -1,3 +1,3 @@
1
- import{vg as N,yg as M}from"./chunk-x04xb9g3.js";import{Qg as H}from"./chunk-9neq5xrb.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
1
+ import{Bg as N,Eg as M}from"./chunk-pm9kt54d.js";import{Wg as H}from"./chunk-m3dvta6k.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
2
2
  `,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
3
- export{K as pg,X as qg,J as rg,L as sg,hu as tg};
3
+ export{K as vg,X as wg,J as xg,L as yg,hu as zg};