blade-code 0.10.205 → 0.11.1

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 (184) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-7ajvrtb3.js → chunk-06hkf59s.js} +1 -1
  3. package/dist/{chunk-p0wyhp5a.js → chunk-0b83mt1c.js} +2 -2
  4. package/dist/{chunk-qtwgm95z.js → chunk-0wcnkxe8.js} +3 -3
  5. package/dist/{chunk-b8ast0cp.js → chunk-1beqtjsw.js} +1 -1
  6. package/dist/chunk-1kxpnt9q.js +1 -0
  7. package/dist/chunk-25s0c8km.js +1726 -0
  8. package/dist/{chunk-ak5xvsxr.js → chunk-27bjk35b.js} +1 -1
  9. package/dist/{chunk-515yj7mt.js → chunk-2ftyzk83.js} +1 -1
  10. package/dist/chunk-2g3v9qpz.js +1 -0
  11. package/dist/{chunk-5zmp7p0n.js → chunk-2vrsfb8p.js} +59 -59
  12. package/dist/{chunk-17d4m89n.js → chunk-30p7aff1.js} +2 -2
  13. package/dist/{chunk-kehgewqh.js → chunk-3kszepm6.js} +1 -1
  14. package/dist/{chunk-ys8gysg8.js → chunk-3y2x6fb6.js} +1 -1
  15. package/dist/chunk-43gg1wdc.js +1 -0
  16. package/dist/{chunk-xbs91jd8.js → chunk-447ps2te.js} +2 -2
  17. package/dist/{chunk-0eajnhrj.js → chunk-4cdk4mds.js} +1 -1
  18. package/dist/{chunk-8pd1hp4r.js → chunk-5034apfz.js} +2 -2
  19. package/dist/{chunk-ynd1v33f.js → chunk-5bc4hwt9.js} +1 -1
  20. package/dist/chunk-72wn385d.js +1 -0
  21. package/dist/chunk-7eset766.js +25 -0
  22. package/dist/chunk-7vzz3rsx.js +332 -0
  23. package/dist/{chunk-xxbxc31z.js → chunk-80946c9a.js} +1 -1
  24. package/dist/chunk-8emp6ysb.js +1 -0
  25. package/dist/chunk-8evyh5t0.js +1 -0
  26. package/dist/chunk-8hdtssvs.js +1 -0
  27. package/dist/chunk-8n3jythp.js +733 -0
  28. package/dist/{chunk-zj1g4nbq.js → chunk-8sth12hd.js} +1 -1
  29. package/dist/{chunk-fdr4fcrf.js → chunk-9qxch6sy.js} +1 -1
  30. package/dist/chunk-9ydrwcpy.js +3 -0
  31. package/dist/chunk-9yn01a90.js +12 -0
  32. package/dist/chunk-a1tt14a2.js +2 -0
  33. package/dist/{chunk-egss0m1x.js → chunk-a731hdwa.js} +1 -1
  34. package/dist/{chunk-gn9er641.js → chunk-a74ynw4t.js} +1 -1
  35. package/dist/chunk-b36egepz.js +1 -0
  36. package/dist/chunk-dxq7462e.js +352 -0
  37. package/dist/{chunk-eg3ms291.js → chunk-f552hzcx.js} +1 -1
  38. package/dist/{chunk-g01mth5d.js → chunk-f6hc7t65.js} +2 -2
  39. package/dist/{chunk-qq5y7b2r.js → chunk-fqxzzsgr.js} +1 -1
  40. package/dist/{chunk-xyypxrad.js → chunk-g0hhqxpg.js} +1 -1
  41. package/dist/{chunk-4wx5sya5.js → chunk-gzbb747a.js} +1 -1
  42. package/dist/{chunk-w42j9p3t.js → chunk-h8w3ahnk.js} +1 -1
  43. package/dist/chunk-hmw99nm1.js +94 -0
  44. package/dist/chunk-hrtf7dba.js +2 -0
  45. package/dist/chunk-j7dx054r.js +1 -0
  46. package/dist/chunk-j9ppeg6v.js +1 -0
  47. package/dist/chunk-jemb0vwa.js +1 -0
  48. package/dist/{chunk-qdbbke8f.js → chunk-m30qwpe9.js} +1 -1
  49. package/dist/{chunk-kvp523gt.js → chunk-m70cnaeg.js} +1 -1
  50. package/dist/{chunk-rtwd35gd.js → chunk-m8te4s8f.js} +2 -2
  51. package/dist/chunk-ms0wve9g.js +14 -0
  52. package/dist/{chunk-wezr6wfq.js → chunk-n8qg68y2.js} +1 -1
  53. package/dist/chunk-pm5ssr7m.js +25 -0
  54. package/dist/chunk-r9m3b170.js +1 -0
  55. package/dist/chunk-rt3f4xjz.js +23 -0
  56. package/dist/{chunk-430b319j.js → chunk-s1cch8tt.js} +1 -1
  57. package/dist/chunk-sa9fxss4.js +2 -0
  58. package/dist/{chunk-xmymx75h.js → chunk-ta99scbr.js} +1 -1
  59. package/dist/chunk-tf1qz4q6.js +1 -0
  60. package/dist/{chunk-efjjkha8.js → chunk-tqt5c2f5.js} +2 -2
  61. package/dist/{chunk-9jz1q7bk.js → chunk-ts5xzefm.js} +2 -2
  62. package/dist/chunk-v17q4bsd.js +6 -0
  63. package/dist/{chunk-qp2qc4p2.js → chunk-v1k6nvth.js} +2 -2
  64. package/dist/{chunk-1cy4ab77.js → chunk-vbjgcn49.js} +1 -1
  65. package/dist/{chunk-kkzznz4w.js → chunk-wcps5gjm.js} +1 -1
  66. package/dist/{chunk-vz88tqtd.js → chunk-xcj23spc.js} +2 -2
  67. package/dist/chunk-xcy45yxx.js +8 -0
  68. package/dist/chunk-xseh3f4m.js +2 -0
  69. package/dist/chunk-xz7dddaj.js +4 -0
  70. package/dist/{chunk-c51wwnh2.js → chunk-xzva8y4e.js} +5 -6
  71. package/dist/chunk-y0wc0hef.js +10 -0
  72. package/dist/chunk-yrr9mdjn.js +44 -0
  73. package/dist/{chunk-f8kjdxz7.js → chunk-zjezws85.js} +2 -2
  74. package/dist/web/assets/ChatView-BA3kB_z1.js +17 -0
  75. package/dist/web/assets/CodeBlockHighlighter-B5kcdVCA.js +8 -0
  76. package/dist/web/assets/FilePreview-BQid6G2-.js +8 -0
  77. package/dist/web/assets/KanbanBoard-CTR7bMLa.js +1 -0
  78. package/dist/web/assets/MarkdownRenderer-d7DdyYdx.js +30 -0
  79. package/dist/web/assets/ScrollArea-D1tPWHKZ.js +1 -0
  80. package/dist/web/assets/SessionHistorySurface-Cv_jRoJr.js +1 -0
  81. package/dist/web/assets/SettingsModal-CFa2uCzI.js +5 -0
  82. package/dist/web/assets/Sidebar-DrRNJOgU.js +1 -0
  83. package/dist/web/assets/TaskSwitcher-C9AKJrl-.js +1 -0
  84. package/dist/web/assets/TerminalPanel-BxBGcuB9.js +1 -0
  85. package/dist/web/assets/archive-DNa9b1YE.js +1 -0
  86. package/dist/web/assets/arrow-left-BQh8jlfT.js +1 -0
  87. package/dist/web/assets/calendar-clock-CC7FeYTg.js +1 -0
  88. package/dist/web/assets/chevron-right-6ZTOJE0p.js +1 -0
  89. package/dist/web/assets/clock-3-P2q6i6vm.js +1 -0
  90. package/dist/web/assets/copy-C-KvzjCC.js +1 -0
  91. package/dist/web/assets/dist-DiQNoDMg.js +11 -0
  92. package/dist/web/assets/download-CJHn20x1.js +1 -0
  93. package/dist/web/assets/folder-DmyFehXD.js +1 -0
  94. package/dist/web/assets/index-BVEiHNFk.css +1 -0
  95. package/dist/web/assets/index-D-oma3Je.js +11 -0
  96. package/dist/web/assets/message-square-plus-CKu9bFq3.js +1 -0
  97. package/dist/web/assets/pause-D2FxNG-w.js +1 -0
  98. package/dist/web/assets/pencil-D6HI7KC8.js +1 -0
  99. package/dist/web/assets/play-4jKCDYR-.js +1 -0
  100. package/dist/web/assets/plus-C4p8E1Nk.js +1 -0
  101. package/dist/web/assets/preload-helper-BC9Zf9qO.js +1 -0
  102. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  103. package/dist/web/assets/session-events-CvFfHkFA.js +23 -0
  104. package/dist/web/assets/settings-fWlqCZ-U.js +1 -0
  105. package/dist/web/assets/team-qGS2kixH.js +1 -0
  106. package/dist/web/assets/teamService-DfIvlI2_.js +1 -0
  107. package/dist/web/assets/terminal-DZkEoiSb.js +1 -0
  108. package/dist/web/assets/triangle-alert-Detl9fRQ.js +1 -0
  109. package/dist/web/assets/vendor-radix-CHeA_3Pt.js +41 -0
  110. package/dist/web/assets/vendor-react-hNfZDUf2.js +9 -0
  111. package/dist/web/assets/vendor-xterm-CANZO_wP.js +16 -0
  112. package/dist/web/assets/vendor-xterm-CHOd7Rch.css +1 -0
  113. package/dist/web/index.html +6 -4
  114. package/package.json +11 -10
  115. package/dist/chunk-18swytk4.js +0 -25
  116. package/dist/chunk-3297ghav.js +0 -1
  117. package/dist/chunk-33ck9ryb.js +0 -1
  118. package/dist/chunk-4fa11h6f.js +0 -94
  119. package/dist/chunk-535s1mm8.js +0 -1
  120. package/dist/chunk-57939tb3.js +0 -8
  121. package/dist/chunk-6169xxb4.js +0 -2
  122. package/dist/chunk-6v0cdqkw.js +0 -1
  123. package/dist/chunk-8kwj6px8.js +0 -1
  124. package/dist/chunk-a8z11yd2.js +0 -3
  125. package/dist/chunk-aatfjx15.js +0 -2
  126. package/dist/chunk-b2ek44t5.js +0 -12
  127. package/dist/chunk-b9d0ex8n.js +0 -4
  128. package/dist/chunk-bwe49m6n.js +0 -1719
  129. package/dist/chunk-ccgtbzrz.js +0 -14
  130. package/dist/chunk-jgxfhk9k.js +0 -733
  131. package/dist/chunk-jhpwwwjt.js +0 -1
  132. package/dist/chunk-jjj86dej.js +0 -1
  133. package/dist/chunk-kejvty9z.js +0 -23
  134. package/dist/chunk-kf9gj2gn.js +0 -2
  135. package/dist/chunk-mhe1zppc.js +0 -1
  136. package/dist/chunk-pb1q26gw.js +0 -181
  137. package/dist/chunk-pc5f77qh.js +0 -1
  138. package/dist/chunk-pkx6kfy6.js +0 -1
  139. package/dist/chunk-qjptyj18.js +0 -1
  140. package/dist/chunk-shgxzmdw.js +0 -1
  141. package/dist/chunk-thytjs86.js +0 -44
  142. package/dist/chunk-tm3789m3.js +0 -2
  143. package/dist/chunk-tnmcrvk2.js +0 -25
  144. package/dist/chunk-wejthch2.js +0 -1
  145. package/dist/chunk-xv6ejk2z.js +0 -353
  146. package/dist/chunk-yvgef7rp.js +0 -10
  147. package/dist/chunk-zj48897e.js +0 -6
  148. package/dist/web/assets/ChatView-BF6HUrBw.js +0 -70
  149. package/dist/web/assets/CodeBlockHighlighter-C4CgCiRf.js +0 -8
  150. package/dist/web/assets/FilePreview-BS4PgFKb.js +0 -55
  151. package/dist/web/assets/KanbanBoard-DDXB-yq1.js +0 -16
  152. package/dist/web/assets/MarkdownRenderer-DS7RznBE.js +0 -30
  153. package/dist/web/assets/ScrollArea-BM9NzGZM.js +0 -1
  154. package/dist/web/assets/SessionHistorySurface-DnRySeLE.js +0 -6
  155. package/dist/web/assets/SettingsModal-D5YLUtIo.js +0 -20
  156. package/dist/web/assets/Sidebar-BZC6OkDJ.js +0 -31
  157. package/dist/web/assets/TaskSwitcher-WewOkw5m.js +0 -26
  158. package/dist/web/assets/TerminalPanel-C5SGdRNr.js +0 -6
  159. package/dist/web/assets/archive-DkczUU08.js +0 -6
  160. package/dist/web/assets/arrow-left-9pBiQwu7.js +0 -6
  161. package/dist/web/assets/calendar-clock-BFnUlxrU.js +0 -6
  162. package/dist/web/assets/chevron-right-yCVkAEcj.js +0 -6
  163. package/dist/web/assets/clock-3-CcoWoRQs.js +0 -6
  164. package/dist/web/assets/copy-HJF0oQBS.js +0 -6
  165. package/dist/web/assets/download-DSBCIqk3.js +0 -6
  166. package/dist/web/assets/external-link-zIgEO0KB.js +0 -11
  167. package/dist/web/assets/folder-BdRo64o3.js +0 -11
  168. package/dist/web/assets/index-B5mUEr6D.js +0 -11
  169. package/dist/web/assets/index-BVDkKudh.js +0 -211
  170. package/dist/web/assets/index-CaCifsSK.css +0 -1
  171. package/dist/web/assets/message-square-plus-3klTXO0S.js +0 -21
  172. package/dist/web/assets/pause-B9Q5JWvH.js +0 -6
  173. package/dist/web/assets/pencil-CbYIz1b1.js +0 -6
  174. package/dist/web/assets/play-CZMTj43e.js +0 -6
  175. package/dist/web/assets/plus-Cc7I8fhb.js +0 -6
  176. package/dist/web/assets/session-events-NEjosinC.js +0 -31
  177. package/dist/web/assets/settings-DSF3exX2.js +0 -6
  178. package/dist/web/assets/team-qfeJHL9s.js +0 -6
  179. package/dist/web/assets/teamService-Bs9qBKI8.js +0 -1
  180. package/dist/web/assets/terminal-DQLqe-Ed.js +0 -6
  181. package/dist/web/assets/vendor-radix-D6QrtXqd.js +0 -45
  182. package/dist/web/assets/vendor-react-DofNRwfy.js +0 -49
  183. package/dist/web/assets/vendor-xterm-9CEnUXvW.css +0 -32
  184. package/dist/web/assets/vendor-xterm-DuYZoU4T.js +0 -49
@@ -1,5 +1,5 @@
1
- import{Eh as YO}from"./chunk-ys8gysg8.js";import{cj as P}from"./chunk-qdbbke8f.js";import{Ej as XO,Gj as qO,Ij as S,Lj as y}from"./chunk-a8z11yd2.js";import{bk as n}from"./chunk-f8kjdxz7.js";import{fk as r}from"./chunk-4wx5sya5.js";import{Mk as w}from"./chunk-eg3ms291.js";var b;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(b||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import C from"node:path";import{LRUCache as fO}from"lru-cache";import{nanoid as R}from"nanoid";var N={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import DO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import k from"node:path";import{Mutex as SO}from"async-mutex";import GO from"write-file-atomic";var h=1,VO=1048576,LO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function zO(O){let q={};for(let Q of Object.values(b)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(b))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(zO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new SO;filePath;constructor(O=k.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let W;try{W=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let J=W.projects[Z];if(!J)return{...X,state:"untrusted"};return{...X,state:J.digest===$?"trusted":"modified",trustedDigest:J.digest,trustedAt:J.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:h,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>VO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==h)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!k.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!LO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:h,projects:Z}}async writeStore(O){let q=k.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await GO(this.filePath,`${JSON.stringify(O,null,2)}
2
- `,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(BO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(AO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(PO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function BO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function AO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function PO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var UO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),_O=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),KO=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),NO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),MO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),wO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),CO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),EO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),jO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([UO,_O,KO,bO,NO,MO,TO,wO,CO,EO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(jO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",W=Q?.failureBehavior||"ignore",J=`Invalid hook output JSON: ${X}`;if(W==="deny")return{success:!1,blocking:!0,error:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(W==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class u{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class l{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:W}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),J=new u(this.MAX_STDOUT_SIZE),G=new u(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{J.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await W.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,F)=>{let z=!1,V=!1,B,U=()=>{return B??=W.terminate(),B},K=null,H=()=>{if(K&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",K),K=null},I=setTimeout(()=>{z=!0,U()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),z)await U();L({stdout:J.getContent(),stderr:G.getContent(),exitCode:z?124:f??1,timedOut:z})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),F(f)}),Q.abortSignal){if(K=()=>{if(V)return;V=!0,clearTimeout(I),H(),U().then(()=>{L({stdout:J.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",K),Q.abortSignal.aborted)K()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),yO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new l;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},W=await this.executeHook($,X,Q);if(!W.success){if(W.blocking)return{decision:"deny",reason:W.error};if(W.needsConfirmation)return{decision:"ask",reason:W.warning||W.error};if(W.warning)Y.push(W.warning);continue}let J=W.output?.hookSpecificOutput;if(J&&"permissionDecision"in J){switch(J.permissionDecision){case"deny":return{decision:"deny",reason:J.permissionDecisionReason};case"ask":return{decision:"ask",reason:J.permissionDecisionReason};case"allow":break}if("updatedInput"in J&&J.updatedInput)Z={...Z,...J.updatedInput}}}catch(X){let W=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${W}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:W};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${W}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
1
+ import{Dh as YO}from"./chunk-3y2x6fb6.js";import{Yi as P}from"./chunk-m30qwpe9.js";import{Dj as XO,Fj as qO,Hj as S,Kj as y}from"./chunk-9ydrwcpy.js";import{ak as n}from"./chunk-zjezws85.js";import{ek as r}from"./chunk-gzbb747a.js";import{Kk as w}from"./chunk-f552hzcx.js";var b;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(b||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import C from"node:path";import{LRUCache as fO}from"lru-cache";import{nanoid as A}from"nanoid";var N={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import DO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import k from"node:path";import{Mutex as SO}from"async-mutex";import GO from"write-file-atomic";var h=1,VO=1048576,LO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function zO(O){let q={};for(let Q of Object.values(b)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(b))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(zO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class B{static instance=null;mutex=new SO;filePath;constructor(O=k.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}static resetInstance(){B.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let W;try{W=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let J=W.projects[Z];if(!J)return{...X,state:"untrusted"};return{...X,state:J.digest===$?"trusted":"modified",trustedDigest:J.digest,trustedAt:J.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:h,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>VO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==h)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!k.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!LO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:h,projects:Z}}async writeStore(O){let q=k.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await GO(this.filePath,`${JSON.stringify(O,null,2)}
2
+ `,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(BO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(AO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(PO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function BO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function AO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function PO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var UO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),_O=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),KO=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),NO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),MO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),wO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),CO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),EO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),jO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([UO,_O,KO,bO,NO,MO,TO,wO,CO,EO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(jO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",W=Q?.failureBehavior||"ignore",J=`Invalid hook output JSON: ${X}`;if(W==="deny")return{success:!1,blocking:!0,error:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(W==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class u{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class l{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:W}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),J=new u(this.MAX_STDOUT_SIZE),G=new u(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{J.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await W.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,F)=>{let z=!1,V=!1,R,U=()=>{return R??=W.terminate(),R},K=null,H=()=>{if(K&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",K),K=null},I=setTimeout(()=>{z=!0,U()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),z)await U();L({stdout:J.getContent(),stderr:G.getContent(),exitCode:z?124:f??1,timedOut:z})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),F(f)}),Q.abortSignal){if(K=()=>{if(V)return;V=!0,clearTimeout(I),H(),U().then(()=>{L({stdout:J.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",K),Q.abortSignal.aborted)K()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),yO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new l;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},W=await this.executeHook($,X,Q);if(!W.success){if(W.blocking)return{decision:"deny",reason:W.error};if(W.needsConfirmation)return{decision:"ask",reason:W.warning||W.error};if(W.warning)Y.push(W.warning);continue}let J=W.output?.hookSpecificOutput;if(J&&"permissionDecision"in J){switch(J.permissionDecision){case"deny":return{decision:"deny",reason:J.permissionDecisionReason};case"ask":return{decision:"ask",reason:J.permissionDecisionReason};case"allow":break}if("updatedInput"in J&&J.updatedInput)Z={...Z,...J.updatedInput}}}catch(X){let W=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${W}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:W};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${W}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
3
3
  `):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,W=[];for(let J of Y){if(!J.success&&J.warning){W.push(J.warning);continue}let G=J.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
4
4
 
5
5
  `):void 0,modifiedOutput:X,warning:W.length>0?W.join(`
@@ -22,10 +22,9 @@ import{Eh as YO}from"./chunk-ys8gysg8.js";import{cj as P}from"./chunk-qdbbke8f.j
22
22
  `):void 0}}async executePostToolUseFailureHooks(O,q,Q){if(O.length===0)return{};let Z=[],Y=[],$=Q.config.maxConcurrentHooks||5,X=await this.executeHooksConcurrently(O,q,Q,$);for(let W of X){if(!W.success&&W.warning){Z.push(W.warning);continue}if(W.stdout&&W.stdout.trim())Y.push(W.stdout.trim())}return{additionalContext:Y.length>0?Y.join(`
23
23
 
24
24
  `):void 0,warning:Z.length>0?Z.join(`
25
- `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
25
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
26
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-jjj86dej.js"),{createChatServiceAsync:W}=await import("./chunk-33ck9ryb.js"),{resolveModelConfig:J}=await import("./chunk-8kwj6px8.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-qjptyj18.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
27
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await B.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((R)=>setTimeout(R,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let R=V.name==="AbortError"||V.code==="ABORT_ERR";if(R&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(R){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-1kxpnt9q.js"),{createChatServiceAsync:W}=await import("./chunk-j7dx054r.js"),{resolveModelConfig:J}=await import("./chunk-72wn385d.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-r9m3b170.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((R)=>R.id===O):F.config.models.find((R)=>R.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
28
 
30
29
  `+`## 评估指令
31
30
  ${O.prompt}
@@ -41,5 +40,5 @@ ${O.prompt}
41
40
  `+`重要规则:
42
41
  `+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
43
42
  `+`- 如果没有发现问题,使用 "approve"
44
- `+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let q=O.trim(),Q=q.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Q)return Q[1].trim();return q}async executeHooksConcurrently(O,q,Q,Z){let Y=[],$=new Set;for(let X of O){if($.size>=Z)await Promise.race($);let W=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),J=W.then(()=>{$.delete(J)}).catch(()=>{$.delete(J)});$.add(J),Y.push(W)}return Promise.all(Y)}}async function HO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:W}=await Q.read();if(W)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var IO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class i{matches(O,q){if(!O)return!0;if(O.tools&&q.toolName){if(!this.matchTools(O.tools,q))return!1}if(O.paths){let Q=q.filePaths??(q.filePath?[q.filePath]:[]);if(Q.length===0||!Q.some((Z)=>this.matchPaths(O.paths,Z)))return!1}if(O.commands&&q.command){if(!this.matchCommands(O.commands,q.command))return!1}return!0}matchTools(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchToolWithParams(Q,q));return this.matchToolWithParams(O,q)}matchPaths(O,q){if(Array.isArray(O))return O.some((Z)=>{return a(Z)(q)});return a(O)(q)}matchCommands(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchPattern(q,Q));return this.matchPattern(q,O)}matchToolWithParams(O,q){let{toolName:Q,command:Z,filePath:Y}=q,$=IO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,W]=$;if(!this.matchPattern(Q,X))return!1;let J=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(J.length===0)return!1;return J.some((G)=>this.matchGlobOrPattern(G,W))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}var WO=64;class _{static instance=null;config=N;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new fO({max:WO});sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!_.instance)_.instance=new _;return _.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){let Z=this.sessionConfigKey(O,q[0]??P()),Y=this.disabledSessions.has(Z);for(let $ of q){let X=this.sessionConfigKey(O,$);if(Y||=this.disabledSessions.has(X),this.sessionStateAliases.set(X,Z),this.sessionConfigs.set(X,this.snapshotConfig(Q)),X!==Z)this.disabledSessions.delete(X)}if(Y)this.disabledSessions.add(Z)}async unbindSessionModelResources(O,q){let Q=`${O}\x00`;for(let Z of this.sessionConfigs.keys()){if(!Z.startsWith(Q))continue;this.sessionConfigs.delete(Z)}for(let Z of this.sessionStateAliases.keys()){if(!Z.startsWith(Q))continue;this.sessionStateAliases.delete(Z)}for(let Z of this.disabledSessions){if(!Z.startsWith(Q))continue;this.disabledSessions.delete(Z)}await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){_.instance?.cleanup(),_.instance=null}loadConfig(O,q=P()){let Q=E(N,O),Z=c();Q=E(Q,Z),this.storeProjectConfig(q,Q)}isEnabled(O=P(),q){if(!(q?this.getExecutionConfig(q,O):this.getConfig(O)).enabled)return!1;if(this.processDisabled)return!1;if(q&&this.disabledSessions.has(this.sessionStateKey(q,O)))return!1;return!0}disable(){this.processDisabled=!0,console.log("[HookManager] Hooks disabled for this process")}enable(){this.processDisabled=!1,console.log("[HookManager] Hooks enabled for this process")}disableSession(O,q){this.disabledSessions.add(this.sessionStateKey(O,q))}enableSession(O,q){this.disabledSessions.delete(this.sessionStateKey(O,q))}isSessionEnabled(O,q){return this.isEnabled(q,O)}isSessionPaused(O,q){return this.disabledSessions.has(this.sessionStateKey(O,q))}getConfig(O=P()){let q=C.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===C.resolve(P()))return this.config;return{...N,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}isExecutionEnabled(O,q,Q){return O.enabled===!0&&!this.processDisabled&&!this.disabledSessions.has(this.sessionStateKey(q,Q))}sessionStateKey(O,q){let Q=this.sessionConfigKey(O,q);return this.sessionStateAliases.get(Q)??Q}sessionConfigKey(O,q){return`${O}\x00${C.resolve(q)}`}snapshotConfig(O){let q=E(N,O);for(let Q of Object.values(b))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}storeProjectConfig(O,q){let Q=C.resolve(O);if(Q===C.resolve(P())){this.config=q,this.projectConfigs.delete(Q);return}this.projectConfigs.set(Q,q)}inheritProjectConfig(O,q,Q){let Z=Q?this.getExecutionConfig(Q,O):this.getConfig(O);if(this.storeProjectConfig(q,this.snapshotConfig(Z)),!Q)return;let Y=this.sessionConfigKey(Q,O),$=this.sessionConfigKey(Q,q),X=this.sessionStateAliases.get(Y)??Y,W=this.disabledSessions.has(X)||this.disabledSessions.has($);if(this.sessionConfigs.set($,this.snapshotConfig(Z)),this.sessionStateAliases.set($,X),$!==X)this.disabledSessions.delete($);if(W)this.disabledSessions.add(X)}getResidencyStats(){return{projectCapacity:WO,projectConfigs:this.projectConfigs.size,sessionConfigs:this.sessionConfigs.size,sessionAliases:this.sessionStateAliases.size}}getTrustStatus(O=P()){return A.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=P(),q){return A.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=P()){return A.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let W=C.resolve(Z.projectDir),J=this.getConfig(W),G=J[O]??[];return J[O]=[...G,$],this.storeProjectConfig(W,J),()=>{let L=J[O];if(!L)return;J[O]=L.filter((F)=>F!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let W=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=W.filter((J)=>J!==$)}}async reloadConfig(O=P()){let q=await import("node:fs/promises"),Q=await import("node:path");try{let Z=Q.join(O,".blade","settings.local.json"),Y=await q.readFile(Z,"utf-8"),$=JSON.parse(Y);if($.hooks)this.loadConfig($.hooks,O)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let J=await this.executor.executePreToolHooks(X,$,W);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(J.decision==="deny")return J;return{decision:"allow",modifiedInput:J.modifiedInput,warning:J.warning,reason:J.reason}}return J}catch(J){return console.error("[HookManager] Error executing PreToolUse hooks:",J),{decision:"allow",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(W,X,J);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,W)}catch(J){return console.error("[HookManager] Error executing PermissionRequest hooks:",J),{decision:"ask",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:R(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(W,X,J)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{suppress:!1,message:q};let Y={hook_event_name:"Notification",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,notification_type:O,title:Q.title,message:q},$=this.getMatchingHooks("Notification",{},Z);if($.length===0)return{suppress:!1,message:q};let X={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeNotificationHooks($,Y,X)}catch(W){return console.error("[HookManager] Error executing Notification hooks:",W),{suppress:!1,message:q,warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"Elicitation",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll(),this.config=N,this.processDisabled=!1,this.disabledSessions.clear(),this.sessionStateAliases.clear(),this.projectConfigs.clear(),this.sessionConfigs.clear(),this.managedFunctionMatchers={}}}
45
- export{b as yh,o as zh,_ as Ah};
43
+ `+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let q=O.trim(),Q=q.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Q)return Q[1].trim();return q}async executeHooksConcurrently(O,q,Q,Z){let Y=[],$=new Set;for(let X of O){if($.size>=Z)await Promise.race($);let W=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),J=W.then(()=>{$.delete(J)}).catch(()=>{$.delete(J)});$.add(J),Y.push(W)}return Promise.all(Y)}}async function HO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:W}=await Q.read();if(W)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var IO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class i{matches(O,q){if(!O)return!0;if(O.tools&&q.toolName){if(!this.matchTools(O.tools,q))return!1}if(O.paths){let Q=q.filePaths??(q.filePath?[q.filePath]:[]);if(Q.length===0||!Q.some((Z)=>this.matchPaths(O.paths,Z)))return!1}if(O.commands&&q.command){if(!this.matchCommands(O.commands,q.command))return!1}return!0}matchTools(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchToolWithParams(Q,q));return this.matchToolWithParams(O,q)}matchPaths(O,q){if(Array.isArray(O))return O.some((Z)=>{return a(Z)(q)});return a(O)(q)}matchCommands(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchPattern(q,Q));return this.matchPattern(q,O)}matchToolWithParams(O,q){let{toolName:Q,command:Z,filePath:Y}=q,$=IO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,W]=$;if(!this.matchPattern(Q,X))return!1;let J=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(J.length===0)return!1;return J.some((G)=>this.matchGlobOrPattern(G,W))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}var WO=64;class _{static instance=null;config=N;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new fO({max:WO});sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!_.instance)_.instance=new _;return _.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){let Z=this.sessionConfigKey(O,q[0]??P()),Y=this.disabledSessions.has(Z);for(let $ of q){let X=this.sessionConfigKey(O,$);if(Y||=this.disabledSessions.has(X),this.sessionStateAliases.set(X,Z),this.sessionConfigs.set(X,this.snapshotConfig(Q)),X!==Z)this.disabledSessions.delete(X)}if(Y)this.disabledSessions.add(Z)}async unbindSessionModelResources(O,q){let Q=`${O}\x00`;for(let Z of this.sessionConfigs.keys()){if(!Z.startsWith(Q))continue;this.sessionConfigs.delete(Z)}for(let Z of this.sessionStateAliases.keys()){if(!Z.startsWith(Q))continue;this.sessionStateAliases.delete(Z)}for(let Z of this.disabledSessions){if(!Z.startsWith(Q))continue;this.disabledSessions.delete(Z)}await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){_.instance?.cleanup(),_.instance=null}loadConfig(O,q=P()){let Q=E(N,O),Z=c();Q=E(Q,Z),this.storeProjectConfig(q,Q)}isEnabled(O=P(),q){if(!(q?this.getExecutionConfig(q,O):this.getConfig(O)).enabled)return!1;if(this.processDisabled)return!1;if(q&&this.disabledSessions.has(this.sessionStateKey(q,O)))return!1;return!0}disable(){this.processDisabled=!0,console.log("[HookManager] Hooks disabled for this process")}enable(){this.processDisabled=!1,console.log("[HookManager] Hooks enabled for this process")}disableSession(O,q){this.disabledSessions.add(this.sessionStateKey(O,q))}enableSession(O,q){this.disabledSessions.delete(this.sessionStateKey(O,q))}isSessionEnabled(O,q){return this.isEnabled(q,O)}isSessionPaused(O,q){return this.disabledSessions.has(this.sessionStateKey(O,q))}getConfig(O=P()){let q=C.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===C.resolve(P()))return this.config;return{...N,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}isExecutionEnabled(O,q,Q){return O.enabled===!0&&!this.processDisabled&&!this.disabledSessions.has(this.sessionStateKey(q,Q))}sessionStateKey(O,q){let Q=this.sessionConfigKey(O,q);return this.sessionStateAliases.get(Q)??Q}sessionConfigKey(O,q){return`${O}\x00${C.resolve(q)}`}snapshotConfig(O){let q=E(N,O);for(let Q of Object.values(b))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}storeProjectConfig(O,q){let Q=C.resolve(O);if(Q===C.resolve(P())){this.config=q,this.projectConfigs.delete(Q);return}this.projectConfigs.set(Q,q)}inheritProjectConfig(O,q,Q){let Z=Q?this.getExecutionConfig(Q,O):this.getConfig(O);if(this.storeProjectConfig(q,this.snapshotConfig(Z)),!Q)return;let Y=this.sessionConfigKey(Q,O),$=this.sessionConfigKey(Q,q),X=this.sessionStateAliases.get(Y)??Y,W=this.disabledSessions.has(X)||this.disabledSessions.has($);if(this.sessionConfigs.set($,this.snapshotConfig(Z)),this.sessionStateAliases.set($,X),$!==X)this.disabledSessions.delete($);if(W)this.disabledSessions.add(X)}getResidencyStats(){return{projectCapacity:WO,projectConfigs:this.projectConfigs.size,sessionConfigs:this.sessionConfigs.size,sessionAliases:this.sessionStateAliases.size}}getTrustStatus(O=P()){return B.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=P(),q){return B.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=P()){return B.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let W=C.resolve(Z.projectDir),J=this.getConfig(W),G=J[O]??[];return J[O]=[...G,$],this.storeProjectConfig(W,J),()=>{let L=J[O];if(!L)return;J[O]=L.filter((F)=>F!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let W=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=W.filter((J)=>J!==$)}}async reloadConfig(O=P()){let q=await import("node:fs/promises"),Q=await import("node:path");try{let Z=Q.join(O,".blade","settings.local.json"),Y=await q.readFile(Z,"utf-8"),$=JSON.parse(Y);if($.hooks)this.loadConfig($.hooks,O)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:A(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let J=await this.executor.executePreToolHooks(X,$,W);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(J.decision==="deny")return J;return{decision:"allow",modifiedInput:J.modifiedInput,warning:J.warning,reason:J.reason}}return J}catch(J){return console.error("[HookManager] Error executing PreToolUse hooks:",J),{decision:"allow",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:A(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(W,X,J);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:A(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,W)}catch(J){return console.error("[HookManager] Error executing PermissionRequest hooks:",J),{decision:"ask",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:A(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:A(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(W,X,J)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"Elicitation",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:A(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll(),this.config=N,this.processDisabled=!1,this.disabledSessions.clear(),this.sessionStateAliases.clear(),this.projectConfigs.clear(),this.sessionConfigs.clear(),this.managedFunctionMatchers={}}}
44
+ export{b as xh,o as yh,_ as zh};
@@ -0,0 +1,10 @@
1
+ import{a as T,b as W,c as X,d as Y}from"./chunk-ms0wve9g.js";import"./chunk-1beqtjsw.js";import"./chunk-8sth12hd.js";import"./chunk-sa9fxss4.js";import"./chunk-v1k6nvth.js";import"./chunk-30p7aff1.js";import"./chunk-25s0c8km.js";import"./chunk-f6hc7t65.js";import"./chunk-pm5ssr7m.js";import"./chunk-xseh3f4m.js";import"./chunk-7vzz3rsx.js";import"./chunk-9qxch6sy.js";import"./chunk-hmw99nm1.js";import"./chunk-a731hdwa.js";import"./chunk-dxq7462e.js";import"./chunk-tqt5c2f5.js";import{Df as R}from"./chunk-447ps2te.js";import"./chunk-0b83mt1c.js";import{Zf as Q}from"./chunk-7eset766.js";import"./chunk-5yyp6njq.js";import"./chunk-v508x7cg.js";import"./chunk-xcy45yxx.js";import"./chunk-5bc4hwt9.js";import"./chunk-h8w3ahnk.js";import"./chunk-zfxcef0z.js";import"./chunk-g0hhqxpg.js";import"./chunk-8n3jythp.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-xzva8y4e.js";import"./chunk-3y2x6fb6.js";import"./chunk-yrr9mdjn.js";import"./chunk-m30qwpe9.js";import"./chunk-n8qg68y2.js";import"./chunk-hrtf7dba.js";import"./chunk-9ydrwcpy.js";import"./chunk-0wcnkxe8.js";import"./chunk-4cdk4mds.js";import{Xj as M}from"./chunk-a1tt14a2.js";import"./chunk-zjezws85.js";import"./chunk-gzbb747a.js";import"./chunk-f552hzcx.js";import m from"chalk";import K from"open";var A=`
2
+ ____ _ _
3
+ | __ )| | __ _ __| | ___
4
+ | _ \\| |/ _\` |/ _\` |/ _ \\
5
+ | |_) | | (_| | (_| | __/
6
+ |____/|_|\\__,_|\\__,_|\\___|
7
+ `,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
8
+ `));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
9
+ `)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
10
+ `));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
@@ -0,0 +1,44 @@
1
+ import{Yi as i}from"./chunk-m30qwpe9.js";import{$i as Hn,Zi as rn,_i as Kn,dj as Yn,ej as _n,fj as Fn,gj as Vn,hj as qn,ij as ct,jj as Jn,kj as Qn,lj as Mn,mj as jn,nj as Wn,oj as Sn,pj as Zn,qj as kn,rj as ln,sj as yn,tj as vn,uj as te}from"./chunk-n8qg68y2.js";import{vj as Pn,wj as xn}from"./chunk-hrtf7dba.js";import{Dj as Ut,Fj as Lt,Gj as St,Hj as m}from"./chunk-9ydrwcpy.js";import{Mj as Gn,Pj as tt}from"./chunk-0wcnkxe8.js";import{Xj as xt,Yj as Bt}from"./chunk-a1tt14a2.js";import{dk as b}from"./chunk-zjezws85.js";import{ek as It}from"./chunk-gzbb747a.js";var nt;((r)=>{r.DEFAULT="default";r.AUTO_EDIT="autoEdit";r.YOLO="yolo";r.PLAN="plan"})(nt||={});var ne=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function ee(t){return t==="127.0.0.1"||t==="[::1]"||t.toLowerCase()==="localhost"}function $(t,n="MCP OAuth URL"){let e=new URL(t);if(e.username||e.password)throw Error(`${n} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ee(e.hostname)))throw Error(`${n} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var K=async(t,n)=>{$(t,"MCP OAuth request URL");let e=await fetch(t,{...n,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function et(t){let n=t.oauth;if(!n)return;let e=n;for(let s of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[s]!==void 0)throw Error(`MCP OAuth "${s}" is not supported; use standards-based discovery`);if(n.enabled!==!0)return{enabled:!1};if(t.type!=="http"&&t.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!t.url)throw Error("MCP OAuth requires an MCP server URL");if($(t.url,"MCP OAuth server URL"),Object.keys(t.headers??{}).find((s)=>s.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=n.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=n.scopes?.map((s)=>s.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((s)=>!s||s.length>128||!ne.test(s)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let M=n.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as Et}from"node:crypto";import ge from"node:http";import{auth as wt}from"@modelcontextprotocol/sdk/client/auth.js";import ce from"open";import{createHash as _e,randomUUID as Me}from"node:crypto";import{constants as rt,promises as I}from"node:fs";import _t from"node:path";import Se from"write-file-atomic";import{Mutex as re}from"async-mutex";class U{entries=new Map;async runExclusive(t,n){let e=this.entries.get(t);if(!e)e={mutex:new re,operations:0},this.entries.set(t,e);e.operations++;try{return await e.mutex.runExclusive(n)}finally{if(e.operations--,e.operations===0&&this.entries.get(t)===e)this.entries.delete(t)}}getStats(){let t=0;for(let n of this.entries.values())t+=n.operations;return{keys:this.entries.size,operations:t}}}var bt=1,se=1048576,Ee=5000,ue=50,oe=/^[a-f0-9]{64}$/,me=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Te=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ae=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),dt=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(me),tokens:m.Optional(Te),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ae),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),it=m.Object({version:m.Literal(bt),credentials:m.Record(m.String(),dt)},{additionalProperties:!1});function H(t,n){return t instanceof Error&&"code"in t&&t.code===n}function Ae(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(n){return H(n,"EPERM")}}function Mt(t){return structuredClone(t)}function ht(t){if(Object.keys(t.credentials).some((n)=>!oe.test(n)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(t){let n=new URL(t);return n.hash="",n.toString()}function st(t,n,e=[]){return _e("sha256").update(JSON.stringify({serverUrl:Y(t),clientId:n?.trim()||null,scopes:[...e].sort()})).digest("hex")}class N{static locks=new U;stateRoot;tokenFilePath;constructor(t=It()){this.stateRoot=_t.join(t,"mcp"),this.tokenFilePath=_t.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[t];return e?Mt(e):null})}async updateCredential(t,n){return this.runMutation(async(e)=>{let _=e.credentials[t],r=await n(_?Mt(_):null);if(r)e.credentials[t]=St(dt,r);else delete e.credentials[t];return r?Mt(e.credentials[t]):null})}async deleteCredential(t){await this.updateCredential(t,()=>null)}async listCredentialIds(){return N.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let n=await this.acquireStoreLock();try{let e=await this.readStore(),_=await t(e);return await this.writeStore(e),_}finally{await n()}})}async ensureStateRoot(){await I.mkdir(this.stateRoot,{recursive:!0,mode:448});let t=await I.lstat(this.stateRoot);if(!t.isDirectory()||t.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((t.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let t=await I.lstat(this.tokenFilePath);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((t.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(t.size>se)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let n=JSON.parse(await I.readFile(this.tokenFilePath,"utf8")),e=Lt(it,n);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return ht(e.data),e.data}catch(t){if(H(t,"ENOENT"))return{version:bt,credentials:{}};throw t}}async writeStore(t){await this.ensureStateRoot();let n=St(it,t);ht(n),await Se(this.tokenFilePath,`${JSON.stringify(n,null,2)}
2
+ `,{mode:384,encoding:"utf8"}),await I.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let t=_t.join(this.stateRoot,".oauth-credentials.lock"),n=Me(),e=Date.now()+Ee;while(Date.now()<e)try{let _=await I.open(t,rt.O_CREAT|rt.O_EXCL|rt.O_WRONLY,384);return await _.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:n,createdAt:new Date().toISOString()})}
3
+ `,"utf8"),await _.close(),async()=>{try{if(JSON.parse(await I.readFile(t,"utf8")).token===n)await I.unlink(t)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(_){if(!H(_,"EEXIST"))throw _;await this.removeDeadLock(t),await new Promise((r)=>setTimeout(r,ue))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(t){let n=await I.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&n.uid!==process.getuid()||(n.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await I.readFile(t,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!Ae(e.pid))await I.unlink(t)}}var Nt="127.0.0.1",ft=7777,Pt="/oauth/callback",ie=300000;class ut extends Error{constructor(t){super(`MCP server "${t}" requires OAuth authorization; run "blade mcp login ${t}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Ct extends Error{constructor(t){super(`MCP OAuth credentials are unavailable in this runtime for server "${t}"`);this.name="McpOAuthUnavailableError"}}function he(t){let n=t?"Authentication complete":"Authentication failed";return`<!doctype html>
4
+ <html lang="en">
5
+ <head>
6
+ <meta charset="utf-8">
7
+ <meta name="viewport" content="width=device-width,initial-scale=1">
8
+ <title>${n}</title>
9
+ </head>
10
+ <body>
11
+ <main>
12
+ <h1>${n}</h1>
13
+ <p>${t?"You can close this window and return to Blade.":"Return to Blade and retry the OAuth login."}</p>
14
+ </main>
15
+ </body>
16
+ </html>`}function O(t,n,e){t.writeHead(n,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"}),t.end(he(e))}class B{serverName;config;static activeFlowIdentity;tokenStorage;serverUrl;identity;callbackUrl;openAuthorizationUrl;codeVerifierValue;activeFlow;lastError;constructor(t,n,e,_={}){this.serverName=t;this.config=e;this.serverUrl=Y(n),this.identity=st(this.serverUrl,e.clientId,e.scopes),this.tokenStorage=_.tokenStorage??new N;let r=e.callbackPort??ft;this.callbackUrl=`http://${Nt}:${r}${Pt}`,this.openAuthorizationUrl=_.openAuthorizationUrl??(async(S)=>{await ce(S,{wait:!1})})}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{redirect_uris:[this.callbackUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`${Bt()} ${xt()}`,...this.config.scopes?.length?{scope:this.config.scopes.join(" ")}:{}}}async state(){return this.activeFlow?.state??Et()}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId};return(await this.readCredential())?.clientInformation}async saveClientInformation(t){await this.updateCredential((n)=>({...this.baseCredential(n),clientInformation:t}))}async tokens(){let t=await this.readCredential();if(!t?.tokens)return;if(t.tokenExpiresAt!==void 0&&t.tokenExpiresAt<=Date.now()&&!t.tokens.refresh_token)return;return structuredClone(t.tokens)}async saveTokens(t){let n=t.expires_in===void 0?void 0:Date.now()+t.expires_in*1000;await this.updateCredential((e)=>({...this.baseCredential(e),tokens:structuredClone(t),...n===void 0?{}:{tokenExpiresAt:n}})),this.lastError=void 0}async redirectToAuthorization(t){let n=this.activeFlow;if(!n)throw new ut(this.serverName);n.authorizationUrl=$(t,"MCP OAuth authorization URL").toString()}async saveCodeVerifier(t){this.codeVerifierValue=t}async codeVerifier(){if(!this.codeVerifierValue)throw Error("MCP OAuth PKCE verifier is unavailable");return this.codeVerifierValue}async saveDiscoveryState(t){await this.updateCredential((n)=>({...this.baseCredential(n),discoveryState:structuredClone(t)}))}async discoveryState(){let t=(await this.readCredential())?.discoveryState;return t?structuredClone(t):void 0}async invalidateCredentials(t){if(t==="verifier"){this.codeVerifierValue=void 0;return}if(t==="all"){await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0;return}await this.updateCredential((n)=>{if(!n)return null;let e={...n};if(t==="client")delete e.clientInformation,delete e.tokens,delete e.tokenExpiresAt;else if(t==="tokens")delete e.tokens,delete e.tokenExpiresAt;else if(t==="discovery")delete e.discoveryState;return{...e,updatedAt:new Date().toISOString()}})}async getStatus(){if(this.activeFlow)return"authorizing";if(this.lastError)return"error";return await this.hasUsableCredentials()?"authenticated":"unauthenticated"}async hasUsableCredentials(){let t=await this.readCredential();if(!t?.tokens?.access_token)return!1;if(t.tokenExpiresAt===void 0||t.tokenExpiresAt>Date.now())return!0;return Boolean(t.tokens.refresh_token)}async beginAuthorization(){if(this.activeFlow)return this.toHandle(this.activeFlow);if(await this.hasUsableCredentials())throw Error(`MCP server "${this.serverName}" already has OAuth credentials`);if(B.activeFlowIdentity)throw Error("Another MCP OAuth authorization is already in progress");B.activeFlowIdentity=this.identity,this.lastError=void 0,this.codeVerifierValue=void 0;try{let t=await this.createFlow();if(this.activeFlow=t,await wt(this,{serverUrl:this.serverUrl,fetchFn:K})!=="REDIRECT"||!t.authorizationUrl)throw Error("MCP OAuth server did not start an authorization redirect");return this.toHandle(t)}catch(t){let n=t instanceof Error?t:Error(String(t));throw await this.failActiveFlow(n),n}}async openAuthorization(){let t=await this.beginAuthorization();return await this.openAuthorizationUrl(t.authorizationUrl),t}async logout(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"));await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0,this.lastError=void 0}async dispose(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"))}async createFlow(){let t,n,e=new Promise((M,s)=>{t=M,n=s});e.catch(()=>{return});let _=Et(),r=ge.createServer((M,s)=>{this.handleCallback(M,s)});r.on("clientError",(M,s)=>{s.end(`HTTP/1.1 400 Bad Request\r
17
+ Connection: close\r
18
+ \r
19
+ `)}),await new Promise((M,s)=>{let E=(o)=>s(o);r.once("error",E),r.listen(this.config.callbackPort??ft,Nt,()=>{r.off("error",E),M()})});let S={flowId:Et(),state:_,callbackUrl:this.callbackUrl,server:r,timeout:setTimeout(()=>{this.failActiveFlow(Error("MCP OAuth authorization timed out"))},ie),completion:e,resolve:t,reject:n,settled:!1};return S.timeout.unref(),S}async handleCallback(t,n){let e=this.activeFlow;if(!e){O(n,410,!1);return}try{if(t.method!=="GET"){n.setHeader("Allow","GET"),O(n,405,!1);return}let _=new URL(t.url??"/",e.callbackUrl);if(_.pathname!==Pt){O(n,404,!1);return}let r=_.searchParams.get("state"),S=_.searchParams.get("code");if(_.searchParams.get("error"))throw Error("MCP OAuth authorization was denied");if(!r||r!==e.state)throw Error("MCP OAuth state mismatch");if(!S)throw Error("MCP OAuth callback is missing the authorization code");if(await wt(this,{serverUrl:this.serverUrl,authorizationCode:S,fetchFn:K})!=="AUTHORIZED")throw Error("MCP OAuth token exchange did not complete");O(n,200,!0),await this.completeActiveFlow()}catch(_){O(n,400,!1),await this.failActiveFlow(_ instanceof Error?_:Error(String(_)))}}async completeActiveFlow(){let t=this.activeFlow;if(!t||t.settled)return;t.settled=!0,clearTimeout(t.timeout),await new Promise((n)=>t.server.close(()=>n())),this.activeFlow=void 0,B.activeFlowIdentity=void 0,this.codeVerifierValue=void 0,this.lastError=void 0,t.resolve()}async failActiveFlow(t){let n=this.activeFlow;if(this.lastError=t,this.codeVerifierValue=void 0,B.activeFlowIdentity=void 0,!n||n.settled){this.activeFlow=void 0;return}n.settled=!0,clearTimeout(n.timeout),await new Promise((e)=>n.server.close(()=>e())),this.activeFlow=void 0,n.reject(t)}toHandle(t){if(!t.authorizationUrl)throw Error("MCP OAuth authorization URL is unavailable");return{flowId:t.flowId,authorizationUrl:t.authorizationUrl,callbackUrl:t.callbackUrl,completion:t.completion}}readCredential(){return this.tokenStorage.getCredential(this.identity)}updateCredential(t){return this.tokenStorage.updateCredential(this.identity,t)}baseCredential(t){return{...t??{},serverUrl:this.serverUrl,...this.config.clientId?{clientId:this.config.clientId}:{},updatedAt:new Date().toISOString()}}}import{promises as W}from"node:fs";import Xt from"node:os";import w from"node:path";import{merge as Ie}from"lodash-es";import Le from"write-file-atomic";var F=1,pt=256,V=4096,q=30000,Rt=1800000,J=86400000,hr=30000,Ir=30000;function Q(t){return Number.isSafeInteger(t)&&t>=1&&t<=4096}function j(t){return Number.isSafeInteger(t)&&t>=30000&&t<=86400000}var $t=Ut("Service"),f=(t,n)=>Object.fromEntries(t.map((e)=>[e,n])),P={...f(["models","modelProviders","currentModelId","temperature","maxOutputTokens","timeout","bashForegroundHandoffMs","providerForegroundRecoveryMs","providerCircuitBreakerOpenMs","providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency","providerRequestAdmissionMs","providerRequestPendingBytes","agentTeamsEnabled","codeTheme","uiTheme","language","debug","fontSize","autoSaveSessions","notifyBuild","notifyErrors","notifySounds","privacyTelemetry","privacyCrash","communicationStyle","mcpServers","lspServers"],{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0}),...f(["stream","topP","topK","mcpEnabled"],{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1}),...f(["permissions","disableAllHooks","maxTurns","maxConcurrentTasks","maxQueuedTasks","maxQueuedTaskBytes"],{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0}),...f(["hooks","enabledPlugins","env"],{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0}),...f(["pluginSourcePolicy","maxResidentSessionRuntimes","sessionRuntimeIdleMs"],{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0}),...f(["maxResidentSessionProjections","sessionProjectionIdleMs"],{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0,allowedScopes:["global"]}),...f(["permissionMode","systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1})},Rr=new Set(Object.entries(P).filter(([t,n])=>n.persistable).map(([t])=>t)),Xr=new Set(Object.entries(P).filter(([t,n])=>!n.persistable).map(([t])=>t));class C extends Error{code;field;constructor(t,n,e){super(n);this.code=t;this.field=e;this.name="ConfigSaveError"}}class L{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new U;debounceDelay=300;constructor(){}static getInstance(){if(!L.instance)L.instance=new L;return L.instance}static resetInstance(){if(L.instance)for(let t of L.instance.timers.values())clearTimeout(t);L.instance=null}coordinationStatsForTests(){return this.fileLocks.getStats()}async save(t,n={}){this.validatePersistableFields(t),this.validateAllowedScopes(t,n.scope),this.validateFieldValues(t);let e=this.groupUpdatesByTarget(t,n.scope,n.projectDir);if(n.immediate)await Promise.all(Array.from(e.entries()).map(([_,r])=>this.flushTarget(_,r)));else for(let[_,r]of e)this.scheduleSave(_,r)}async flush(){for(let n of this.timers.values())clearTimeout(n);this.timers.clear();let t=Array.from(this.pendingUpdates.entries()).map(([n,e])=>this.flushTarget(n,e));this.pendingUpdates.clear(),await Promise.all(t)}async appendPermissionRule(t,n={}){await this.appendPermissionRuleForDecision(t,"allow",n)}async appendPermissionDenyRule(t,n={}){await this.appendPermissionRuleForDecision(t,"deny",n)}async appendPermissionRuleForDecision(t,n,e){let _=e.scope??"local",r=this.resolveFilePath("settings",_,e.projectDir);await this.flushTargetWithModifier(r,(S)=>{let M=S.permissions??{allow:[],ask:[],deny:[]},s={allow:n==="allow"?this.dedupeArray([...M.allow||[],t]):M.allow||[],ask:M.ask||[],deny:n==="deny"?this.dedupeArray([...M.deny||[],t]):M.deny||[]};return{...S,permissions:s}})}async appendLocalPermissionRule(t,n={}){await this.appendPermissionRule(t,{...n,scope:"local"})}async appendLocalPermissionDenyRule(t,n={}){await this.appendPermissionDenyRule(t,{...n,scope:"local"})}async removePluginSetting(t,n={}){let e=n.scope??"local",_=this.resolveFilePath("settings",e,n.projectDir);await this.flushTargetWithModifier(_,(r)=>{let S={...r.enabledPlugins??{}};delete S[t];let M={...r};if(Object.keys(S).length>0)M.enabledPlugins=S;else delete M.enabledPlugins;return M})}validatePersistableFields(t){for(let n of Object.keys(t)){let e=P[n];if(!e)throw new C("UNKNOWN_CONFIG_FIELD",`Unknown config field: ${n}`);if(!e.persistable)throw new C("NON_PERSISTABLE_FIELD",`Field "${n}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`,n)}}validateAllowedScopes(t,n){for(let e of Object.keys(t)){let _=P[e];if(!_?.allowedScopes)continue;let r=n??_.defaultScope;if(!_.allowedScopes.includes(r))throw new C("INVALID_CONFIG_SCOPE",`Field "${e}" only supports scopes: ${_.allowedScopes.join(", ")}`,e)}}validateFieldValues(t){if(t.maxResidentSessionProjections!==void 0&&!Q(t.maxResidentSessionProjections))throw new C("INVALID_CONFIG_VALUE",`Field "maxResidentSessionProjections" must be a safe integer between ${F} and ${V}`,"maxResidentSessionProjections");if(t.sessionProjectionIdleMs!==void 0&&!j(t.sessionProjectionIdleMs))throw new C("INVALID_CONFIG_VALUE",`Field "sessionProjectionIdleMs" must be a safe integer between ${q} and ${J}`,"sessionProjectionIdleMs")}groupUpdatesByTarget(t,n,e){let _=new Map;for(let[r,S]of Object.entries(t)){let M=P[r];if(!M)continue;let s=n??M.defaultScope,E=this.resolveFilePath(M.target,s,e);if(!_.has(E))_.set(E,{});_.get(E)[r]=S}return _}resolveFilePath(t,n,e){let _=e??i();if(t==="config")return n==="global"?w.join(Xt.homedir(),".blade","config.json"):w.join(_,".blade","config.json");switch(n){case"local":return w.join(_,".blade","settings.local.json");case"project":return w.join(_,".blade","settings.json");case"global":return w.join(Xt.homedir(),".blade","settings.json");default:return w.join(_,".blade","settings.local.json")}}scheduleSave(t,n){let e=this.pendingUpdates.get(t)??{},_=this.mergePendingUpdates(e,n);this.pendingUpdates.set(t,_);let r=this.timers.get(t);if(r)clearTimeout(r);let S=setTimeout(async()=>{let M=this.pendingUpdates.get(t);if(M){this.pendingUpdates.delete(t),this.timers.delete(t);try{await this.flushTarget(t,M)}catch(s){let E=s instanceof Error?s:Error(String(s));$t.error(`Failed to save config to ${t}:`,E.message),$t.error("Stack trace:",E.stack)}}},this.debounceDelay);this.timers.set(t,S)}mergePendingUpdates(t,n){let e={...t};for(let[_,r]of Object.entries(n)){let S=P[_];if(!S){e[_]=r;continue}switch(S.mergeStrategy){case"replace":e[_]=r;break;case"append-dedupe":this.applyAppendDedupe(e,_,r);break;case"deep-merge":this.applyDeepMerge(e,_,r);break}}return e}async flushTarget(t,n){await this.fileLocks.runExclusive(t,async()=>{await this.performWrite(t,n)})}async flushTargetWithModifier(t,n){await this.fileLocks.runExclusive(t,async()=>{await W.mkdir(w.dirname(t),{recursive:!0,mode:493});let e={};try{let r=await W.readFile(t,"utf-8");e=JSON.parse(r)}catch{e={}}let _=n(e);await this.atomicWrite(t,_)})}async performWrite(t,n){await W.mkdir(w.dirname(t),{recursive:!0,mode:493});let e={};try{let r=await W.readFile(t,"utf-8");e=JSON.parse(r)}catch{e={}}let _={...e};if(typeof _.theme==="string"&&_.codeTheme===void 0)_.codeTheme=_.theme;delete _.theme;for(let[r,S]of Object.entries(n)){let M=P[r];if(!M){_[r]=S;continue}switch(M.mergeStrategy){case"replace":_[r]=S;break;case"append-dedupe":this.applyAppendDedupe(_,r,S);break;case"deep-merge":this.applyDeepMerge(_,r,S);break}}await this.atomicWrite(t,_)}applyAppendDedupe(t,n,e){if(n==="permissions"&&typeof e==="object"&&e!==null){let _=t[n]??{allow:[],ask:[],deny:[]},r=e;t[n]={allow:this.dedupeArray([..._.allow||[],...r.allow||[]]),ask:this.dedupeArray([..._.ask||[],...r.ask||[]]),deny:this.dedupeArray([..._.deny||[],...r.deny||[]])}}else if(Array.isArray(e)){let _=Array.isArray(t[n])?t[n]:[];t[n]=this.dedupeArray([..._,...e])}else t[n]=e}applyDeepMerge(t,n,e){if(typeof e==="object"&&e!==null&&!Array.isArray(e)){let _=typeof t[n]==="object"&&t[n]!==null?t[n]:{};t[n]=Ie({},_,e)}else t[n]=e}dedupeArray(t){return Array.from(new Set(t))}async atomicWrite(t,n){await Le(t,JSON.stringify(n,null,2),{mode:384,encoding:"utf-8"})}}function $r(){return L.getInstance()}var Ot={allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]};var zt=15000,Dt=1000,Gt=300000;function ot(t){return t===0||typeof t==="number"&&Number.isSafeInteger(t)&&t>=1000&&t<=300000}function zr(t,n=15000){return ot(t)?t:n}var Kt=1,Ht=32,Yt=256,Ft=30000,Vt=300000,qt=3600000,Gr=30000;function Jt(t){return Number.isSafeInteger(t)&&t>=1&&t<=256}function Qt(t){return Number.isSafeInteger(t)&&t>=30000&&t<=3600000}var jt=1,Wt=64,Zt=1,kt=1e4,lt=67108864,yt=65536,vt=134217728;function tn(t){return Number.isInteger(t)&&t>=1&&t<=64}function nn(t){return Number.isInteger(t)&&t>=1&&t<=1e4}function en(t){return Number.isSafeInteger(t)&&t>=65536&&t<=134217728}var T={currentModelId:"",models:[],modelProviders:{},temperature:0,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,bashForegroundHandoffMs:zt,providerForegroundRecoveryMs:rn,providerCircuitBreakerOpenMs:_n,providerRequestAdmissionMs:Mn,agentTeamsEnabled:!1,providerRequestPendingBytes:Sn,codeTheme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},lspServers:{},permissions:Ot,permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},enabledPlugins:{},pluginSourcePolicy:{restrictToAllowedSources:!1,requireGitCommitSha:!1,allowedGitHosts:[],allowedMarketplaces:[],allowedLocalRoots:[]},env:{},disableAllHooks:!1,maxTurns:-1,maxConcurrentTasks:3,maxQueuedTasks:100,maxQueuedTaskBytes:lt,maxResidentSessionRuntimes:Ht,sessionRuntimeIdleMs:Vt,maxResidentSessionProjections:pt,sessionProjectionIdleMs:Rt};var sn=/^[A-Za-z0-9_-]{21}$/;function En(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[._-]+$/g,"").slice(0,80)||"model"}function de(t,n){let e=new Set(n.map((M)=>M.id)),_=En(t.model);if(!e.has(_))return _;let r=`${En(t.provider)}-${_}`.slice(0,120);if(!e.has(r))return r;let S=2;while(e.has(`${r}-${S}`))S++;return`${r}-${S}`}function un(t,n){let e=t.filter((S)=>!sn.test(S.id)).map((S)=>({id:S.id})),_=new Map;return{models:t.map((S)=>{if(!sn.test(S.id))return{...S};let{id:M,...s}=S,E=de(s,e);return e.push({id:E}),_.set(M,E),{...S,id:E}}),currentModelId:_.get(n)??n,changed:_.size>0}}import{promises as Dn}from"fs";import{merge as G}from"lodash-es";import g from"os";import u from"path";function mn(t){let n=on(t.timeout??300000,"MCP timeout"),e=on(t.idleTimeout??Math.min(60000,n),"MCP idleTimeout");if(e>n)throw Error("MCP idleTimeout must not exceed timeout");return{totalTimeoutMs:n,idleTimeoutMs:e,maxProgressEvents:128}}function vr(t,n,e){if(n.count>=e.maxProgressEvents)return;if(!Number.isFinite(t.progress)||t.progress<0)return;if(t.total!==void 0&&(!Number.isFinite(t.total)||t.total<=0))return;if(n.lastProgress!==void 0&&t.progress<n.lastProgress)return;n.count++,n.lastProgress=t.progress;let _=t.message?.replace(/\0/g,"").trim().slice(0,1000);return{progress:t.progress,...t.total!==void 0?{total:t.total}:{},message:_||we(t.progress,t.total)}}function on(t,n){if(!Number.isSafeInteger(t)||t<1000||t>1800000)throw Error(`${n} must be an integer between 1000 and 1800000 milliseconds`);return t}function we(t,n){if(n!==void 0)return`MCP progress ${Math.max(0,Math.min(100,t/n*100)).toFixed(0)}%`;return`MCP progress ${t}`}import{createHash as Ne}from"node:crypto";var Z=["debug","info","notice","warning","error","critical","alert","emergency"],e_=64,r_=64,__=256,fe=8192,gn=16384,Pe=256,xe=6,Be=128,Tn=64,an=64,Ce=128,pe=/authorization|api[-_]?key|cookie|credential|password|secret|token/i;function cn(t){let n=t.logging;if(n!==void 0&&(n===null||typeof n!=="object"||Array.isArray(n)))throw Error("MCP logging configuration must be an object");let e=n?.enabled??!0;if(typeof e!=="boolean")throw Error("MCP logging enabled must be a boolean");let _=n?.level??"warning";if(!Re(_))throw Error(`MCP logging level must be one of: ${Z.join(", ")}`);return{enabled:e,level:_}}function Re(t){return typeof t==="string"&&Z.includes(t)}function M_(t,n){return Z.indexOf(t)>=Z.indexOf(n)}function Xe(t,n={}){let e=$e(t.data),_=typeof e.value==="string"?e.value:JSON.stringify(e.value),r=An(_,gn),S=r.value,M=Buffer.byteLength(S),s=Ne("sha256").update(S).digest("hex"),E=n.exposeDetails!==!1,o=E?An(S,fe):{value:`[MCP log details omitted; sha256=${s}]`,truncated:!1},a=E&&t.logger?k(Tt(t.logger),Pe):void 0;return{level:t.level,...a?{logger:a}:{},message:o.value||"[empty MCP log message]",projectedBytes:M,dataSha256:s,truncated:e.truncated||r.truncated||o.truncated,detailsOmitted:!E,timestamp:n.now??Date.now()}}function S_(t,n={}){return{...Xe({level:"warning",logger:"blade.mcp.logging",data:`MCP log rate exceeded; dropped at least ${Math.max(1,t)} message(s)`},n),synthetic:!0}}function $e(t){let n={nodes:0,remainingStringBytes:gn,truncated:!1,seen:new WeakSet};return{value:mt(t,0,n),truncated:n.truncated}}function mt(t,n,e){if(e.nodes++,e.nodes>Be)return e.truncated=!0,"[node limit reached]";if(t===null||typeof t==="boolean")return t;if(typeof t==="number")return Number.isFinite(t)?t:String(t);if(typeof t==="bigint")return t.toString();if(typeof t==="string"){let _=Tt(t),r=Math.max(0,e.remainingStringBytes),S=k(_,r),M=Buffer.byteLength(S);if(e.remainingStringBytes-=M,M<Buffer.byteLength(_))e.truncated=!0;return S}if(typeof t>"u")return"[undefined]";if(typeof t==="symbol"||typeof t==="function")return`[${typeof t}]`;if(n>=xe)return e.truncated=!0,"[depth limit reached]";if(e.seen.has(t))return e.truncated=!0,"[circular]";e.seen.add(t);try{if(Array.isArray(t)){if(t.length>Tn)e.truncated=!0;return t.slice(0,Tn).map((S)=>mt(S,n+1,e))}let _=Object.create(null),r=Object.entries(t);if(r.length>an)e.truncated=!0;for(let[S,M]of r.slice(0,an)){let s=k(Tt(S),Ce)||"[empty-key]";if(S==="_meta"||pe.test(S))_[s]="[redacted]";else _[s]=mt(M,n+1,e)}return _}finally{e.seen.delete(t)}}function Tt(t){return[...t.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")].filter((e)=>{let _=e.charCodeAt(0);return(_===9||_===10||_===13||_>=32)&&_!==127}).join("")}function k(t,n){if(n<=0)return"";if(Buffer.byteLength(t)<=n)return t;let e=Buffer.from(t).subarray(0,n).toString("utf8");while(Buffer.byteLength(e)>n)e=e.slice(0,-1);return e}function An(t,n){if(Buffer.byteLength(t)<=n)return{value:t,truncated:!1};let e=`
20
+ ...[MCP log truncated]`;return{value:k(t,n-Buffer.byteLength(e))+e,truncated:!0}}var hn=1024,Ue=4096,In=2,Oe=8,Ln=65536,ze=1048576,bn=50,dn=16000,wn=4,De=100,Nn=1048576,Ge=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Bn(t){if(!t)return{enabled:!1,maxTokens:hn,maxRequestsPerToolCall:In,maxInputBytes:Ln};if(typeof t.enabled!=="boolean")throw Error("MCP sampling.enabled must be a boolean");return{enabled:t.enabled,maxTokens:l(t.maxTokens??hn,1,Ue,"MCP sampling.maxTokens"),maxRequestsPerToolCall:l(t.maxRequestsPerToolCall??In,1,Oe,"MCP sampling.maxRequestsPerToolCall"),maxInputBytes:l(t.maxInputBytes??Ln,1,ze,"MCP sampling.maxInputBytes")}}function u_(t,n){if(!n.enabled)throw Error("MCP sampling is disabled");if(t.task)throw Error("Task-based MCP sampling is not supported");if(t.tools?.length)throw Error("MCP sampling tools were not negotiated");if(t.includeContext&&t.includeContext!=="none")throw Error("MCP sampling server context was not negotiated");if(t.messages.length===0||t.messages.length>bn)throw Error(`MCP sampling messages must contain 1-${bn} entries`);if(t.systemPrompt!==void 0&&t.systemPrompt.length>dn)throw Error(`MCP sampling system prompt exceeds ${dn} characters`);if(t.temperature!==void 0&&(!Number.isFinite(t.temperature)||t.temperature<0||t.temperature>2))throw Error("MCP sampling temperature must be between 0 and 2");let e=t.stopSequences??[];if(e.length>wn||e.some((o)=>!o||o.length>De||o.includes("\x00")))throw Error(`MCP sampling stop sequences must contain at most ${wn} non-empty bounded values`);let _=[],r=0,S=0,M=0,s=[];if(t.systemPrompt)r+=Buffer.byteLength(t.systemPrompt,"utf8"),_.push({role:"system",content:t.systemPrompt}),s.push(`System: ${fn(t.systemPrompt)}`);for(let o of t.messages){let a=Array.isArray(o.content)?o.content:[o.content],h=[],c=[];for(let A of a){if(A.type==="text"){r+=Buffer.byteLength(A.text,"utf8"),h.push({type:"text",text:A.text}),c.push(fn(A.text));continue}if(A.type==="image"){if(o.role!=="user")throw Error("MCP sampling images are only supported in user messages");if(!Ge.has(A.mimeType))throw Error(`Unsupported MCP sampling image type: ${A.mimeType}`);let X=Ke(A.data);S+=X,M++,h.push({type:"image_url",image_url:{url:`data:${A.mimeType};base64,${A.data}`}}),c.push(`[${A.mimeType} image, ${X} bytes]`);continue}throw Error(`Unsupported MCP sampling content type: ${A.type}`)}if(h.length===0)throw Error("MCP sampling message has no supported content");_.push({role:o.role,content:h.length===1&&h[0]?.type==="text"?h[0].text:h}),s.push(`${o.role==="user"?"User":"Assistant"}: ${c.join(" ")}`)}if(r+S>n.maxInputBytes)throw Error(`MCP sampling input exceeds ${n.maxInputBytes} bytes`);if(M>Pn||S>xn)throw Error("MCP sampling image input exceeds the shared attachment budget");let E=l(t.maxTokens,1,Number.MAX_SAFE_INTEGER,"MCP sampling maxTokens");return{messages:_,maxTokens:Math.min(E,n.maxTokens),...t.temperature!==void 0?{temperature:t.temperature}:{},stopSequences:[...e],preview:s.join(`
21
+ `).slice(0,8000)}}function o_(t,n,e){if(t.toolCalls?.length)throw Error("Model returned tools for basic MCP sampling");let _=t.content,r=t.finishReason==="length"||t.finishReason==="max_tokens"?"maxTokens":"endTurn",S=-1;for(let M of e.stopSequences){let s=_.indexOf(M);if(s>=0&&(S===-1||s<S))S=s}if(S>=0)_=_.slice(0,S),r="stopSequence";if(Buffer.byteLength(_,"utf8")>Nn)throw Error(`MCP sampling response exceeds ${Nn} bytes`);return{model:n,role:"assistant",content:{type:"text",text:_},stopReason:r}}function l(t,n,e,_){if(!Number.isSafeInteger(t)||t<n||t>e)throw Error(`${_} must be an integer between ${n} and ${e}`);return t}function Ke(t){if(!t||t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error("MCP sampling image contains invalid base64 data");return Buffer.from(t,"base64").byteLength}function fn(t){return t.replace(/\s+/g," ").trim().slice(0,1000)}var T_=256,a_=1e4,A_=86400000;var He=/[\p{Cf}\p{Co}\p{Cn}]/u;function pn(t){if(!t)return{enabled:!1,defaultTtlMs:600000,pollIntervalMs:500,maxTasksPerSession:32,maxLifetimeMs:1800000};if(typeof t.enabled!=="boolean")throw Error("MCP tasks.enabled must be a boolean");let n=x(t.defaultTtlMs??600000,1e4,86400000,"MCP tasks.defaultTtlMs"),e=x(t.maxLifetimeMs??1800000,1e4,86400000,"MCP tasks.maxLifetimeMs");if(n>e)throw Error("MCP tasks.defaultTtlMs must not exceed tasks.maxLifetimeMs");return{enabled:t.enabled,defaultTtlMs:n,pollIntervalMs:x(t.pollIntervalMs??500,100,1e4,"MCP tasks.pollIntervalMs"),maxTasksPerSession:x(t.maxTasksPerSession??32,1,32,"MCP tasks.maxTasksPerSession"),maxLifetimeMs:e}}function g_(t,n){return x(t??n.defaultTtlMs,1e4,Math.min(86400000,n.maxLifetimeMs),"MCP task ttl")}function c_(t,n,e){let _=Fe(t.taskId,"task ID",512),r=Cn(t.createdAt,"createdAt"),S=Cn(t.lastUpdatedAt,"lastUpdatedAt");if(Date.parse(S)<Date.parse(r))throw Error("MCP task lastUpdatedAt precedes createdAt");if(e&&(_!==e.taskId||r!==e.createdAt))throw Error("MCP task identity changed across connection generation");let M=t.ttl===null?null:x(t.ttl,0,86400000,"MCP task ttl"),s=t.pollInterval===void 0?n.pollIntervalMs:x(t.pollInterval,0,Number.MAX_SAFE_INTEGER,"MCP task pollInterval"),E=Math.min(1e4,Math.max(100,s)),o=t.statusMessage?Ye(t.statusMessage,_):void 0;return{taskId:_,status:t.status,createdAt:r,lastUpdatedAt:S,ttl:M,pollIntervalMs:E,...o?{statusMessage:o}:{}}}function i_(t){return["completed","failed","cancelled"].includes(t)}function h_(t){let n=t instanceof Error?t.message:String(t);return Rn(at(n.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")),1024)}function Ye(t,n){return Rn(at(t.replaceAll(n,"[redacted-task-id]")),1024)}function at(t){return[...t.normalize("NFKC")].filter((n)=>{let e=n.codePointAt(0)??0;if(e===0||e>=1&&e<=8||e===11||e===12||e>=14&&e<=31||e===127)return!1;return!He.test(n)}).join("").trim()}function Cn(t,n){let e=Date.parse(t);if(!Number.isFinite(e))throw Error(`MCP task ${n} is invalid`);return new Date(e).toISOString()}function Fe(t,n,e){if(!t||Buffer.byteLength(t)>e||at(t)!==t)throw Error(`MCP ${n} is invalid`);return t}function x(t,n,e,_){if(!Number.isSafeInteger(t)||t<n||t>e)throw Error(`${_} must be an integer between ${n} and ${e}`);return t}function Rn(t,n){let e=Buffer.from(t);if(e.length<=n)return t;let _=e.subarray(0,n).toString("utf8");while(Buffer.byteLength(_)>n)_=_.slice(0,-1);return _}var Ve={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function At(t){let n=t.toLowerCase().trim();return Ve[n]??t}var qe=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/,Je=/^\.[A-Za-z0-9_+-]{1,32}$/;function y(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function p(t,n,e,_,r){if(t===void 0)return r;if(!Number.isInteger(t)||Number(t)<e||Number(t)>_)throw Error(`${n} must be an integer between ${e} and ${_}`);return Number(t)}function Xn(t,n){if(t===void 0)return;let e;try{e=JSON.stringify(t)}catch{throw Error(`${n} must be JSON serializable`)}if(e===void 0||Buffer.byteLength(e)>262144)throw Error(`${n} exceeds the 256 KiB limit`);return structuredClone(t)}function Qe(t,n){if(t===void 0)return{};if(!y(t))throw Error(`${n} must be an object`);let e={};for(let[_,r]of Object.entries(t)){if(!_||typeof r!=="string"||r.includes("\x00"))throw Error(`${n} must contain non-empty string values`);e[_]=r}return e}function d(t){if(t===void 0)return{};if(!y(t))throw Error("lspServers must be an object");let n=Object.entries(t);if(n.length>32)throw Error("lspServers exceeds the 32-server limit");let e={};for(let[_,r]of n){if(!qe.test(_))throw Error(`Invalid LSP server name: ${_}`);if(!y(r))throw Error(`lspServers.${_} must be an object`);let S=new Set(["command","args","extensionToLanguage","env","initializationOptions","settings","enabled","priority","startupTimeout","shutdownTimeout","requestTimeout","diagnosticWaitTimeout","maxRestarts"]),M=Object.keys(r).filter((c)=>!S.has(c));if(M.length>0)throw Error(`Unknown LSP server field: ${_}.${M[0]}`);if(typeof r.command!=="string"||!r.command.trim()||r.command.includes("\x00")||r.command.includes(`
22
+ `))throw Error(`lspServers.${_}.command must be a non-empty command`);if(r.args!==void 0&&!Array.isArray(r.args))throw Error(`lspServers.${_}.args must be an array`);let s=(r.args??[]).map((c,A)=>{if(typeof c!=="string"||c.includes("\x00"))throw Error(`lspServers.${_}.args.${A} must be a string`);return c});if(s.length>128)throw Error(`lspServers.${_}.args exceeds the 128-item limit`);if(!y(r.extensionToLanguage))throw Error(`lspServers.${_}.extensionToLanguage must be an object`);let E=Object.entries(r.extensionToLanguage);if(E.length===0||E.length>64)throw Error(`lspServers.${_}.extensionToLanguage must contain 1-64 entries`);let o={};for(let[c,A]of E){let X=c.startsWith(".")?c.toLowerCase():`.${c.toLowerCase()}`;if(!Je.test(X)||typeof A!=="string"||!A.trim())throw Error(`Invalid lspServers.${_}.extensionToLanguage entry: ${c}`);o[X]=A.trim()}if(r.enabled!==void 0&&typeof r.enabled!=="boolean")throw Error(`lspServers.${_}.enabled must be a boolean`);let a=Xn(r.initializationOptions,`lspServers.${_}.initializationOptions`),h=Xn(r.settings,`lspServers.${_}.settings`);e[_]={command:r.command.trim(),...s.length>0?{args:s}:{},extensionToLanguage:o,...r.env!==void 0?{env:Qe(r.env,`lspServers.${_}.env`)}:{},...a!==void 0?{initializationOptions:a}:{},...h!==void 0?{settings:h}:{},...r.enabled!==void 0?{enabled:r.enabled}:{},priority:p(r.priority,`lspServers.${_}.priority`,-1000,1000,0),startupTimeout:p(r.startupTimeout,`lspServers.${_}.startupTimeout`,100,60000,1e4),shutdownTimeout:p(r.shutdownTimeout,`lspServers.${_}.shutdownTimeout`,100,1e4,2000),requestTimeout:p(r.requestTimeout,`lspServers.${_}.requestTimeout`,100,60000,1e4),diagnosticWaitTimeout:p(r.diagnosticWaitTimeout,`lspServers.${_}.diagnosticWaitTimeout`,0,5000,750),maxRestarts:p(r.maxRestarts,`lspServers.${_}.maxRestarts`,0,10,3)}}return e}function $n(t){return Number.isInteger(t)&&(t===-1||t>=0)}function Un(){return"-1 (unlimited), 0 (disabled), or any positive integer"}import On from"node:path";var zn=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,je=/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;function z(t){let n=[];for(let[e,_]of Object.entries(t)){if(!zn.test(e))throw Error(`Invalid plugin name in enabledPlugins: ${e}`);if(typeof _!=="boolean")throw Error(`Invalid enabledPlugins value for ${e}`);n.push([e,_])}return Object.fromEntries(n)}function gt(t,n,e){if(!Array.isArray(t))throw Error(`${n} must be an array`);return[...new Set(t.map((_,r)=>{if(typeof _!=="string"||!_.trim())throw Error(`${n}[${r}] must be a non-empty string`);return e(_.trim())}))].sort()}function D(t){let n=new Set(["restrictToAllowedSources","requireGitCommitSha","allowedGitHosts","allowedMarketplaces","allowedLocalRoots"]),e=Object.keys(t).filter((r)=>!n.has(r));if(e.length>0)throw Error(`Unknown pluginSourcePolicy fields: ${e.join(", ")}`);let _={};for(let r of["restrictToAllowedSources","requireGitCommitSha"]){if(t[r]===void 0)continue;if(typeof t[r]!=="boolean")throw Error(`pluginSourcePolicy.${r} must be boolean`);_[r]=t[r]}if(t.allowedGitHosts!==void 0)_.allowedGitHosts=gt(t.allowedGitHosts,"pluginSourcePolicy.allowedGitHosts",(r)=>{let S=r.toLowerCase();if(!je.test(S))throw Error(`Invalid plugin Git host pattern: ${r}`);return S});if(t.allowedMarketplaces!==void 0)_.allowedMarketplaces=gt(t.allowedMarketplaces,"pluginSourcePolicy.allowedMarketplaces",(r)=>{if(!zn.test(r))throw Error(`Invalid allowed Marketplace name: ${r}`);return r});if(t.allowedLocalRoots!==void 0)_.allowedLocalRoots=gt(t.allowedLocalRoots,"pluginSourcePolicy.allowedLocalRoots",(r)=>{if(!On.isAbsolute(r))throw Error(`Plugin local allowlist root must be absolute: ${r}`);return On.resolve(r)});return _}function v(t){let n=[];for(let[e,_]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error(`Invalid environment variable name: ${e}`);if(typeof _!=="string"||_.includes("\x00"))throw Error(`Invalid environment variable value: ${e}`);n.push([e,_])}return Object.fromEntries(n)}class R{static instance=null;runtimePermissionOverrides;lastAdditionalSettings;warnedGlobalOnlyProjectionResidencyFiles=new Set;constructor(){}static getInstance(){if(!R.instance)R.instance=new R;return R.instance}static resetInstance(){R.instance=null}async initialize(t){try{this.lastAdditionalSettings=t,this.runtimePermissionOverrides=t?.permissions;let e=(await b.getInstance().getStatus(i())).state==="trusted",_=await this.loadConfigFiles(e),r=await this.loadSettingsFiles(e),S={..._,...r,enabledPlugins:{..._.enabledPlugins||{},...r.enabledPlugins||{}}};if(t)S=this.mergeSettings(S,t);let M=this.normalizeConfig(S),s={...T,...M};if(s.enabledPlugins=z(s.enabledPlugins),s.lspServers=d(s.lspServers),s.pluginSourcePolicy={...T.pluginSourcePolicy,...D(s.pluginSourcePolicy)},this.resolveEnvInterpolation(s),process.env.BLADE_MODEL&&s.models?.length>0){let E=At(process.env.BLADE_MODEL),o=s.models.find((a)=>a.id===E||a.model===E||a.id===process.env.BLADE_MODEL||a.model===process.env.BLADE_MODEL);if(o)s.currentModelId=o.id}if(process.env.BLADE_DEBUG)s.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(tt().configureModelProviders(s.modelProviders,s.models),s.models.length>0)this.validateConfig(s);if(s.debug)console.log("[ConfigManager] Configuration loaded successfully");return s}catch(n){return console.error("[ConfigManager] Failed to initialize:",n),tt().configureModelProviders({},[]),T}}async reload(){return this.initialize(this.lastAdditionalSettings)}async loadConfigFiles(t){let n=u.join(g.homedir(),".blade","config.json"),e=u.join(i(),".blade","config.json"),_={},r=await this.loadJsonFile(n),S=r?await this.migrateLegacyUserConfig(r):null;if(S)_={..._,...S};let M=await this.loadJsonFile(e);if(M&&t){let s={..._.mcpServers||{},...M.mcpServers||{}},E={..._.lspServers||{},...M.lspServers||{}},o={..._.modelProviders||{},...M.modelProviders||{}},a={..._.enabledPlugins||{},...M.enabledPlugins||{}};if(_={..._,...M},Object.keys(s).length>0)_.mcpServers=s;if(Object.keys(E).length>0)_.lspServers=d(E);if(Object.keys(o).length>0)_.modelProviders=o;if(Object.keys(a).length>0)_.enabledPlugins=z(a)}else if(M?.hooks)_.hooks=M.hooks;return _}async migrateLegacyUserConfig(t){let n=t,e={...t},_={};if(e.codeTheme===void 0&&typeof n.theme==="string")e.codeTheme=n.theme,_.codeTheme=n.theme;if(Array.isArray(e.models)){let r=un(e.models,e.currentModelId??"");if(r.changed)e.models=r.models,e.currentModelId=r.currentModelId,_.models=r.models,_.currentModelId=r.currentModelId}if(delete e.theme,Object.keys(_).length>0)try{await L.getInstance().save(_,{scope:"global",immediate:!0})}catch{console.warn("[ConfigManager] Could not persist legacy config migration")}return e}async loadSettingsFiles(t){let n=u.join(g.homedir(),".blade","settings.json"),e=u.join(i(),".blade","settings.json"),_=u.join(i(),".blade","settings.local.json"),r={},S=await this.loadJsonFile(n);if(S)r=this.mergeSettings(r,S);let M=this.stripGlobalOnlyProjectionResidencyFromLayer(await this.loadJsonFile(e),e,"project");if(M&&t)r=this.mergeSettings(r,M);else if(M?.hooks)r=this.mergeSettings(r,{hooks:M.hooks});let s=this.stripGlobalOnlyProjectionResidencyFromLayer(await this.loadJsonFile(_),_,"local");if(s&&t)r=this.mergeSettings(r,s);else if(s?.hooks)r=this.mergeSettings(r,{hooks:s.hooks});return r}stripGlobalOnlyProjectionResidencyFromLayer(t,n,e){if(!t)return t;let _=t.maxResidentSessionProjections!==void 0,r=t.sessionProjectionIdleMs!==void 0;if(!_&&!r)return t;this.warnGlobalOnlyProjectionResidencyOnce(n,e);let S={...t};return delete S.maxResidentSessionProjections,delete S.sessionProjectionIdleMs,S}warnGlobalOnlyProjectionResidencyOnce(t,n){if(this.warnedGlobalOnlyProjectionResidencyFiles.has(t))return;this.warnedGlobalOnlyProjectionResidencyFiles.add(t),console.warn(`[ConfigManager] Ignoring global-only session projection residency settings in ${n} settings file:`,t)}async loadWorkspacePermissions(t,n){let e={allow:[...n.allow],ask:[...n.ask],deny:[...n.deny]};if(u.resolve(t)!==u.resolve(i())){let r=await this.loadWorkspacePermissionOverrides(i(),{includeUntrusted:!0}),S=await this.loadJsonFile(u.join(g.homedir(),".blade","settings.json")),M={allow:Array.from(new Set([...T.permissions.allow,...S?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...T.permissions.ask,...S?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...T.permissions.deny,...S?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let s of["allow","ask","deny"]){let E=new Set(r[s].filter((o)=>!M[s].includes(o)));e[s]=e[s].filter((o)=>!E.has(o))}}let _=await this.loadWorkspacePermissionOverrides(t);for(let r of["allow","ask","deny"])e[r]=Array.from(new Set([...e[r],..._[r]]));return e}async loadWorkspaceMcpServers(t,n){if(u.resolve(t)===u.resolve(i()))return{...n};let e=await b.getInstance().getStatus(t),_=e.state==="trusted",r=e.projectPath,S={},M=async(E)=>{let o=await this.loadJsonFile(E);if(o?.mcpServers)S={...S,...o.mcpServers}};if(await M(u.join(g.homedir(),".blade","config.json")),await M(u.join(g.homedir(),".blade","settings.json")),_)await M(u.join(r,".blade","config.json")),await M(u.join(r,".blade","settings.json")),await M(u.join(r,".blade","settings.local.json"));if(this.lastAdditionalSettings?.mcpServers)S={...S,...this.lastAdditionalSettings.mcpServers};let s={mcpServers:S};return this.resolveEnvInterpolation(s),s.mcpServers}async loadWorkspaceLspServers(t,n){if(u.resolve(t)===u.resolve(i()))return d(n);let e=await b.getInstance().getStatus(t),_={},r=async(M)=>{let s=await this.loadJsonFile(M);if(s?.lspServers)_={..._,...d(s.lspServers)}};if(await r(u.join(g.homedir(),".blade","config.json")),await r(u.join(g.homedir(),".blade","settings.json")),e.state==="trusted")for(let M of["config.json","settings.json","settings.local.json"])await r(u.join(e.projectPath,".blade",M));if(this.lastAdditionalSettings?.lspServers)_={..._,...d(this.lastAdditionalSettings.lspServers)};let S={lspServers:_};return this.resolveEnvInterpolation(S),d(S.lspServers)}async loadWorkspaceModelConfig(t,n){if(u.resolve(t)===u.resolve(i()))return{currentModelId:n.currentModelId,models:n.models.map((M)=>structuredClone(M)),modelProviders:structuredClone(n.modelProviders),temperature:n.temperature,...n.maxOutputTokens!==void 0?{maxOutputTokens:n.maxOutputTokens}:{},timeout:n.timeout,...n.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:n.providerCircuitBreakerOpenMs}:{},...n.providerRequestConcurrency!==void 0?{providerRequestConcurrency:n.providerRequestConcurrency}:{},...n.providerGlobalConcurrency!==void 0?{providerGlobalConcurrency:n.providerGlobalConcurrency}:{},...n.providerOwnerConcurrency!==void 0?{providerOwnerConcurrency:n.providerOwnerConcurrency}:{},...n.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:n.providerRequestAdmissionMs}:{},...n.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:n.providerRequestPendingBytes}:{}};let e=await b.getInstance().getStatus(t),_=e.projectPath,r={currentModelId:T.currentModelId,models:T.models.map((M)=>structuredClone(M)),modelProviders:structuredClone(T.modelProviders),temperature:T.temperature,...T.maxOutputTokens!==void 0?{maxOutputTokens:T.maxOutputTokens}:{},timeout:T.timeout,...T.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:T.providerCircuitBreakerOpenMs}:{},...T.providerRequestConcurrency!==void 0?{providerRequestConcurrency:T.providerRequestConcurrency}:{},...T.providerGlobalConcurrency!==void 0?{providerGlobalConcurrency:T.providerGlobalConcurrency}:{},...T.providerOwnerConcurrency!==void 0?{providerOwnerConcurrency:T.providerOwnerConcurrency}:{},...T.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:T.providerRequestAdmissionMs}:{},...T.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:T.providerRequestPendingBytes}:{}},S=(M)=>{if(!M)return;if(M.modelProviders)r.modelProviders={...r.modelProviders,...structuredClone(M.modelProviders)};if(M.models)r.models=M.models.map((s)=>structuredClone(s));if(M.currentModelId!==void 0)r.currentModelId=M.currentModelId;if(M.temperature!==void 0)r.temperature=M.temperature;if(M.maxOutputTokens!==void 0)r.maxOutputTokens=M.maxOutputTokens;if(M.timeout!==void 0)r.timeout=M.timeout;if(M.providerCircuitBreakerOpenMs!==void 0)r.providerCircuitBreakerOpenMs=M.providerCircuitBreakerOpenMs;if(M.providerRequestConcurrency!==void 0)r.providerRequestConcurrency=M.providerRequestConcurrency;if(M.providerGlobalConcurrency!==void 0)r.providerGlobalConcurrency=M.providerGlobalConcurrency;if(M.providerOwnerConcurrency!==void 0)r.providerOwnerConcurrency=M.providerOwnerConcurrency;if(M.providerRequestAdmissionMs!==void 0)r.providerRequestAdmissionMs=M.providerRequestAdmissionMs;if(M.providerRequestPendingBytes!==void 0)r.providerRequestPendingBytes=M.providerRequestPendingBytes};if(S(await this.loadJsonFile(u.join(g.homedir(),".blade","config.json"))),S(await this.loadJsonFile(u.join(g.homedir(),".blade","settings.json"))),e.state==="trusted")S(await this.loadJsonFile(u.join(_,".blade","config.json"))),S(await this.loadJsonFile(u.join(_,".blade","settings.json"))),S(await this.loadJsonFile(u.join(_,".blade","settings.local.json")));if(S(this.lastAdditionalSettings),r=this.normalizeConfig(r),this.resolveEnvInterpolation(r),process.env.BLADE_MODEL&&r.models.length>0){let M=process.env.BLADE_MODEL,s=At(M),E=r.models.find((o)=>o.id===s||o.model===s||o.id===M||o.model===M);if(E)r.currentModelId=E.id}if(!r.models.some((M)=>M.id===r.currentModelId))r.currentModelId=r.models[0]?.id??"";return r}async loadWorkspaceRuntimeSettings(t,n){if(u.resolve(t)===u.resolve(i()))return{env:v(n.env),disableAllHooks:n.disableAllHooks,maxTurns:n.maxTurns,permissionMode:n.permissionMode};let e=await b.getInstance().getStatus(t),_=e.projectPath,r={env:{},disableAllHooks:T.disableAllHooks,maxTurns:T.maxTurns,permissionMode:T.permissionMode},S=(E,o)=>{if(!E)return;if(o.allowExecutionSettings){if(E.env)r.env={...r.env,...v(E.env)};if(E.maxTurns!==void 0)r.maxTurns=E.maxTurns;if(E.permissionMode!==void 0)r.permissionMode=E.permissionMode;if(E.disableAllHooks!==void 0)r.disableAllHooks=E.disableAllHooks}else if(E.disableAllHooks===!0)r.disableAllHooks=!0};S(await this.loadJsonFile(u.join(g.homedir(),".blade","config.json")),{allowExecutionSettings:!0}),S(await this.loadJsonFile(u.join(g.homedir(),".blade","settings.json")),{allowExecutionSettings:!0});let M=await Promise.all([this.loadJsonFile(u.join(_,".blade","config.json")),this.loadJsonFile(u.join(_,".blade","settings.json")),this.loadJsonFile(u.join(_,".blade","settings.local.json"))]);for(let E of M)S(E,{allowExecutionSettings:e.state==="trusted"});S(this.lastAdditionalSettings,{allowExecutionSettings:!0});let s={env:r.env};return this.resolveEnvInterpolation(s),r.env=v(s.env),r}async loadWorkspacePluginSettings(t){return(await this.loadWorkspacePluginSettingsResolution(t)).effective}async loadWorkspacePluginSettingsResolution(t){let n=await b.getInstance().getStatus(t),e={},_={},r=(S,M,s)=>{if(!S?.enabledPlugins)return;let E=z(S.enabledPlugins);for(let[o,a]of Object.entries(E)){if(!s&&a!==!1)continue;let h=_[o];e[o]=a,_[o]={effective:a,effectiveScope:M,layers:{...h?.layers??{},[M]:a}}}};r(await this.loadJsonFile(u.join(g.homedir(),".blade","config.json")),"global",!0),r(await this.loadJsonFile(u.join(g.homedir(),".blade","settings.json")),"global",!0);for(let S of["config.json","settings.json"])r(await this.loadJsonFile(u.join(n.projectPath,".blade",S)),"project",n.state==="trusted");return r(await this.loadJsonFile(u.join(n.projectPath,".blade","settings.local.json")),"local",n.state==="trusted"),r(this.lastAdditionalSettings,"invocation",!0),{effective:e,settings:_,workspaceTrusted:n.state==="trusted"}}async loadWorkspacePluginSourcePolicy(t){let n=await b.getInstance().getStatus(t),e={...T.pluginSourcePolicy,allowedGitHosts:[...T.pluginSourcePolicy.allowedGitHosts],allowedMarketplaces:[...T.pluginSourcePolicy.allowedMarketplaces],allowedLocalRoots:[...T.pluginSourcePolicy.allowedLocalRoots]},_=(M)=>{if(!M?.pluginSourcePolicy)return;Object.assign(e,D(M.pluginSourcePolicy))},r=(M,s)=>{if(!s)return M;if(M.length===0&&!e.restrictToAllowedSources)return s;let E=new Set(s);return M.filter((o)=>E.has(o))},S=(M)=>{if(!M?.pluginSourcePolicy)return;let s=D(M.pluginSourcePolicy);e.allowedGitHosts=r(e.allowedGitHosts,s.allowedGitHosts),e.allowedMarketplaces=r(e.allowedMarketplaces,s.allowedMarketplaces),e.allowedLocalRoots=r(e.allowedLocalRoots,s.allowedLocalRoots),e.restrictToAllowedSources=e.restrictToAllowedSources||s.restrictToAllowedSources===!0,e.requireGitCommitSha=e.requireGitCommitSha||s.requireGitCommitSha===!0};_(await this.loadJsonFile(u.join(g.homedir(),".blade","config.json"))),_(await this.loadJsonFile(u.join(g.homedir(),".blade","settings.json")));for(let M of["config.json","settings.json","settings.local.json"])S(await this.loadJsonFile(u.join(n.projectPath,".blade",M)));if(S(this.lastAdditionalSettings),process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true")e.requireGitCommitSha=!0;return e}async loadWorkspaceHooks(t,n,e={}){if(u.resolve(t)===u.resolve(i())&&e.includeBaseForCurrentWorkspace!==!1)return G({},n);let _=G({},T.hooks),r=[u.join(g.homedir(),".blade","settings.json"),u.join(t,".blade","settings.json"),u.join(t,".blade","settings.local.json")];for(let S of r){let M=await this.loadJsonFile(S);if(M?.hooks)_=G({},_,M.hooks)}return _}async loadWorkspacePermissionOverrides(t,n={}){let e={allow:[],ask:[],deny:[]},_=(await b.getInstance().getStatus(t)).state==="trusted",r=[..._||n.includeUntrusted?[u.join(t,".blade","settings.json")]:[],..._||n.includeUntrusted?[u.join(t,".blade","settings.local.json")]:[]];for(let S of r){let M=await this.loadJsonFile(S);if(!M?.permissions)continue;for(let s of["allow","ask","deny"])e[s]=Array.from(new Set([...e[s],...M.permissions[s]||[]]))}return e}mergeSettings(t,n){let e={...JSON.parse(JSON.stringify(t)),...JSON.parse(JSON.stringify(n))};if(n.permissions)e.permissions={allow:Array.from(new Set([...t.permissions?.allow||[],...n.permissions.allow||[]])),ask:Array.from(new Set([...t.permissions?.ask||[],...n.permissions.ask||[]])),deny:Array.from(new Set([...t.permissions?.deny||[],...n.permissions.deny||[]]))};if(n.hooks)e.hooks=G({},e.hooks,n.hooks);if(n.enabledPlugins)e.enabledPlugins={...t.enabledPlugins||{},...z(n.enabledPlugins)};if(n.pluginSourcePolicy)e.pluginSourcePolicy={...t.pluginSourcePolicy??T.pluginSourcePolicy,...D(n.pluginSourcePolicy)};if(n.env)e.env=G({},e.env,n.env);if(n.mcpServers)e.mcpServers={...e.mcpServers||{},...n.mcpServers};if(n.lspServers)e.lspServers={...e.lspServers||{},...d(n.lspServers)};if(n.disableAllHooks!==void 0)e.disableAllHooks=n.disableAllHooks;if(n.permissionMode!==void 0)e.permissionMode=n.permissionMode;if(n.maxTurns!==void 0)e.maxTurns=n.maxTurns;return e}resolveEnvInterpolation(t){let n=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,e=(r)=>{if(typeof r==="string")return r.replace(n,(S,M,s,E)=>{return process.env[M]||E||S});if(Array.isArray(r))return r.map(e);if(typeof r==="object"&&r!==null){let S=r;for(let[M,s]of Object.entries(S))S[M]=e(s);return S}return r},_=t;for(let[r,S]of Object.entries(_))_[r]=e(S)}async loadJsonFile(t){try{if(await this.fileExists(t)){let n=await Dn.readFile(t,"utf-8");return JSON.parse(n)}}catch(n){console.warn(`[ConfigManager] Failed to load ${t}:`,n)}return null}async fileExists(t){try{return await Dn.access(t),!0}catch{return!1}}normalizeConfig(t){let n=JSON.parse(JSON.stringify(t));if(n.codeTheme===void 0&&typeof n.theme==="string")n.codeTheme=n.theme;delete n.theme;let e=(r)=>r.trim().replace(/^`|`$/g,""),_=(r)=>{for(let[S,M]of Object.entries(r))if(typeof M==="string")r[S]=e(M);else if(Array.isArray(M))M.forEach((s,E)=>{if(typeof s==="string")M[E]=e(s);else if(typeof s==="object"&&s!==null)_(s)});else if(typeof M==="object"&&M!==null)_(M)};return _(n),n}validateConfig(t,n=tt()){let e=[];try{t.lspServers=d(t.lspServers)}catch(_){e.push(_ instanceof Error?_.message:"Invalid LSP server configuration")}for(let[_,r]of Object.entries(t.mcpServers||{}))try{mn(r),r.oauth=et(r);let S=cn(r);if(r.logging!==void 0)r.logging=S;if(r.sampling)r.sampling=Bn(r.sampling);if(r.tasks)r.tasks=pn(r.tasks)}catch(S){e.push(`MCP server "${_}": ${S instanceof Error?S.message:"invalid sampling policy"}`)}for(let[_,r]of Object.entries(t.modelProviders||{}))if(e.push(...Gn(_,r)),n.isReservedProviderId(_))e.push(`modelProviders.${_}: built-in provider ids cannot be overridden`);if(e.length===0)try{n.configureModelProviders(t.modelProviders||{},t.models)}catch(_){e.push(_ instanceof Error?_.message:"Failed to configure custom model providers")}if(!t.models||t.models.length===0)e.push("没有可用的模型配置");if(!$n(t.maxTurns))e.push(`maxTurns 必须是 ${Un()}`);if(!tn(t.maxConcurrentTasks))e.push(`maxConcurrentTasks 必须是 ${jt}-${Wt} 之间的整数`);if(!nn(t.maxQueuedTasks))e.push(`maxQueuedTasks 必须是 ${Zt}-${kt} 之间的整数`);if(!en(t.maxQueuedTaskBytes))e.push(`maxQueuedTaskBytes 必须是 ${yt}-${vt} 之间的整数`);if(!Jt(t.maxResidentSessionRuntimes))e.push(`maxResidentSessionRuntimes 必须是 ${Kt}-${Yt} 之间的整数`);if(!Qt(t.sessionRuntimeIdleMs))e.push(`sessionRuntimeIdleMs 必须是 ${Ft}-${qt} 之间的整数`);if(!Q(t.maxResidentSessionProjections))e.push("maxResidentSessionProjections 必须是 "+`${F}-${V} 之间的整数`);if(!j(t.sessionProjectionIdleMs))e.push(`sessionProjectionIdleMs 必须是 ${q}-${J} 之间的整数`);if(t.bashForegroundHandoffMs!==void 0&&!ot(t.bashForegroundHandoffMs))e.push("bashForegroundHandoffMs 必须是 0,或 "+`${Dt}-${Gt} 之间的整数`);if(t.providerForegroundRecoveryMs!==void 0&&!Yn(t.providerForegroundRecoveryMs))e.push("providerForegroundRecoveryMs 必须是 0,或 "+`${Kn}-${Hn} 之间的整数`);if(t.providerCircuitBreakerOpenMs!==void 0&&!qn(t.providerCircuitBreakerOpenMs))e.push("providerCircuitBreakerOpenMs 必须是 0,或 "+`${Fn}-${Vn} 之间的整数`);if(t.providerRequestConcurrency!==void 0&&!ln(t.providerRequestConcurrency))e.push("providerRequestConcurrency 必须是 "+`${ct}-${Jn} 之间的整数`);for(let[_,r]of[["providerGlobalConcurrency",t.providerGlobalConcurrency],["providerOwnerConcurrency",t.providerOwnerConcurrency]])if(r!==void 0&&!yn(r))e.push(`${_} 必须是 ${ct}-${Qn} 之间的整数`);if(t.providerRequestAdmissionMs!==void 0&&!vn(t.providerRequestAdmissionMs))e.push("providerRequestAdmissionMs 必须是 0,或 "+`${jn}-${Wn} 之间的整数`);if(t.providerRequestPendingBytes!==void 0&&!te(t.providerRequestPendingBytes))e.push("providerRequestPendingBytes 必须是 "+`${Zn}-${kn} 之间的整数`);if(t.models&&t.models.length>0){if(!t.currentModelId)e.push("未设置当前模型 ID");else if(!t.models.find((r)=>r.id===t.currentModelId))e.push(`当前模型 ID "${t.currentModelId}" 在 models 列表中不存在`);for(let _ of t.models){let r=`模型 "${_.displayName||_.id}"`,S=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((s)=>(s in _));if(S.length>0)e.push(`${r}: 不再支持旧字段 ${S.join(", ")};请重新配置模型`);if(!_.model)e.push(`${r}: model 字段必填`);if(!_.provider)e.push(`${r}: provider 字段必填`);if(_.overrides?.baseUrl&&!_.overrides.baseUrl.startsWith("http"))e.push(`${r}: overrides.baseUrl "${_.overrides.baseUrl}" 不是有效的 HTTP URL`);let M=_.overrides?.streamIdleTimeout;if(M!==void 0&&(!Number.isFinite(M)||M<1000))e.push(`${r}: overrides.streamIdleTimeout 必须至少为 1000ms`);try{n.getModel(_.provider,_.model)}catch{e.push(`${r}: 内置 catalog 中不存在 ${_.provider}/${_.model}`)}}}if(e.length>0)throw Error(`配置验证失败:
23
+ ${e.map((_)=>` - ${_}`).join(`
24
+ `)}
25
+
26
+ `+`请通过以下方式之一提供配置:
27
+ `+` 1. 首次启动: 运行 blade,系统会自动引导配置
28
+ `+` 2. 添加模型: blade 后输入 /model add
29
+ `+` 3. 初始化向导: 输入 /init
30
+
31
+ `+`配置文件示例 (~/.blade/config.json):
32
+ `+`{
33
+ "currentModelId": "model-id-123",
34
+ "models": [
35
+ {
36
+ "id": "model-id-123",
37
+ `+` "displayName": "默认模型",
38
+ `+` "provider": "deepseek",
39
+ "model": "deepseek-v4-pro"
40
+ }
41
+ ]
42
+ }
43
+ `)}}function rM(t,n={}){let e={...t};if(n.debug!==void 0)e.debug=n.debug===""?!0:n.debug;if(n.model){if(!t.models.some((r)=>r.id===n.model))throw Error(`模型配置未找到: ${n.model}`);e.currentModelId=n.model}if(n.yolo===!0)e.permissionMode="yolo";else if(n.permissionMode!==void 0)e.permissionMode=n.permissionMode;if(n.maxTurns!==void 0)e.maxTurns=n.maxTurns;if(n.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=n.maxConcurrentTasks;if(n.maxQueuedTasks!==void 0)e.maxQueuedTasks=n.maxQueuedTasks;if(n.maxQueuedTaskBytes!==void 0)e.maxQueuedTaskBytes=n.maxQueuedTaskBytes;if(n.maxResidentSessionRuntimes!==void 0)e.maxResidentSessionRuntimes=n.maxResidentSessionRuntimes;if(n.sessionRuntimeIdleMs!==void 0)e.sessionRuntimeIdleMs=n.sessionRuntimeIdleMs;if(n.maxResidentSessionProjections!==void 0)e.maxResidentSessionProjections=n.maxResidentSessionProjections;if(n.sessionProjectionIdleMs!==void 0)e.sessionProjectionIdleMs=n.sessionProjectionIdleMs;return e.systemPrompt=n.systemPrompt,e.appendSystemPrompt=n.appendSystemPrompt,e.model=n.model,e.resumeSessionId=n.sessionId,e.forkSession=n.forkSession,e.allowedTools=n.allowedTools,e.disallowedTools=n.disallowedTools,e.mcpConfigPaths=n.mcpConfig,e.strictMcpConfig=n.strictMcpConfig,e.addDirs=n.addDir,e.outputFormat=n.outputFormat,e.inputFormat=n.inputFormat,e.print=n.print,e.includePartialMessages=n.includePartialMessages,e.replayUserMessages=n.replayUserMessages,e.agentsConfig=n.agents,e.settingSources=n.settingSources,e}
44
+ export{nt as Eh,K as Fh,et as Gh,U as Hh,N as Ih,ut as Jh,Ct as Kh,B as Lh,mn as Mh,vr as Nh,Z as Oh,e_ as Ph,r_ as Qh,__ as Rh,cn as Sh,Re as Th,M_ as Uh,Xe as Vh,S_ as Wh,Bn as Xh,u_ as Yh,o_ as Zh,T_ as _h,a_ as $h,A_ as ai,pn as bi,g_ as ci,c_ as di,i_ as ei,h_ as fi,F as gi,pt as hi,V as ii,q as ji,Rt as ki,J as li,hr as mi,Ir as ni,Q as oi,j as pi,C as qi,$r as ri,Dt as si,Gt as ti,zr as ui,Kt as vi,Ht as wi,Yt as xi,Ft as yi,Vt as zi,qt as Ai,Gr as Bi,Jt as Ci,Qt as Di,jt as Ei,Wt as Fi,Zt as Gi,kt as Hi,lt as Ii,yt as Ji,vt as Ki,tn as Li,nn as Mi,en as Ni,T as Oi,d as Pi,de as Qi,D as Ri,v as Si,R as Ti,rM as Ui};
@@ -1,3 +1,3 @@
1
- import{fk as E}from"./chunk-4wx5sya5.js";import{createHash as y}from"node:crypto";import{constants as I,promises as b}from"node:fs";import S from"node:os";import Y from"node:path";import{Mutex as P}from"async-mutex";import{LRUCache as v}from"lru-cache";import f from"write-file-atomic";import{promises as G}from"node:fs";import K from"node:path";import{LRUCache as k}from"lru-cache";var g=512,W=new k({max:g});async function m(q){let Q=q;while(!0){try{return await G.lstat(K.join(Q,".git")),Q}catch($){if($.code!=="ENOENT")return}let Z=K.dirname(Q);if(Z===Q)return;Q=Z}}async function j(q){let Q=K.join(q,".git"),Z=await G.lstat(Q);if(Z.isDirectory())return q;if(!Z.isFile())return;let $=await G.readFile(Q,"utf8"),H=/^gitdir:\s*(.+)\s*$/im.exec($);if(!H)return;let J=await G.realpath(K.isAbsolute(H[1])?H[1]:K.resolve(q,H[1])),F=J;try{let L=(await G.readFile(K.join(J,"commondir"),"utf8")).trim();if(L)F=await G.realpath(K.resolve(J,L))}catch(L){if(L.code!=="ENOENT")throw L}return K.basename(F)===".git"?G.realpath(K.dirname(F)):void 0}async function A(q){if(!K.isAbsolute(q))throw Error("Workspace path must be absolute");let Q=await G.realpath(q),Z=W.get(Q);if(Z)return Z;let $=Q;try{let J=await m(Q);if(J){let F=await j(J),L=K.relative(J,Q);if(F&&(L===""||!L.startsWith(`..${K.sep}`)&&L!==".."&&!K.isAbsolute(L))){let z=K.resolve(F,L);$=await G.realpath(z).catch(()=>z)}}}catch{}let H={projectPath:Q,trustRoot:$};return W.set(Q,H),H}async function _(q){if(!K.isAbsolute(q))throw Error("Workspace path must be absolute");let Q=await G.realpath(q);W.delete(Q)}var N=1,l=65536,R=1048576,V=100,D=64;function Bq(q){return q.state==="trusted"||q.state==="not_required"}function U(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function M(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function T(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return M(`${Q.origin}${Q.pathname}`)}catch{return M(q)}}function w(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function h(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",J=typeof $.command==="string"?$.command:void 0,F=w($.args),L=H==="stdio"?M([J,...F].filter(Boolean).join(" ")):T($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function d(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.command==="string"?M($.command):void 0,J=U($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${J})`,...H?{target:H}:{}}})}function u(q){if(!Array.isArray(q))return[];return q.slice(0,V).flatMap((Q)=>{if(!U(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",J=U(Q.overrides)?Q.overrides:{},F=T(J.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...F?{target:F}:{}}]})}function p(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",J=T($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...J?{target:J}:{}}})}function n(q){if(!U(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of w(q[Z]).slice(0,V))Q.push({kind:"permission",name:`${Z}: ${M($,512)}`});return Q}function c(q){let Q=[...h(q.mcpServers),...d(q.lspServers),...u(q.models),...p(q.modelProviders),...n(q.permissions)];if(U(q.env))for(let Z of Object.keys(q.env).slice(0,V))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function s(q){return q!=="hooks"&&q!=="disableAllHooks"}function o(q){return y("sha256").update(q).digest("hex")}function i(q,Q){let Z=Y.relative(q,Q);return Z===""||!Z.startsWith(`..${Y.sep}`)&&Z!==".."&&!Y.isAbsolute(Z)}class O{storeDir;static instance=null;mutex=new P;statusCache=new v({max:D});constructor(q=Y.join(E(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static resetInstance(){O.instance=null}async getStatus(q){let Q=await A(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(B){let X={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:B instanceof Error?B.message:"Workspace trust review failed"};return this.cacheStatus(q,X),X}if(Z.length===0){let B={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,B),B}let $;try{$=await this.readDecisions()}catch(B){let X={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:B instanceof Error?B.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,X),X}let H=$.filter((B)=>i(B.path,Q.trustRoot)),J=Math.max(-1,...H.map((B)=>B.path.split(Y.sep).length)),F=H.filter((B)=>B.path.split(Y.sep).length===J),L=F.length>0&&F.every((B)=>B.trusted),z=F[0],x=z?.path===Q.trustRoot,C={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:z?x?z.trusted?"trusted":"untrusted":"inherited":"undecided",...z?.decidedAt?{decidedAt:z.decidedAt}:{},...!x&&z?.path?{inheritedFrom:z.path}:{}};return this.cacheStatus(q,C),C}cacheStatus(q,Q){this.statusCache.set(Y.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(Y.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:D,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await _(q);let Z=await A(q);await this.assertSafeTrustRoot(Z);let $={version:N,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=Y.parse(q.trustRoot).root,Z=await b.realpath(S.homedir()).catch(()=>Y.resolve(S.homedir()));if(!Y.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let J=await this.reviewConfigFile(q,$,H);if(J)Q.push(J)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,J]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let F=await this.reviewResourceDirectory(q,$,H,J);if(F)Q.push(F)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=Y.join(q,"package.json"),Z;try{Z=await b.stat(Q)}catch(F){if(F.code==="ENOENT")return;throw F}if(!Z.isFile())return;if(Z.size>R)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await b.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!U($)||!U($.scripts))return;let H=$.scripts,J=Object.keys(H).filter((F)=>typeof H[F]==="string").sort().slice(0,V);if(J.length===0)return;return{path:"package.json",kind:"package",keys:J,effects:J.map((F)=>({kind:"command",name:`package script: ${F}`}))}}async reviewInstructionFile(q,Q){try{if(!(await b.stat(Y.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=Y.join(q,Q),H;try{H=await b.stat($)}catch(x){if(x.code==="ENOENT")return;throw x}if(!H.isFile())return;if(H.size>R)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let J;try{J=JSON.parse(await b.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!U(J))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let F=Object.keys(J).filter(s).sort();if(F.length===0)return;let L=c(J),z=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let x of F)if(!z.has(x))L.push({kind:"configuration",name:x});return{path:Q,kind:Z,keys:F,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=Y.join(q,Q),J;try{J=await b.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let F=J.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,V);if(F.length===0)return;return{path:Q,kind:Z,keys:F.map((L)=>L.name),effects:F.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await b.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await b.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(Y.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await b.open(q,I.O_RDONLY|I.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>l)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!U($)||$.version!==N||typeof $.path!=="string"||!Y.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:N,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=Y.join(this.storeDir,`${o(q.path)}.json`);try{let Z=await b.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await f(Q,`${JSON.stringify(q,null,2)}
1
+ import{ek as E}from"./chunk-gzbb747a.js";import{createHash as y}from"node:crypto";import{constants as I,promises as b}from"node:fs";import S from"node:os";import Y from"node:path";import{Mutex as P}from"async-mutex";import{LRUCache as v}from"lru-cache";import f from"write-file-atomic";import{promises as G}from"node:fs";import K from"node:path";import{LRUCache as k}from"lru-cache";var g=512,W=new k({max:g});async function m(q){let Q=q;while(!0){try{return await G.lstat(K.join(Q,".git")),Q}catch($){if($.code!=="ENOENT")return}let Z=K.dirname(Q);if(Z===Q)return;Q=Z}}async function j(q){let Q=K.join(q,".git"),Z=await G.lstat(Q);if(Z.isDirectory())return q;if(!Z.isFile())return;let $=await G.readFile(Q,"utf8"),H=/^gitdir:\s*(.+)\s*$/im.exec($);if(!H)return;let J=await G.realpath(K.isAbsolute(H[1])?H[1]:K.resolve(q,H[1])),F=J;try{let L=(await G.readFile(K.join(J,"commondir"),"utf8")).trim();if(L)F=await G.realpath(K.resolve(J,L))}catch(L){if(L.code!=="ENOENT")throw L}return K.basename(F)===".git"?G.realpath(K.dirname(F)):void 0}async function A(q){if(!K.isAbsolute(q))throw Error("Workspace path must be absolute");let Q=await G.realpath(q),Z=W.get(Q);if(Z)return Z;let $=Q;try{let J=await m(Q);if(J){let F=await j(J),L=K.relative(J,Q);if(F&&(L===""||!L.startsWith(`..${K.sep}`)&&L!==".."&&!K.isAbsolute(L))){let z=K.resolve(F,L);$=await G.realpath(z).catch(()=>z)}}}catch{}let H={projectPath:Q,trustRoot:$};return W.set(Q,H),H}async function _(q){if(!K.isAbsolute(q))throw Error("Workspace path must be absolute");let Q=await G.realpath(q);W.delete(Q)}var N=1,l=65536,R=1048576,V=100,D=64;function Bq(q){return q.state==="trusted"||q.state==="not_required"}function U(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function M(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function T(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return M(`${Q.origin}${Q.pathname}`)}catch{return M(q)}}function w(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function h(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",J=typeof $.command==="string"?$.command:void 0,F=w($.args),L=H==="stdio"?M([J,...F].filter(Boolean).join(" ")):T($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function d(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.command==="string"?M($.command):void 0,J=U($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${J})`,...H?{target:H}:{}}})}function u(q){if(!Array.isArray(q))return[];return q.slice(0,V).flatMap((Q)=>{if(!U(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",J=U(Q.overrides)?Q.overrides:{},F=T(J.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...F?{target:F}:{}}]})}function p(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",J=T($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...J?{target:J}:{}}})}function n(q){if(!U(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of w(q[Z]).slice(0,V))Q.push({kind:"permission",name:`${Z}: ${M($,512)}`});return Q}function c(q){let Q=[...h(q.mcpServers),...d(q.lspServers),...u(q.models),...p(q.modelProviders),...n(q.permissions)];if(U(q.env))for(let Z of Object.keys(q.env).slice(0,V))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function s(q){return q!=="hooks"&&q!=="disableAllHooks"}function o(q){return y("sha256").update(q).digest("hex")}function i(q,Q){let Z=Y.relative(q,Q);return Z===""||!Z.startsWith(`..${Y.sep}`)&&Z!==".."&&!Y.isAbsolute(Z)}class O{storeDir;static instance=null;mutex=new P;statusCache=new v({max:D});constructor(q=Y.join(E(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static resetInstance(){O.instance=null}async getStatus(q){let Q=await A(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(B){let X={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:B instanceof Error?B.message:"Workspace trust review failed"};return this.cacheStatus(q,X),X}if(Z.length===0){let B={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,B),B}let $;try{$=await this.readDecisions()}catch(B){let X={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:B instanceof Error?B.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,X),X}let H=$.filter((B)=>i(B.path,Q.trustRoot)),J=Math.max(-1,...H.map((B)=>B.path.split(Y.sep).length)),F=H.filter((B)=>B.path.split(Y.sep).length===J),L=F.length>0&&F.every((B)=>B.trusted),z=F[0],x=z?.path===Q.trustRoot,C={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:z?x?z.trusted?"trusted":"untrusted":"inherited":"undecided",...z?.decidedAt?{decidedAt:z.decidedAt}:{},...!x&&z?.path?{inheritedFrom:z.path}:{}};return this.cacheStatus(q,C),C}cacheStatus(q,Q){this.statusCache.set(Y.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(Y.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:D,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await _(q);let Z=await A(q);await this.assertSafeTrustRoot(Z);let $={version:N,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=Y.parse(q.trustRoot).root,Z=await b.realpath(S.homedir()).catch(()=>Y.resolve(S.homedir()));if(!Y.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let J=await this.reviewConfigFile(q,$,H);if(J)Q.push(J)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,J]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let F=await this.reviewResourceDirectory(q,$,H,J);if(F)Q.push(F)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=Y.join(q,"package.json"),Z;try{Z=await b.stat(Q)}catch(F){if(F.code==="ENOENT")return;throw F}if(!Z.isFile())return;if(Z.size>R)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await b.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!U($)||!U($.scripts))return;let H=$.scripts,J=Object.keys(H).filter((F)=>typeof H[F]==="string").sort().slice(0,V);if(J.length===0)return;return{path:"package.json",kind:"package",keys:J,effects:J.map((F)=>({kind:"command",name:`package script: ${F}`}))}}async reviewInstructionFile(q,Q){try{if(!(await b.stat(Y.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=Y.join(q,Q),H;try{H=await b.stat($)}catch(x){if(x.code==="ENOENT")return;throw x}if(!H.isFile())return;if(H.size>R)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let J;try{J=JSON.parse(await b.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!U(J))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let F=Object.keys(J).filter(s).sort();if(F.length===0)return;let L=c(J),z=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let x of F)if(!z.has(x))L.push({kind:"configuration",name:x});return{path:Q,kind:Z,keys:F,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=Y.join(q,Q),J;try{J=await b.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let F=J.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,V);if(F.length===0)return;return{path:Q,kind:Z,keys:F.map((L)=>L.name),effects:F.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await b.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await b.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(Y.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await b.open(q,I.O_RDONLY|I.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>l)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!U($)||$.version!==N||typeof $.path!=="string"||!Y.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:N,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=Y.join(this.storeDir,`${o(q.path)}.json`);try{let Z=await b.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await f(Q,`${JSON.stringify(q,null,2)}
2
2
  `,{mode:384}),await b.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await b.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await b.mkdir(this.storeDir,{recursive:!0,mode:448}),await b.chmod(this.storeDir,448)}}}
3
- export{A as bk,D as ck,Bq as dk,O as ek};
3
+ export{A as ak,D as bk,Bq as ck,O as dk};