blade-code 0.10.30 → 0.10.32

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 (104) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-z5eaph4a.js → chunk-14zhd8qs.js} +1 -1
  3. package/dist/chunk-191xtaca.js +1 -0
  4. package/dist/chunk-273ak5v8.js +10 -0
  5. package/dist/{chunk-qv1v32ts.js → chunk-2969c7yb.js} +2 -2
  6. package/dist/{chunk-82jdnt03.js → chunk-2jr254j7.js} +2 -2
  7. package/dist/{chunk-qs9wwe8d.js → chunk-2tb3qm3v.js} +1 -1
  8. package/dist/{chunk-xr033fd3.js → chunk-3bhh4v42.js} +1 -1
  9. package/dist/{chunk-4qyhtrhx.js → chunk-3ck3fxff.js} +1 -1
  10. package/dist/chunk-42ns4a92.js +1 -0
  11. package/dist/{chunk-4qtb8yf6.js → chunk-5mszemkz.js} +2 -2
  12. package/dist/{chunk-p6s92zj1.js → chunk-6gngfvwt.js} +1 -1
  13. package/dist/chunk-6r89cn2n.js +2 -0
  14. package/dist/{chunk-e3qzedvj.js → chunk-758hxypj.js} +1 -1
  15. package/dist/{chunk-ekv4hpy8.js → chunk-75y3mb0z.js} +2 -2
  16. package/dist/{chunk-hdr8bcxt.js → chunk-774excyf.js} +1 -1
  17. package/dist/{chunk-s3zfyy7r.js → chunk-799zdv81.js} +1 -1
  18. package/dist/{chunk-1sswefqp.js → chunk-7bpwnpfx.js} +1 -1
  19. package/dist/{chunk-1ggxyyar.js → chunk-7fgx7ztz.js} +1 -1
  20. package/dist/{chunk-0rwz7tm0.js → chunk-7m4qc5vv.js} +1 -1
  21. package/dist/{chunk-2d35rmyg.js → chunk-7xytd1h7.js} +2 -2
  22. package/dist/{chunk-9mamc250.js → chunk-80r40y6k.js} +2 -2
  23. package/dist/{chunk-ej1z75jf.js → chunk-8y2nh9sm.js} +1 -1
  24. package/dist/chunk-9r0fxre0.js +1 -0
  25. package/dist/{chunk-37se34rx.js → chunk-aspqajv2.js} +1 -1
  26. package/dist/{chunk-7e7zgzag.js → chunk-azcjz03h.js} +2 -2
  27. package/dist/{chunk-fr3kysfm.js → chunk-b0en9trj.js} +1 -1
  28. package/dist/{chunk-1444wfhr.js → chunk-b0mha3tr.js} +2 -2
  29. package/dist/{chunk-j7ebts5c.js → chunk-b4xcn24b.js} +1 -1
  30. package/dist/{chunk-n1byt26d.js → chunk-bcs58pet.js} +1 -1
  31. package/dist/{chunk-rh5g6em4.js → chunk-bmsv08sa.js} +2 -2
  32. package/dist/{chunk-4p9cwr9s.js → chunk-c7b5wmpm.js} +2 -2
  33. package/dist/{chunk-h9c7xec5.js → chunk-cdkrdsbw.js} +1 -1
  34. package/dist/{chunk-d4327k1v.js → chunk-cjgnf6qy.js} +1 -1
  35. package/dist/{chunk-vz0zsct0.js → chunk-e66zyvph.js} +1 -1
  36. package/dist/{chunk-9pww3s5m.js → chunk-fb514tmd.js} +1 -1
  37. package/dist/chunk-fd5dzcht.js +1 -0
  38. package/dist/{chunk-4djps7bz.js → chunk-fp1892aa.js} +1 -1
  39. package/dist/{chunk-64hndcnj.js → chunk-g2gvcp09.js} +43 -43
  40. package/dist/chunk-gs18nx4h.js +1 -0
  41. package/dist/chunk-gy51z423.js +1 -0
  42. package/dist/chunk-hdje6ywy.js +1 -0
  43. package/dist/{chunk-kkpxmhjv.js → chunk-jdq05trf.js} +3 -3
  44. package/dist/chunk-jtk2t4wy.js +204 -0
  45. package/dist/chunk-mspp2qpn.js +1 -0
  46. package/dist/{chunk-gdp6fg4e.js → chunk-mwae107k.js} +1 -1
  47. package/dist/{chunk-5m5nxkfs.js → chunk-nah8b1gv.js} +1 -1
  48. package/dist/{chunk-x9940mcy.js → chunk-ntmfefxh.js} +2 -2
  49. package/dist/{chunk-heydawsf.js → chunk-q4q0r97b.js} +2 -2
  50. package/dist/{chunk-d38t0wa2.js → chunk-qe49h8e0.js} +1 -1
  51. package/dist/{chunk-kk071ywk.js → chunk-qgvgd1kq.js} +2 -2
  52. package/dist/{chunk-d9gthet1.js → chunk-r68y2q62.js} +2 -2
  53. package/dist/{chunk-48tz6s0s.js → chunk-rakyf5b7.js} +2 -2
  54. package/dist/chunk-rzxk60wq.js +1 -0
  55. package/dist/{chunk-rezjy4mp.js → chunk-s61wcay9.js} +2 -2
  56. package/dist/chunk-sfhevsq1.js +1 -0
  57. package/dist/chunk-t23a5yvk.js +1 -0
  58. package/dist/{chunk-0prp87ys.js → chunk-t23t9yff.js} +1 -1
  59. package/dist/{chunk-mbrgz77y.js → chunk-tx77qaz8.js} +2 -2
  60. package/dist/chunk-txqctnca.js +1 -0
  61. package/dist/chunk-w0wzx47n.js +1 -0
  62. package/dist/{chunk-btfxa4w8.js → chunk-w49crtzx.js} +2 -2
  63. package/dist/chunk-wmsak7d3.js +1610 -0
  64. package/dist/{chunk-39gb49pv.js → chunk-x0x5e65d.js} +1 -1
  65. package/dist/chunk-x1r4b7pt.js +2 -0
  66. package/dist/{chunk-vx8a7e1j.js → chunk-xh1y705a.js} +2 -2
  67. package/dist/{chunk-6kc12pma.js → chunk-xhdm1b4g.js} +1 -1
  68. package/dist/{chunk-8gv6hsrf.js → chunk-y5rsamex.js} +2 -2
  69. package/dist/{chunk-m8jen593.js → chunk-yekzckgm.js} +3 -3
  70. package/dist/chunk-yvwmfddz.js +1 -0
  71. package/dist/{chunk-6h9d9ykg.js → chunk-z1qa6vm5.js} +1 -1
  72. package/dist/web/assets/{ChatView-CjEyCR8V.js → ChatView-D2g5ADlO.js} +5 -5
  73. package/dist/web/assets/{CodeBlockHighlighter-DZxXrhQO.js → CodeBlockHighlighter-CheLBzlr.js} +1 -1
  74. package/dist/web/assets/{FilePreview-8fbolCzV.js → FilePreview-DWiuoQOM.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-Bfm5TG2z.js → MarkdownRenderer-C8h_WRI9.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-KATzS3Iy.js → SettingsModal-CKIKFL6a.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-BrfN6F0-.js → TaskSwitcher-DMaOLa_m.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-sbqhmFcK.js → TerminalPanel-BXLKU2zU.js} +1 -1
  79. package/dist/web/assets/index-7zaeanZL.css +1 -0
  80. package/dist/web/assets/{index-xB4mFHWl.js → index-CxwsVMYL.js} +4 -4
  81. package/dist/web/assets/session-events-BZdQ71sF.js +22 -0
  82. package/dist/web/index.html +3 -3
  83. package/package.json +1 -1
  84. package/dist/chunk-1zpqxjj7.js +0 -2
  85. package/dist/chunk-2wdmt91f.js +0 -1
  86. package/dist/chunk-3y97cpzv.js +0 -1
  87. package/dist/chunk-56hphybe.js +0 -1
  88. package/dist/chunk-7brnbdq8.js +0 -10
  89. package/dist/chunk-a5yd0c77.js +0 -1
  90. package/dist/chunk-b634n0ts.js +0 -1608
  91. package/dist/chunk-e269454y.js +0 -1
  92. package/dist/chunk-f90v5vza.js +0 -1
  93. package/dist/chunk-j3k3xdac.js +0 -1
  94. package/dist/chunk-m3epqvpc.js +0 -1
  95. package/dist/chunk-pdkj959x.js +0 -1
  96. package/dist/chunk-pwwm04bc.js +0 -1
  97. package/dist/chunk-q9ghq6jw.js +0 -204
  98. package/dist/chunk-s6rdv601.js +0 -2
  99. package/dist/chunk-szmm21q9.js +0 -1
  100. package/dist/chunk-x96czg8t.js +0 -1
  101. package/dist/chunk-xh2c6ycd.js +0 -1
  102. package/dist/chunk-ze8rmhs1.js +0 -1
  103. package/dist/web/assets/index-BC7ygRH_.css +0 -1
  104. package/dist/web/assets/session-events-C2PMff2v.js +0 -22
@@ -1,2 +1,2 @@
1
- import{Kf as o}from"./chunk-8gv6hsrf.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
1
+ import{Mf as o}from"./chunk-y5rsamex.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
2
2
  export{e as j,i as k};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as wf,T as xf,A as yf};
@@ -1,4 +1,4 @@
1
- import{of as En,pf as j,qf as T}from"./chunk-4qyhtrhx.js";import{uf as On,vf as Zn}from"./chunk-s6rdv601.js";import{Af as L}from"./chunk-1ggxyyar.js";import{Ef as $n}from"./chunk-ekv4hpy8.js";import{Hf as rt,Kf as p}from"./chunk-8gv6hsrf.js";import{Sf as sn,Tf as wn}from"./chunk-7e7zgzag.js";import{Xf as $}from"./chunk-2d35rmyg.js";import{fg as Sn}from"./chunk-heydawsf.js";var et=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function St(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function B(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&St(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{B(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function y(n){let t=n.oauth;if(!t)return;let M=t;for(let S of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[S]!==void 0)throw Error(`MCP OAuth "${S}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(B(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((S)=>S.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let e=t.scopes?.map((S)=>S.trim());if(e){if(e.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(e.some((S)=>!S||S.length>128||!et.test(S)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(e).size!==e.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...e?.length?{scopes:e}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as l}from"node:crypto";import xt from"node:http";import{auth as Tn}from"@modelcontextprotocol/sdk/client/auth.js";import $t from"open";import{createHash as Et,randomUUID as mt}from"node:crypto";import{constants as D,promises as P}from"node:fs";import W from"node:path";import{Mutex as At}from"async-mutex";import Tt from"write-file-atomic";var mn=1,bt=1048576,ct=5000,ot=50,st=/^[a-f0-9]{64}$/,wt=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Lt=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ft=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),An=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(wt),tokens:T.Optional(Lt),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(ft),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),rn=T.Object({version:T.Literal(mn),credentials:T.Record(T.String(),An)},{additionalProperties:!1});function q(n,t){return n instanceof Error&&"code"in n&&n.code===t}function Pt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return q(t,"EPERM")}}function k(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!st.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function G(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Et("sha256").update(JSON.stringify({serverUrl:G(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=Sn()){this.stateRoot=W.join(n,"mcp"),this.tokenFilePath=W.join(this.stateRoot,"oauth-credentials.json");let t=I.mutexes.get(this.tokenFilePath);if(!t)t=new At,I.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?k(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let u=M.credentials[n],_=await t(u?k(u):null);if(_)M.credentials[n]=j(An,_);else delete M.credentials[n];return _?k(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),u=await n(M);return await this.writeStore(M),u}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>bt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=En(rn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return en(M.data),M.data}catch(n){if(q(n,"ENOENT"))return{version:mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(rn,n);en(t),await Tt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{qf as En,rf as j,sf as T}from"./chunk-3ck3fxff.js";import{wf as On,xf as Zn}from"./chunk-x1r4b7pt.js";import{Cf as L}from"./chunk-7fgx7ztz.js";import{Gf as $n}from"./chunk-75y3mb0z.js";import{Jf as rt,Mf as p}from"./chunk-y5rsamex.js";import{Uf as sn,Vf as wn}from"./chunk-azcjz03h.js";import{Zf as $}from"./chunk-7xytd1h7.js";import{hg as Sn}from"./chunk-q4q0r97b.js";var et=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function St(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function B(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&St(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{B(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function y(n){let t=n.oauth;if(!t)return;let M=t;for(let S of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[S]!==void 0)throw Error(`MCP OAuth "${S}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(B(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((S)=>S.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let e=t.scopes?.map((S)=>S.trim());if(e){if(e.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(e.some((S)=>!S||S.length>128||!et.test(S)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(e).size!==e.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...e?.length?{scopes:e}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as l}from"node:crypto";import xt from"node:http";import{auth as Tn}from"@modelcontextprotocol/sdk/client/auth.js";import $t from"open";import{createHash as Et,randomUUID as mt}from"node:crypto";import{constants as D,promises as P}from"node:fs";import W from"node:path";import{Mutex as At}from"async-mutex";import Tt from"write-file-atomic";var mn=1,bt=1048576,ct=5000,ot=50,st=/^[a-f0-9]{64}$/,wt=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Lt=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ft=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),An=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(wt),tokens:T.Optional(Lt),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(ft),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),rn=T.Object({version:T.Literal(mn),credentials:T.Record(T.String(),An)},{additionalProperties:!1});function q(n,t){return n instanceof Error&&"code"in n&&n.code===t}function Pt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return q(t,"EPERM")}}function k(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!st.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function G(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Et("sha256").update(JSON.stringify({serverUrl:G(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=Sn()){this.stateRoot=W.join(n,"mcp"),this.tokenFilePath=W.join(this.stateRoot,"oauth-credentials.json");let t=I.mutexes.get(this.tokenFilePath);if(!t)t=new At,I.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?k(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let u=M.credentials[n],_=await t(u?k(u):null);if(_)M.credentials[n]=j(An,_);else delete M.credentials[n];return _?k(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),u=await n(M);return await this.writeStore(M),u}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>bt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=En(rn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return en(M.data),M.data}catch(n){if(q(n,"ENOENT"))return{version:mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(rn,n);en(t),await Tt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=W.join(this.stateRoot,".oauth-credentials.lock"),t=mt(),M=Date.now()+ct;while(Date.now()<M)try{let u=await P.open(n,D.O_CREAT|D.O_EXCL|D.O_WRONLY,384);return await u.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await u.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(_){if(!q(_,"ENOENT"))throw _}}}catch(u){if(!q(u,"EEXIST"))throw u;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,ot))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!Pt(M.pid))await P.unlink(n)}}var bn="127.0.0.1",cn=7777,on="/oauth/callback",dt=300000;class v extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Ln extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function Xt(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -41,4 +41,4 @@ ${M.map((u)=>` - ${u}`).join(`
41
41
  ]
42
42
  }
43
43
  `)}}function Uu(n,t={}){let M={...n};if(t.debug!==void 0)M.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);M.currentModelId=t.model}if(t.yolo===!0)M.permissionMode="yolo";else if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)M.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)M.maxQueuedTasks=t.maxQueuedTasks;return M.systemPrompt=t.systemPrompt,M.appendSystemPrompt=t.appendSystemPrompt,M.model=t.model,M.resumeSessionId=t.sessionId,M.forkSession=t.forkSession,M.allowedTools=t.allowedTools,M.disallowedTools=t.disallowedTools,M.mcpConfigPaths=t.mcpConfig,M.strictMcpConfig=t.strictMcpConfig,M.addDirs=t.addDir,M.outputFormat=t.outputFormat,M.inputFormat=t.inputFormat,M.print=t.print,M.includePartialMessages=t.includePartialMessages,M.replayUserMessages=t.replayUserMessages,M.agentsConfig=t.agents,M.settingSources=t.settingSources,M}
44
- export{U as ze,y as Ae,I as Be,v as Ce,Ln as De,N as Ee,Nn as Fe,qM as Ge,V as He,VM as Ie,OM as Je,ZM as Ke,Bn as Le,Ut as Me,JM as Ne,qt as Oe,QM as Pe,Jn as Qe,DM as Re,WM as Se,jM as Te,FM as Ue,lM as Ve,pn as We,vM as Xe,nu as Ye,tu as Ze,Mu as _e,BM as $e,b as af,d as bf,gt as cf,i as df,Q as ef,ln as ff,vn as gf,nt as hf,tt as if,Mt as jf,ut as kf,R as lf,Uu as mf};
44
+ export{U as Be,y as Ce,I as De,v as Ee,Ln as Fe,N as Ge,Nn as He,qM as Ie,V as Je,VM as Ke,OM as Le,ZM as Me,Bn as Ne,Ut as Oe,JM as Pe,qt as Qe,QM as Re,Jn as Se,DM as Te,WM as Ue,jM as Ve,FM as We,lM as Xe,pn as Ye,vM as Ze,nu as _e,tu as $e,Mu as af,BM as bf,b as cf,d as df,gt as ef,i as ff,Q as gf,ln as hf,vn as if,nt as jf,tt as kf,Mt as lf,ut as mf,R as nf,Uu as of};
@@ -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 wd};
2
+ export{B as yd};
@@ -1,3 +1,3 @@
1
- import{Mf as N,Pf as M}from"./chunk-5m5nxkfs.js";import{fg as H}from"./chunk-heydawsf.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
1
+ import{Of as N,Rf as M}from"./chunk-nah8b1gv.js";import{hg as H}from"./chunk-q4q0r97b.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
2
2
  `,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
3
- export{K as Gf,X as Hf,J as If,L as Jf,hu as Kf};
3
+ export{K as If,X as Jf,J as Kf,L as Lf,hu as Mf};
@@ -1,4 +1,4 @@
1
- import{ye as YO}from"./chunk-s3zfyy7r.js";import{of as qO,qf as S,tf as y}from"./chunk-4qyhtrhx.js";import{Af as K}from"./chunk-1ggxyyar.js";import{Ef as XO}from"./chunk-ekv4hpy8.js";import{Yf as n}from"./chunk-d4327k1v.js";import{fg as r}from"./chunk-heydawsf.js";import{hg as w}from"./chunk-37se34rx.js";var N;((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"})(N||={});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 _ from"node:path";import{nanoid as z}from"nanoid";var C={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 jO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import h from"node:path";import{Mutex as WO}from"async-mutex";import SO from"write-file-atomic";var k=1,GO=1048576,VO=/^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 LO(O){let q={};for(let Q of Object.values(N)){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(N))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(LO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new WO;filePath;constructor(O=h.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 J;try{J=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let W=J.projects[Z];if(!W)return{...X,state:"untrusted"};return{...X,state:W.digest===$?"trusted":"modified",trustedDigest:W.digest,trustedAt:W.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:k,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>GO)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!==k)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(!h.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!VO.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:k,projects:Z}}async writeStore(O){let q=h.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await SO(this.filePath,`${JSON.stringify(O,null,2)}
1
+ import{Ae as YO}from"./chunk-799zdv81.js";import{qf as qO,sf as S,vf as y}from"./chunk-3ck3fxff.js";import{Cf as K}from"./chunk-7fgx7ztz.js";import{Gf as XO}from"./chunk-75y3mb0z.js";import{_f as n}from"./chunk-cjgnf6qy.js";import{hg as r}from"./chunk-q4q0r97b.js";import{jg as w}from"./chunk-aspqajv2.js";var N;((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"})(N||={});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 _ from"node:path";import{nanoid as z}from"nanoid";var C={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 jO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import h from"node:path";import{Mutex as WO}from"async-mutex";import SO from"write-file-atomic";var k=1,GO=1048576,VO=/^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 LO(O){let q={};for(let Q of Object.values(N)){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(N))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(LO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new WO;filePath;constructor(O=h.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 J;try{J=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let W=J.projects[Z];if(!W)return{...X,state:"untrusted"};return{...X,state:W.digest===$?"trusted":"modified",trustedDigest:W.digest,trustedAt:W.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:k,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>GO)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!==k)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(!h.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!VO.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:k,projects:Z}}async writeStore(O){let q=h.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await SO(this.filePath,`${JSON.stringify(O,null,2)}
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(zO(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(BO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(AO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function zO(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 BO(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 AO(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 KO=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()))}),PO=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),_O=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),UO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),bO=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}),NO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),MO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),wO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),CO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),EO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([KO,PO,_O,UO,bO,NO,MO,TO,wO,CO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(EO,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",J=Q?.failureBehavior||"ignore",W=`Invalid hook output JSON: ${X}`;if(J==="deny")return{success:!1,blocking:!0,error:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(J==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${W}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:W,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 l{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 u{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:J}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),W=new l(this.MAX_STDOUT_SIZE),G=new l(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{W.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await J.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,R)=>{let F=!1,V=!1,B,P=()=>{return B??=J.terminate(),B},b=null,H=()=>{if(b&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",b),b=null},I=setTimeout(()=>{F=!0,P()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),F)await P();L({stdout:W.getContent(),stderr:G.getContent(),exitCode:F?124:f??1,timedOut:F})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),R(f)}),Q.abortSignal){if(b=()=>{if(V)return;V=!0,clearTimeout(I),H(),P().then(()=>{L({stdout:W.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",b),Q.abortSignal.aborted)b()}})}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"),DO={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 u;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}},J=await this.executeHook($,X,Q);if(!J.success){if(J.blocking)return{decision:"deny",reason:J.error};if(J.needsConfirmation)return{decision:"ask",reason:J.warning||J.error};if(J.warning)Y.push(J.warning);continue}let W=J.output?.hookSpecificOutput;if(W&&"permissionDecision"in W){switch(W.permissionDecision){case"deny":return{decision:"deny",reason:W.permissionDecisionReason};case"ask":return{decision:"ask",reason:W.permissionDecisionReason};case"allow":break}if("updatedInput"in W&&W.updatedInput)Z={...Z,...W.updatedInput}}}catch(X){let J=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${J}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:J};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${J}. 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,J=[];for(let W of Y){if(!W.success&&W.warning){J.push(W.warning);continue}let G=W.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
 
@@ -25,7 +25,7 @@ import{ye as YO}from"./chunk-s3zfyy7r.js";import{of as qO,qf as S,tf as y}from".
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,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,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(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)},J=JSON.stringify(q),W;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,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,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){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.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-56hphybe.js"),{createChatServiceAsync:J}=await import("./chunk-szmm21q9.js"),{resolveModelConfig:W}=await import("./chunk-pwwm04bc.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-ze8rmhs1.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.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=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,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,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(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)},J=JSON.stringify(q),W;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,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,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){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.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-9r0fxre0.js"),{createChatServiceAsync:J}=await import("./chunk-w0wzx47n.js"),{resolveModelConfig:W}=await import("./chunk-gy51z423.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-42ns4a92.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.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=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -42,4 +42,4 @@ ${O.prompt}
42
42
  `+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
43
43
  `+`- 如果没有发现问题,使用 "approve"
44
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 J=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),W=J.then(()=>{$.delete(W)}).catch(()=>{$.delete(W)});$.add(W),Y.push(J)}return Promise.all(Y)}}async function yO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:J}=await Q.read();if(J)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 HO=/^([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,$=HO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,J]=$;if(!this.matchPattern(Q,X))return!1;let W=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(W.length===0)return!1;return W.some((G)=>this.matchGlobOrPattern(G,J))}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}}}class U{static instance=null;config=C;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new Map;sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!U.instance)U.instance=new U;return U.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]??K()),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=new Set;for(let Z of q){let Y=this.sessionConfigKey(O,Z);Q.add(this.sessionStateAliases.get(Y)??Y),this.sessionConfigs.delete(Y),this.sessionStateAliases.delete(Y),this.disabledSessions.delete(Y)}for(let Z of Q)this.disabledSessions.delete(Z);await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){U.instance?.cleanup(),U.instance=null}loadConfig(O,q=K()){let Q=E(C,O),Z=c();Q=E(Q,Z);let Y=_.resolve(q);if(Y===_.resolve(K()))this.config=Q;this.projectConfigs.set(Y,Q)}isEnabled(O=K(),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=K()){let q=_.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===_.resolve(K()))return this.config;return{...C,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${_.resolve(q)}`}snapshotConfig(O){let q=E(C,O);for(let Q of Object.values(N))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}inheritProjectConfig(O,q){this.projectConfigs.set(_.resolve(q),this.getConfig(O))}getTrustStatus(O=K()){return A.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=K(),q){return A.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=K()){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 J=_.resolve(Z.projectDir),W=this.getConfig(J),G=W[O]??[];return W[O]=[...G,$],this.projectConfigs.set(J,W),()=>{let L=W[O];if(!L)return;W[O]=L.filter((R)=>R!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let J=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=J.filter((W)=>W!==$)}}async reloadConfig(O=K()){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:z(),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 J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let W=await this.executor.executePreToolHooks(X,$,J);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(W.decision==="deny")return W;return{decision:"allow",modifiedInput:W.modifiedInput,warning:W.warning,reason:W.reason}}return W}catch(W){return console.error("[HookManager] Error executing PreToolUse hooks:",W),{decision:"allow",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}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:z(),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},J=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(J,X,W);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:z(),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:z(),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:z(),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 J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,J)}catch(W){return console.error("[HookManager] Error executing PermissionRequest hooks:",W),{decision:"ask",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}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:z(),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:z(),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:z(),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:z(),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},J=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(J,X,W)}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:z(),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(J){return console.error("[HookManager] Error executing Notification hooks:",J),{suppress:!1,message:q,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}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:z(),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:z(),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:z(),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.disabledSessions.clear(),this.sessionStateAliases.clear()}}
45
- export{N as se,o as te,U as ue};
45
+ export{N as ue,o as ve,U as we};
@@ -0,0 +1 @@
1
+ import{Oc as a,Pc as b,Qc as c}from"./chunk-b0mha3tr.js";import"./chunk-rakyf5b7.js";import"./chunk-tx77qaz8.js";import"./chunk-v508x7cg.js";import"./chunk-xhdm1b4g.js";import"./chunk-7m4qc5vv.js";import"./chunk-xh1y705a.js";import"./chunk-mwae107k.js";import"./chunk-3ck3fxff.js";import"./chunk-x1r4b7pt.js";import"./chunk-7fgx7ztz.js";import"./chunk-75y3mb0z.js";import"./chunk-y5rsamex.js";import"./chunk-nah8b1gv.js";import"./chunk-azcjz03h.js";import"./chunk-7xytd1h7.js";import"./chunk-cjgnf6qy.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,2 +1,2 @@
1
- import{Sf as S}from"./chunk-7e7zgzag.js";import{hg as f}from"./chunk-37se34rx.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{Uf as S}from"./chunk-azcjz03h.js";import{jg as f}from"./chunk-aspqajv2.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as a,u as b,g as c,C as d,V as e};