blade-code 0.10.71 → 0.10.73

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 (120) hide show
  1. package/README.md +1 -1
  2. package/dist/blade.js +2 -2
  3. package/dist/{chunk-wfy851et.js → chunk-0hrj06t7.js} +1 -1
  4. package/dist/chunk-0qqzd0hq.js +1 -0
  5. package/dist/{chunk-jzntxp7f.js → chunk-1ava19kd.js} +2 -2
  6. package/dist/chunk-1cyy8wqj.js +10 -0
  7. package/dist/{chunk-97aywyzn.js → chunk-2wdxpdz3.js} +2 -2
  8. package/dist/chunk-3fzy7q6x.js +1 -0
  9. package/dist/chunk-3hv57n95.js +1635 -0
  10. package/dist/{chunk-bjqjdw34.js → chunk-3r0x2p7z.js} +2 -2
  11. package/dist/chunk-4cpgcm7q.js +44 -0
  12. package/dist/{chunk-m57w4p91.js → chunk-4ehgjdm0.js} +1 -1
  13. package/dist/{chunk-hat9v5c5.js → chunk-4khtsmrf.js} +1 -1
  14. package/dist/{chunk-axtzde5k.js → chunk-5d1gbm41.js} +2 -2
  15. package/dist/chunk-64jq6jcr.js +2 -0
  16. package/dist/{chunk-4ke8k0xw.js → chunk-67ddp3ns.js} +3 -3
  17. package/dist/{chunk-trn6r1g3.js → chunk-77hn7hf6.js} +1 -1
  18. package/dist/{chunk-ahg9vjb6.js → chunk-8fm3xamc.js} +1 -1
  19. package/dist/chunk-8h35w91f.js +1 -0
  20. package/dist/{chunk-2px6hzdc.js → chunk-948efzyp.js} +2 -2
  21. package/dist/{chunk-qgrq04hb.js → chunk-9cgsheg0.js} +2 -2
  22. package/dist/chunk-9e6dcbqq.js +160 -0
  23. package/dist/{chunk-gtcxybv5.js → chunk-a0ns74mh.js} +1 -1
  24. package/dist/{chunk-5te2jqt3.js → chunk-a37mn58w.js} +1 -1
  25. package/dist/{chunk-3hy06st1.js → chunk-a5e4sy4q.js} +2 -2
  26. package/dist/{chunk-k0pa8874.js → chunk-ah12xhh6.js} +1 -1
  27. package/dist/{chunk-j9q1wyxg.js → chunk-ax610gqh.js} +1 -1
  28. package/dist/chunk-b28zsp1t.js +166 -0
  29. package/dist/{chunk-rm9hbew3.js → chunk-b3413dtc.js} +1 -1
  30. package/dist/{chunk-1je1xw6v.js → chunk-bhhdvqe7.js} +18 -18
  31. package/dist/{chunk-0j22w4wh.js → chunk-c9e0fbyh.js} +1 -1
  32. package/dist/{chunk-fcv8b6ny.js → chunk-cvvtrvk6.js} +2 -2
  33. package/dist/chunk-fdmcef2p.js +2 -0
  34. package/dist/{chunk-x9tvjkjv.js → chunk-fgh6mjdp.js} +1 -1
  35. package/dist/chunk-hswyrd88.js +1 -0
  36. package/dist/chunk-jeazjp08.js +8 -0
  37. package/dist/{chunk-zvz2cnt4.js → chunk-jkh9s1ht.js} +1 -1
  38. package/dist/{chunk-yn51162x.js → chunk-js4vqnds.js} +1 -1
  39. package/dist/chunk-jsg7vmxp.js +1 -0
  40. package/dist/{chunk-v0rsz1rt.js → chunk-k82ff14t.js} +1 -1
  41. package/dist/chunk-kka51s0k.js +2 -0
  42. package/dist/{chunk-cff9gphh.js → chunk-meee1cbq.js} +1 -1
  43. package/dist/{chunk-r9d4mjxj.js → chunk-mefb27ch.js} +1 -1
  44. package/dist/{chunk-0vrgrw71.js → chunk-n1w40gq2.js} +2 -2
  45. package/dist/{chunk-t8xmh4w2.js → chunk-ne7vres8.js} +1 -1
  46. package/dist/chunk-p0qjjyex.js +22 -0
  47. package/dist/{chunk-h0ft81a3.js → chunk-p7y79y6c.js} +1 -1
  48. package/dist/{chunk-0tm20v38.js → chunk-q6ak67n8.js} +2 -2
  49. package/dist/{chunk-byqxaa9v.js → chunk-r5bpvfym.js} +1 -1
  50. package/dist/{chunk-th4jjfgm.js → chunk-r8wbvxn7.js} +1 -1
  51. package/dist/{chunk-0wxkymqv.js → chunk-skw3b17a.js} +1 -1
  52. package/dist/{chunk-dwb2nmms.js → chunk-sxjs66h6.js} +1 -1
  53. package/dist/{chunk-s77sbxr7.js → chunk-tmvg7taj.js} +1 -1
  54. package/dist/{chunk-1pjkgfez.js → chunk-traa01dd.js} +1 -1
  55. package/dist/{chunk-9hchc346.js → chunk-tvv3syt3.js} +1 -1
  56. package/dist/{chunk-t2wgf9tq.js → chunk-tzytnhbp.js} +2 -2
  57. package/dist/chunk-vhadycw2.js +2 -0
  58. package/dist/{chunk-s7jsadnc.js → chunk-vw0gg08s.js} +2 -2
  59. package/dist/chunk-vxd30mnx.js +1 -0
  60. package/dist/chunk-wbzvy99s.js +1 -0
  61. package/dist/chunk-wg3z2epq.js +1 -0
  62. package/dist/{chunk-mtphps19.js → chunk-wp0794r2.js} +2 -2
  63. package/dist/{chunk-azw0jckv.js → chunk-xjc0bthz.js} +2 -2
  64. package/dist/chunk-xkc6v9nb.js +1 -0
  65. package/dist/{chunk-be30r8an.js → chunk-xv92c582.js} +1 -1
  66. package/dist/chunk-y36rdy4v.js +5 -0
  67. package/dist/chunk-yg6c4xrs.js +1 -0
  68. package/dist/{chunk-cdy9efgm.js → chunk-yvnm25nb.js} +1 -1
  69. package/dist/chunk-yx82ang3.js +6 -0
  70. package/dist/chunk-z8a5ebep.js +1 -0
  71. package/dist/chunk-z95pw8nb.js +1 -0
  72. package/dist/chunk-zh2x0tcm.js +1 -0
  73. package/dist/chunk-zr1mg5kq.js +1 -0
  74. package/dist/{chunk-9q852bsc.js → chunk-zxn7f308.js} +2 -2
  75. package/dist/web/assets/ChatView-Dm-DMbOV.js +18 -0
  76. package/dist/web/assets/{CodeBlockHighlighter-Dy7QpAmC.js → CodeBlockHighlighter-XaY8h0vd.js} +1 -1
  77. package/dist/web/assets/{FilePreview-BI3nkxz1.js → FilePreview-CVHV6oga.js} +1 -1
  78. package/dist/web/assets/{KanbanBoard-D5dYOyPH.js → KanbanBoard-D1_61uZi.js} +1 -1
  79. package/dist/web/assets/{MarkdownRenderer-Da1vB81L.js → MarkdownRenderer-DUPwAzs4.js} +3 -3
  80. package/dist/web/assets/{SettingsModal-jcCFqLqS.js → SettingsModal-DHnU7uMN.js} +2 -2
  81. package/dist/web/assets/{TaskSwitcher-CQ--jOLB.js → TaskSwitcher-CpXhLtO5.js} +1 -1
  82. package/dist/web/assets/{TerminalPanel-CWzjEXOb.js → TerminalPanel-eYsA-A62.js} +1 -1
  83. package/dist/web/assets/index-8G4ejlcH.css +1 -0
  84. package/dist/web/assets/index-gjBOFzd1.js +11 -0
  85. package/dist/web/assets/{session-events-BvtUOaNG.js → session-events-Bgir_Gl_.js} +6 -6
  86. package/dist/web/assets/team-QZ9byb3E.js +1 -0
  87. package/dist/web/assets/teamService-Bb2kW8Hh.js +1 -0
  88. package/dist/web/assets/{vendor-icons-B63aW_OM.js → vendor-icons-DovdPN7M.js} +51 -41
  89. package/dist/web/index.html +4 -4
  90. package/package.json +1 -1
  91. package/dist/chunk-1w83z8j0.js +0 -1
  92. package/dist/chunk-2428hhvj.js +0 -6
  93. package/dist/chunk-3as0bkqy.js +0 -1
  94. package/dist/chunk-4pexpa3h.js +0 -160
  95. package/dist/chunk-6pyktfa4.js +0 -2
  96. package/dist/chunk-82htkvz8.js +0 -44
  97. package/dist/chunk-8j568nm6.js +0 -1
  98. package/dist/chunk-92x15fzx.js +0 -2
  99. package/dist/chunk-93tvxmqg.js +0 -8
  100. package/dist/chunk-ckqpt15b.js +0 -1
  101. package/dist/chunk-d3ttqmyt.js +0 -1620
  102. package/dist/chunk-fcmgwzrj.js +0 -10
  103. package/dist/chunk-gvbx0t4j.js +0 -1
  104. package/dist/chunk-j0p54tqt.js +0 -1
  105. package/dist/chunk-n827nys9.js +0 -1
  106. package/dist/chunk-nwzpnx7m.js +0 -22
  107. package/dist/chunk-nx31fkkf.js +0 -166
  108. package/dist/chunk-qnsvae10.js +0 -1
  109. package/dist/chunk-sp3bn8qh.js +0 -1
  110. package/dist/chunk-v7p533ff.js +0 -1
  111. package/dist/chunk-vthgpdbd.js +0 -1
  112. package/dist/chunk-wneeq8cr.js +0 -1
  113. package/dist/chunk-wrfay5r3.js +0 -2
  114. package/dist/chunk-xdz5zrjt.js +0 -1
  115. package/dist/chunk-xz6y0w4n.js +0 -2
  116. package/dist/chunk-xzz69esf.js +0 -1
  117. package/dist/chunk-zdnk7qtn.js +0 -5
  118. package/dist/web/assets/ChatView-BVrhnE2j.js +0 -18
  119. package/dist/web/assets/index-BOgOL4hG.js +0 -11
  120. package/dist/web/assets/index-DbWgTuT3.css +0 -1
@@ -1,4 +1,4 @@
1
- import{tg as L,wg as _}from"./chunk-k0pa8874.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
1
+ import{Bg as L,Eg as _}from"./chunk-ah12xhh6.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
2
2
  You have been invoked in the following environment:
3
3
  - Primary working directory: ${B.workingDirectory}
4
4
  - Is a git repository: ${$?"true":"false"}
@@ -25,4 +25,4 @@ ${I.join(`
25
25
 
26
26
  Project root directory listing:
27
27
  ${K}`}return N}function f(z){let q=z,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??z}function x(z,q){let M=j(z)?z:R(q||process.cwd(),z),W;try{W=b(M)}catch{W=M}L(W)}
28
- export{v as td,f as ud,x as vd};
28
+ export{v as Bd,f as Cd,x as Dd};
@@ -0,0 +1,44 @@
1
+ import{rg as Y}from"./chunk-p7y79y6c.js";import{sg as on,tg as F,ug as o}from"./chunk-k82ff14t.js";import{yg as ct,zg as bt}from"./chunk-64jq6jcr.js";import{Eg as x}from"./chunk-ah12xhh6.js";import{$g as Qt,Fg as Jn,Gg as Xt,Hg as pt,Lg as gt,Mg as kn,Ng as it,Og as Rt,Pg as Ct,Qg as un,Rg as zt,Sg as Bt,Tg as On,Ug as Kt,Vg as Ut,Wg as jn,Xg as Ht,Yg as Yt,Zg as qt,_g as Vt,ah as Gt}from"./chunk-kka51s0k.js";import{eh as fn}from"./chunk-tzytnhbp.js";import{hh as $t,kh as J}from"./chunk-948efzyp.js";import{sh as Pn,th as Ln}from"./chunk-xjc0bthz.js";import{zh as h}from"./chunk-1ava19kd.js";import{Kh as Tn}from"./chunk-zxn7f308.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(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:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(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 k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" 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(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.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 S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let 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:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.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 L.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>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
+ `,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
+ `,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.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 L.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(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn 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 an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
+ <html lang="en">
5
+ <head>
6
+ <meta charset="utf-8">
7
+ <meta name="viewport" content="width=device-width,initial-scale=1">
8
+ <title>${t}</title>
9
+ </head>
10
+ <body>
11
+ <main>
12
+ <h1>${t}</h1>
13
+ <p>${n?"You can close this window and return to Blade.":"Return to Blade and retry the OAuth login."}</p>
14
+ </main>
15
+ </body>
16
+ </html>`}function C(n,t,M){n.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer"}),n.end(rM(M))}class ${serverName;config;static activeFlowIdentity;tokenStorage;serverUrl;identity;callbackUrl;openAuthorizationUrl;codeVerifierValue;activeFlow;lastError;constructor(n,t,M,e={}){this.serverName=n;this.config=M;this.serverUrl=q(t),this.identity=l(this.serverUrl,M.clientId,M.scopes),this.tokenStorage=e.tokenStorage??new I;let _=M.callbackPort??wn;this.callbackUrl=`http://${bn}:${_}${xn}`,this.openAuthorizationUrl=e.openAuthorizationUrl??(async(S)=>{await _M(S,{wait:!1})})}get redirectUrl(){return this.callbackUrl}get clientMetadata(){return{redirect_uris:[this.callbackUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`${Ln()} ${Pn()}`,...this.config.scopes?.length?{scope:this.config.scopes.join(" ")}:{}}}async state(){return this.activeFlow?.state??v()}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId};return(await this.readCredential())?.clientInformation}async saveClientInformation(n){await this.updateCredential((t)=>({...this.baseCredential(t),clientInformation:n}))}async tokens(){let n=await this.readCredential();if(!n?.tokens)return;if(n.tokenExpiresAt!==void 0&&n.tokenExpiresAt<=Date.now()&&!n.tokens.refresh_token)return;return structuredClone(n.tokens)}async saveTokens(n){let t=n.expires_in===void 0?void 0:Date.now()+n.expires_in*1000;await this.updateCredential((M)=>({...this.baseCredential(M),tokens:structuredClone(n),...t===void 0?{}:{tokenExpiresAt:t}})),this.lastError=void 0}async redirectToAuthorization(n){let t=this.activeFlow;if(!t)throw new nn(this.serverName);t.authorizationUrl=R(n,"MCP OAuth authorization URL").toString()}async saveCodeVerifier(n){this.codeVerifierValue=n}async codeVerifier(){if(!this.codeVerifierValue)throw Error("MCP OAuth PKCE verifier is unavailable");return this.codeVerifierValue}async saveDiscoveryState(n){await this.updateCredential((t)=>({...this.baseCredential(t),discoveryState:structuredClone(n)}))}async discoveryState(){let n=(await this.readCredential())?.discoveryState;return n?structuredClone(n):void 0}async invalidateCredentials(n){if(n==="verifier"){this.codeVerifierValue=void 0;return}if(n==="all"){await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0;return}await this.updateCredential((t)=>{if(!t)return null;let M={...t};if(n==="client")delete M.clientInformation,delete M.tokens,delete M.tokenExpiresAt;else if(n==="tokens")delete M.tokens,delete M.tokenExpiresAt;else if(n==="discovery")delete M.discoveryState;return{...M,updatedAt:new Date().toISOString()}})}async getStatus(){if(this.activeFlow)return"authorizing";if(this.lastError)return"error";return await this.hasUsableCredentials()?"authenticated":"unauthenticated"}async hasUsableCredentials(){let n=await this.readCredential();if(!n?.tokens?.access_token)return!1;if(n.tokenExpiresAt===void 0||n.tokenExpiresAt>Date.now())return!0;return Boolean(n.tokens.refresh_token)}async beginAuthorization(){if(this.activeFlow)return this.toHandle(this.activeFlow);if(await this.hasUsableCredentials())throw Error(`MCP server "${this.serverName}" already has OAuth credentials`);if($.activeFlowIdentity)throw Error("Another MCP OAuth authorization is already in progress");$.activeFlowIdentity=this.identity,this.lastError=void 0,this.codeVerifierValue=void 0;try{let n=await this.createFlow();if(this.activeFlow=n,await cn(this,{serverUrl:this.serverUrl,fetchFn:U})!=="REDIRECT"||!n.authorizationUrl)throw Error("MCP OAuth server did not start an authorization redirect");return this.toHandle(n)}catch(n){let t=n instanceof Error?n:Error(String(n));throw await this.failActiveFlow(t),t}}async openAuthorization(){let n=await this.beginAuthorization();return await this.openAuthorizationUrl(n.authorizationUrl),n}async logout(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"));await this.tokenStorage.deleteCredential(this.identity),this.codeVerifierValue=void 0,this.lastError=void 0}async dispose(){if(this.activeFlow)await this.failActiveFlow(Error("MCP OAuth authorization cancelled"))}async createFlow(){let n,t,M=new Promise((r,u)=>{n=r,t=u});M.catch(()=>{return});let e=v(),_=MM.createServer((r,u)=>{this.handleCallback(r,u)});_.on("clientError",(r,u)=>{u.end(`HTTP/1.1 400 Bad Request\r
17
+ Connection: close\r
18
+ \r
19
+ `)}),await new Promise((r,u)=>{let E=(T)=>u(T);_.once("error",E),_.listen(this.config.callbackPort??wn,bn,()=>{_.off("error",E),r()})});let S={flowId:v(),state:e,callbackUrl:this.callbackUrl,server:_,timeout:setTimeout(()=>{this.failActiveFlow(Error("MCP OAuth authorization timed out"))},eM),completion:M,resolve:n,reject:t,settled:!1};return S.timeout.unref(),S}async handleCallback(n,t){let M=this.activeFlow;if(!M){C(t,410,!1);return}try{if(n.method!=="GET"){t.setHeader("Allow","GET"),C(t,405,!1);return}let e=new URL(n.url??"/",M.callbackUrl);if(e.pathname!==xn){C(t,404,!1);return}let _=e.searchParams.get("state"),S=e.searchParams.get("code");if(e.searchParams.get("error"))throw Error("MCP OAuth authorization was denied");if(!_||_!==M.state)throw Error("MCP OAuth state mismatch");if(!S)throw Error("MCP OAuth callback is missing the authorization code");if(await cn(this,{serverUrl:this.serverUrl,authorizationCode:S,fetchFn:U})!=="AUTHORIZED")throw Error("MCP OAuth token exchange did not complete");C(t,200,!0),await this.completeActiveFlow()}catch(e){C(t,400,!1),await this.failActiveFlow(e instanceof Error?e:Error(String(e)))}}async completeActiveFlow(){let n=this.activeFlow;if(!n||n.settled)return;n.settled=!0,clearTimeout(n.timeout),await new Promise((t)=>n.server.close(()=>t())),this.activeFlow=void 0,$.activeFlowIdentity=void 0,this.codeVerifierValue=void 0,this.lastError=void 0,n.resolve()}async failActiveFlow(n){let t=this.activeFlow;if(this.lastError=n,this.codeVerifierValue=void 0,$.activeFlowIdentity=void 0,!t||t.settled){this.activeFlow=void 0;return}t.settled=!0,clearTimeout(t.timeout),await new Promise((M)=>t.server.close(()=>M())),this.activeFlow=void 0,t.reject(n)}toHandle(n){if(!n.authorizationUrl)throw Error("MCP OAuth authorization URL is unavailable");return{flowId:n.flowId,authorizationUrl:n.authorizationUrl,callbackUrl:n.callbackUrl,completion:n.completion}}readCredential(){return this.tokenStorage.getCredential(this.identity)}updateCredential(n){return this.tokenStorage.updateCredential(this.identity,n)}baseCredential(n){return{...n??{},serverUrl:this.serverUrl,...this.config.clientId?{clientId:this.config.clientId}:{},updatedAt:new Date().toISOString()}}}import{promises as V}from"node:fs";import hn from"node:os";import f from"node:path";import{merge as SM}from"lodash-es";import uM from"write-file-atomic";var dn=fn("Service"),X={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},modelProviders:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},bashForegroundHandoffMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerForegroundRecoveryMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerCircuitBreakerOpenMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestConcurrency:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerGlobalConcurrency:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerOwnerConcurrency:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestAdmissionMs:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},providerRequestPendingBytes:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},agentTeamsEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},codeTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},communicationStyle:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},enabledPlugins:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},pluginSourcePolicy:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxConcurrentTasks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxQueuedTasks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxQueuedTaskBytes:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxResidentSessionRuntimes:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},sessionRuntimeIdleMs:{target:"settings",defaultScope:"global",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},lspServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},o_=new Set(Object.entries(X).filter(([n,t])=>t.persistable).map(([n])=>n)),A_=new Set(Object.entries(X).filter(([n,t])=>!t.persistable).map(([n])=>n));class a{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Y;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!a.instance)a.instance=new a;return a.instance}static resetInstance(){if(a.instance)for(let n of a.instance.timers.values())clearTimeout(n);a.instance=null}coordinationStatsForTests(){return this.fileLocks.getStats()}async save(n,t={}){this.validatePersistableFields(n);let M=this.groupUpdatesByTarget(n,t.scope,t.projectDir);if(t.immediate)await Promise.all(Array.from(M.entries()).map(([e,_])=>this.flushTarget(e,_)));else for(let[e,_]of M)this.scheduleSave(e,_)}async flush(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear();let n=Array.from(this.pendingUpdates.entries()).map(([t,M])=>this.flushTarget(t,M));this.pendingUpdates.clear(),await Promise.all(n)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(n,t={}){await this.appendPermissionRuleForDecision(n,"allow",t)}async appendPermissionDenyRule(n,t={}){await this.appendPermissionRuleForDecision(n,"deny",t)}async appendPermissionRuleForDecision(n,t,M){let e=M.scope??"local",_=this.resolveFilePath("settings",e,M.projectDir);await this.flushTargetWithModifier(_,(S)=>{let r=S.permissions??{allow:[],ask:[],deny:[]},u={allow:t==="allow"?this.dedupeArray([...r.allow||[],n]):r.allow||[],ask:r.ask||[],deny:t==="deny"?this.dedupeArray([...r.deny||[],n]):r.deny||[]};return{...S,permissions:u}})}async appendLocalPermissionRule(n,t={}){await this.appendPermissionRule(n,{...t,scope:"local"})}async appendLocalPermissionDenyRule(n,t={}){await this.appendPermissionDenyRule(n,{...t,scope:"local"})}async removePluginSetting(n,t={}){let M=t.scope??"local",e=this.resolveFilePath("settings",M,t.projectDir);await this.flushTargetWithModifier(e,(_)=>{let S={..._.enabledPlugins??{}};delete S[n];let r={..._};if(Object.keys(S).length>0)r.enabledPlugins=S;else delete r.enabledPlugins;return r})}validatePersistableFields(n){for(let t of Object.keys(n)){let M=X[t];if(!M)throw Error(`Unknown config field: ${t}`);if(!M.persistable)throw Error(`Field "${t}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(n,t,M){let e=new Map;for(let[_,S]of Object.entries(n)){let r=X[_];if(!r)continue;let u=t??r.defaultScope,E=this.resolveFilePath(r.target,u,M);if(!e.has(E))e.set(E,{});e.get(E)[_]=S}return e}resolveFilePath(n,t,M){let e=M??x();if(n==="config")return t==="global"?f.join(hn.homedir(),".blade","config.json"):f.join(e,".blade","config.json");switch(t){case"local":return f.join(e,".blade","settings.local.json");case"project":return f.join(e,".blade","settings.json");case"global":return f.join(hn.homedir(),".blade","settings.json");default:return f.join(e,".blade","settings.local.json")}}scheduleSave(n,t){let M=this.pendingUpdates.get(n)??{},e=this.mergePendingUpdates(M,t);this.pendingUpdates.set(n,e);let _=this.timers.get(n);if(_)clearTimeout(_);let S=setTimeout(async()=>{let r=this.pendingUpdates.get(n);if(r){this.pendingUpdates.delete(n),this.timers.delete(n);try{await this.flushTarget(n,r),this.lastSaveError=null}catch(u){let E=u instanceof Error?u:Error(String(u));this.lastSaveError=E,dn.error(`Failed to save config to ${n}:`,E.message),dn.error("Stack trace:",E.stack)}}},this.debounceDelay);this.timers.set(n,S)}mergePendingUpdates(n,t){let M={...n};for(let[e,_]of Object.entries(t)){let S=X[e];if(!S){M[e]=_;continue}switch(S.mergeStrategy){case"replace":M[e]=_;break;case"append-dedupe":this.applyAppendDedupe(M,e,_);break;case"deep-merge":this.applyDeepMerge(M,e,_);break}}return M}async flushTarget(n,t){await this.fileLocks.runExclusive(n,async()=>{await this.performWrite(n,t)})}async flushTargetWithModifier(n,t){await this.fileLocks.runExclusive(n,async()=>{await V.mkdir(f.dirname(n),{recursive:!0,mode:493});let M={};try{let _=await V.readFile(n,"utf-8");M=JSON.parse(_)}catch{M={}}let e=t(M);await this.atomicWrite(n,e)})}async performWrite(n,t){await V.mkdir(f.dirname(n),{recursive:!0,mode:493});let M={};try{let _=await V.readFile(n,"utf-8");M=JSON.parse(_)}catch{M={}}let e={...M};if(typeof e.theme==="string"&&e.codeTheme===void 0)e.codeTheme=e.theme;delete e.theme;for(let[_,S]of Object.entries(t)){let r=X[_];if(!r){e[_]=S;continue}switch(r.mergeStrategy){case"replace":e[_]=S;break;case"append-dedupe":this.applyAppendDedupe(e,_,S);break;case"deep-merge":this.applyDeepMerge(e,_,S);break}}await this.atomicWrite(n,e)}applyAppendDedupe(n,t,M){if(t==="permissions"&&typeof M==="object"&&M!==null){let e=n[t]??{allow:[],ask:[],deny:[]},_=M;n[t]={allow:this.dedupeArray([...e.allow||[],..._.allow||[]]),ask:this.dedupeArray([...e.ask||[],..._.ask||[]]),deny:this.dedupeArray([...e.deny||[],..._.deny||[]])}}else if(Array.isArray(M)){let e=Array.isArray(n[t])?n[t]:[];n[t]=this.dedupeArray([...e,...M])}else n[t]=M}applyDeepMerge(n,t,M){if(typeof M==="object"&&M!==null&&!Array.isArray(M)){let e=typeof n[t]==="object"&&n[t]!==null?n[t]:{};n[t]=SM({},e,M)}else n[t]=M}dedupeArray(n){return Array.from(new Set(n))}async atomicWrite(n,t){await uM(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}}function s_(){return a.getInstance()}var In=15000,Nn=1000,$n=300000;function tn(n){return n===0||typeof n==="number"&&Number.isSafeInteger(n)&&n>=1000&&n<=300000}function b_(n,t=15000){return tn(n)?n:t}var Xn=1,pn=32,gn=256,Rn=30000,Cn=300000,zn=3600000,x_=30000;function Bn(n){return Number.isSafeInteger(n)&&n>=1&&n<=256}function Kn(n){return Number.isSafeInteger(n)&&n>=30000&&n<=3600000}var Un=1,Hn=64,Yn=1,qn=1e4,Vn=67108864,Qn=65536,Gn=134217728;function Wn(n){return Number.isInteger(n)&&n>=1&&n<=64}function Zn(n){return Number.isInteger(n)&&n>=1&&n<=1e4}function Dn(n){return Number.isSafeInteger(n)&&n>=65536&&n<=134217728}var A={currentModelId:"",models:[],modelProviders:{},temperature:0,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,bashForegroundHandoffMs:In,providerForegroundRecoveryMs:Jn,providerCircuitBreakerOpenMs:kn,providerRequestAdmissionMs:On,agentTeamsEnabled:!1,providerRequestPendingBytes:jn,codeTheme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},lspServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},enabledPlugins:{},pluginSourcePolicy:{restrictToAllowedSources:!1,requireGitCommitSha:!1,allowedGitHosts:[],allowedMarketplaces:[],allowedLocalRoots:[]},env:{},disableAllHooks:!1,maxTurns:-1,maxConcurrentTasks:3,maxQueuedTasks:100,maxQueuedTaskBytes:Vn,maxResidentSessionRuntimes:pn,sessionRuntimeIdleMs:Cn};var yn=/^[A-Za-z0-9_-]{21}$/;function Fn(n){return n.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[._-]+$/g,"").slice(0,80)||"model"}function mM(n,t){let M=new Set(t.map((r)=>r.id)),e=Fn(n.model);if(!M.has(e))return e;let _=`${Fn(n.provider)}-${e}`.slice(0,120);if(!M.has(_))return _;let S=2;while(M.has(`${_}-${S}`))S++;return`${_}-${S}`}function ln(n,t){let M=n.filter((S)=>!yn.test(S.id)).map((S)=>({id:S.id})),e=new Map;return{models:n.map((S)=>{if(!yn.test(S.id))return{...S};let{id:r,...u}=S,E=mM(u,M);return M.push({id:E}),e.set(r,E),{...S,id:E}}),currentModelId:e.get(t)??t,changed:e.size>0}}import{promises as Nt}from"fs";import{merge as K}from"lodash-es";import b from"os";import m from"path";function nt(n){let t=vn(n.timeout??300000,"MCP timeout"),M=vn(n.idleTimeout??Math.min(60000,t),"MCP idleTimeout");if(M>t)throw Error("MCP idleTimeout must not exceed timeout");return{totalTimeoutMs:t,idleTimeoutMs:M,maxProgressEvents:128}}function i_(n,t,M){if(t.count>=M.maxProgressEvents)return;if(!Number.isFinite(n.progress)||n.progress<0)return;if(n.total!==void 0&&(!Number.isFinite(n.total)||n.total<=0))return;if(t.lastProgress!==void 0&&n.progress<t.lastProgress)return;t.count++,t.lastProgress=n.progress;let e=n.message?.replace(/\0/g,"").trim().slice(0,1000);return{progress:n.progress,...n.total!==void 0?{total:n.total}:{},message:e||TM(n.progress,n.total)}}function vn(n,t){if(!Number.isSafeInteger(n)||n<1000||n>1800000)throw Error(`${t} must be an integer between 1000 and 1800000 milliseconds`);return n}function TM(n,t){if(t!==void 0)return`MCP progress ${Math.max(0,Math.min(100,n/t*100)).toFixed(0)}%`;return`MCP progress ${n}`}import{createHash as oM}from"node:crypto";var Q=["debug","info","notice","warning","error","critical","alert","emergency"],z_=64,B_=64,K_=256,AM=8192,et=16384,sM=256,cM=6,bM=128,tt=64,Mt=64,wM=128,xM=/authorization|api[-_]?key|cookie|credential|password|secret|token/i;function rt(n){let t=n.logging;if(t!==void 0&&(t===null||typeof t!=="object"||Array.isArray(t)))throw Error("MCP logging configuration must be an object");let M=t?.enabled??!0;if(typeof M!=="boolean")throw Error("MCP logging enabled must be a boolean");let e=t?.level??"warning";if(!PM(e))throw Error(`MCP logging level must be one of: ${Q.join(", ")}`);return{enabled:M,level:e}}function PM(n){return typeof n==="string"&&Q.includes(n)}function U_(n,t){return Q.indexOf(n)>=Q.indexOf(t)}function LM(n,t={}){let M=aM(n.data),e=typeof M.value==="string"?M.value:JSON.stringify(M.value),_=_t(e,et),S=_.value,r=Buffer.byteLength(S),u=oM("sha256").update(S).digest("hex"),E=t.exposeDetails!==!1,T=E?_t(S,AM):{value:`[MCP log details omitted; sha256=${u}]`,truncated:!1},s=E&&n.logger?G(_n(n.logger),sM):void 0;return{level:n.level,...s?{logger:s}:{},message:T.value||"[empty MCP log message]",projectedBytes:r,dataSha256:u,truncated:M.truncated||_.truncated||T.truncated,detailsOmitted:!E,timestamp:t.now??Date.now()}}function H_(n,t={}){return{...LM({level:"warning",logger:"blade.mcp.logging",data:`MCP log rate exceeded; dropped at least ${Math.max(1,n)} message(s)`},t),synthetic:!0}}function aM(n){let t={nodes:0,remainingStringBytes:et,truncated:!1,seen:new WeakSet};return{value:Mn(n,0,t),truncated:t.truncated}}function Mn(n,t,M){if(M.nodes++,M.nodes>bM)return M.truncated=!0,"[node limit reached]";if(n===null||typeof n==="boolean")return n;if(typeof n==="number")return Number.isFinite(n)?n:String(n);if(typeof n==="bigint")return n.toString();if(typeof n==="string"){let e=_n(n),_=Math.max(0,M.remainingStringBytes),S=G(e,_),r=Buffer.byteLength(S);if(M.remainingStringBytes-=r,r<Buffer.byteLength(e))M.truncated=!0;return S}if(typeof n>"u")return"[undefined]";if(typeof n==="symbol"||typeof n==="function")return`[${typeof n}]`;if(t>=cM)return M.truncated=!0,"[depth limit reached]";if(M.seen.has(n))return M.truncated=!0,"[circular]";M.seen.add(n);try{if(Array.isArray(n)){if(n.length>tt)M.truncated=!0;return n.slice(0,tt).map((S)=>Mn(S,t+1,M))}let e=Object.create(null),_=Object.entries(n);if(_.length>Mt)M.truncated=!0;for(let[S,r]of _.slice(0,Mt)){let u=G(_n(S),wM)||"[empty-key]";if(S==="_meta"||xM.test(S))e[u]="[redacted]";else e[u]=Mn(r,t+1,M)}return e}finally{M.seen.delete(n)}}function _n(n){return[...n.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")].filter((M)=>{let e=M.charCodeAt(0);return(e===9||e===10||e===13||e>=32)&&e!==127}).join("")}function G(n,t){if(t<=0)return"";if(Buffer.byteLength(n)<=t)return n;let M=Buffer.from(n).subarray(0,t).toString("utf8");while(Buffer.byteLength(M)>t)M=M.slice(0,-1);return M}function _t(n,t){if(Buffer.byteLength(n)<=t)return{value:n,truncated:!1};let M=`
20
+ ...[MCP log truncated]`;return{value:G(n,t-Buffer.byteLength(M))+M,truncated:!0}}var St=1024,hM=4096,ut=2,dM=8,Et=65536,fM=1048576,mt=50,Tt=16000,ot=4,IM=100,At=1048576,NM=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function wt(n){if(!n)return{enabled:!1,maxTokens:St,maxRequestsPerToolCall:ut,maxInputBytes:Et};if(typeof n.enabled!=="boolean")throw Error("MCP sampling.enabled must be a boolean");return{enabled:n.enabled,maxTokens:W(n.maxTokens??St,1,hM,"MCP sampling.maxTokens"),maxRequestsPerToolCall:W(n.maxRequestsPerToolCall??ut,1,dM,"MCP sampling.maxRequestsPerToolCall"),maxInputBytes:W(n.maxInputBytes??Et,1,fM,"MCP sampling.maxInputBytes")}}function V_(n,t){if(!t.enabled)throw Error("MCP sampling is disabled");if(n.task)throw Error("Task-based MCP sampling is not supported");if(n.tools?.length)throw Error("MCP sampling tools were not negotiated");if(n.includeContext&&n.includeContext!=="none")throw Error("MCP sampling server context was not negotiated");if(n.messages.length===0||n.messages.length>mt)throw Error(`MCP sampling messages must contain 1-${mt} entries`);if(n.systemPrompt!==void 0&&n.systemPrompt.length>Tt)throw Error(`MCP sampling system prompt exceeds ${Tt} characters`);if(n.temperature!==void 0&&(!Number.isFinite(n.temperature)||n.temperature<0||n.temperature>2))throw Error("MCP sampling temperature must be between 0 and 2");let M=n.stopSequences??[];if(M.length>ot||M.some((T)=>!T||T.length>IM||T.includes("\x00")))throw Error(`MCP sampling stop sequences must contain at most ${ot} non-empty bounded values`);let e=[],_=0,S=0,r=0,u=[];if(n.systemPrompt)_+=Buffer.byteLength(n.systemPrompt,"utf8"),e.push({role:"system",content:n.systemPrompt}),u.push(`System: ${st(n.systemPrompt)}`);for(let T of n.messages){let s=Array.isArray(T.content)?T.content:[T.content],P=[],w=[];for(let c of s){if(c.type==="text"){_+=Buffer.byteLength(c.text,"utf8"),P.push({type:"text",text:c.text}),w.push(st(c.text));continue}if(c.type==="image"){if(T.role!=="user")throw Error("MCP sampling images are only supported in user messages");if(!NM.has(c.mimeType))throw Error(`Unsupported MCP sampling image type: ${c.mimeType}`);let i=$M(c.data);S+=i,r++,P.push({type:"image_url",image_url:{url:`data:${c.mimeType};base64,${c.data}`}}),w.push(`[${c.mimeType} image, ${i} bytes]`);continue}throw Error(`Unsupported MCP sampling content type: ${c.type}`)}if(P.length===0)throw Error("MCP sampling message has no supported content");e.push({role:T.role,content:P.length===1&&P[0]?.type==="text"?P[0].text:P}),u.push(`${T.role==="user"?"User":"Assistant"}: ${w.join(" ")}`)}if(_+S>t.maxInputBytes)throw Error(`MCP sampling input exceeds ${t.maxInputBytes} bytes`);if(r>ct||S>bt)throw Error("MCP sampling image input exceeds the shared attachment budget");let E=W(n.maxTokens,1,Number.MAX_SAFE_INTEGER,"MCP sampling maxTokens");return{messages:e,maxTokens:Math.min(E,t.maxTokens),...n.temperature!==void 0?{temperature:n.temperature}:{},stopSequences:[...M],preview:u.join(`
21
+ `).slice(0,8000)}}function Q_(n,t,M){if(n.toolCalls?.length)throw Error("Model returned tools for basic MCP sampling");let e=n.content,_=n.finishReason==="length"||n.finishReason==="max_tokens"?"maxTokens":"endTurn",S=-1;for(let r of M.stopSequences){let u=e.indexOf(r);if(u>=0&&(S===-1||u<S))S=u}if(S>=0)e=e.slice(0,S),_="stopSequence";if(Buffer.byteLength(e,"utf8")>At)throw Error(`MCP sampling response exceeds ${At} bytes`);return{model:t,role:"assistant",content:{type:"text",text:e},stopReason:_}}function W(n,t,M,e){if(!Number.isSafeInteger(n)||n<t||n>M)throw Error(`${e} must be an integer between ${t} and ${M}`);return n}function $M(n){if(!n||n.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(n))throw Error("MCP sampling image contains invalid base64 data");return Buffer.from(n,"base64").byteLength}function st(n){return n.replace(/\s+/g," ").trim().slice(0,1000)}var W_=256,Z_=1e4,D_=86400000;var XM=/[\p{Cf}\p{Co}\p{Cn}]/u;function Pt(n){if(!n)return{enabled:!1,defaultTtlMs:600000,pollIntervalMs:500,maxTasksPerSession:32,maxLifetimeMs:1800000};if(typeof n.enabled!=="boolean")throw Error("MCP tasks.enabled must be a boolean");let t=N(n.defaultTtlMs??600000,1e4,86400000,"MCP tasks.defaultTtlMs"),M=N(n.maxLifetimeMs??1800000,1e4,86400000,"MCP tasks.maxLifetimeMs");if(t>M)throw Error("MCP tasks.defaultTtlMs must not exceed tasks.maxLifetimeMs");return{enabled:n.enabled,defaultTtlMs:t,pollIntervalMs:N(n.pollIntervalMs??500,100,1e4,"MCP tasks.pollIntervalMs"),maxTasksPerSession:N(n.maxTasksPerSession??32,1,32,"MCP tasks.maxTasksPerSession"),maxLifetimeMs:M}}function J_(n,t){return N(n??t.defaultTtlMs,1e4,Math.min(86400000,t.maxLifetimeMs),"MCP task ttl")}function k_(n,t,M){let e=gM(n.taskId,"task ID",512),_=xt(n.createdAt,"createdAt"),S=xt(n.lastUpdatedAt,"lastUpdatedAt");if(Date.parse(S)<Date.parse(_))throw Error("MCP task lastUpdatedAt precedes createdAt");if(M&&(e!==M.taskId||_!==M.createdAt))throw Error("MCP task identity changed across connection generation");let r=n.ttl===null?null:N(n.ttl,0,86400000,"MCP task ttl"),u=n.pollInterval===void 0?t.pollIntervalMs:N(n.pollInterval,0,Number.MAX_SAFE_INTEGER,"MCP task pollInterval"),E=Math.min(1e4,Math.max(100,u)),T=n.statusMessage?pM(n.statusMessage,e):void 0;return{taskId:e,status:n.status,createdAt:_,lastUpdatedAt:S,ttl:r,pollIntervalMs:E,...T?{statusMessage:T}:{}}}function O_(n){return["completed","failed","cancelled"].includes(n)}function j_(n){let t=n instanceof Error?n.message:String(n);return Lt(en(t.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")),1024)}function pM(n,t){return Lt(en(n.replaceAll(t,"[redacted-task-id]")),1024)}function en(n){return[...n.normalize("NFKC")].filter((t)=>{let M=t.codePointAt(0)??0;if(M===0||M>=1&&M<=8||M===11||M===12||M>=14&&M<=31||M===127)return!1;return!XM.test(t)}).join("").trim()}function xt(n,t){let M=Date.parse(n);if(!Number.isFinite(M))throw Error(`MCP task ${t} is invalid`);return new Date(M).toISOString()}function gM(n,t,M){if(!n||Buffer.byteLength(n)>M||en(n)!==n)throw Error(`MCP ${t} is invalid`);return n}function N(n,t,M,e){if(!Number.isSafeInteger(n)||n<t||n>M)throw Error(`${e} must be an integer between ${t} and ${M}`);return n}function Lt(n,t){let M=Buffer.from(n);if(M.length<=t)return n;let e=M.subarray(0,t).toString("utf8");while(Buffer.byteLength(e)>t)e=e.slice(0,-1);return e}var iM={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function rn(n){let t=n.toLowerCase().trim();return iM[t]??n}var RM=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/,CM=/^\.[A-Za-z0-9_+-]{1,32}$/;function Z(n){return n!==null&&typeof n==="object"&&!Array.isArray(n)}function p(n,t,M,e,_){if(n===void 0)return _;if(!Number.isInteger(n)||Number(n)<M||Number(n)>e)throw Error(`${t} must be an integer between ${M} and ${e}`);return Number(n)}function at(n,t){if(n===void 0)return;let M;try{M=JSON.stringify(n)}catch{throw Error(`${t} must be JSON serializable`)}if(M===void 0||Buffer.byteLength(M)>262144)throw Error(`${t} exceeds the 256 KiB limit`);return structuredClone(n)}function zM(n,t){if(n===void 0)return{};if(!Z(n))throw Error(`${t} must be an object`);let M={};for(let[e,_]of Object.entries(n)){if(!e||typeof _!=="string"||_.includes("\x00"))throw Error(`${t} must contain non-empty string values`);M[e]=_}return M}function d(n){if(n===void 0)return{};if(!Z(n))throw Error("lspServers must be an object");let t=Object.entries(n);if(t.length>32)throw Error("lspServers exceeds the 32-server limit");let M={};for(let[e,_]of t){if(!RM.test(e))throw Error(`Invalid LSP server name: ${e}`);if(!Z(_))throw Error(`lspServers.${e} must be an object`);let S=new Set(["command","args","extensionToLanguage","env","initializationOptions","settings","enabled","priority","startupTimeout","shutdownTimeout","requestTimeout","diagnosticWaitTimeout","maxRestarts"]),r=Object.keys(_).filter((w)=>!S.has(w));if(r.length>0)throw Error(`Unknown LSP server field: ${e}.${r[0]}`);if(typeof _.command!=="string"||!_.command.trim()||_.command.includes("\x00")||_.command.includes(`
22
+ `))throw Error(`lspServers.${e}.command must be a non-empty command`);if(_.args!==void 0&&!Array.isArray(_.args))throw Error(`lspServers.${e}.args must be an array`);let u=(_.args??[]).map((w,c)=>{if(typeof w!=="string"||w.includes("\x00"))throw Error(`lspServers.${e}.args.${c} must be a string`);return w});if(u.length>128)throw Error(`lspServers.${e}.args exceeds the 128-item limit`);if(!Z(_.extensionToLanguage))throw Error(`lspServers.${e}.extensionToLanguage must be an object`);let E=Object.entries(_.extensionToLanguage);if(E.length===0||E.length>64)throw Error(`lspServers.${e}.extensionToLanguage must contain 1-64 entries`);let T={};for(let[w,c]of E){let i=w.startsWith(".")?w.toLowerCase():`.${w.toLowerCase()}`;if(!CM.test(i)||typeof c!=="string"||!c.trim())throw Error(`Invalid lspServers.${e}.extensionToLanguage entry: ${w}`);T[i]=c.trim()}if(_.enabled!==void 0&&typeof _.enabled!=="boolean")throw Error(`lspServers.${e}.enabled must be a boolean`);let s=at(_.initializationOptions,`lspServers.${e}.initializationOptions`),P=at(_.settings,`lspServers.${e}.settings`);M[e]={command:_.command.trim(),...u.length>0?{args:u}:{},extensionToLanguage:T,..._.env!==void 0?{env:zM(_.env,`lspServers.${e}.env`)}:{},...s!==void 0?{initializationOptions:s}:{},...P!==void 0?{settings:P}:{},..._.enabled!==void 0?{enabled:_.enabled}:{},priority:p(_.priority,`lspServers.${e}.priority`,-1000,1000,0),startupTimeout:p(_.startupTimeout,`lspServers.${e}.startupTimeout`,100,60000,1e4),shutdownTimeout:p(_.shutdownTimeout,`lspServers.${e}.shutdownTimeout`,100,1e4,2000),requestTimeout:p(_.requestTimeout,`lspServers.${e}.requestTimeout`,100,60000,1e4),diagnosticWaitTimeout:p(_.diagnosticWaitTimeout,`lspServers.${e}.diagnosticWaitTimeout`,0,5000,750),maxRestarts:p(_.maxRestarts,`lspServers.${e}.maxRestarts`,0,10,3)}}return M}function ht(n){return Number.isInteger(n)&&(n===-1||n>=0)}function dt(){return"-1 (unlimited), 0 (disabled), or any positive integer"}import ft from"node:path";var It=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,BM=/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;function z(n){let t=[];for(let[M,e]of Object.entries(n)){if(!It.test(M))throw Error(`Invalid plugin name in enabledPlugins: ${M}`);if(typeof e!=="boolean")throw Error(`Invalid enabledPlugins value for ${M}`);t.push([M,e])}return Object.fromEntries(t)}function Sn(n,t,M){if(!Array.isArray(n))throw Error(`${t} must be an array`);return[...new Set(n.map((e,_)=>{if(typeof e!=="string"||!e.trim())throw Error(`${t}[${_}] must be a non-empty string`);return M(e.trim())}))].sort()}function B(n){let t=new Set(["restrictToAllowedSources","requireGitCommitSha","allowedGitHosts","allowedMarketplaces","allowedLocalRoots"]),M=Object.keys(n).filter((_)=>!t.has(_));if(M.length>0)throw Error(`Unknown pluginSourcePolicy fields: ${M.join(", ")}`);let e={};for(let _ of["restrictToAllowedSources","requireGitCommitSha"]){if(n[_]===void 0)continue;if(typeof n[_]!=="boolean")throw Error(`pluginSourcePolicy.${_} must be boolean`);e[_]=n[_]}if(n.allowedGitHosts!==void 0)e.allowedGitHosts=Sn(n.allowedGitHosts,"pluginSourcePolicy.allowedGitHosts",(_)=>{let S=_.toLowerCase();if(!BM.test(S))throw Error(`Invalid plugin Git host pattern: ${_}`);return S});if(n.allowedMarketplaces!==void 0)e.allowedMarketplaces=Sn(n.allowedMarketplaces,"pluginSourcePolicy.allowedMarketplaces",(_)=>{if(!It.test(_))throw Error(`Invalid allowed Marketplace name: ${_}`);return _});if(n.allowedLocalRoots!==void 0)e.allowedLocalRoots=Sn(n.allowedLocalRoots,"pluginSourcePolicy.allowedLocalRoots",(_)=>{if(!ft.isAbsolute(_))throw Error(`Plugin local allowlist root must be absolute: ${_}`);return ft.resolve(_)});return e}function D(n){let t=[];for(let[M,e]of Object.entries(n)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(M))throw Error(`Invalid environment variable name: ${M}`);if(typeof e!=="string"||e.includes("\x00"))throw Error(`Invalid environment variable value: ${M}`);t.push([M,e])}return Object.fromEntries(t)}class g{static instance=null;runtimePermissionOverrides;lastAdditionalSettings;constructor(){}static getInstance(){if(!g.instance)g.instance=new g;return g.instance}static resetInstance(){g.instance=null}async initialize(n){try{this.lastAdditionalSettings=n,this.runtimePermissionOverrides=n?.permissions;let M=(await h.getInstance().getStatus(x())).state==="trusted",e=await this.loadConfigFiles(M),_=await this.loadSettingsFiles(M),S={...e,..._,enabledPlugins:{...e.enabledPlugins||{},..._.enabledPlugins||{}}};if(n)S=this.mergeSettings(S,n);let r=this.normalizeConfig(S),u={...A,...r};if(u.enabledPlugins=z(u.enabledPlugins),u.lspServers=d(u.lspServers),u.pluginSourcePolicy={...A.pluginSourcePolicy,...B(u.pluginSourcePolicy)},this.resolveEnvInterpolation(u),process.env.BLADE_MODEL&&u.models?.length>0){let E=rn(process.env.BLADE_MODEL),T=u.models.find((s)=>s.id===E||s.model===E||s.id===process.env.BLADE_MODEL||s.model===process.env.BLADE_MODEL);if(T)u.currentModelId=T.id}if(process.env.BLADE_DEBUG)u.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(J().configureModelProviders(u.modelProviders,u.models),u.models.length>0)this.validateConfig(u);if(u.debug)console.log("[ConfigManager] Configuration loaded successfully");return u}catch(t){return console.error("[ConfigManager] Failed to initialize:",t),J().configureModelProviders({},[]),A}}async reload(){return this.initialize(this.lastAdditionalSettings)}async loadConfigFiles(n){let t=m.join(b.homedir(),".blade","config.json"),M=m.join(x(),".blade","config.json"),e={},_=await this.loadJsonFile(t),S=_?await this.migrateLegacyUserConfig(_):null;if(S)e={...e,...S};let r=await this.loadJsonFile(M);if(r&&n){let u={...e.mcpServers||{},...r.mcpServers||{}},E={...e.lspServers||{},...r.lspServers||{}},T={...e.modelProviders||{},...r.modelProviders||{}},s={...e.enabledPlugins||{},...r.enabledPlugins||{}};if(e={...e,...r},Object.keys(u).length>0)e.mcpServers=u;if(Object.keys(E).length>0)e.lspServers=d(E);if(Object.keys(T).length>0)e.modelProviders=T;if(Object.keys(s).length>0)e.enabledPlugins=z(s)}else if(r?.hooks)e.hooks=r.hooks;return e}async migrateLegacyUserConfig(n){let t=n,M={...n},e={};if(M.codeTheme===void 0&&typeof t.theme==="string")M.codeTheme=t.theme,e.codeTheme=t.theme;if(Array.isArray(M.models)){let _=ln(M.models,M.currentModelId??"");if(_.changed)M.models=_.models,M.currentModelId=_.currentModelId,e.models=_.models,e.currentModelId=_.currentModelId}if(delete M.theme,Object.keys(e).length>0)try{await a.getInstance().save(e,{scope:"global",immediate:!0})}catch{console.warn("[ConfigManager] Could not persist legacy config migration")}return M}async loadSettingsFiles(n){let t=m.join(b.homedir(),".blade","settings.json"),M=m.join(x(),".blade","settings.json"),e=m.join(x(),".blade","settings.local.json"),_={},S=await this.loadJsonFile(t);if(S)_=this.mergeSettings(_,S);let r=await this.loadJsonFile(M);if(r&&n)_=this.mergeSettings(_,r);else if(r?.hooks)_=this.mergeSettings(_,{hooks:r.hooks});let u=await this.loadJsonFile(e);if(u&&n)_=this.mergeSettings(_,u);else if(u?.hooks)_=this.mergeSettings(_,{hooks:u.hooks});return _}async loadWorkspacePermissions(n,t){let M={allow:[...t.allow],ask:[...t.ask],deny:[...t.deny]};if(m.resolve(n)!==m.resolve(x())){let _=await this.loadWorkspacePermissionOverrides(x(),{includeUntrusted:!0}),S=await this.loadJsonFile(m.join(b.homedir(),".blade","settings.json")),r={allow:Array.from(new Set([...A.permissions.allow,...S?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...A.permissions.ask,...S?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...A.permissions.deny,...S?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let u of["allow","ask","deny"]){let E=new Set(_[u].filter((T)=>!r[u].includes(T)));M[u]=M[u].filter((T)=>!E.has(T))}}let e=await this.loadWorkspacePermissionOverrides(n);for(let _ of["allow","ask","deny"])M[_]=Array.from(new Set([...M[_],...e[_]]));return M}async loadWorkspaceMcpServers(n,t){if(m.resolve(n)===m.resolve(x()))return{...t};let M=await h.getInstance().getStatus(n),e=M.state==="trusted",_=M.projectPath,S={},r=async(E)=>{let T=await this.loadJsonFile(E);if(T?.mcpServers)S={...S,...T.mcpServers}};if(await r(m.join(b.homedir(),".blade","config.json")),await r(m.join(b.homedir(),".blade","settings.json")),e)await r(m.join(_,".blade","config.json")),await r(m.join(_,".blade","settings.json")),await r(m.join(_,".blade","settings.local.json"));if(this.lastAdditionalSettings?.mcpServers)S={...S,...this.lastAdditionalSettings.mcpServers};let u={mcpServers:S};return this.resolveEnvInterpolation(u),u.mcpServers}async loadWorkspaceLspServers(n,t){if(m.resolve(n)===m.resolve(x()))return d(t);let M=await h.getInstance().getStatus(n),e={},_=async(r)=>{let u=await this.loadJsonFile(r);if(u?.lspServers)e={...e,...d(u.lspServers)}};if(await _(m.join(b.homedir(),".blade","config.json")),await _(m.join(b.homedir(),".blade","settings.json")),M.state==="trusted")for(let r of["config.json","settings.json","settings.local.json"])await _(m.join(M.projectPath,".blade",r));if(this.lastAdditionalSettings?.lspServers)e={...e,...d(this.lastAdditionalSettings.lspServers)};let S={lspServers:e};return this.resolveEnvInterpolation(S),d(S.lspServers)}async loadWorkspaceModelConfig(n,t){if(m.resolve(n)===m.resolve(x()))return{currentModelId:t.currentModelId,models:t.models.map((r)=>structuredClone(r)),modelProviders:structuredClone(t.modelProviders),temperature:t.temperature,...t.maxOutputTokens!==void 0?{maxOutputTokens:t.maxOutputTokens}:{},timeout:t.timeout,...t.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:t.providerCircuitBreakerOpenMs}:{},...t.providerRequestConcurrency!==void 0?{providerRequestConcurrency:t.providerRequestConcurrency}:{},...t.providerGlobalConcurrency!==void 0?{providerGlobalConcurrency:t.providerGlobalConcurrency}:{},...t.providerOwnerConcurrency!==void 0?{providerOwnerConcurrency:t.providerOwnerConcurrency}:{},...t.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:t.providerRequestAdmissionMs}:{},...t.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:t.providerRequestPendingBytes}:{}};let M=await h.getInstance().getStatus(n),e=M.projectPath,_={currentModelId:A.currentModelId,models:A.models.map((r)=>structuredClone(r)),modelProviders:structuredClone(A.modelProviders),temperature:A.temperature,...A.maxOutputTokens!==void 0?{maxOutputTokens:A.maxOutputTokens}:{},timeout:A.timeout,...A.providerCircuitBreakerOpenMs!==void 0?{providerCircuitBreakerOpenMs:A.providerCircuitBreakerOpenMs}:{},...A.providerRequestConcurrency!==void 0?{providerRequestConcurrency:A.providerRequestConcurrency}:{},...A.providerGlobalConcurrency!==void 0?{providerGlobalConcurrency:A.providerGlobalConcurrency}:{},...A.providerOwnerConcurrency!==void 0?{providerOwnerConcurrency:A.providerOwnerConcurrency}:{},...A.providerRequestAdmissionMs!==void 0?{providerRequestAdmissionMs:A.providerRequestAdmissionMs}:{},...A.providerRequestPendingBytes!==void 0?{providerRequestPendingBytes:A.providerRequestPendingBytes}:{}},S=(r)=>{if(!r)return;if(r.modelProviders)_.modelProviders={..._.modelProviders,...structuredClone(r.modelProviders)};if(r.models)_.models=r.models.map((u)=>structuredClone(u));if(r.currentModelId!==void 0)_.currentModelId=r.currentModelId;if(r.temperature!==void 0)_.temperature=r.temperature;if(r.maxOutputTokens!==void 0)_.maxOutputTokens=r.maxOutputTokens;if(r.timeout!==void 0)_.timeout=r.timeout;if(r.providerCircuitBreakerOpenMs!==void 0)_.providerCircuitBreakerOpenMs=r.providerCircuitBreakerOpenMs;if(r.providerRequestConcurrency!==void 0)_.providerRequestConcurrency=r.providerRequestConcurrency;if(r.providerGlobalConcurrency!==void 0)_.providerGlobalConcurrency=r.providerGlobalConcurrency;if(r.providerOwnerConcurrency!==void 0)_.providerOwnerConcurrency=r.providerOwnerConcurrency;if(r.providerRequestAdmissionMs!==void 0)_.providerRequestAdmissionMs=r.providerRequestAdmissionMs;if(r.providerRequestPendingBytes!==void 0)_.providerRequestPendingBytes=r.providerRequestPendingBytes};if(S(await this.loadJsonFile(m.join(b.homedir(),".blade","config.json"))),S(await this.loadJsonFile(m.join(b.homedir(),".blade","settings.json"))),M.state==="trusted")S(await this.loadJsonFile(m.join(e,".blade","config.json"))),S(await this.loadJsonFile(m.join(e,".blade","settings.json"))),S(await this.loadJsonFile(m.join(e,".blade","settings.local.json")));if(S(this.lastAdditionalSettings),_=this.normalizeConfig(_),this.resolveEnvInterpolation(_),process.env.BLADE_MODEL&&_.models.length>0){let r=process.env.BLADE_MODEL,u=rn(r),E=_.models.find((T)=>T.id===u||T.model===u||T.id===r||T.model===r);if(E)_.currentModelId=E.id}if(!_.models.some((r)=>r.id===_.currentModelId))_.currentModelId=_.models[0]?.id??"";return _}async loadWorkspaceRuntimeSettings(n,t){if(m.resolve(n)===m.resolve(x()))return{env:D(t.env),disableAllHooks:t.disableAllHooks,maxTurns:t.maxTurns,permissionMode:t.permissionMode};let M=await h.getInstance().getStatus(n),e=M.projectPath,_={env:{},disableAllHooks:A.disableAllHooks,maxTurns:A.maxTurns,permissionMode:A.permissionMode},S=(E,T)=>{if(!E)return;if(T.allowExecutionSettings){if(E.env)_.env={..._.env,...D(E.env)};if(E.maxTurns!==void 0)_.maxTurns=E.maxTurns;if(E.permissionMode!==void 0)_.permissionMode=E.permissionMode;if(E.disableAllHooks!==void 0)_.disableAllHooks=E.disableAllHooks}else if(E.disableAllHooks===!0)_.disableAllHooks=!0};S(await this.loadJsonFile(m.join(b.homedir(),".blade","config.json")),{allowExecutionSettings:!0}),S(await this.loadJsonFile(m.join(b.homedir(),".blade","settings.json")),{allowExecutionSettings:!0});let r=await Promise.all([this.loadJsonFile(m.join(e,".blade","config.json")),this.loadJsonFile(m.join(e,".blade","settings.json")),this.loadJsonFile(m.join(e,".blade","settings.local.json"))]);for(let E of r)S(E,{allowExecutionSettings:M.state==="trusted"});S(this.lastAdditionalSettings,{allowExecutionSettings:!0});let u={env:_.env};return this.resolveEnvInterpolation(u),_.env=D(u.env),_}async loadWorkspacePluginSettings(n){return(await this.loadWorkspacePluginSettingsResolution(n)).effective}async loadWorkspacePluginSettingsResolution(n){let t=await h.getInstance().getStatus(n),M={},e={},_=(S,r,u)=>{if(!S?.enabledPlugins)return;let E=z(S.enabledPlugins);for(let[T,s]of Object.entries(E)){if(!u&&s!==!1)continue;let P=e[T];M[T]=s,e[T]={effective:s,effectiveScope:r,layers:{...P?.layers??{},[r]:s}}}};_(await this.loadJsonFile(m.join(b.homedir(),".blade","config.json")),"global",!0),_(await this.loadJsonFile(m.join(b.homedir(),".blade","settings.json")),"global",!0);for(let S of["config.json","settings.json"])_(await this.loadJsonFile(m.join(t.projectPath,".blade",S)),"project",t.state==="trusted");return _(await this.loadJsonFile(m.join(t.projectPath,".blade","settings.local.json")),"local",t.state==="trusted"),_(this.lastAdditionalSettings,"invocation",!0),{effective:M,settings:e,workspaceTrusted:t.state==="trusted"}}async loadWorkspacePluginSourcePolicy(n){let t=await h.getInstance().getStatus(n),M={...A.pluginSourcePolicy,allowedGitHosts:[...A.pluginSourcePolicy.allowedGitHosts],allowedMarketplaces:[...A.pluginSourcePolicy.allowedMarketplaces],allowedLocalRoots:[...A.pluginSourcePolicy.allowedLocalRoots]},e=(r)=>{if(!r?.pluginSourcePolicy)return;Object.assign(M,B(r.pluginSourcePolicy))},_=(r,u)=>{if(!u)return r;if(r.length===0&&!M.restrictToAllowedSources)return u;let E=new Set(u);return r.filter((T)=>E.has(T))},S=(r)=>{if(!r?.pluginSourcePolicy)return;let u=B(r.pluginSourcePolicy);M.allowedGitHosts=_(M.allowedGitHosts,u.allowedGitHosts),M.allowedMarketplaces=_(M.allowedMarketplaces,u.allowedMarketplaces),M.allowedLocalRoots=_(M.allowedLocalRoots,u.allowedLocalRoots),M.restrictToAllowedSources=M.restrictToAllowedSources||u.restrictToAllowedSources===!0,M.requireGitCommitSha=M.requireGitCommitSha||u.requireGitCommitSha===!0};e(await this.loadJsonFile(m.join(b.homedir(),".blade","config.json"))),e(await this.loadJsonFile(m.join(b.homedir(),".blade","settings.json")));for(let r of["config.json","settings.json","settings.local.json"])S(await this.loadJsonFile(m.join(t.projectPath,".blade",r)));if(S(this.lastAdditionalSettings),process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true")M.requireGitCommitSha=!0;return M}async loadWorkspaceHooks(n,t,M={}){if(m.resolve(n)===m.resolve(x())&&M.includeBaseForCurrentWorkspace!==!1)return K({},t);let e=K({},A.hooks),_=[m.join(b.homedir(),".blade","settings.json"),m.join(n,".blade","settings.json"),m.join(n,".blade","settings.local.json")];for(let S of _){let r=await this.loadJsonFile(S);if(r?.hooks)e=K({},e,r.hooks)}return e}async loadWorkspacePermissionOverrides(n,t={}){let M={allow:[],ask:[],deny:[]},e=(await h.getInstance().getStatus(n)).state==="trusted",_=[...e||t.includeUntrusted?[m.join(n,".blade","settings.json")]:[],...e||t.includeUntrusted?[m.join(n,".blade","settings.local.json")]:[]];for(let S of _){let r=await this.loadJsonFile(S);if(!r?.permissions)continue;for(let u of["allow","ask","deny"])M[u]=Array.from(new Set([...M[u],...r.permissions[u]||[]]))}return M}mergeSettings(n,t){let M={...JSON.parse(JSON.stringify(n)),...JSON.parse(JSON.stringify(t))};if(t.permissions)M.permissions={allow:Array.from(new Set([...n.permissions?.allow||[],...t.permissions.allow||[]])),ask:Array.from(new Set([...n.permissions?.ask||[],...t.permissions.ask||[]])),deny:Array.from(new Set([...n.permissions?.deny||[],...t.permissions.deny||[]]))};if(t.hooks)M.hooks=K({},M.hooks,t.hooks);if(t.enabledPlugins)M.enabledPlugins={...n.enabledPlugins||{},...z(t.enabledPlugins)};if(t.pluginSourcePolicy)M.pluginSourcePolicy={...n.pluginSourcePolicy??A.pluginSourcePolicy,...B(t.pluginSourcePolicy)};if(t.env)M.env=K({},M.env,t.env);if(t.mcpServers)M.mcpServers={...M.mcpServers||{},...t.mcpServers};if(t.lspServers)M.lspServers={...M.lspServers||{},...d(t.lspServers)};if(t.disableAllHooks!==void 0)M.disableAllHooks=t.disableAllHooks;if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;return M}resolveEnvInterpolation(n){let t=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,M=(_)=>{if(typeof _==="string")return _.replace(t,(S,r,u,E)=>{return process.env[r]||E||S});if(Array.isArray(_))return _.map(M);if(typeof _==="object"&&_!==null){let S=_;for(let[r,u]of Object.entries(S))S[r]=M(u);return S}return _},e=n;for(let[_,S]of Object.entries(e))e[_]=M(S)}async loadJsonFile(n){try{if(await this.fileExists(n)){let t=await Nt.readFile(n,"utf-8");return JSON.parse(t)}}catch(t){console.warn(`[ConfigManager] Failed to load ${n}:`,t)}return null}async fileExists(n){try{return await Nt.access(n),!0}catch{return!1}}normalizeConfig(n){let t=JSON.parse(JSON.stringify(n));if(t.codeTheme===void 0&&typeof t.theme==="string")t.codeTheme=t.theme;delete t.theme;let M=(_)=>_.trim().replace(/^`|`$/g,""),e=(_)=>{for(let[S,r]of Object.entries(_))if(typeof r==="string")_[S]=M(r);else if(Array.isArray(r))r.forEach((u,E)=>{if(typeof u==="string")r[E]=M(u);else if(typeof u==="object"&&u!==null)e(u)});else if(typeof r==="object"&&r!==null)e(r)};return e(t),t}validateConfig(n,t=J()){let M=[];try{n.lspServers=d(n.lspServers)}catch(e){M.push(e instanceof Error?e.message:"Invalid LSP server configuration")}for(let[e,_]of Object.entries(n.mcpServers||{}))try{nt(_),_.oauth=k(_);let S=rt(_);if(_.logging!==void 0)_.logging=S;if(_.sampling)_.sampling=wt(_.sampling);if(_.tasks)_.tasks=Pt(_.tasks)}catch(S){M.push(`MCP server "${e}": ${S instanceof Error?S.message:"invalid sampling policy"}`)}for(let[e,_]of Object.entries(n.modelProviders||{}))if(M.push(...$t(e,_)),t.isReservedProviderId(e))M.push(`modelProviders.${e}: built-in provider ids cannot be overridden`);if(M.length===0)try{t.configureModelProviders(n.modelProviders||{},n.models)}catch(e){M.push(e instanceof Error?e.message:"Failed to configure custom model providers")}if(!n.models||n.models.length===0)M.push("没有可用的模型配置");if(!ht(n.maxTurns))M.push(`maxTurns 必须是 ${dt()}`);if(!Wn(n.maxConcurrentTasks))M.push(`maxConcurrentTasks 必须是 ${Un}-${Hn} 之间的整数`);if(!Zn(n.maxQueuedTasks))M.push(`maxQueuedTasks 必须是 ${Yn}-${qn} 之间的整数`);if(!Dn(n.maxQueuedTaskBytes))M.push(`maxQueuedTaskBytes 必须是 ${Qn}-${Gn} 之间的整数`);if(!Bn(n.maxResidentSessionRuntimes))M.push(`maxResidentSessionRuntimes 必须是 ${Xn}-${gn} 之间的整数`);if(!Kn(n.sessionRuntimeIdleMs))M.push(`sessionRuntimeIdleMs 必须是 ${Rn}-${zn} 之间的整数`);if(n.bashForegroundHandoffMs!==void 0&&!tn(n.bashForegroundHandoffMs))M.push("bashForegroundHandoffMs 必须是 0,或 "+`${Nn}-${$n} 之间的整数`);if(n.providerForegroundRecoveryMs!==void 0&&!gt(n.providerForegroundRecoveryMs))M.push("providerForegroundRecoveryMs 必须是 0,或 "+`${Xt}-${pt} 之间的整数`);if(n.providerCircuitBreakerOpenMs!==void 0&&!Ct(n.providerCircuitBreakerOpenMs))M.push("providerCircuitBreakerOpenMs 必须是 0,或 "+`${it}-${Rt} 之间的整数`);if(n.providerRequestConcurrency!==void 0&&!qt(n.providerRequestConcurrency))M.push("providerRequestConcurrency 必须是 "+`${un}-${zt} 之间的整数`);for(let[e,_]of[["providerGlobalConcurrency",n.providerGlobalConcurrency],["providerOwnerConcurrency",n.providerOwnerConcurrency]])if(_!==void 0&&!Vt(_))M.push(`${e} 必须是 ${un}-${Bt} 之间的整数`);if(n.providerRequestAdmissionMs!==void 0&&!Qt(n.providerRequestAdmissionMs))M.push("providerRequestAdmissionMs 必须是 0,或 "+`${Kt}-${Ut} 之间的整数`);if(n.providerRequestPendingBytes!==void 0&&!Gt(n.providerRequestPendingBytes))M.push("providerRequestPendingBytes 必须是 "+`${Ht}-${Yt} 之间的整数`);if(n.models&&n.models.length>0){if(!n.currentModelId)M.push("未设置当前模型 ID");else if(!n.models.find((_)=>_.id===n.currentModelId))M.push(`当前模型 ID "${n.currentModelId}" 在 models 列表中不存在`);for(let e of n.models){let _=`模型 "${e.displayName||e.id}"`,S=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((u)=>(u in e));if(S.length>0)M.push(`${_}: 不再支持旧字段 ${S.join(", ")};请重新配置模型`);if(!e.model)M.push(`${_}: model 字段必填`);if(!e.provider)M.push(`${_}: provider 字段必填`);if(e.overrides?.baseUrl&&!e.overrides.baseUrl.startsWith("http"))M.push(`${_}: overrides.baseUrl "${e.overrides.baseUrl}" 不是有效的 HTTP URL`);let r=e.overrides?.streamIdleTimeout;if(r!==void 0&&(!Number.isFinite(r)||r<1000))M.push(`${_}: overrides.streamIdleTimeout 必须至少为 1000ms`);try{t.getModel(e.provider,e.model)}catch{M.push(`${_}: 内置 catalog 中不存在 ${e.provider}/${e.model}`)}}}if(M.length>0)throw Error(`配置验证失败:
23
+ ${M.map((e)=>` - ${e}`).join(`
24
+ `)}
25
+
26
+ `+`请通过以下方式之一提供配置:
27
+ `+` 1. 首次启动: 运行 blade,系统会自动引导配置
28
+ `+` 2. 添加模型: blade 后输入 /model add
29
+ `+` 3. 初始化向导: 输入 /init
30
+
31
+ `+`配置文件示例 (~/.blade/config.json):
32
+ `+`{
33
+ "currentModelId": "model-id-123",
34
+ "models": [
35
+ {
36
+ "id": "model-id-123",
37
+ `+` "displayName": "默认模型",
38
+ `+` "provider": "deepseek",
39
+ "model": "deepseek-v4-pro"
40
+ }
41
+ ]
42
+ }
43
+ `)}}function ze(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;if(t.maxQueuedTaskBytes!==void 0)M.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)M.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)M.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;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 mf,k as nf,I as of,nn as pf,an as qf,$ as rf,nt as sf,i_ as tf,Q as uf,z_ as vf,B_ as wf,K_ as xf,rt as yf,PM as zf,U_ as Af,LM as Bf,H_ as Cf,wt as Df,V_ as Ef,Q_ as Ff,W_ as Gf,Z_ as Hf,D_ as If,Pt as Jf,J_ as Kf,k_ as Lf,O_ as Mf,j_ as Nf,s_ as Of,Nn as Pf,$n as Qf,b_ as Rf,Xn as Sf,pn as Tf,gn as Uf,Rn as Vf,Cn as Wf,zn as Xf,x_ as Yf,Bn as Zf,Kn as _f,Un as $f,Hn as ag,Yn as bg,qn as cg,Vn as dg,Qn as eg,Gn as fg,Wn as gg,Zn as hg,Dn as ig,A as jg,d as kg,mM as lg,B as mg,D as ng,g as og,ze as pg};
@@ -1,2 +1,2 @@
1
1
  import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
2
- export{G as af,F as bf,R as cf,v as df};
2
+ export{G as if,F as jf,R as kf,v as lf};
@@ -1,2 +1,2 @@
1
1
  var i="verification",E="goal-verification",e="review";function t(n){return n==="verification"||n==="goal-verification"}function o(n){return t(n)||n==="review"}
2
- export{i as Oe,E as Pe,e as Qe,t as Re,o as Se};
2
+ export{i as We,E as Xe,e as Ye,t as Ze,o as _e};
@@ -1,4 +1,4 @@
1
- import{Oe as j1,Pe as L0,Qe as F1}from"./chunk-hat9v5c5.js";import{Ue as WO,Ve as IO}from"./chunk-cdy9efgm.js";import{Ye as B1}from"./chunk-zvz2cnt4.js";import{$e as J0,Ze as b0}from"./chunk-4ke8k0xw.js";import{bg as z0,cg as $O,gg as I0}from"./chunk-82htkvz8.js";import{kg as u,mg as L,pg as P1}from"./chunk-v0rsz1rt.js";import{wg as M}from"./chunk-k0pa8874.js";import{Xg as k,Yg as z}from"./chunk-t2wgf9tq.js";import{jh as g0}from"./chunk-azw0jckv.js";import{qh as N}from"./chunk-jzntxp7f.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
1
+ import{We as j1,Xe as L0,Ye as F1}from"./chunk-4khtsmrf.js";import{af as WO,bf as IO}from"./chunk-yvnm25nb.js";import{ef as B1}from"./chunk-jkh9s1ht.js";import{ff as b0,hf as J0}from"./chunk-67ddp3ns.js";import{jg as z0,kg as $O,og as I0}from"./chunk-4cpgcm7q.js";import{sg as u,ug as L,xg as P1}from"./chunk-k82ff14t.js";import{Eg as M}from"./chunk-ah12xhh6.js";import{eh as k,fh as z}from"./chunk-tzytnhbp.js";import{sh as g0}from"./chunk-xjc0bthz.js";import{zh as N}from"./chunk-1ava19kd.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -716,4 +716,4 @@ ${Z.join(`
716
716
  </${Q}>`:"";return{content:q,files:[...O],references:O.map(n$),triggerPaths:[...$],contentBytes:Buffer.byteLength(q,"utf8"),provenanceSha256:w0(O.map((K)=>`${K.id}:${K.contentSha256}`).join(`
717
717
  `))}}function BO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let q=O[J];if(!q)continue;let K=Buffer.byteLength(q.content,"utf8");if(K>Q)continue;Z.push(q),Q-=K}return Z.reverse()}class d{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=K1(O),this.definitions=Object.freeze([...$].sort(G1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=w0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
718
718
  `))}static empty(O){return new d(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new d(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=k$){if(this.definitions.length===0)return K0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&q1(J.scopeDirectory,Q));return K0(BO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=P$){if(this.definitions.length===0)return K0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),q=[...new Set($.map((G)=>L1(S.relative(this.projectRoot,K1(G)))).filter(X1))].sort(),K=new Map;for(let G of q)for(let W of this.definitions){if(Q.has(W.id))continue;if(!q1(W.scopeDirectory,G))continue;if(W.conditional){let Y=S.posix.relative(W.scopeDirectory||".",G);if(!W.patterns?.some((V)=>zO(V,{dot:!0})(Y)))continue}else if(q1(W.scopeDirectory,J))continue;K.set(W.id,W)}let X=BO([...K.values()].sort(G1),Z);return K0(X,q,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return K0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(G1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=L1(S.relative(this.projectRoot,K1(O)));if($&&!X1($))throw Error("Project instruction source is outside the catalog root");return $}}async function i$(O,$){let Q=await m.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>FO)throw Error(`Project rule exceeds ${FO} bytes`);let Z=await m.realpath($),J=L1(S.relative(O,Z));if(!X1(J))throw Error("Project rule escapes its repository root");let q=await m.readFile(Z,"utf8");if(SO(q))throw Error("Project rule contains hidden control characters");let K=h$(q),X=K.content.trim();if(!X)throw Error("Project rule content must not be empty");let G=l$(K.data.paths),W=s$(J),Y=w0(JSON.stringify({relativePath:J,patterns:G??[],content:X}));return{id:`${W.source}:${w0(J).slice(0,20)}`,relativePath:J,source:W.source,kind:W.kind,scopeDirectory:W.scopeDirectory,priority:W.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:X,contentSha256:Y}}async function MO(O,$){let Q=c$(O);if(!$.projectTrusted)return d.empty(Q);let Z=await m.realpath(Q),J=f$.stream([...g$],{cwd:Z,absolute:!0,dot:!0,deep:d$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...u$]}),q=[];for await(let W of J)if(q.push(W.toString()),q.length>HO)throw Error(`Project rule catalog exceeds ${HO} files`);q.sort();let K=new Set(q.filter((W)=>S.basename(W)==="AGENTS.override.md").map((W)=>S.dirname(W))),X=[],G=0;for(let W of q){if(S.basename(W)==="AGENTS.md"&&K.has(S.dirname(W)))continue;try{let Y=await i$(Z,W);if(G+=Buffer.byteLength(Y.content,"utf8"),G>VO)throw Error(`Project rule catalog exceeds ${VO} bytes`);X.push(Y)}catch(Y){p$.warn(`[ProjectRules] Ignoring rule: ${Y instanceof Error?Y.message:String(Y)}`)}}return new d(Z,X)}var bO=32,D0=64;class AO extends Error{capacity=D0;constructor(){super(`Workspace agent resource capacity is full (${D0})`);this.name="WorkspaceAgentResourceCapacityError"}}var x=new Map,W1=0,xO=[];async function o$(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await J1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function a$(O){let $={...O};for(let Q of Object.values(b0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function o2(O){xO=[...new Set(O.map(($)=>Y1.resolve($)))]}function _O(O,$){JO(O,$.plugins),C.releaseInstance(O,$.subagents),P.releaseInstance({cwd:O},$.skills),_.releaseInstance(O,$.commands),D.releaseInstance(O,$.plugins)}function TO(O){_O(O.workspaceRoot,O)}function q0(){while(x.size>bO){let O=!1;for(let[$,Q]of x){if(!Q.resources||Q.users>0)continue;if(x.get($)!==Q)continue;x.delete($),TO(Q.resources),O=!0;break}if(!O)return}}function t$(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),q0()}).unref?.()}async function r$(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),q=_.getInstance(O),K=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),q.isInitialized()?void 0:q.initialize(O),K.isInitialized()?void 0:K.initialize(O,[...$.cliPluginDirs??xO])]),A0(O),await Q1(O);let X=await J1(O,{projectTrusted:Q.state==="trusted",plugins:K.getActive()}),G=await MO(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:q,plugins:K,communicationStyles:X,projectRules:G}}catch(X){throw _O(O,{subagents:Z,skills:J,commands:q,plugins:K}),X}}function e$(O,$){let Q={generation:W1,users:0};return Q.promise=r$(O,$).then((Z)=>{if(Q.generation!==W1||x.get(O)!==Q)return TO(Z),Z;return Q.resources=Z,q0(),Z},(Z)=>{if(x.get(O)===Q)x.delete(O);throw Z}),x.set(O,Q),Q}async function wO(O,$){let Q=Y1.resolve(O),Z=x.get(Q);if(!Z){if(q0(),x.size>=D0)throw new AO;Z=e$(Q,$)}else x.delete(Q),x.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(q){throw Z.users=Math.max(0,Z.users-1),q0(),q}return{entry:Z,resources:J}}async function DO(O,$){if(!$)return;A0(O.workspaceRoot),await Q1(O.workspaceRoot),await o$(O)}async function a2(O,$={}){let Q=await wO(O,$);try{return await DO(Q.resources,$.reconcilePlugins),Q.resources}finally{t$(Q.entry)}}async function t2(O,$,Q={}){let Z=await wO(O,Q);try{return await DO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),q0()}}function r2(){let O=0,$=0;for(let Q of x.values()){if(Q.resources)O++;$+=Q.users}return{capacity:bO,activeCapacity:D0,entries:x.size,initialized:O,inFlight:x.size-O,activeUsers:$}}function e2(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:Y1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??IO.snapshot(),projectRules:O.projectRules?.snapshot()??d.empty($),hooks:a$("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function O5(){W1++;for(let[O,$]of x)if($.resources)A0(O);x.clear(),C.resetInstances(),P.resetInstance(),_.resetInstance(),D.resetInstance()}
719
- export{Q4 as ne,Z4 as oe,V1 as pe,L4 as qe,X4 as re,o as se,_4 as te,I1 as ue,g as ve,_ as we,t0 as xe,M0 as ye,D as ze,Q0 as Ae,Q1 as Be,A0 as Ce,d as De,bO as Ee,D0 as Fe,AO as Ge,o$ as He,o2 as Ie,a2 as Je,t2 as Ke,r2 as Le,e2 as Me,O5 as Ne};
719
+ export{Q4 as ve,Z4 as we,V1 as xe,L4 as ye,X4 as ze,o as Ae,_4 as Be,I1 as Ce,g as De,_ as Ee,t0 as Fe,M0 as Ge,D as He,Q0 as Ie,Q1 as Je,A0 as Ke,d as Le,bO as Me,D0 as Ne,AO as Oe,o$ as Pe,o2 as Qe,a2 as Re,t2 as Se,r2 as Te,e2 as Ue,O5 as Ve};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as yg,T as zg,A as Ag};
@@ -1,4 +1,4 @@
1
- import{df as YO}from"./chunk-m57w4p91.js";import{kg as qO,mg as S,pg as y}from"./chunk-v0rsz1rt.js";import{wg as P}from"./chunk-k0pa8874.js";import{Xg as XO}from"./chunk-t2wgf9tq.js";import{rh as n}from"./chunk-r9d4mjxj.js";import{Bh as r}from"./chunk-9q852bsc.js";import{Dh as w}from"./chunk-wfy851et.js";var b;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(b||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import C from"node:path";import{LRUCache as fO}from"lru-cache";import{nanoid as R}from"nanoid";var N={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import DO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import k from"node:path";import{Mutex as SO}from"async-mutex";import GO from"write-file-atomic";var h=1,VO=1048576,LO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function zO(O){let q={};for(let Q of Object.values(b)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(b))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(zO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new SO;filePath;constructor(O=k.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let W;try{W=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let J=W.projects[Z];if(!J)return{...X,state:"untrusted"};return{...X,state:J.digest===$?"trusted":"modified",trustedDigest:J.digest,trustedAt:J.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:h,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>VO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==h)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!k.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!LO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:h,projects:Z}}async writeStore(O){let q=k.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await GO(this.filePath,`${JSON.stringify(O,null,2)}
1
+ import{lf as YO}from"./chunk-4ehgjdm0.js";import{sg as qO,ug as S,xg as y}from"./chunk-k82ff14t.js";import{Eg as P}from"./chunk-ah12xhh6.js";import{eh as XO}from"./chunk-tzytnhbp.js";import{Ah as n}from"./chunk-mefb27ch.js";import{Kh as r}from"./chunk-zxn7f308.js";import{Mh as w}from"./chunk-0hrj06t7.js";var b;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(b||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import C from"node:path";import{LRUCache as fO}from"lru-cache";import{nanoid as R}from"nanoid";var N={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import DO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import k from"node:path";import{Mutex as SO}from"async-mutex";import GO from"write-file-atomic";var h=1,VO=1048576,LO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function zO(O){let q={};for(let Q of Object.values(b)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(b))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(zO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new SO;filePath;constructor(O=k.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let W;try{W=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let J=W.projects[Z];if(!J)return{...X,state:"untrusted"};return{...X,state:J.digest===$?"trusted":"modified",trustedDigest:J.digest,trustedAt:J.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:h,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>VO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==h)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!k.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!LO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:h,projects:Z}}async writeStore(O){let q=k.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await GO(this.filePath,`${JSON.stringify(O,null,2)}
2
2
  `,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(BO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(AO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(PO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function BO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function AO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function PO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var UO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),_O=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),KO=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),NO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),MO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),wO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),CO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),EO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),jO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([UO,_O,KO,bO,NO,MO,TO,wO,CO,EO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(jO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",W=Q?.failureBehavior||"ignore",J=`Invalid hook output JSON: ${X}`;if(W==="deny")return{success:!1,blocking:!0,error:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(W==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class u{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class l{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:W}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),J=new u(this.MAX_STDOUT_SIZE),G=new u(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{J.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await W.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,F)=>{let z=!1,V=!1,B,U=()=>{return B??=W.terminate(),B},K=null,H=()=>{if(K&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",K),K=null},I=setTimeout(()=>{z=!0,U()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),z)await U();L({stdout:J.getContent(),stderr:G.getContent(),exitCode:z?124:f??1,timedOut:z})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),F(f)}),Q.abortSignal){if(K=()=>{if(V)return;V=!0,clearTimeout(I),H(),U().then(()=>{L({stdout:J.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",K),Q.abortSignal.aborted)K()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),yO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new l;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},W=await this.executeHook($,X,Q);if(!W.success){if(W.blocking)return{decision:"deny",reason:W.error};if(W.needsConfirmation)return{decision:"ask",reason:W.warning||W.error};if(W.warning)Y.push(W.warning);continue}let J=W.output?.hookSpecificOutput;if(J&&"permissionDecision"in J){switch(J.permissionDecision){case"deny":return{decision:"deny",reason:J.permissionDecisionReason};case"ask":return{decision:"ask",reason:J.permissionDecisionReason};case"allow":break}if("updatedInput"in J&&J.updatedInput)Z={...Z,...J.updatedInput}}}catch(X){let W=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${W}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:W};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${W}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
3
3
  `):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,W=[];for(let J of Y){if(!J.success&&J.warning){W.push(J.warning);continue}let G=J.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
4
4
 
@@ -25,7 +25,7 @@ import{df as YO}from"./chunk-m57w4p91.js";import{kg as qO,mg as S,pg 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 W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
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,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-xdz5zrjt.js"),{createChatServiceAsync:W}=await import("./chunk-wneeq8cr.js"),{resolveModelConfig:J}=await import("./chunk-xzz69esf.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-3as0bkqy.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-wbzvy99s.js"),{createChatServiceAsync:W}=await import("./chunk-jsg7vmxp.js"),{resolveModelConfig:J}=await import("./chunk-vxd30mnx.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-yg6c4xrs.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
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 W=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),J=W.then(()=>{$.delete(J)}).catch(()=>{$.delete(J)});$.add(J),Y.push(W)}return Promise.all(Y)}}async function HO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:W}=await Q.read();if(W)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var IO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class i{matches(O,q){if(!O)return!0;if(O.tools&&q.toolName){if(!this.matchTools(O.tools,q))return!1}if(O.paths){let Q=q.filePaths??(q.filePath?[q.filePath]:[]);if(Q.length===0||!Q.some((Z)=>this.matchPaths(O.paths,Z)))return!1}if(O.commands&&q.command){if(!this.matchCommands(O.commands,q.command))return!1}return!0}matchTools(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchToolWithParams(Q,q));return this.matchToolWithParams(O,q)}matchPaths(O,q){if(Array.isArray(O))return O.some((Z)=>{return a(Z)(q)});return a(O)(q)}matchCommands(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchPattern(q,Q));return this.matchPattern(q,O)}matchToolWithParams(O,q){let{toolName:Q,command:Z,filePath:Y}=q,$=IO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,W]=$;if(!this.matchPattern(Q,X))return!1;let J=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(J.length===0)return!1;return J.some((G)=>this.matchGlobOrPattern(G,W))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}var WO=64;class _{static instance=null;config=N;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new fO({max:WO});sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!_.instance)_.instance=new _;return _.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){let Z=this.sessionConfigKey(O,q[0]??P()),Y=this.disabledSessions.has(Z);for(let $ of q){let X=this.sessionConfigKey(O,$);if(Y||=this.disabledSessions.has(X),this.sessionStateAliases.set(X,Z),this.sessionConfigs.set(X,this.snapshotConfig(Q)),X!==Z)this.disabledSessions.delete(X)}if(Y)this.disabledSessions.add(Z)}async unbindSessionModelResources(O,q){let Q=`${O}\x00`;for(let Z of this.sessionConfigs.keys()){if(!Z.startsWith(Q))continue;this.sessionConfigs.delete(Z)}for(let Z of this.sessionStateAliases.keys()){if(!Z.startsWith(Q))continue;this.sessionStateAliases.delete(Z)}for(let Z of this.disabledSessions){if(!Z.startsWith(Q))continue;this.disabledSessions.delete(Z)}await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){_.instance?.cleanup(),_.instance=null}loadConfig(O,q=P()){let Q=E(N,O),Z=c();Q=E(Q,Z),this.storeProjectConfig(q,Q)}isEnabled(O=P(),q){if(!(q?this.getExecutionConfig(q,O):this.getConfig(O)).enabled)return!1;if(this.processDisabled)return!1;if(q&&this.disabledSessions.has(this.sessionStateKey(q,O)))return!1;return!0}disable(){this.processDisabled=!0,console.log("[HookManager] Hooks disabled for this process")}enable(){this.processDisabled=!1,console.log("[HookManager] Hooks enabled for this process")}disableSession(O,q){this.disabledSessions.add(this.sessionStateKey(O,q))}enableSession(O,q){this.disabledSessions.delete(this.sessionStateKey(O,q))}isSessionEnabled(O,q){return this.isEnabled(q,O)}isSessionPaused(O,q){return this.disabledSessions.has(this.sessionStateKey(O,q))}getConfig(O=P()){let q=C.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===C.resolve(P()))return this.config;return{...N,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}isExecutionEnabled(O,q,Q){return O.enabled===!0&&!this.processDisabled&&!this.disabledSessions.has(this.sessionStateKey(q,Q))}sessionStateKey(O,q){let Q=this.sessionConfigKey(O,q);return this.sessionStateAliases.get(Q)??Q}sessionConfigKey(O,q){return`${O}\x00${C.resolve(q)}`}snapshotConfig(O){let q=E(N,O);for(let Q of Object.values(b))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}storeProjectConfig(O,q){let Q=C.resolve(O);if(Q===C.resolve(P())){this.config=q,this.projectConfigs.delete(Q);return}this.projectConfigs.set(Q,q)}inheritProjectConfig(O,q,Q){let Z=Q?this.getExecutionConfig(Q,O):this.getConfig(O);if(this.storeProjectConfig(q,this.snapshotConfig(Z)),!Q)return;let Y=this.sessionConfigKey(Q,O),$=this.sessionConfigKey(Q,q),X=this.sessionStateAliases.get(Y)??Y,W=this.disabledSessions.has(X)||this.disabledSessions.has($);if(this.sessionConfigs.set($,this.snapshotConfig(Z)),this.sessionStateAliases.set($,X),$!==X)this.disabledSessions.delete($);if(W)this.disabledSessions.add(X)}getResidencyStats(){return{projectCapacity:WO,projectConfigs:this.projectConfigs.size,sessionConfigs:this.sessionConfigs.size,sessionAliases:this.sessionStateAliases.size}}getTrustStatus(O=P()){return A.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=P(),q){return A.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=P()){return A.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let W=C.resolve(Z.projectDir),J=this.getConfig(W),G=J[O]??[];return J[O]=[...G,$],this.storeProjectConfig(W,J),()=>{let L=J[O];if(!L)return;J[O]=L.filter((F)=>F!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let W=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=W.filter((J)=>J!==$)}}async reloadConfig(O=P()){let q=await import("node:fs/promises"),Q=await import("node:path");try{let Z=Q.join(O,".blade","settings.local.json"),Y=await q.readFile(Z,"utf-8"),$=JSON.parse(Y);if($.hooks)this.loadConfig($.hooks,O)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let J=await this.executor.executePreToolHooks(X,$,W);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(J.decision==="deny")return J;return{decision:"allow",modifiedInput:J.modifiedInput,warning:J.warning,reason:J.reason}}return J}catch(J){return console.error("[HookManager] Error executing PreToolUse hooks:",J),{decision:"allow",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(W,X,J);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,W)}catch(J){return console.error("[HookManager] Error executing PermissionRequest hooks:",J),{decision:"ask",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:R(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(W,X,J)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{suppress:!1,message:q};let Y={hook_event_name:"Notification",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,notification_type:O,title:Q.title,message:q},$=this.getMatchingHooks("Notification",{},Z);if($.length===0)return{suppress:!1,message:q};let X={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeNotificationHooks($,Y,X)}catch(W){return console.error("[HookManager] Error executing Notification hooks:",W),{suppress:!1,message:q,warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"Elicitation",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll(),this.config=N,this.processDisabled=!1,this.disabledSessions.clear(),this.sessionStateAliases.clear(),this.projectConfigs.clear(),this.sessionConfigs.clear(),this.managedFunctionMatchers={}}}
45
- export{b as Ze,o as _e,_ as $e};
45
+ export{b as ff,o as gf,_ as hf};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-be30r8an.js";import"./chunk-azw0jckv.js";import"./chunk-wfy851et.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-xv92c582.js";import"./chunk-xjc0bthz.js";import"./chunk-0hrj06t7.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1,4 +1,4 @@
1
- import{O as P}from"./chunk-d3ttqmyt.js";import{fb as K}from"./chunk-nx31fkkf.js";import{$b as s,Nc as B,Xb as G,Yb as N,Zb as S,_b as O}from"./chunk-97aywyzn.js";import{Wc as j}from"./chunk-mtphps19.js";import{Xd as q}from"./chunk-0j22w4wh.js";import{pe as v}from"./chunk-axtzde5k.js";import{xh as z}from"./chunk-9q852bsc.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{R as P}from"./chunk-3hv57n95.js";import{lb as K}from"./chunk-b28zsp1t.js";import{Vc as B,dc as G,ec as N,fc as S,gc as O,hc as s}from"./chunk-2wdxpdz3.js";import{cd as j}from"./chunk-wp0794r2.js";import{de as q}from"./chunk-c9e0fbyh.js";import{xe as v}from"./chunk-5d1gbm41.js";import{Gh as z}from"./chunk-zxn7f308.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -0,0 +1 @@
1
+ import{Me as a,Ne as b,Oe as c,Pe as d,Qe as e,Re as f,Se as g,Te as h,Ue as i,Ve as j}from"./chunk-5d1gbm41.js";import"./chunk-4khtsmrf.js";import"./chunk-yvnm25nb.js";import"./chunk-jkh9s1ht.js";import"./chunk-67ddp3ns.js";import"./chunk-4ehgjdm0.js";import"./chunk-4cpgcm7q.js";import"./chunk-p7y79y6c.js";import"./chunk-k82ff14t.js";import"./chunk-64jq6jcr.js";import"./chunk-ah12xhh6.js";import"./chunk-kka51s0k.js";import"./chunk-tzytnhbp.js";import"./chunk-948efzyp.js";import"./chunk-ne7vres8.js";import"./chunk-xjc0bthz.js";import"./chunk-1ava19kd.js";import"./chunk-mefb27ch.js";import"./chunk-zxn7f308.js";import"./chunk-0hrj06t7.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1,3 +1,3 @@
1
- import{dh as N,gh as M}from"./chunk-t8xmh4w2.js";import{Bh as H}from"./chunk-9q852bsc.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{mh as N,ph as M}from"./chunk-ne7vres8.js";import{Kh as H}from"./chunk-zxn7f308.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 Zg,X as _g,J as $g,L as ah,hu as bh};
3
+ export{K as gh,X as hh,J as ih,L as jh,hu as kh};