blade-code 0.8.3 → 0.10.0

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 (133) hide show
  1. package/README.md +20 -5
  2. package/dist/blade.js +4 -4
  3. package/dist/chunk-0aj7gp37.js +2 -0
  4. package/dist/{chunk-7bqkkjxf.js → chunk-0h81hxkw.js} +1 -1
  5. package/dist/chunk-2beq0syt.js +2 -0
  6. package/dist/chunk-2fdjn926.js +1 -0
  7. package/dist/chunk-3c5gvxr6.js +1 -0
  8. package/dist/chunk-44wkjs2j.js +114 -0
  9. package/dist/chunk-4vaywb2r.js +2 -0
  10. package/dist/{chunk-crbh6x86.js → chunk-61087jc8.js} +2 -2
  11. package/dist/chunk-6g21dh3n.js +1 -0
  12. package/dist/chunk-6hj2dk75.js +3 -0
  13. package/dist/chunk-6n5xdf2r.js +2 -0
  14. package/dist/chunk-6qe5k7dw.js +4 -0
  15. package/dist/chunk-7dcm1aqd.js +1 -0
  16. package/dist/chunk-7eptyk20.js +1 -0
  17. package/dist/chunk-88vy9hh0.js +4 -0
  18. package/dist/chunk-8nm1hqr1.js +2 -0
  19. package/dist/chunk-8rg05w47.js +174 -0
  20. package/dist/chunk-93ptxa5p.js +4 -0
  21. package/dist/chunk-949btxxx.js +1485 -0
  22. package/dist/chunk-9jy87d0y.js +3 -0
  23. package/dist/chunk-9kd14cwq.js +1 -0
  24. package/dist/chunk-a7nbn5kf.js +3 -0
  25. package/dist/chunk-af49jmns.js +5 -0
  26. package/dist/chunk-asbp4cv4.js +1 -0
  27. package/dist/chunk-beqaxytd.js +2 -0
  28. package/dist/chunk-bqdc3m0p.js +6 -0
  29. package/dist/chunk-bx50res5.js +99 -0
  30. package/dist/chunk-cznge1n7.js +1 -0
  31. package/dist/{chunk-5yt80bn2.js → chunk-d3236505.js} +1 -1
  32. package/dist/chunk-d9ddpapp.js +18 -0
  33. package/dist/chunk-e3tk2jna.js +636 -0
  34. package/dist/chunk-f8db8ftd.js +10 -0
  35. package/dist/chunk-fjp5tvh8.js +1 -0
  36. package/dist/chunk-fjw32ex5.js +2 -0
  37. package/dist/chunk-gafbzeyk.js +1 -0
  38. package/dist/chunk-hh3xw391.js +6 -0
  39. package/dist/chunk-hzvp3bc1.js +44 -0
  40. package/dist/chunk-jv4nkkb5.js +1 -0
  41. package/dist/{chunk-eyypmc9m.js → chunk-jxv6r0c7.js} +2 -2
  42. package/dist/{chunk-mqqajem9.js → chunk-kq5my0yy.js} +2 -2
  43. package/dist/chunk-m3tx1k0s.js +1 -0
  44. package/dist/chunk-m78ceafk.js +1 -0
  45. package/dist/{chunk-be7qz4cv.js → chunk-mjp61rqd.js} +1 -1
  46. package/dist/chunk-mvwp3c11.js +45 -0
  47. package/dist/chunk-mwrn7mcr.js +1 -0
  48. package/dist/chunk-mxhg6jt9.js +25 -0
  49. package/dist/chunk-nah0cbnp.js +2 -0
  50. package/dist/chunk-px5ck9pf.js +2 -0
  51. package/dist/chunk-qev36qrb.js +2 -0
  52. package/dist/{chunk-ar5564sf.js → chunk-sndbq5xt.js} +1 -1
  53. package/dist/chunk-t8q9ks7e.js +3 -0
  54. package/dist/{chunk-wcf80p9y.js → chunk-th7sxjtk.js} +2 -2
  55. package/dist/{chunk-97qxd4yb.js → chunk-ty2kc6kg.js} +2 -2
  56. package/dist/chunk-v4mr98vm.js +1 -0
  57. package/dist/chunk-vb0t2hhd.js +25 -0
  58. package/dist/chunk-vjpd3nee.js +2 -0
  59. package/dist/chunk-vvy506b3.js +3 -0
  60. package/dist/chunk-vyq9r31h.js +22 -0
  61. package/dist/chunk-w4qsayn6.js +9 -0
  62. package/dist/chunk-wsqz3x2e.js +161 -0
  63. package/dist/{chunk-vxpdjtqc.js → chunk-wvj9h7mb.js} +1 -1
  64. package/dist/chunk-yvah5h4x.js +13 -0
  65. package/dist/chunk-z5ae4qvf.js +2 -0
  66. package/dist/chunk-zcw7kyf4.js +2 -0
  67. package/dist/{chunk-qvtahmff.js → chunk-zkbf8n6y.js} +1 -1
  68. package/dist/web/assets/ChatView-CnwNosSG.js +7 -0
  69. package/dist/web/assets/CodeBlockHighlighter-CBo_AxjZ.js +8 -0
  70. package/dist/web/assets/FilePreview-hNo6RCNY.js +8 -0
  71. package/dist/web/assets/MarkdownRenderer-BON4fqSr.js +30 -0
  72. package/dist/web/assets/McpModal-Go_8v1Vu.js +5 -0
  73. package/dist/web/assets/SettingsModal-CRu1zGQf.js +1 -0
  74. package/dist/web/assets/TaskSwitcher-Ds8CBVtp.js +1 -0
  75. package/dist/web/assets/TerminalPanel-Dm4bu6ib.js +1 -0
  76. package/dist/web/assets/index-BNsnHxlt.js +32 -0
  77. package/dist/web/assets/index-DI8ZWdWH.js +11 -0
  78. package/dist/web/assets/index-DVTiq-7u.css +1 -0
  79. package/dist/web/assets/vendor-icons-CsBKlDXT.js +381 -0
  80. package/dist/web/assets/vendor-radix-DXRuAJHH.js +45 -0
  81. package/dist/web/assets/vendor-react-DG5dkZ_t.js +49 -0
  82. package/dist/web/index.html +5 -2
  83. package/package.json +37 -34
  84. package/dist/chunk-1m63zddw.js +0 -2
  85. package/dist/chunk-23h9grdr.js +0 -1
  86. package/dist/chunk-2c69g6t9.js +0 -34
  87. package/dist/chunk-5sccs44n.js +0 -1
  88. package/dist/chunk-6msfa7jh.js +0 -9
  89. package/dist/chunk-6spmzx13.js +0 -6
  90. package/dist/chunk-724djh7r.js +0 -1
  91. package/dist/chunk-804j7say.js +0 -1
  92. package/dist/chunk-8yk5w2ks.js +0 -1
  93. package/dist/chunk-9cr3jexy.js +0 -2
  94. package/dist/chunk-b922cq7k.js +0 -41
  95. package/dist/chunk-bqhghfmt.js +0 -6
  96. package/dist/chunk-d7nrqg5b.js +0 -5
  97. package/dist/chunk-fma9cbq5.js +0 -10
  98. package/dist/chunk-ghf5tgjr.js +0 -1
  99. package/dist/chunk-hqtskyc1.js +0 -2
  100. package/dist/chunk-jc7k8pfn.js +0 -22
  101. package/dist/chunk-kf43f8sy.js +0 -1577
  102. package/dist/chunk-kjc2aqww.js +0 -2
  103. package/dist/chunk-kjddt9xy.js +0 -1
  104. package/dist/chunk-m0ded6ky.js +0 -615
  105. package/dist/chunk-msr67f6q.js +0 -3
  106. package/dist/chunk-mvww9cmc.js +0 -151
  107. package/dist/chunk-nbpjzzrg.js +0 -13
  108. package/dist/chunk-ncvr73ev.js +0 -1
  109. package/dist/chunk-qwn46cd6.js +0 -2
  110. package/dist/chunk-sva5bdgz.js +0 -2
  111. package/dist/chunk-t9cqscfq.js +0 -2
  112. package/dist/chunk-tzr992v4.js +0 -1
  113. package/dist/chunk-x8xfx9nv.js +0 -1
  114. package/dist/chunk-yewg510f.js +0 -24
  115. package/dist/chunk-zj3q4btp.js +0 -4
  116. package/dist/chunk-zjks0ncc.js +0 -6
  117. package/dist/chunk-zsyff0ky.js +0 -3
  118. package/dist/web/assets/CodeBlockHighlighter-D8_cOYpG.js +0 -1
  119. package/dist/web/assets/FilePreview-B5g8yi8d.js +0 -7
  120. package/dist/web/assets/MarkdownRenderer-qBCxzEb_.js +0 -1
  121. package/dist/web/assets/McpModal-C7y2Fsqc.js +0 -5
  122. package/dist/web/assets/SettingsModal-Dmc7Dw_E.js +0 -1
  123. package/dist/web/assets/SettingsStore-BfoB9tNV.js +0 -1
  124. package/dist/web/assets/SkillsModal-CqFAIfj5.js +0 -1
  125. package/dist/web/assets/TerminalPanel-EHh8-9b9.js +0 -1
  126. package/dist/web/assets/index-B-BRpW1c.js +0 -16
  127. package/dist/web/assets/index-Ch0eqSLM.css +0 -1
  128. package/dist/web/assets/useRequest-B4kP-cmG.js +0 -1
  129. package/dist/web/assets/vendor-icons-DBM55KTG.js +0 -251
  130. package/dist/web/assets/vendor-markdown-b9iCqZWK.js +0 -36
  131. package/dist/web/assets/vendor-monaco-w6PwaWGP.js +0 -11
  132. package/dist/web/assets/vendor-radix-DyP_DOwV.js +0 -45
  133. package/dist/web/assets/vendor-react-FPIC4Czm.js +0 -49
@@ -0,0 +1,10 @@
1
+ import{a as Q,b as R,c as T,d as W}from"./chunk-9jy87d0y.js";import"./chunk-wvj9h7mb.js";import"./chunk-t8q9ks7e.js";import"./chunk-zcw7kyf4.js";import"./chunk-949btxxx.js";import"./chunk-mxhg6jt9.js";import"./chunk-8rg05w47.js";import"./chunk-88vy9hh0.js";import"./chunk-bx50res5.js";import"./chunk-44wkjs2j.js";import"./chunk-kq5my0yy.js";import{ac as M}from"./chunk-vb0t2hhd.js";import"./chunk-gafbzeyk.js";import"./chunk-0h81hxkw.js";import"./chunk-af49jmns.js";import"./chunk-px5ck9pf.js";import"./chunk-fjw32ex5.js";import"./chunk-z5ae4qvf.js";import"./chunk-e3tk2jna.js";import"./chunk-d9ddpapp.js";import"./chunk-sndbq5xt.js";import"./chunk-mvwp3c11.js";import"./chunk-beqaxytd.js";import"./chunk-jxv6r0c7.js";import"./chunk-hzvp3bc1.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import{ue as J}from"./chunk-0aj7gp37.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";import b from"chalk";import H from"open";var $=`
2
+ ____ _ _
3
+ | __ )| | __ _ __| | ___
4
+ | _ \\| |/ _\` |/ _\` |/ _ \\
5
+ | |_) | | (_| | (_| | __/
6
+ |____/|_|\\__,_|\\__,_|\\___|
7
+ `,E={command:"web",describe:"Start Blade server and open web interface",builder:Q,handler:async(X)=>{let F=R(X);if(await M(),!process.env.BLADE_SERVER_PASSWORD)console.log(b.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(b.gray(` Set this environment variable to enable Basic Auth.
8
+ `));let C=await W.listenAsync(F);if(console.log(b.cyan($)),console.log(b.gray(` v${J()}
9
+ `)),F.hostname==="0.0.0.0"){let q=`http://localhost:${C.port}`;console.log(b.blue.bold(" Local access: "),b.white(q));let Y=T();for(let Z of Y)console.log(b.blue.bold(" Network access: "),b.white(`http://${Z}:${C.port}`));H(q).catch(()=>{})}else{let q=C.url.toString();console.log(b.blue.bold(" Web interface: "),b.white(q)),H(q).catch(()=>{})}console.log(""),console.log(b.gray(` Press Ctrl+C to stop the server.
10
+ `)),await new Promise(()=>{}),await C.stop()}};export{E as webCommand};
@@ -0,0 +1 @@
1
+ import{Ab as b,zb as a}from"./chunk-ty2kc6kg.js";import"./chunk-0aj7gp37.js";import"./chunk-mjp61rqd.js";export{a as globalOptions,b as cliConfig};
@@ -0,0 +1,2 @@
1
+ import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
2
+ export{s as vc,g as wc};
@@ -0,0 +1 @@
1
+ import{dd as F}from"./chunk-jxv6r0c7.js";import{he as G}from"./chunk-vjpd3nee.js";import{promises as $}from"node:fs";import b from"node:os";import W from"node:path";import{Mutex as j}from"async-mutex";import{merge as N}from"lodash-es";import A from"write-file-atomic";var B=F("Service"),Z={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},theme:{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},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},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}},S=new Set(Object.entries(Z).filter(([q,z])=>z.persistable).map(([q])=>q)),m=new Set(Object.entries(Z).filter(([q,z])=>!z.persistable).map(([q])=>q));class V{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!V.instance)V.instance=new V;return V.instance}static resetInstance(){if(V.instance)for(let q of V.instance.timers.values())clearTimeout(q);V.instance=null}async save(q,z={}){this.validatePersistableFields(q);let H=this.groupUpdatesByTarget(q,z.scope,z.projectDir);if(z.immediate)await Promise.all(Array.from(H.entries()).map(([J,K])=>this.flushTarget(J,K)));else for(let[J,K]of H)this.scheduleSave(J,K)}async flush(){for(let z of this.timers.values())clearTimeout(z);this.timers.clear();let q=Array.from(this.pendingUpdates.entries()).map(([z,H])=>this.flushTarget(z,H));this.pendingUpdates.clear(),await Promise.all(q)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(q,z={}){await this.appendPermissionRuleForDecision(q,"allow",z)}async appendPermissionDenyRule(q,z={}){await this.appendPermissionRuleForDecision(q,"deny",z)}async appendPermissionRuleForDecision(q,z,H){let J=H.scope??"local",K=this.resolveFilePath("settings",J,H.projectDir);await this.flushTargetWithModifier(K,(M)=>{let Q=M.permissions??{allow:[],ask:[],deny:[]},X={allow:z==="allow"?this.dedupeArray([...Q.allow||[],q]):Q.allow||[],ask:Q.ask||[],deny:z==="deny"?this.dedupeArray([...Q.deny||[],q]):Q.deny||[]};return{...M,permissions:X}})}async appendLocalPermissionRule(q,z={}){await this.appendPermissionRule(q,{...z,scope:"local"})}async appendLocalPermissionDenyRule(q,z={}){await this.appendPermissionDenyRule(q,{...z,scope:"local"})}async removePluginSetting(q,z={}){let H=z.scope??"local",J=this.resolveFilePath("settings",H,z.projectDir);await this.flushTargetWithModifier(J,(K)=>{let M={...K.enabledPlugins??{}};delete M[q];let Q={...K};if(Object.keys(M).length>0)Q.enabledPlugins=M;else delete Q.enabledPlugins;return Q})}validatePersistableFields(q){for(let z of Object.keys(q)){let H=Z[z];if(!H)throw Error(`Unknown config field: ${z}`);if(!H.persistable)throw Error(`Field "${z}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(q,z,H){let J=new Map;for(let[K,M]of Object.entries(q)){let Q=Z[K];if(!Q)continue;let X=z??Q.defaultScope,Y=this.resolveFilePath(Q.target,X,H);if(!J.has(Y))J.set(Y,{});J.get(Y)[K]=M}return J}resolveFilePath(q,z,H){let J=H??G();if(q==="config")return z==="global"?W.join(b.homedir(),".blade","config.json"):W.join(J,".blade","config.json");switch(z){case"local":return W.join(J,".blade","settings.local.json");case"project":return W.join(J,".blade","settings.json");case"global":return W.join(b.homedir(),".blade","settings.json");default:return W.join(J,".blade","settings.local.json")}}scheduleSave(q,z){let H=this.pendingUpdates.get(q)??{},J=this.mergePendingUpdates(H,z);this.pendingUpdates.set(q,J);let K=this.timers.get(q);if(K)clearTimeout(K);let M=setTimeout(async()=>{let Q=this.pendingUpdates.get(q);if(Q){this.pendingUpdates.delete(q),this.timers.delete(q);try{await this.flushTarget(q,Q),this.lastSaveError=null}catch(X){let Y=X instanceof Error?X:Error(String(X));this.lastSaveError=Y,B.error(`Failed to save config to ${q}:`,Y.message),B.error("Stack trace:",Y.stack)}}},this.debounceDelay);this.timers.set(q,M)}mergePendingUpdates(q,z){let H={...q};for(let[J,K]of Object.entries(z)){let M=Z[J];if(!M){H[J]=K;continue}switch(M.mergeStrategy){case"replace":H[J]=K;break;case"append-dedupe":this.applyAppendDedupe(H,J,K);break;case"deep-merge":this.applyDeepMerge(H,J,K);break}}return H}async flushTarget(q,z){let H=this.fileLocks.get(q);if(!H)H=new j,this.fileLocks.set(q,H);await H.runExclusive(async()=>{await this.performWrite(q,z)})}async flushTargetWithModifier(q,z){let H=this.fileLocks.get(q);if(!H)H=new j,this.fileLocks.set(q,H);await H.runExclusive(async()=>{await $.mkdir(W.dirname(q),{recursive:!0,mode:493});let J={};try{let M=await $.readFile(q,"utf-8");J=JSON.parse(M)}catch{J={}}let K=z(J);await this.atomicWrite(q,K)})}async performWrite(q,z){await $.mkdir(W.dirname(q),{recursive:!0,mode:493});let H={};try{let K=await $.readFile(q,"utf-8");H=JSON.parse(K)}catch{H={}}let J={...H};for(let[K,M]of Object.entries(z)){let Q=Z[K];if(!Q){J[K]=M;continue}switch(Q.mergeStrategy){case"replace":J[K]=M;break;case"append-dedupe":this.applyAppendDedupe(J,K,M);break;case"deep-merge":this.applyDeepMerge(J,K,M);break}}await this.atomicWrite(q,J)}applyAppendDedupe(q,z,H){if(z==="permissions"&&typeof H==="object"&&H!==null){let J=q[z]??{allow:[],ask:[],deny:[]},K=H;q[z]={allow:this.dedupeArray([...J.allow||[],...K.allow||[]]),ask:this.dedupeArray([...J.ask||[],...K.ask||[]]),deny:this.dedupeArray([...J.deny||[],...K.deny||[]])}}else if(Array.isArray(H)){let J=Array.isArray(q[z])?q[z]:[];q[z]=this.dedupeArray([...J,...H])}else q[z]=H}applyDeepMerge(q,z,H){if(typeof H==="object"&&H!==null&&!Array.isArray(H)){let J=typeof q[z]==="object"&&q[z]!==null?q[z]:{};q[z]=N({},J,H)}else q[z]=H}dedupeArray(q){return Array.from(new Set(q))}async atomicWrite(q,z){await A(q,JSON.stringify(z,null,2),{mode:384,encoding:"utf-8"})}}function O(){return V.getInstance()}export{O as lc};
@@ -0,0 +1,6 @@
1
+ import{Eb as I}from"./chunk-nah0cbnp.js";import{Xb as A}from"./chunk-vb0t2hhd.js";import{dd as h}from"./chunk-jxv6r0c7.js";import{Hd as f,Ld as T,Md as w,Nd as M,Od as P,Rd as k,Sd as E}from"./chunk-hzvp3bc1.js";import{Td as c,Ud as S,Wd as n,Zd as m,_d as y}from"./chunk-4vaywb2r.js";import{fe as O}from"./chunk-vjpd3nee.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),r=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),p=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:m(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(r),timeout:n.Optional(r),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(r),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(r),theme:n.Optional(n.String()),uiTheme:n.Optional(m(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(r),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(m(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(m(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(p),ask:n.Optional(p),deny:n.Optional(p)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let l=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${l}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let a=S(B,t);if(!a.success){let s=a.error.issues.map((l)=>`${l.path.join(".")||"settings"}: ${l.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return a.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),a;try{a=await R.readFile(t,"utf8")}catch(s){let l=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${l}`)}return d(a,t)}function b(o,i){if(!i)return;let t=i;for(let[a,s]of _){if(a==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[a]!==void 0)o[s]=t[a]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let a=await k.getInstance().initialize(i),s=E(a,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
2
+ [FAIL] 配置初始化失败
3
+ `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
+ 请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
+ `),process.exit(1)}};function F(o){if(o.continue&&o.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(o.forkSession&&!o.continue&&!o.resume)throw Error("--fork-session requires --resume or --continue");if(o.sessionId&&(o.continue||o.resume)&&!o.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var v=(o)=>{if(o.outputFormat&&o.outputFormat!=="text"&&!o.print&&!o.headless)throw Error("--output-format can only be used with --print or --headless");if(o.headless&&o.outputFormat&&!["text","jsonl"].includes(o.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${o.outputFormat}". Use --print for json|stream-json support.`);if(o.print&&o.outputFormat&&!["text","json","stream-json"].includes(o.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${o.outputFormat}". Use --headless for jsonl support.`);if(o.inputFormat==="stream-json"&&o.print)u.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
+ export{Z as Bb,g as Cb,v as Db};
@@ -0,0 +1,44 @@
1
+ import{$d as Zn,Ud as rn,Vd as D,Wd as m,ae as Jn}from"./chunk-4vaywb2r.js";import{be as Nn,ce as pn}from"./chunk-qev36qrb.js";import{he as b}from"./chunk-vjpd3nee.js";import{je as Dn,me as H}from"./chunk-a7nbn5kf.js";import{ue as En,ve as fn}from"./chunk-0aj7gp37.js";import{ze as P}from"./chunk-6hj2dk75.js";import{Je as un}from"./chunk-8nm1hqr1.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let o of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[o]!==void 0)throw Error(`MCP OAuth "${o}" 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(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((o)=>o.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let _=t.scopes?.map((o)=>o.trim());if(_){if(_.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(_.some((o)=>!o||o.length>128||!Qn.test(o)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(_).size!==_.length)throw Error("MCP OAuth scopes must not contain duplicates")}let M=t.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},..._?.length?{scopes:_}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as J}from"node:crypto";import it from"node:http";import{auth as on}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),_t=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ot=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),_n=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(_t),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ot),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),_n)},{additionalProperties:!1});function y(n,t){return n instanceof Error&&"code"in n&&n.code===t}function st(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return y(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function K(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:K(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(_n,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.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 A.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>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(y(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
+ `,{mode:384,encoding:"utf8"}),await A.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=Y.join(this.stateRoot,".oauth-credentials.lock"),t=Fn(),e=Date.now()+et;while(Date.now()<e)try{let r=await A.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await r.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
+ `,"utf8"),await r.close(),async()=>{try{if(JSON.parse(await A.readFile(n,"utf8")).token===t)await A.unlink(n)}catch(u){if(!y(u,"ENOENT"))throw u}}}catch(r){if(!y(r,"EEXIST"))throw r;await this.removeDeadLock(n),await new Promise((u)=>setTimeout(u,ut))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await A.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 e=JSON.parse(await A.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!st(e.pid))await A.unlink(n)}}var sn="127.0.0.1",Sn=7777,mn="/oauth/callback",mt=300000;class Q 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 Et(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 X(n,t,e){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(Et(e))}class L{serverName;config;static activeFlowIdentity;tokenStorage;serverUrl;identity;callbackUrl;openAuthorizationUrl;codeVerifierValue;activeFlow;lastError;constructor(n,t,e,r={}){this.serverName=n;this.config=e;this.serverUrl=K(t),this.identity=Z(this.serverUrl,e.clientId,e.scopes),this.tokenStorage=r.tokenStorage??new x;let u=e.callbackPort??Sn;this.callbackUrl=`http://${sn}:${u}${mn}`,this.openAuthorizationUrl=r.openAuthorizationUrl??(async(_)=>{await St(_,{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:`${fn()} ${En()}`,...this.config.scopes?.length?{scope:this.config.scopes.join(" ")}:{}}}async state(){return this.activeFlow?.state??J()}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((e)=>({...this.baseCredential(e),tokens:structuredClone(n),...t===void 0?{}:{tokenExpiresAt:t}})),this.lastError=void 0}async redirectToAuthorization(n){let t=this.activeFlow;if(!t)throw new Q(this.serverName);t.authorizationUrl=I(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 e={...t};if(n==="client")delete e.clientInformation,delete e.tokens,delete e.tokenExpiresAt;else if(n==="tokens")delete e.tokens,delete e.tokenExpiresAt;else if(n==="discovery")delete e.discoveryState;return{...e,updatedAt:new Date().toISOString()}})}async getStatus(){if(this.activeFlow)return"authorizing";if(this.lastError)return"error";return await this.hasUsableCredentials()?"authenticated":"unauthenticated"}async hasUsableCredentials(){let 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(L.activeFlowIdentity)throw Error("Another MCP OAuth authorization is already in progress");L.activeFlowIdentity=this.identity,this.lastError=void 0,this.codeVerifierValue=void 0;try{let n=await this.createFlow();if(this.activeFlow=n,await on(this,{serverUrl:this.serverUrl,fetchFn:B})!=="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,e=new Promise((M,o)=>{n=M,t=o});e.catch(()=>{return});let r=J(),u=it.createServer((M,o)=>{this.handleCallback(M,o)});u.on("clientError",(M,o)=>{o.end(`HTTP/1.1 400 Bad Request\r
17
+ Connection: close\r
18
+ \r
19
+ `)}),await new Promise((M,o)=>{let s=(S)=>o(S);u.once("error",s),u.listen(this.config.callbackPort??Sn,sn,()=>{u.off("error",s),M()})});let _={flowId:J(),state:r,callbackUrl:this.callbackUrl,server:u,timeout:setTimeout(()=>{this.failActiveFlow(Error("MCP OAuth authorization timed out"))},mt),completion:e,resolve:n,reject:t,settled:!1};return _.timeout.unref(),_}async handleCallback(n,t){let e=this.activeFlow;if(!e){X(t,410,!1);return}try{if(n.method!=="GET"){t.setHeader("Allow","GET"),X(t,405,!1);return}let r=new URL(n.url??"/",e.callbackUrl);if(r.pathname!==mn){X(t,404,!1);return}let u=r.searchParams.get("state"),_=r.searchParams.get("code");if(r.searchParams.get("error"))throw Error("MCP OAuth authorization was denied");if(!u||u!==e.state)throw Error("MCP OAuth state mismatch");if(!_)throw Error("MCP OAuth callback is missing the authorization code");if(await on(this,{serverUrl:this.serverUrl,authorizationCode:_,fetchFn:B})!=="AUTHORIZED")throw Error("MCP OAuth token exchange did not complete");X(t,200,!0),await this.completeActiveFlow()}catch(r){X(t,400,!1),await this.failActiveFlow(r instanceof Error?r:Error(String(r)))}}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,L.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,L.activeFlowIdentity=void 0,!t||t.settled){this.activeFlow=void 0;return}t.settled=!0,clearTimeout(t.timeout),await new Promise((e)=>t.server.close(()=>e())),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()}}}var E={currentModelId:"",models:[],modelProviders:{},temperature:0,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"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};import{promises as Vn}from"fs";import{merge as R}from"lodash-es";import a from"os";import i from"path";function Tn(n){let t=cn(n.timeout??300000,"MCP timeout"),e=cn(n.idleTimeout??Math.min(60000,t),"MCP idleTimeout");if(e>t)throw Error("MCP idleTimeout must not exceed timeout");return{totalTimeoutMs:t,idleTimeoutMs:e,maxProgressEvents:128}}function ie(n,t,e){if(t.count>=e.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 r=n.message?.replace(/\0/g,"").trim().slice(0,1000);return{progress:n.progress,...n.total!==void 0?{total:n.total}:{},message:r||at(n.progress,n.total)}}function cn(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 at(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 ct}from"node:crypto";var U=["debug","info","notice","warning","error","critical","alert","emergency"],Ee=64,fe=64,ae=256,Tt=8192,Pn=16384,At=256,bt=6,gt=128,An=64,bn=64,Pt=128,wt=/authorization|api[-_]?key|cookie|credential|password|secret|token/i;function wn(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 e=t?.enabled??!0;if(typeof e!=="boolean")throw Error("MCP logging enabled must be a boolean");let r=t?.level??"warning";if(!dt(r))throw Error(`MCP logging level must be one of: ${U.join(", ")}`);return{enabled:e,level:r}}function dt(n){return typeof n==="string"&&U.includes(n)}function ce(n,t){return U.indexOf(n)>=U.indexOf(t)}function xt(n,t={}){let e=Lt(n.data),r=typeof e.value==="string"?e.value:JSON.stringify(e.value),u=gn(r,Pn),_=u.value,M=Buffer.byteLength(_),o=ct("sha256").update(_).digest("hex"),s=t.exposeDetails!==!1,S=s?gn(_,Tt):{value:`[MCP log details omitted; sha256=${o}]`,truncated:!1},T=s&&n.logger?k(j(n.logger),At):void 0;return{level:n.level,...T?{logger:T}:{},message:S.value||"[empty MCP log message]",projectedBytes:M,dataSha256:o,truncated:e.truncated||u.truncated||S.truncated,detailsOmitted:!s,timestamp:t.now??Date.now()}}function Te(n,t={}){return{...xt({level:"warning",logger:"blade.mcp.logging",data:`MCP log rate exceeded; dropped at least ${Math.max(1,n)} message(s)`},t),synthetic:!0}}function Lt(n){let t={nodes:0,remainingStringBytes:Pn,truncated:!1,seen:new WeakSet};return{value:W(n,0,t),truncated:t.truncated}}function W(n,t,e){if(e.nodes++,e.nodes>gt)return e.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 r=j(n),u=Math.max(0,e.remainingStringBytes),_=k(r,u),M=Buffer.byteLength(_);if(e.remainingStringBytes-=M,M<Buffer.byteLength(r))e.truncated=!0;return _}if(typeof n>"u")return"[undefined]";if(typeof n==="symbol"||typeof n==="function")return`[${typeof n}]`;if(t>=bt)return e.truncated=!0,"[depth limit reached]";if(e.seen.has(n))return e.truncated=!0,"[circular]";e.seen.add(n);try{if(Array.isArray(n)){if(n.length>An)e.truncated=!0;return n.slice(0,An).map((_)=>W(_,t+1,e))}let r=Object.create(null),u=Object.entries(n);if(u.length>bn)e.truncated=!0;for(let[_,M]of u.slice(0,bn)){let o=k(j(_),Pt)||"[empty-key]";if(_==="_meta"||wt.test(_))r[o]="[redacted]";else r[o]=W(M,t+1,e)}return r}finally{e.seen.delete(n)}}function j(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((e)=>{let r=e.charCodeAt(0);return(r===9||r===10||r===13||r>=32)&&r!==127}).join("")}function k(n,t){if(t<=0)return"";if(Buffer.byteLength(n)<=t)return n;let e=Buffer.from(n).subarray(0,t).toString("utf8");while(Buffer.byteLength(e)>t)e=e.slice(0,-1);return e}function gn(n,t){if(Buffer.byteLength(n)<=t)return{value:n,truncated:!1};let e=`
20
+ ...[MCP log truncated]`;return{value:k(n,t-Buffer.byteLength(e))+e,truncated:!0}}var dn=1024,ht=4096,xn=2,Ct=8,Ln=65536,$t=1048576,hn=50,Cn=16000,$n=4,It=100,In=1048576,Xt=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Rn(n){if(!n)return{enabled:!1,maxTokens:dn,maxRequestsPerToolCall:xn,maxInputBytes:Ln};if(typeof n.enabled!=="boolean")throw Error("MCP sampling.enabled must be a boolean");return{enabled:n.enabled,maxTokens:z(n.maxTokens??dn,1,ht,"MCP sampling.maxTokens"),maxRequestsPerToolCall:z(n.maxRequestsPerToolCall??xn,1,Ct,"MCP sampling.maxRequestsPerToolCall"),maxInputBytes:z(n.maxInputBytes??Ln,1,$t,"MCP sampling.maxInputBytes")}}function ge(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>hn)throw Error(`MCP sampling messages must contain 1-${hn} entries`);if(n.systemPrompt!==void 0&&n.systemPrompt.length>Cn)throw Error(`MCP sampling system prompt exceeds ${Cn} 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 e=n.stopSequences??[];if(e.length>$n||e.some((S)=>!S||S.length>It||S.includes("\x00")))throw Error(`MCP sampling stop sequences must contain at most ${$n} non-empty bounded values`);let r=[],u=0,_=0,M=0,o=[];if(n.systemPrompt)u+=Buffer.byteLength(n.systemPrompt,"utf8"),r.push({role:"system",content:n.systemPrompt}),o.push(`System: ${Xn(n.systemPrompt)}`);for(let S of n.messages){let T=Array.isArray(S.content)?S.content:[S.content],g=[],c=[];for(let f of T){if(f.type==="text"){u+=Buffer.byteLength(f.text,"utf8"),g.push({type:"text",text:f.text}),c.push(Xn(f.text));continue}if(f.type==="image"){if(S.role!=="user")throw Error("MCP sampling images are only supported in user messages");if(!Xt.has(f.mimeType))throw Error(`Unsupported MCP sampling image type: ${f.mimeType}`);let $=Nt(f.data);_+=$,M++,g.push({type:"image_url",image_url:{url:`data:${f.mimeType};base64,${f.data}`}}),c.push(`[${f.mimeType} image, ${$} bytes]`);continue}throw Error(`Unsupported MCP sampling content type: ${f.type}`)}if(g.length===0)throw Error("MCP sampling message has no supported content");r.push({role:S.role,content:g.length===1&&g[0]?.type==="text"?g[0].text:g}),o.push(`${S.role==="user"?"User":"Assistant"}: ${c.join(" ")}`)}if(u+_>t.maxInputBytes)throw Error(`MCP sampling input exceeds ${t.maxInputBytes} bytes`);if(M>Nn||_>pn)throw Error("MCP sampling image input exceeds the shared attachment budget");let s=z(n.maxTokens,1,Number.MAX_SAFE_INTEGER,"MCP sampling maxTokens");return{messages:r,maxTokens:Math.min(s,t.maxTokens),...n.temperature!==void 0?{temperature:n.temperature}:{},stopSequences:[...e],preview:o.join(`
21
+ `).slice(0,8000)}}function Pe(n,t,e){if(n.toolCalls?.length)throw Error("Model returned tools for basic MCP sampling");let r=n.content,u=n.finishReason==="length"||n.finishReason==="max_tokens"?"maxTokens":"endTurn",_=-1;for(let M of e.stopSequences){let o=r.indexOf(M);if(o>=0&&(_===-1||o<_))_=o}if(_>=0)r=r.slice(0,_),u="stopSequence";if(Buffer.byteLength(r,"utf8")>In)throw Error(`MCP sampling response exceeds ${In} bytes`);return{model:t,role:"assistant",content:{type:"text",text:r},stopReason:u}}function z(n,t,e,r){if(!Number.isSafeInteger(n)||n<t||n>e)throw Error(`${r} must be an integer between ${t} and ${e}`);return n}function Nt(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 Xn(n){return n.replace(/\s+/g," ").trim().slice(0,1000)}var de=256,xe=1e4,Le=86400000;var pt=/[\p{Cf}\p{Co}\p{Cn}]/u;function yn(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=d(n.defaultTtlMs??600000,1e4,86400000,"MCP tasks.defaultTtlMs"),e=d(n.maxLifetimeMs??1800000,1e4,86400000,"MCP tasks.maxLifetimeMs");if(t>e)throw Error("MCP tasks.defaultTtlMs must not exceed tasks.maxLifetimeMs");return{enabled:n.enabled,defaultTtlMs:t,pollIntervalMs:d(n.pollIntervalMs??500,100,1e4,"MCP tasks.pollIntervalMs"),maxTasksPerSession:d(n.maxTasksPerSession??32,1,32,"MCP tasks.maxTasksPerSession"),maxLifetimeMs:e}}function he(n,t){return d(n??t.defaultTtlMs,1e4,Math.min(86400000,t.maxLifetimeMs),"MCP task ttl")}function Ce(n,t,e){let r=Bt(n.taskId,"task ID",512),u=Bn(n.createdAt,"createdAt"),_=Bn(n.lastUpdatedAt,"lastUpdatedAt");if(Date.parse(_)<Date.parse(u))throw Error("MCP task lastUpdatedAt precedes createdAt");if(e&&(r!==e.taskId||u!==e.createdAt))throw Error("MCP task identity changed across connection generation");let M=n.ttl===null?null:d(n.ttl,0,86400000,"MCP task ttl"),o=n.pollInterval===void 0?t.pollIntervalMs:d(n.pollInterval,0,Number.MAX_SAFE_INTEGER,"MCP task pollInterval"),s=Math.min(1e4,Math.max(100,o)),S=n.statusMessage?Rt(n.statusMessage,r):void 0;return{taskId:r,status:n.status,createdAt:u,lastUpdatedAt:_,ttl:M,pollIntervalMs:s,...S?{statusMessage:S}:{}}}function $e(n){return["completed","failed","cancelled"].includes(n)}function Ie(n){let t=n instanceof Error?n.message:String(n);return Kn(F(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 Rt(n,t){return Kn(F(n.replaceAll(t,"[redacted-task-id]")),1024)}function F(n){return[...n.normalize("NFKC")].filter((t)=>{let e=t.codePointAt(0)??0;if(e===0||e>=1&&e<=8||e===11||e===12||e>=14&&e<=31||e===127)return!1;return!pt.test(t)}).join("").trim()}function Bn(n,t){let e=Date.parse(n);if(!Number.isFinite(e))throw Error(`MCP task ${t} is invalid`);return new Date(e).toISOString()}function Bt(n,t,e){if(!n||Buffer.byteLength(n)>e||F(n)!==n)throw Error(`MCP ${t} is invalid`);return n}function d(n,t,e,r){if(!Number.isSafeInteger(n)||n<t||n>e)throw Error(`${r} must be an integer between ${t} and ${e}`);return n}function Kn(n,t){let e=Buffer.from(n);if(e.length<=t)return n;let r=e.subarray(0,t).toString("utf8");while(Buffer.byteLength(r)>t)r=r.slice(0,-1);return r}var yt={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 v(n){let t=n.toLowerCase().trim();return yt[t]??n}var Kt=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/,Ut=/^\.[A-Za-z0-9_+-]{1,32}$/;function l(n){return n!==null&&typeof n==="object"&&!Array.isArray(n)}function h(n,t,e,r,u){if(n===void 0)return u;if(!Number.isInteger(n)||Number(n)<e||Number(n)>r)throw Error(`${t} must be an integer between ${e} and ${r}`);return Number(n)}function Un(n,t){if(n===void 0)return;let e;try{e=JSON.stringify(n)}catch{throw Error(`${t} must be JSON serializable`)}if(e===void 0||Buffer.byteLength(e)>262144)throw Error(`${t} exceeds the 256 KiB limit`);return structuredClone(n)}function kt(n,t){if(n===void 0)return{};if(!l(n))throw Error(`${t} must be an object`);let e={};for(let[r,u]of Object.entries(n)){if(!r||typeof u!=="string"||u.includes("\x00"))throw Error(`${t} must contain non-empty string values`);e[r]=u}return e}function w(n){if(n===void 0)return{};if(!l(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 e={};for(let[r,u]of t){if(!Kt.test(r))throw Error(`Invalid LSP server name: ${r}`);if(!l(u))throw Error(`lspServers.${r} must be an object`);let _=new Set(["command","args","extensionToLanguage","env","initializationOptions","settings","enabled","priority","startupTimeout","shutdownTimeout","requestTimeout","diagnosticWaitTimeout","maxRestarts"]),M=Object.keys(u).filter((c)=>!_.has(c));if(M.length>0)throw Error(`Unknown LSP server field: ${r}.${M[0]}`);if(typeof u.command!=="string"||!u.command.trim()||u.command.includes("\x00")||u.command.includes(`
22
+ `))throw Error(`lspServers.${r}.command must be a non-empty command`);if(u.args!==void 0&&!Array.isArray(u.args))throw Error(`lspServers.${r}.args must be an array`);let o=(u.args??[]).map((c,f)=>{if(typeof c!=="string"||c.includes("\x00"))throw Error(`lspServers.${r}.args.${f} must be a string`);return c});if(o.length>128)throw Error(`lspServers.${r}.args exceeds the 128-item limit`);if(!l(u.extensionToLanguage))throw Error(`lspServers.${r}.extensionToLanguage must be an object`);let s=Object.entries(u.extensionToLanguage);if(s.length===0||s.length>64)throw Error(`lspServers.${r}.extensionToLanguage must contain 1-64 entries`);let S={};for(let[c,f]of s){let $=c.startsWith(".")?c.toLowerCase():`.${c.toLowerCase()}`;if(!Ut.test($)||typeof f!=="string"||!f.trim())throw Error(`Invalid lspServers.${r}.extensionToLanguage entry: ${c}`);S[$]=f.trim()}if(u.enabled!==void 0&&typeof u.enabled!=="boolean")throw Error(`lspServers.${r}.enabled must be a boolean`);let T=Un(u.initializationOptions,`lspServers.${r}.initializationOptions`),g=Un(u.settings,`lspServers.${r}.settings`);e[r]={command:u.command.trim(),...o.length>0?{args:o}:{},extensionToLanguage:S,...u.env!==void 0?{env:kt(u.env,`lspServers.${r}.env`)}:{},...T!==void 0?{initializationOptions:T}:{},...g!==void 0?{settings:g}:{},...u.enabled!==void 0?{enabled:u.enabled}:{},priority:h(u.priority,`lspServers.${r}.priority`,-1000,1000,0),startupTimeout:h(u.startupTimeout,`lspServers.${r}.startupTimeout`,100,60000,1e4),shutdownTimeout:h(u.shutdownTimeout,`lspServers.${r}.shutdownTimeout`,100,1e4,2000),requestTimeout:h(u.requestTimeout,`lspServers.${r}.requestTimeout`,100,60000,1e4),diagnosticWaitTimeout:h(u.diagnosticWaitTimeout,`lspServers.${r}.diagnosticWaitTimeout`,0,5000,750),maxRestarts:h(u.maxRestarts,`lspServers.${r}.maxRestarts`,0,10,3)}}return e}import kn from"node:path";var zn=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,zt=/^(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;function N(n){let t=[];for(let[e,r]of Object.entries(n)){if(!zn.test(e))throw Error(`Invalid plugin name in enabledPlugins: ${e}`);if(typeof r!=="boolean")throw Error(`Invalid enabledPlugins value for ${e}`);t.push([e,r])}return Object.fromEntries(t)}function nn(n,t,e){if(!Array.isArray(n))throw Error(`${t} must be an array`);return[...new Set(n.map((r,u)=>{if(typeof r!=="string"||!r.trim())throw Error(`${t}[${u}] must be a non-empty string`);return e(r.trim())}))].sort()}function p(n){let t=new Set(["restrictToAllowedSources","requireGitCommitSha","allowedGitHosts","allowedMarketplaces","allowedLocalRoots"]),e=Object.keys(n).filter((u)=>!t.has(u));if(e.length>0)throw Error(`Unknown pluginSourcePolicy fields: ${e.join(", ")}`);let r={};for(let u of["restrictToAllowedSources","requireGitCommitSha"]){if(n[u]===void 0)continue;if(typeof n[u]!=="boolean")throw Error(`pluginSourcePolicy.${u} must be boolean`);r[u]=n[u]}if(n.allowedGitHosts!==void 0)r.allowedGitHosts=nn(n.allowedGitHosts,"pluginSourcePolicy.allowedGitHosts",(u)=>{let _=u.toLowerCase();if(!zt.test(_))throw Error(`Invalid plugin Git host pattern: ${u}`);return _});if(n.allowedMarketplaces!==void 0)r.allowedMarketplaces=nn(n.allowedMarketplaces,"pluginSourcePolicy.allowedMarketplaces",(u)=>{if(!zn.test(u))throw Error(`Invalid allowed Marketplace name: ${u}`);return u});if(n.allowedLocalRoots!==void 0)r.allowedLocalRoots=nn(n.allowedLocalRoots,"pluginSourcePolicy.allowedLocalRoots",(u)=>{if(!kn.isAbsolute(u))throw Error(`Plugin local allowlist root must be absolute: ${u}`);return kn.resolve(u)});return r}function G(n){let t=[];for(let[e,r]of Object.entries(n)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error(`Invalid environment variable name: ${e}`);if(typeof r!=="string"||r.includes("\x00"))throw Error(`Invalid environment variable value: ${e}`);t.push([e,r])}return Object.fromEntries(t)}var ln=1,Gn=64,Hn=1,qn=1e4;function On(n){return Number.isInteger(n)&&n>=1&&n<=64}function Yn(n){return Number.isInteger(n)&&n>=1&&n<=1e4}class C{static instance=null;runtimePermissionOverrides;lastAdditionalSettings;constructor(){}static getInstance(){if(!C.instance)C.instance=new C;return C.instance}static resetInstance(){C.instance=null}async initialize(n){try{this.lastAdditionalSettings=n,this.runtimePermissionOverrides=n?.permissions;let e=(await P.getInstance().getStatus(b())).state==="trusted",r=await this.loadConfigFiles(e),u=await this.loadSettingsFiles(e),_={...r,...u,enabledPlugins:{...r.enabledPlugins||{},...u.enabledPlugins||{}}};if(n)_=this.mergeSettings(_,n);let M=this.normalizeConfig(_),o={...E,...M};if(o.enabledPlugins=N(o.enabledPlugins),o.lspServers=w(o.lspServers),o.pluginSourcePolicy={...E.pluginSourcePolicy,...p(o.pluginSourcePolicy)},this.resolveEnvInterpolation(o),process.env.BLADE_MODEL&&o.models?.length>0){let s=v(process.env.BLADE_MODEL),S=o.models.find((T)=>T.id===s||T.model===s||T.id===process.env.BLADE_MODEL||T.model===process.env.BLADE_MODEL);if(S)o.currentModelId=S.id}if(process.env.BLADE_DEBUG)o.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(H().configureModelProviders(o.modelProviders,o.models),o.models.length>0)this.validateConfig(o);if(o.debug)console.log("[ConfigManager] Configuration loaded successfully");return o}catch(t){return console.error("[ConfigManager] Failed to initialize:",t),H().configureModelProviders({},[]),E}}async reload(){return this.initialize(this.lastAdditionalSettings)}async loadConfigFiles(n){let t=i.join(a.homedir(),".blade","config.json"),e=i.join(b(),".blade","config.json"),r={},u=await this.loadJsonFile(t);if(u)r={...r,...u};let _=await this.loadJsonFile(e);if(_&&n){let M={...r.mcpServers||{},..._.mcpServers||{}},o={...r.lspServers||{},..._.lspServers||{}},s={...r.modelProviders||{},..._.modelProviders||{}},S={...r.enabledPlugins||{},..._.enabledPlugins||{}};if(r={...r,..._},Object.keys(M).length>0)r.mcpServers=M;if(Object.keys(o).length>0)r.lspServers=w(o);if(Object.keys(s).length>0)r.modelProviders=s;if(Object.keys(S).length>0)r.enabledPlugins=N(S)}else if(_?.hooks)r.hooks=_.hooks;return r}async loadSettingsFiles(n){let t=i.join(a.homedir(),".blade","settings.json"),e=i.join(b(),".blade","settings.json"),r=i.join(b(),".blade","settings.local.json"),u={},_=await this.loadJsonFile(t);if(_)u=this.mergeSettings(u,_);let M=await this.loadJsonFile(e);if(M&&n)u=this.mergeSettings(u,M);else if(M?.hooks)u=this.mergeSettings(u,{hooks:M.hooks});let o=await this.loadJsonFile(r);if(o&&n)u=this.mergeSettings(u,o);else if(o?.hooks)u=this.mergeSettings(u,{hooks:o.hooks});return u}async loadWorkspacePermissions(n,t){let e={allow:[...t.allow],ask:[...t.ask],deny:[...t.deny]};if(i.resolve(n)!==i.resolve(b())){let u=await this.loadWorkspacePermissionOverrides(b(),{includeUntrusted:!0}),_=await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json")),M={allow:Array.from(new Set([...E.permissions.allow,..._?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...E.permissions.ask,..._?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...E.permissions.deny,..._?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let o of["allow","ask","deny"]){let s=new Set(u[o].filter((S)=>!M[o].includes(S)));e[o]=e[o].filter((S)=>!s.has(S))}}let r=await this.loadWorkspacePermissionOverrides(n);for(let u of["allow","ask","deny"])e[u]=Array.from(new Set([...e[u],...r[u]]));return e}async loadWorkspaceMcpServers(n,t){if(i.resolve(n)===i.resolve(b()))return{...t};let e=await P.getInstance().getStatus(n),r=e.state==="trusted",u=e.projectPath,_={},M=async(s)=>{let S=await this.loadJsonFile(s);if(S?.mcpServers)_={..._,...S.mcpServers}};if(await M(i.join(a.homedir(),".blade","config.json")),await M(i.join(a.homedir(),".blade","settings.json")),r)await M(i.join(u,".blade","config.json")),await M(i.join(u,".blade","settings.json")),await M(i.join(u,".blade","settings.local.json"));if(this.lastAdditionalSettings?.mcpServers)_={..._,...this.lastAdditionalSettings.mcpServers};let o={mcpServers:_};return this.resolveEnvInterpolation(o),o.mcpServers}async loadWorkspaceLspServers(n,t){if(i.resolve(n)===i.resolve(b()))return w(t);let e=await P.getInstance().getStatus(n),r={},u=async(M)=>{let o=await this.loadJsonFile(M);if(o?.lspServers)r={...r,...w(o.lspServers)}};if(await u(i.join(a.homedir(),".blade","config.json")),await u(i.join(a.homedir(),".blade","settings.json")),e.state==="trusted")for(let M of["config.json","settings.json","settings.local.json"])await u(i.join(e.projectPath,".blade",M));if(this.lastAdditionalSettings?.lspServers)r={...r,...w(this.lastAdditionalSettings.lspServers)};let _={lspServers:r};return this.resolveEnvInterpolation(_),w(_.lspServers)}async loadWorkspaceModelConfig(n,t){if(i.resolve(n)===i.resolve(b()))return{currentModelId:t.currentModelId,models:t.models.map((M)=>structuredClone(M)),modelProviders:structuredClone(t.modelProviders),temperature:t.temperature,...t.maxOutputTokens!==void 0?{maxOutputTokens:t.maxOutputTokens}:{},timeout:t.timeout};let e=await P.getInstance().getStatus(n),r=e.projectPath,u={currentModelId:E.currentModelId,models:E.models.map((M)=>structuredClone(M)),modelProviders:structuredClone(E.modelProviders),temperature:E.temperature,...E.maxOutputTokens!==void 0?{maxOutputTokens:E.maxOutputTokens}:{},timeout:E.timeout},_=(M)=>{if(!M)return;if(M.modelProviders)u.modelProviders={...u.modelProviders,...structuredClone(M.modelProviders)};if(M.models)u.models=M.models.map((o)=>structuredClone(o));if(M.currentModelId!==void 0)u.currentModelId=M.currentModelId;if(M.temperature!==void 0)u.temperature=M.temperature;if(M.maxOutputTokens!==void 0)u.maxOutputTokens=M.maxOutputTokens;if(M.timeout!==void 0)u.timeout=M.timeout};if(_(await this.loadJsonFile(i.join(a.homedir(),".blade","config.json"))),_(await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json"))),e.state==="trusted")_(await this.loadJsonFile(i.join(r,".blade","config.json"))),_(await this.loadJsonFile(i.join(r,".blade","settings.json"))),_(await this.loadJsonFile(i.join(r,".blade","settings.local.json")));if(_(this.lastAdditionalSettings),u=this.normalizeConfig(u),this.resolveEnvInterpolation(u),process.env.BLADE_MODEL&&u.models.length>0){let M=process.env.BLADE_MODEL,o=v(M),s=u.models.find((S)=>S.id===o||S.model===o||S.id===M||S.model===M);if(s)u.currentModelId=s.id}if(!u.models.some((M)=>M.id===u.currentModelId))u.currentModelId=u.models[0]?.id??"";return u}async loadWorkspaceRuntimeSettings(n,t){if(i.resolve(n)===i.resolve(b()))return{env:G(t.env),disableAllHooks:t.disableAllHooks,maxTurns:t.maxTurns,permissionMode:t.permissionMode};let e=await P.getInstance().getStatus(n),r=e.projectPath,u={env:{},disableAllHooks:E.disableAllHooks,maxTurns:E.maxTurns,permissionMode:E.permissionMode},_=(s,S)=>{if(!s)return;if(S.allowExecutionSettings){if(s.env)u.env={...u.env,...G(s.env)};if(s.maxTurns!==void 0)u.maxTurns=s.maxTurns;if(s.permissionMode!==void 0)u.permissionMode=s.permissionMode;if(s.disableAllHooks!==void 0)u.disableAllHooks=s.disableAllHooks}else if(s.disableAllHooks===!0)u.disableAllHooks=!0};_(await this.loadJsonFile(i.join(a.homedir(),".blade","config.json")),{allowExecutionSettings:!0}),_(await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json")),{allowExecutionSettings:!0});let M=await Promise.all([this.loadJsonFile(i.join(r,".blade","config.json")),this.loadJsonFile(i.join(r,".blade","settings.json")),this.loadJsonFile(i.join(r,".blade","settings.local.json"))]);for(let s of M)_(s,{allowExecutionSettings:e.state==="trusted"});_(this.lastAdditionalSettings,{allowExecutionSettings:!0});let o={env:u.env};return this.resolveEnvInterpolation(o),u.env=G(o.env),u}async loadWorkspacePluginSettings(n){let t=await P.getInstance().getStatus(n),e={},r=(u,_)=>{if(!u?.enabledPlugins)return;let M=N(u.enabledPlugins);for(let[o,s]of Object.entries(M))if(_||s===!1)e[o]=s};r(await this.loadJsonFile(i.join(a.homedir(),".blade","config.json")),!0),r(await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json")),!0);for(let u of["config.json","settings.json","settings.local.json"])r(await this.loadJsonFile(i.join(t.projectPath,".blade",u)),t.state==="trusted");return r(this.lastAdditionalSettings,!0),e}async loadWorkspacePluginSourcePolicy(n){let t=await P.getInstance().getStatus(n),e={...E.pluginSourcePolicy,allowedGitHosts:[...E.pluginSourcePolicy.allowedGitHosts],allowedMarketplaces:[...E.pluginSourcePolicy.allowedMarketplaces],allowedLocalRoots:[...E.pluginSourcePolicy.allowedLocalRoots]},r=(M)=>{if(!M?.pluginSourcePolicy)return;Object.assign(e,p(M.pluginSourcePolicy))},u=(M,o)=>{if(!o)return M;if(M.length===0&&!e.restrictToAllowedSources)return o;let s=new Set(o);return M.filter((S)=>s.has(S))},_=(M)=>{if(!M?.pluginSourcePolicy)return;let o=p(M.pluginSourcePolicy);e.allowedGitHosts=u(e.allowedGitHosts,o.allowedGitHosts),e.allowedMarketplaces=u(e.allowedMarketplaces,o.allowedMarketplaces),e.allowedLocalRoots=u(e.allowedLocalRoots,o.allowedLocalRoots),e.restrictToAllowedSources=e.restrictToAllowedSources||o.restrictToAllowedSources===!0,e.requireGitCommitSha=e.requireGitCommitSha||o.requireGitCommitSha===!0};r(await this.loadJsonFile(i.join(a.homedir(),".blade","config.json"))),r(await this.loadJsonFile(i.join(a.homedir(),".blade","settings.json")));for(let M of["config.json","settings.json","settings.local.json"])_(await this.loadJsonFile(i.join(t.projectPath,".blade",M)));if(_(this.lastAdditionalSettings),process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true")e.requireGitCommitSha=!0;return e}async loadWorkspaceHooks(n,t,e={}){if(i.resolve(n)===i.resolve(b())&&e.includeBaseForCurrentWorkspace!==!1)return R({},t);let r=R({},E.hooks),u=[i.join(a.homedir(),".blade","settings.json"),i.join(n,".blade","settings.json"),i.join(n,".blade","settings.local.json")];for(let _ of u){let M=await this.loadJsonFile(_);if(M?.hooks)r=R({},r,M.hooks)}return r}async loadWorkspacePermissionOverrides(n,t={}){let e={allow:[],ask:[],deny:[]},r=(await P.getInstance().getStatus(n)).state==="trusted",u=[...r||t.includeUntrusted?[i.join(n,".blade","settings.json")]:[],...r||t.includeUntrusted?[i.join(n,".blade","settings.local.json")]:[]];for(let _ of u){let M=await this.loadJsonFile(_);if(!M?.permissions)continue;for(let o of["allow","ask","deny"])e[o]=Array.from(new Set([...e[o],...M.permissions[o]||[]]))}return e}mergeSettings(n,t){let e={...JSON.parse(JSON.stringify(n)),...JSON.parse(JSON.stringify(t))};if(t.permissions)e.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)e.hooks=R({},e.hooks,t.hooks);if(t.enabledPlugins)e.enabledPlugins={...n.enabledPlugins||{},...N(t.enabledPlugins)};if(t.pluginSourcePolicy)e.pluginSourcePolicy={...n.pluginSourcePolicy??E.pluginSourcePolicy,...p(t.pluginSourcePolicy)};if(t.env)e.env=R({},e.env,t.env);if(t.mcpServers)e.mcpServers={...e.mcpServers||{},...t.mcpServers};if(t.lspServers)e.lspServers={...e.lspServers||{},...w(t.lspServers)};if(t.disableAllHooks!==void 0)e.disableAllHooks=t.disableAllHooks;if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;return e}resolveEnvInterpolation(n){let t=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,e=(u)=>{if(typeof u==="string")return u.replace(t,(_,M,o,s)=>{return process.env[M]||s||_});if(Array.isArray(u))return u.map(e);if(typeof u==="object"&&u!==null){let _=u;for(let[M,o]of Object.entries(_))_[M]=e(o);return _}return u},r=n;for(let[u,_]of Object.entries(r))r[u]=e(_)}async loadJsonFile(n){try{if(await this.fileExists(n)){let t=await Vn.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 Vn.access(n),!0}catch{return!1}}normalizeConfig(n){let t=JSON.parse(JSON.stringify(n)),e=(u)=>u.trim().replace(/^`|`$/g,""),r=(u)=>{for(let[_,M]of Object.entries(u))if(typeof M==="string")u[_]=e(M);else if(Array.isArray(M))M.forEach((o,s)=>{if(typeof o==="string")M[s]=e(o);else if(typeof o==="object"&&o!==null)r(o)});else if(typeof M==="object"&&M!==null)r(M)};return r(t),t}validateConfig(n,t=H()){let e=[];try{n.lspServers=w(n.lspServers)}catch(r){e.push(r instanceof Error?r.message:"Invalid LSP server configuration")}for(let[r,u]of Object.entries(n.mcpServers||{}))try{Tn(u),u.oauth=q(u);let _=wn(u);if(u.logging!==void 0)u.logging=_;if(u.sampling)u.sampling=Rn(u.sampling);if(u.tasks)u.tasks=yn(u.tasks)}catch(_){e.push(`MCP server "${r}": ${_ instanceof Error?_.message:"invalid sampling policy"}`)}for(let[r,u]of Object.entries(n.modelProviders||{}))if(e.push(...Dn(r,u)),t.isReservedProviderId(r))e.push(`modelProviders.${r}: built-in provider ids cannot be overridden`);if(e.length===0)try{t.configureModelProviders(n.modelProviders||{},n.models)}catch(r){e.push(r instanceof Error?r.message:"Failed to configure custom model providers")}if(!n.models||n.models.length===0)e.push("没有可用的模型配置");if(!Zn(n.maxTurns))e.push(`maxTurns 必须是 ${Jn()}`);if(!On(n.maxConcurrentTasks))e.push(`maxConcurrentTasks 必须是 ${ln}-${Gn} 之间的整数`);if(!Yn(n.maxQueuedTasks))e.push(`maxQueuedTasks 必须是 ${Hn}-${qn} 之间的整数`);if(n.models&&n.models.length>0){if(!n.currentModelId)e.push("未设置当前模型 ID");else if(!n.models.find((u)=>u.id===n.currentModelId))e.push(`当前模型 ID "${n.currentModelId}" 在 models 列表中不存在`);for(let r of n.models){let u=`模型 "${r.displayName||r.id}"`,_=["name","apiKey","baseUrl","maxContextTokens","maxOutputTokens","supportsThinking","thinkingBudget","thinkingMode"].filter((o)=>(o in r));if(_.length>0)e.push(`${u}: 不再支持旧字段 ${_.join(", ")};请重新配置模型`);if(!r.model)e.push(`${u}: model 字段必填`);if(!r.provider)e.push(`${u}: provider 字段必填`);if(r.overrides?.baseUrl&&!r.overrides.baseUrl.startsWith("http"))e.push(`${u}: overrides.baseUrl "${r.overrides.baseUrl}" 不是有效的 HTTP URL`);let M=r.overrides?.streamIdleTimeout;if(M!==void 0&&(!Number.isFinite(M)||M<1000))e.push(`${u}: overrides.streamIdleTimeout 必须至少为 1000ms`);try{t.getModel(r.provider,r.model)}catch{e.push(`${u}: 内置 catalog 中不存在 ${r.provider}/${r.model}`)}}}if(e.length>0)throw Error(`配置验证失败:
23
+ ${e.map((r)=>` - ${r}`).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 Mu(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((u)=>u.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
44
+ export{B as fd,q as gd,x as hd,Q as id,an as jd,L as kd,Tn as ld,ie as md,U as nd,Ee as od,fe as pd,ae as qd,wn as rd,dt as sd,ce as td,xt as ud,Te as vd,Rn as wd,ge as xd,Pe as yd,de as zd,xe as Ad,Le as Bd,yn as Cd,he as Dd,Ce as Ed,$e as Fd,Ie as Gd,E as Hd,w as Id,p as Jd,G as Kd,ln as Ld,Gn as Md,Hn as Nd,qn as Od,On as Pd,Yn as Qd,C as Rd,Mu as Sd};
@@ -0,0 +1 @@
1
+ import{rb as a,sb as b,tb as c,ub as d,vb as e,wb as f,xb as g,yb as h}from"./chunk-44wkjs2j.js";import"./chunk-jxv6r0c7.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
@@ -1,3 +1,3 @@
1
- import{lc as j}from"./chunk-zsyff0ky.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
1
+ import{Je as j}from"./chunk-8nm1hqr1.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
2
2
  `)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
3
- export{m as _b,I as $b,M as ac,V as bc,h as cc};
3
+ export{m as ad,I as bd,M as cd,V as dd,h as ed};
@@ -1,4 +1,4 @@
1
- import{Nb as L,Sb as _}from"./chunk-kjc2aqww.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{ee as L,he as _}from"./chunk-vjpd3nee.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 ha,f as ia,x as ja};
28
+ export{v as Jb,f as Kb,x as Lb};
@@ -0,0 +1 @@
1
+ import{sc as a,tc as b,uc as c}from"./chunk-px5ck9pf.js";import"./chunk-fjw32ex5.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -0,0 +1 @@
1
+ import{h as a,i as b,j as c,k as d,l as e}from"./chunk-th7sxjtk.js";import"./chunk-mjp61rqd.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as a}from"node:module";var c=a(import.meta.url);
2
- export{c as oc};
2
+ export{c as Le};
@@ -0,0 +1,45 @@
1
+ import{$c as YO}from"./chunk-beqaxytd.js";import{dd as XO}from"./chunk-jxv6r0c7.js";import{Ud as qO,Wd as S,Zd as y}from"./chunk-4vaywb2r.js";import{he as A}from"./chunk-vjpd3nee.js";import{Ae as n}from"./chunk-6n5xdf2r.js";import{Je as r}from"./chunk-8nm1hqr1.js";import{Le as w}from"./chunk-mjp61rqd.js";var N;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(N||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import _ from"node:path";import{nanoid as z}from"nanoid";var C={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function j(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 D}from"node:fs";import k from"node:path";import{Mutex as WO}from"async-mutex";import SO from"write-file-atomic";var h=1,GO=1048576,VO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function E(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(!E(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function LO(O){let q={};for(let Q of Object.values(N)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(N))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(LO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class K{static instance=null;mutex=new WO;filePath;constructor(O=k.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!K.instance)K.instance=new K;return K.instance}static resetInstance(){K.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let J;try{J=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let W=J.projects[Z];if(!W)return{...X,state:"untrusted"};return{...X,state:W.digest===$?"trusted":"modified",trustedDigest:W.digest,trustedAt:W.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await D.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>GO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!E(Q)||Q.version!==h)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!E(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!k.isAbsolute(Y)||!E($)||typeof $.digest!=="string"||!VO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:h,projects:Z}}async writeStore(O){let q=k.dirname(this.filePath);await D.mkdir(q,{recursive:!0,mode:448}),await D.chmod(q,448),await SO(this.filePath,`${JSON.stringify(O,null,2)}
2
+ `,{mode:384}),await D.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(zO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(BO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(KO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function zO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function BO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function KO(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 AO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),PO=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),_O=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),UO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),NO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),MO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),wO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),CO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),jO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([AO,PO,_O,UO,bO,NO,MO,TO,wO,CO])),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",J=Q?.failureBehavior||"ignore",W=`Invalid hook output JSON: ${X}`;if(J==="deny")return{success:!1,blocking:!0,error:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(J==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${W}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class l{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class u{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:J}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),W=new l(this.MAX_STDOUT_SIZE),G=new l(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{W.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await J.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,R)=>{let F=!1,V=!1,B,P=()=>{return B??=J.terminate(),B},b=null,I=()=>{if(b&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",b),b=null},H=setTimeout(()=>{F=!0,P()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(H),I(),F)await P();L({stdout:W.getContent(),stderr:G.getContent(),exitCode:F?124:f??1,timedOut:F})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(H),I(),R(f)}),Q.abortSignal){if(b=()=>{if(V)return;V=!0,clearTimeout(H),I(),P().then(()=>{L({stdout:W.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",b),Q.abortSignal.aborted)b()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),EO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new u;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},J=await this.executeHook($,X,Q);if(!J.success){if(J.blocking)return{decision:"deny",reason:J.error};if(J.needsConfirmation)return{decision:"ask",reason:J.warning||J.error};if(J.warning)Y.push(J.warning);continue}let W=J.output?.hookSpecificOutput;if(W&&"permissionDecision"in W){switch(W.permissionDecision){case"deny":return{decision:"deny",reason:W.permissionDecisionReason};case"ask":return{decision:"ask",reason:W.permissionDecisionReason};case"allow":break}if("updatedInput"in W&&W.updatedInput)Z={...Z,...W.updatedInput}}}catch(X){let J=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${J}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:J};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${J}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
3
+ `):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,J=[];for(let W of Y){if(!W.success&&W.warning){J.push(W.warning);continue}let G=W.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
4
+
5
+ `):void 0,modifiedOutput:X,warning:J.length>0?J.join(`
6
+ `):void 0}}async executeStopHooks(O,q,Q){if(O.length===0)return{shouldStop:!0};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&&"continue"in X&&X.continue===!1)return{shouldStop:!1,continueReason:X.continueReason,warning:Z.length>0?Z.join(`
7
+ `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{shouldStop:!0,warning:Z.length>0?Z.join(`
8
+ `):void 0}}async executeSubagentStopHooks(O,q,Q){if(O.length===0)return{shouldStop:!0};let Z=[],Y=[];for(let $ of O)try{let X=await this.executeHook($,q,Q);if(!X.success){if(X.warning)Z.push(X.warning);continue}let J=X.output?.hookSpecificOutput;if(J&&"continue"in J){if(J.continue===!1)return{shouldStop:!1,continueReason:J.continueReason,warning:Z.length>0?Z.join(`
9
+ `):void 0};if("additionalContext"in J&&J.additionalContext)Y.push(J.additionalContext)}}catch(X){let J=X instanceof Error?X.message:String(X);Z.push(`Hook failed: ${J}`)}return{shouldStop:!0,additionalContext:Y.length>0?Y.join(`
10
+
11
+ `):void 0,warning:Z.length>0?Z.join(`
12
+ `):void 0}}async executePermissionRequestHooks(O,q,Q){if(O.length===0)return{decision:"ask"};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&&"permissionDecision"in X){let J=X.permissionDecision;if(J==="approve"||J==="deny")return{decision:J,reason:X.permissionDecisionReason,warning:Z.length>0?Z.join(`
13
+ `):void 0}}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{decision:"ask",warning:Z.length>0?Z.join(`
14
+ `):void 0}}async executeElicitationHooks(O,q,Q){if(O.length===0)return{};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.blocking)return{blockedReason:$.error??"Elicitation blocked by hook",warning:Z.length>0?Z.join(`
15
+ `):void 0};if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"action"in X&&(X.action==="accept"||X.action==="decline"||X.action==="cancel"))return{response:{action:X.action,..."content"in X&&X.content?{content:X.content}:{}},warning:Z.length>0?Z.join(`
16
+ `):void 0}}catch($){Z.push(`Hook failed: ${$ instanceof Error?$.message:String($)}`)}return{warning:Z.length>0?Z.join(`
17
+ `):void 0}}async executeUserPromptSubmitHooks(O,q,Q){if(O.length===0)return{proceed:!0};let Z=[],Y=[],$;for(let X of O)try{let J=await this.executeHook(X,q,Q);if(!J.success){if(J.blocking)return{proceed:!1,warning:J.error};if(J.warning)Z.push(J.warning);continue}if(J.stdout&&J.stdout.trim())Y.push(J.stdout.trim());let W=J.output?.hookSpecificOutput;if(W&&"updatedPrompt"in W){if(W.updatedPrompt)$=W.updatedPrompt;if(W.contextInjection)Y.push(W.contextInjection)}}catch(J){let W=J instanceof Error?J.message:String(J);Z.push(`Hook failed: ${W}`)}return{proceed:!0,updatedPrompt:$,contextInjection:Y.length>0?Y.join(`
18
+
19
+ `):void 0,warning:Z.length>0?Z.join(`
20
+ `):void 0}}async executeSessionStartHooks(O,q,Q){if(O.length===0)return{proceed:!0};let Z=[],Y={};for(let $ of O)try{let X=await this.executeHook($,q,Q);if(!X.success){if(X.blocking)return{proceed:!1,warning:X.error};if(X.warning)Z.push(X.warning);continue}let J=X.output?.hookSpecificOutput;if(J&&"env"in J&&J.env)Object.assign(Y,J.env)}catch(X){let J=X instanceof Error?X.message:String(X);Z.push(`Hook failed: ${J}`)}return{proceed:!0,env:Object.keys(Y).length>0?Y:void 0,warning:Z.length>0?Z.join(`
21
+ `):void 0}}async executeSessionEndHooks(O,q,Q){if(O.length===0)return{};let Z=[],Y=Q.config.maxConcurrentHooks||5,$=await this.executeHooksConcurrently(O,q,Q,Y);for(let X of $)if(!X.success&&X.warning)Z.push(X.warning);return{warning:Z.length>0?Z.join(`
22
+ `):void 0}}async executePostToolUseFailureHooks(O,q,Q){if(O.length===0)return{};let Z=[],Y=[],$=Q.config.maxConcurrentHooks||5,X=await this.executeHooksConcurrently(O,q,Q,$);for(let J of X){if(!J.success&&J.warning){Z.push(J.warning);continue}if(J.stdout&&J.stdout.trim())Y.push(J.stdout.trim())}return{additionalContext:Y.length>0?Y.join(`
23
+
24
+ `):void 0,warning:Z.length>0?Z.join(`
25
+ `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
+ `):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
+ `):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 K.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-cznge1n7.js"),{createChatServiceAsync:J}=await import("./chunk-asbp4cv4.js"),{resolveModelConfig:W}=await import("./chunk-m3tx1k0s.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-9kd14cwq.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${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=EO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
+
30
+ `+`## 评估指令
31
+ ${O.prompt}
32
+
33
+ `+`## 输出格式
34
+ `+`必须返回一个 JSON 对象(不要包含任何其他文本):
35
+ `+`{
36
+ "decision": { "behavior": "approve" | "block" },
37
+ `+` "systemMessage": "可选的说明信息",
38
+ `+` "hookSpecificOutput": ${Q}
39
+ }
40
+
41
+ `+`重要规则:
42
+ `+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
43
+ `+`- 如果没有发现问题,使用 "approve"
44
+ `+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let q=O.trim(),Q=q.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Q)return Q[1].trim();return q}async executeHooksConcurrently(O,q,Q,Z){let Y=[],$=new Set;for(let X of O){if($.size>=Z)await Promise.race($);let J=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),W=J.then(()=>{$.delete(W)}).catch(()=>{$.delete(W)});$.add(W),Y.push(J)}return Promise.all(Y)}}async function yO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:J}=await Q.read();if(J)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var 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,J]=$;if(!this.matchPattern(Q,X))return!1;let W=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(W.length===0)return!1;return W.some((G)=>this.matchGlobOrPattern(G,J))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}class U{static instance=null;config=C;executor=new x;guard=new d;matcher=new i;sessionDisabled=!1;projectConfigs=new Map;sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!U.instance)U.instance=new U;return U.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){for(let Z of q)this.sessionConfigs.set(this.sessionConfigKey(O,Z),this.snapshotConfig(Q))}async unbindSessionModelResources(O,q){for(let Q of q)this.sessionConfigs.delete(this.sessionConfigKey(O,Q));await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){U.instance?.cleanup(),U.instance=null}loadConfig(O,q=A()){let Q=j(C,O),Z=c();Q=j(Q,Z);let Y=_.resolve(q);if(Y===_.resolve(A()))this.config=Q;this.projectConfigs.set(Y,Q)}isEnabled(O=A()){if(!this.getConfig(O).enabled)return!1;if(this.sessionDisabled)return!1;return!0}disable(){this.sessionDisabled=!0,console.log("[HookManager] Hooks disabled for this session")}enable(){this.sessionDisabled=!1,console.log("[HookManager] Hooks enabled for this session")}getConfig(O=A()){let q=_.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===_.resolve(A()))return this.config;return{...C,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}sessionConfigKey(O,q){return`${O}\x00${_.resolve(q)}`}snapshotConfig(O){let q=j(C,O);for(let Q of Object.values(N))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}inheritProjectConfig(O,q){this.projectConfigs.set(_.resolve(q),this.getConfig(O))}getTrustStatus(O=A()){return K.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=A(),q){return K.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=A()){return K.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let J=_.resolve(Z.projectDir),W=this.getConfig(J),G=W[O]??[];return W[O]=[...G,$],this.projectConfigs.set(J,W),()=>{let L=W[O];if(!L)return;W[O]=L.filter((R)=>R!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let J=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=J.filter((W)=>W!==$)}}async reloadConfig(){let O=await import("node:fs/promises"),q=await import("node:path");try{let Q=q.join(A(),".blade","settings.local.json"),Z=await O.readFile(Q,"utf-8"),Y=JSON.parse(Z);if(Y.hooks)this.loadConfig(Y.hooks)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!Y.enabled||this.sessionDisabled)return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let W=await this.executor.executePreToolHooks(X,$,J);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(W.decision==="deny")return W;return{decision:"allow",modifiedInput:W.modifiedInput,warning:W.warning,reason:W.reason}}return W}catch(W){return console.error("[HookManager] Error executing PreToolUse hooks:",W),{decision:"allow",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!$.enabled||this.sessionDisabled)return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(J,X,W);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!q.enabled||this.sessionDisabled)return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!Q.enabled||this.sessionDisabled)return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!Y.enabled||this.sessionDisabled)return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,J)}catch(W){return console.error("[HookManager] Error executing PermissionRequest hooks:",W),{decision:"ask",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!Q.enabled||this.sessionDisabled)return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:z(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!q.enabled||this.sessionDisabled)return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!Q.enabled||this.sessionDisabled)return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!$.enabled||this.sessionDisabled)return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(J,X,W)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!Z.enabled||this.sessionDisabled)return{suppress:!1,message:q};let Y={hook_event_name:"Notification",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,notification_type:O,title:Q.title,message:q},$=this.getMatchingHooks("Notification",{},Z);if($.length===0)return{suppress:!1,message:q};let X={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeNotificationHooks($,Y,X)}catch(J){return console.error("[HookManager] Error executing Notification hooks:",J),{suppress:!1,message:q,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!Q.enabled||this.sessionDisabled)return{};let Z={hook_event_name:"Elicitation",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!Z.enabled||this.sessionDisabled)return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!Q.enabled||this.sessionDisabled)return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll()}}
45
+ export{N as Yc,o as Zc,U as _c};
@@ -0,0 +1 @@
1
+ import{Nc as a,Oc as b,Pc as c,Qc as d,Rc as e}from"./chunk-e3tk2jna.js";import"./chunk-d9ddpapp.js";import"./chunk-sndbq5xt.js";import"./chunk-mvwp3c11.js";import"./chunk-beqaxytd.js";import"./chunk-jxv6r0c7.js";import"./chunk-hzvp3bc1.js";import"./chunk-4vaywb2r.js";import"./chunk-qev36qrb.js";import"./chunk-vjpd3nee.js";import"./chunk-a7nbn5kf.js";import"./chunk-2beq0syt.js";import"./chunk-0aj7gp37.js";import"./chunk-6hj2dk75.js";import"./chunk-6n5xdf2r.js";import"./chunk-8nm1hqr1.js";import"./chunk-mjp61rqd.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};