blade-code 0.10.204 → 0.10.206

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 (146) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-09kqfdpa.js +3 -0
  3. package/dist/{chunk-p6586ftx.js → chunk-0ef47wgr.js} +2 -2
  4. package/dist/chunk-1j39te3t.js +23 -0
  5. package/dist/{chunk-fdr4fcrf.js → chunk-1n4v80hy.js} +1 -1
  6. package/dist/{chunk-4fbpydtn.js → chunk-28n945me.js} +2 -2
  7. package/dist/{chunk-ys8gysg8.js → chunk-28tzj187.js} +1 -1
  8. package/dist/{chunk-j89qk7bp.js → chunk-3crwyd2r.js} +3 -3
  9. package/dist/{chunk-zfxcef0z.js → chunk-50vwafn5.js} +1 -1
  10. package/dist/chunk-514va7ce.js +2 -0
  11. package/dist/{chunk-kkzznz4w.js → chunk-53vh6vpt.js} +1 -1
  12. package/dist/chunk-5k8k56f2.js +731 -0
  13. package/dist/{chunk-f4d8312x.js → chunk-65wc1h38.js} +1 -1
  14. package/dist/{chunk-bx2s02mt.js → chunk-67wy9mm7.js} +2 -2
  15. package/dist/chunk-6p0hkf4f.js +1 -0
  16. package/dist/{chunk-qdbbke8f.js → chunk-6xzk4hsg.js} +1 -1
  17. package/dist/chunk-793wjhvz.js +332 -0
  18. package/dist/chunk-826xegd8.js +6 -0
  19. package/dist/chunk-867bpjzg.js +1 -0
  20. package/dist/{chunk-hnvvve5d.js → chunk-870szc6v.js} +1 -1
  21. package/dist/chunk-983hqzat.js +1 -0
  22. package/dist/{chunk-0eajnhrj.js → chunk-9kj19a8t.js} +1 -1
  23. package/dist/{chunk-55n8ppxf.js → chunk-9sf1t8gw.js} +1 -1
  24. package/dist/chunk-9tpzmy8v.js +4 -0
  25. package/dist/chunk-af0m5227.js +1 -0
  26. package/dist/chunk-asgmmaec.js +3 -0
  27. package/dist/{chunk-m640mr36.js → chunk-av799ng5.js} +2 -2
  28. package/dist/{chunk-rwm71p4g.js → chunk-az3rehz9.js} +360 -360
  29. package/dist/{chunk-p0wyhp5a.js → chunk-dnpkf5mv.js} +2 -2
  30. package/dist/chunk-dpg006xj.js +1 -0
  31. package/dist/{chunk-0xf70s5c.js → chunk-e0ft3vwg.js} +1 -1
  32. package/dist/chunk-e45r1a8r.js +25 -0
  33. package/dist/{chunk-vzdsext4.js → chunk-ebpg1srd.js} +2 -2
  34. package/dist/{chunk-n52n2w5v.js → chunk-ed2hdrwe.js} +1 -1
  35. package/dist/{chunk-7ajvrtb3.js → chunk-erhaedch.js} +1 -1
  36. package/dist/{chunk-kehgewqh.js → chunk-ewwrss2w.js} +1 -1
  37. package/dist/{chunk-9fyjyk2f.js → chunk-fc1gz532.js} +2 -2
  38. package/dist/{chunk-vgf07dhy.js → chunk-fd0a8h55.js} +2 -2
  39. package/dist/{chunk-6dw3pk3c.js → chunk-fnmqxhv1.js} +2 -2
  40. package/dist/chunk-g7tphxme.js +6 -0
  41. package/dist/{chunk-cjfb4kjp.js → chunk-gmpsfkgg.js} +1 -1
  42. package/dist/chunk-gpnkxh4c.js +1 -0
  43. package/dist/{chunk-8j0z248z.js → chunk-gz84aewr.js} +1 -1
  44. package/dist/{chunk-2xpjy0ef.js → chunk-h4k69z1b.js} +1 -1
  45. package/dist/{chunk-dhxx5mwe.js → chunk-h6ahwwpa.js} +2 -2
  46. package/dist/chunk-hpge30p8.js +8 -0
  47. package/dist/{chunk-1cy4ab77.js → chunk-hv8nt7wj.js} +1 -1
  48. package/dist/chunk-mtvbm7xe.js +1 -0
  49. package/dist/chunk-mys9mmcp.js +1 -0
  50. package/dist/{chunk-wezr6wfq.js → chunk-n34qsnks.js} +1 -1
  51. package/dist/chunk-n5jzmwhy.js +25 -0
  52. package/dist/chunk-new78c3h.js +1 -0
  53. package/dist/{chunk-je908ygr.js → chunk-nj6kpdte.js} +2 -2
  54. package/dist/chunk-nng1xbsm.js +10 -0
  55. package/dist/{chunk-pqsjy31p.js → chunk-p2y1zqsb.js} +2 -2
  56. package/dist/chunk-p8vpvx07.js +12 -0
  57. package/dist/{chunk-3cas6rv5.js → chunk-pdna2qvv.js} +2 -2
  58. package/dist/{chunk-gzdk86fm.js → chunk-pga8gxtf.js} +1 -1
  59. package/dist/chunk-pt0y4zrg.js +14 -0
  60. package/dist/{chunk-w4bedq0m.js → chunk-q6abav45.js} +51 -51
  61. package/dist/chunk-r4em0ha7.js +1 -0
  62. package/dist/chunk-rdzbd5vk.js +1 -0
  63. package/dist/chunk-sbfe9vh3.js +94 -0
  64. package/dist/chunk-sqk8cnej.js +44 -0
  65. package/dist/{chunk-5yyp6njq.js → chunk-t0gm0pn1.js} +1 -1
  66. package/dist/{chunk-egss0m1x.js → chunk-tsm8rhmd.js} +1 -1
  67. package/dist/chunk-tzvb0nd2.js +2 -0
  68. package/dist/{chunk-wk869s65.js → chunk-v4cxk10d.js} +1 -1
  69. package/dist/{chunk-g383afnv.js → chunk-v5vx6nz9.js} +1 -1
  70. package/dist/{chunk-x49bw41v.js → chunk-vx2g1faw.js} +1 -1
  71. package/dist/chunk-w6zat4v4.js +1 -0
  72. package/dist/chunk-wsd3rn0q.js +1 -0
  73. package/dist/{chunk-smxdn7kq.js → chunk-xcq0cehr.js} +5 -6
  74. package/dist/chunk-yjjxv7fn.js +352 -0
  75. package/dist/{chunk-z0m9j0e2.js → chunk-yzf2jpam.js} +2 -2
  76. package/dist/web/assets/{ChatView-BF6HUrBw.js → ChatView-lUD-61n0.js} +4 -4
  77. package/dist/web/assets/{CodeBlockHighlighter-C4CgCiRf.js → CodeBlockHighlighter--TbfcBxW.js} +1 -1
  78. package/dist/web/assets/FilePreview-R6OKQPf2.js +55 -0
  79. package/dist/web/assets/{KanbanBoard-DDXB-yq1.js → KanbanBoard-BHOKtiv5.js} +1 -1
  80. package/dist/web/assets/{MarkdownRenderer-DS7RznBE.js → MarkdownRenderer-DqxNq8pa.js} +3 -3
  81. package/dist/web/assets/{ScrollArea-BM9NzGZM.js → ScrollArea-Dhu0B-zB.js} +1 -1
  82. package/dist/web/assets/{SessionHistorySurface-DnRySeLE.js → SessionHistorySurface-aZvoj3ma.js} +1 -1
  83. package/dist/web/assets/{SettingsModal-D5YLUtIo.js → SettingsModal-C7QBnIqa.js} +1 -1
  84. package/dist/web/assets/{Sidebar-BZC6OkDJ.js → Sidebar-Bznnq91x.js} +1 -1
  85. package/dist/web/assets/{TaskSwitcher-WewOkw5m.js → TaskSwitcher-DJczhDRp.js} +1 -1
  86. package/dist/web/assets/{TerminalPanel-C5SGdRNr.js → TerminalPanel-Vk4p0V3p.js} +1 -1
  87. package/dist/web/assets/{archive-DkczUU08.js → archive-0hLYBKQf.js} +1 -1
  88. package/dist/web/assets/{arrow-left-9pBiQwu7.js → arrow-left-CXb6Gqf3.js} +1 -1
  89. package/dist/web/assets/{calendar-clock-BFnUlxrU.js → calendar-clock-DiaFI9Jk.js} +1 -1
  90. package/dist/web/assets/{chevron-right-yCVkAEcj.js → chevron-right-CcPXH37D.js} +1 -1
  91. package/dist/web/assets/{clock-3-CcoWoRQs.js → clock-3-D6VR6gJc.js} +1 -1
  92. package/dist/web/assets/{copy-HJF0oQBS.js → copy-C3eUAQgp.js} +1 -1
  93. package/dist/web/assets/{download-DSBCIqk3.js → download-DHvS9tI3.js} +1 -1
  94. package/dist/web/assets/{external-link-zIgEO0KB.js → external-link-BDVaEuqY.js} +1 -1
  95. package/dist/web/assets/{folder-BdRo64o3.js → folder-B80Ac6rr.js} +1 -1
  96. package/dist/web/assets/index-VwIiNjc8.css +1 -0
  97. package/dist/web/assets/{index-BVDkKudh.js → index-YqughEZk.js} +4 -4
  98. package/dist/web/assets/{message-square-plus-3klTXO0S.js → message-square-plus-D15quyPH.js} +1 -1
  99. package/dist/web/assets/{pause-B9Q5JWvH.js → pause-BjMlj6Bx.js} +1 -1
  100. package/dist/web/assets/{pencil-CbYIz1b1.js → pencil-BMoJvcB7.js} +1 -1
  101. package/dist/web/assets/{play-CZMTj43e.js → play-BHh4py3p.js} +1 -1
  102. package/dist/web/assets/{plus-Cc7I8fhb.js → plus-DeFz_gQq.js} +1 -1
  103. package/dist/web/assets/session-events-DCHBz9We.js +25 -0
  104. package/dist/web/assets/{settings-DSF3exX2.js → settings-CI8xbId2.js} +1 -1
  105. package/dist/web/assets/{team-qfeJHL9s.js → team-zZ803hH9.js} +1 -1
  106. package/dist/web/assets/{teamService-Bs9qBKI8.js → teamService-CgLBXgmv.js} +1 -1
  107. package/dist/web/assets/{terminal-DQLqe-Ed.js → terminal-1WxSJ47E.js} +1 -1
  108. package/dist/web/index.html +2 -2
  109. package/package.json +1 -1
  110. package/dist/chunk-1b8qjgm6.js +0 -181
  111. package/dist/chunk-1vq22245.js +0 -10
  112. package/dist/chunk-3den8b7b.js +0 -1
  113. package/dist/chunk-42vt2eqq.js +0 -1
  114. package/dist/chunk-4ts2s9mz.js +0 -94
  115. package/dist/chunk-5dcsrs7e.js +0 -2
  116. package/dist/chunk-5j94j64z.js +0 -25
  117. package/dist/chunk-6ax5dpd3.js +0 -1
  118. package/dist/chunk-7atwbngw.js +0 -1
  119. package/dist/chunk-7d3msqg3.js +0 -14
  120. package/dist/chunk-81py03y4.js +0 -44
  121. package/dist/chunk-8cncpfhd.js +0 -6
  122. package/dist/chunk-8ej7w92s.js +0 -1
  123. package/dist/chunk-ae0fafmv.js +0 -1
  124. package/dist/chunk-ayvx3h91.js +0 -1
  125. package/dist/chunk-b50smz3h.js +0 -1
  126. package/dist/chunk-bx3b61xw.js +0 -1
  127. package/dist/chunk-d256m8rb.js +0 -1
  128. package/dist/chunk-e49ctwmg.js +0 -1
  129. package/dist/chunk-egc2f1ye.js +0 -733
  130. package/dist/chunk-ggdgk3gy.js +0 -3
  131. package/dist/chunk-h78hhhgt.js +0 -1
  132. package/dist/chunk-hkk83qt6.js +0 -23
  133. package/dist/chunk-ky592ay9.js +0 -2
  134. package/dist/chunk-m0t26vkj.js +0 -4
  135. package/dist/chunk-myvt7yjm.js +0 -8
  136. package/dist/chunk-nsb3cj6t.js +0 -6
  137. package/dist/chunk-p8cmxhbr.js +0 -25
  138. package/dist/chunk-qpmvp4q2.js +0 -2
  139. package/dist/chunk-rmfzym94.js +0 -3
  140. package/dist/chunk-rnt2fejc.js +0 -1
  141. package/dist/chunk-tm3789m3.js +0 -2
  142. package/dist/chunk-vtssm7r5.js +0 -12
  143. package/dist/chunk-ztreczac.js +0 -353
  144. package/dist/web/assets/FilePreview-BS4PgFKb.js +0 -55
  145. package/dist/web/assets/index-CaCifsSK.css +0 -1
  146. package/dist/web/assets/session-events-NEjosinC.js +0 -31
@@ -0,0 +1,44 @@
1
+ import{Ui as Pn,Vi as xn}from"./chunk-514va7ce.js";import{aj as i}from"./chunk-6xzk4hsg.js";import{bj as rn,cj as Kn,dj as Hn,hj as Yn,ij as _n,jj as Fn,kj as Vn,lj as qn,mj as ct,nj as Jn,oj as Qn,pj as Mn,qj as jn,rj as Wn,sj as Sn,tj as Zn,uj as kn,vj as ln,wj as yn,xj as vn,yj as te}from"./chunk-n34qsnks.js";import{Cj as Ut,Ej as Lt,Fj as St,Gj as m}from"./chunk-09kqfdpa.js";import{Lj as Gn,Oj as tt}from"./chunk-3crwyd2r.js";import{Wj as xt,Xj as Bt}from"./chunk-yzf2jpam.js";import{ck as b}from"./chunk-asgmmaec.js";import{dk as It}from"./chunk-ed2hdrwe.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 Dh,K as Eh,et as Fh,U as Gh,N as Hh,ut as Ih,Ct as Jh,B as Kh,mn as Lh,vr as Mh,Z as Nh,e_ as Oh,r_ as Ph,__ as Qh,cn as Rh,Re as Sh,M_ as Th,Xe as Uh,S_ as Vh,Bn as Wh,u_ as Xh,o_ as Yh,T_ as Zh,a_ as _h,A_ as $h,pn as ai,g_ as bi,c_ as ci,i_ as di,h_ as ei,F as fi,pt as gi,V as hi,q as ii,Rt as ji,J as ki,hr as li,Ir as mi,Q as ni,j as oi,C as pi,$r as qi,Dt as ri,Gt as si,zr as ti,Kt as ui,Ht as vi,Yt as wi,Ft as xi,Vt as yi,qt as zi,Gr as Ai,Jt as Bi,Qt as Ci,jt as Di,Wt as Ei,Zt as Fi,kt as Gi,lt as Hi,yt as Ii,vt as Ji,tn as Ki,nn as Li,en as Mi,T as Ni,d as Oi,de as Pi,D as Qi,v as Ri,R as Si,rM as Ti};
@@ -1,2 +1,2 @@
1
1
  import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
2
- export{B as eg};
2
+ export{B as dg};
@@ -1,2 +1,2 @@
1
1
  var q;((h)=>{h.ReadOnly="readonly";h.Write="write";h.Execute="execute"})(q||={});function w(b){return b!==void 0&&typeof b.pattern==="string"&&typeof b.search_path==="string"}function z(b){return b!==void 0&&b.kind==="edit"&&typeof b.matches_found==="number"}var j=Symbol("blade.tool-result-model-images");function B(b,c){return Object.defineProperty(b,j,{value:c,enumerable:!1,configurable:!1,writable:!1}),b}function v(b){return b[j]}function C(b,c){let f=b.success?v(b):void 0;return f&&f.length>0?[{type:"text",text:c},...f]:c}function F(b){return b==="readonly"}
2
- export{q as je,w as ke,z as le,B as me,C as ne,F as oe};
2
+ export{q as me,w as ne,z as oe,B as pe,C as qe,F as re};
@@ -0,0 +1,2 @@
1
+ import{M as N,ja as _,ka as z}from"./chunk-az3rehz9.js";import{Wc as I,Yd as g,_d as R,bd as x,cd as X,dd as B,ed as V,fd as b,vd as A}from"./chunk-sbfe9vh3.js";import{Bi as M,Ci as O}from"./chunk-sqk8cnej.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
2
+ export{C as w,k as x,T as y,a as z};
@@ -1 +1 @@
1
- import{Fa as h,Ha as f,Ia as k}from"./chunk-vzdsext4.js";import"./chunk-cjfb4kjp.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
1
+ import{Ia as h,Ka as f,La as k}from"./chunk-ebpg1srd.js";import"./chunk-gmpsfkgg.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
@@ -1 +1 @@
1
- import{bb as V,db as W,eb as O,wb as J}from"./chunk-9fyjyk2f.js";import"./chunk-p6586ftx.js";import"./chunk-4fbpydtn.js";import"./chunk-kkzznz4w.js";import"./chunk-tm3789m3.js";import{cj as Q}from"./chunk-qdbbke8f.js";import"./chunk-rmfzym94.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
1
+ import{eb as V,gb as W,hb as O,zb as J}from"./chunk-fc1gz532.js";import"./chunk-0ef47wgr.js";import"./chunk-28n945me.js";import"./chunk-53vh6vpt.js";import"./chunk-514va7ce.js";import{aj as Q}from"./chunk-6xzk4hsg.js";import"./chunk-09kqfdpa.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
@@ -1,3 +1,3 @@
1
- import{j as i}from"./chunk-hnvvve5d.js";import{cj as s}from"./chunk-qdbbke8f.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{j as i}from"./chunk-870szc6v.js";import{aj as s}from"./chunk-6xzk4hsg.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -0,0 +1 @@
1
+ import{fe as a,ge as b,he as c,ie as d,je as e,ke as f,le as g}from"./chunk-sbfe9vh3.js";import"./chunk-tsm8rhmd.js";import"./chunk-yjjxv7fn.js";import"./chunk-0ef47wgr.js";import"./chunk-50vwafn5.js";import"./chunk-hv8nt7wj.js";import"./chunk-28tzj187.js";import"./chunk-514va7ce.js";import"./chunk-6xzk4hsg.js";import"./chunk-09kqfdpa.js";import"./chunk-9kj19a8t.js";import"./chunk-yzf2jpam.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -0,0 +1 @@
1
+ import{$f as j,Sf as a,Tf as b,Uf as c,Vf as d,Wf as e,Xf as f,Yf as g,Zf as h,_f as i,ag as k,bg as l,cg as m}from"./chunk-n5jzmwhy.js";import"./chunk-t0gm0pn1.js";import"./chunk-v508x7cg.js";import"./chunk-sqk8cnej.js";import"./chunk-514va7ce.js";import"./chunk-6xzk4hsg.js";import"./chunk-n34qsnks.js";import"./chunk-09kqfdpa.js";import"./chunk-3crwyd2r.js";import"./chunk-9kj19a8t.js";import"./chunk-yzf2jpam.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
@@ -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-rmfzym94.js";import{ek as n}from"./chunk-ky592ay9.js";import{gk as r}from"./chunk-n52n2w5v.js";import{Nk as w}from"./chunk-cjfb4kjp.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{Ch as YO}from"./chunk-28tzj187.js";import{aj as P}from"./chunk-6xzk4hsg.js";import{Cj as XO,Ej as qO,Gj as S,Jj as y}from"./chunk-09kqfdpa.js";import{$j as n}from"./chunk-asgmmaec.js";import{dk as r}from"./chunk-ed2hdrwe.js";import{Jk as w}from"./chunk-gmpsfkgg.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-d256m8rb.js"),{createChatServiceAsync:W}=await import("./chunk-ae0fafmv.js"),{resolveModelConfig:J}=await import("./chunk-42vt2eqq.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-h78hhhgt.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-wsd3rn0q.js"),{createChatServiceAsync:W}=await import("./chunk-rdzbd5vk.js"),{resolveModelConfig:J}=await import("./chunk-af0m5227.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-gpnkxh4c.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 wh,o as xh,_ as yh};