blade-code 0.10.21 → 0.10.23

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 (100) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-72ztan96.js → chunk-0affe05f.js} +3 -3
  3. package/dist/{chunk-2c3zavy2.js → chunk-18n15nn8.js} +1 -1
  4. package/dist/chunk-1ejj4jvg.js +1 -0
  5. package/dist/{chunk-g7p165yz.js → chunk-2j3d4ykq.js} +2 -2
  6. package/dist/{chunk-wc1ee4tc.js → chunk-2kpynwxa.js} +1 -1
  7. package/dist/chunk-2vs6ff2m.js +1 -0
  8. package/dist/{chunk-e9xv0yyr.js → chunk-33wheqb0.js} +1 -1
  9. package/dist/{chunk-73jh6fz9.js → chunk-3d2f82yb.js} +2 -2
  10. package/dist/{chunk-ryhk5qmv.js → chunk-46nbyp0r.js} +459 -369
  11. package/dist/{chunk-bdn1tkyz.js → chunk-48w87cah.js} +1 -1
  12. package/dist/{chunk-095x2ykj.js → chunk-4dnvydyv.js} +1 -1
  13. package/dist/{chunk-6sb7cg95.js → chunk-5sw8j9ae.js} +1 -1
  14. package/dist/{chunk-r1jxbx1h.js → chunk-5xph8r1k.js} +1 -1
  15. package/dist/{chunk-jahf977w.js → chunk-698qsvyb.js} +2 -2
  16. package/dist/{chunk-kfqj54ax.js → chunk-6bywhrm9.js} +2 -2
  17. package/dist/{chunk-ns5015tn.js → chunk-6g2tsx64.js} +1 -1
  18. package/dist/{chunk-4tkn9bky.js → chunk-70jrd752.js} +1 -1
  19. package/dist/chunk-73shq329.js +1 -0
  20. package/dist/{chunk-w5m418w5.js → chunk-8472vz3s.js} +2 -2
  21. package/dist/{chunk-edphxwj1.js → chunk-8efpk2z9.js} +2 -2
  22. package/dist/{chunk-r561wfcz.js → chunk-9ka0bdry.js} +1 -1
  23. package/dist/{chunk-65kbckpt.js → chunk-9m80tr4t.js} +2 -2
  24. package/dist/chunk-9wdg2mqh.js +1 -0
  25. package/dist/{chunk-jhzk287k.js → chunk-abtq0kjb.js} +1 -1
  26. package/dist/chunk-afk22y4r.js +10 -0
  27. package/dist/{chunk-jdsr22s2.js → chunk-afv2grka.js} +1 -1
  28. package/dist/chunk-ak7v70sy.js +100 -0
  29. package/dist/chunk-b183w6w0.js +1 -0
  30. package/dist/{chunk-q4fjec99.js → chunk-c7va41dk.js} +2 -2
  31. package/dist/{chunk-fasxw5bb.js → chunk-c7zk9zj2.js} +1 -1
  32. package/dist/{chunk-033vmd74.js → chunk-cjyrr1c0.js} +2 -2
  33. package/dist/chunk-cwyktf92.js +1 -0
  34. package/dist/{chunk-kmeccj99.js → chunk-czjbz0fp.js} +2 -2
  35. package/dist/chunk-ddj5f5cz.js +1 -0
  36. package/dist/{chunk-77z6x1zb.js → chunk-djh79rde.js} +2 -2
  37. package/dist/{chunk-9wqr1sbq.js → chunk-f9tahtz6.js} +1 -1
  38. package/dist/{chunk-ah8hky46.js → chunk-gcsygn5a.js} +1 -1
  39. package/dist/{chunk-1y52h772.js → chunk-h0q03x9f.js} +1 -1
  40. package/dist/{chunk-k106g2p6.js → chunk-hjvdsrzb.js} +2 -2
  41. package/dist/{chunk-17jpjcvb.js → chunk-hpgee5s3.js} +3 -3
  42. package/dist/{chunk-bjf7ecgy.js → chunk-hvp9kt76.js} +1 -1
  43. package/dist/chunk-k7p4qwdr.js +1 -0
  44. package/dist/{chunk-2wp6h1p8.js → chunk-kaa0np37.js} +2 -2
  45. package/dist/chunk-kky5ydtw.js +2 -0
  46. package/dist/{chunk-afhdpen9.js → chunk-ksm02qjh.js} +2 -2
  47. package/dist/{chunk-dbb20rxh.js → chunk-kvd5nexw.js} +1 -1
  48. package/dist/{chunk-5chec8rs.js → chunk-m27w377p.js} +1 -1
  49. package/dist/{chunk-4v8nxcxp.js → chunk-n7hnp8yj.js} +1 -1
  50. package/dist/chunk-nbwvc4v4.js +1 -0
  51. package/dist/{chunk-mvc0tad6.js → chunk-nfm5j63c.js} +2 -2
  52. package/dist/{chunk-vzgy95tp.js → chunk-nv59nazz.js} +1 -1
  53. package/dist/chunk-p29w4zfc.js +1 -0
  54. package/dist/{chunk-whftbz4b.js → chunk-q8f1k8ns.js} +2 -2
  55. package/dist/chunk-qjzt9pna.js +1 -0
  56. package/dist/chunk-rbwntemj.js +1 -0
  57. package/dist/{chunk-sj2w24fe.js → chunk-rxfmqnf7.js} +2 -2
  58. package/dist/chunk-s1310gqw.js +1 -0
  59. package/dist/{chunk-jyeas4p9.js → chunk-sr2stcda.js} +1 -1
  60. package/dist/{chunk-wxqkpvqw.js → chunk-tffagd03.js} +2 -2
  61. package/dist/{chunk-a1ztrwjb.js → chunk-tw0eh910.js} +1 -1
  62. package/dist/chunk-txqccp76.js +1 -0
  63. package/dist/{chunk-y68sxcgk.js → chunk-vannpbp0.js} +1 -1
  64. package/dist/chunk-vc2c8wkx.js +2 -0
  65. package/dist/{chunk-vprpk6q1.js → chunk-vypake1a.js} +2 -2
  66. package/dist/{chunk-5hhfv1w1.js → chunk-wax3nm7t.js} +1 -1
  67. package/dist/{chunk-pmw9pn3v.js → chunk-x0g7y97q.js} +1 -1
  68. package/dist/{chunk-yz2bsntj.js → chunk-xjqcc0nt.js} +1 -1
  69. package/dist/{chunk-4ypy5bk8.js → chunk-yann89nx.js} +2 -2
  70. package/dist/{chunk-7mpa4esh.js → chunk-yqk501wp.js} +1 -1
  71. package/dist/{chunk-2ygqbd1z.js → chunk-zj651nrm.js} +1 -1
  72. package/dist/web/assets/ChatView-CCxjYDmJ.js +7 -0
  73. package/dist/web/assets/{CodeBlockHighlighter-DYuOTwXS.js → CodeBlockHighlighter-D9MqsrZP.js} +1 -1
  74. package/dist/web/assets/{FilePreview-CWOBOnzz.js → FilePreview-Cn5HOlPw.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-YiYvkN2w.js → MarkdownRenderer-ALTOCdfi.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-BT-oFKGN.js → SettingsModal-Dk69F1bS.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-D5Gd6FN9.js → TaskSwitcher-DRZZocE1.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-C1hLHq_K.js → TerminalPanel-ByAqKZ47.js} +1 -1
  79. package/dist/web/assets/{index-DuYx6fkN.js → index-CRCirUK7.js} +5 -5
  80. package/dist/web/index.html +1 -1
  81. package/package.json +1 -1
  82. package/dist/chunk-0et4h9p3.js +0 -1
  83. package/dist/chunk-0qayfsc9.js +0 -2
  84. package/dist/chunk-1p5822w7.js +0 -100
  85. package/dist/chunk-303cba4k.js +0 -1
  86. package/dist/chunk-51vnya3v.js +0 -1
  87. package/dist/chunk-6f3rp67k.js +0 -1
  88. package/dist/chunk-6v4dwkw7.js +0 -1
  89. package/dist/chunk-7p4qvftj.js +0 -1
  90. package/dist/chunk-9snsxf18.js +0 -1
  91. package/dist/chunk-c23c1vn6.js +0 -1
  92. package/dist/chunk-cb0rb9ss.js +0 -1
  93. package/dist/chunk-cysaxtfp.js +0 -10
  94. package/dist/chunk-efkqwhff.js +0 -1
  95. package/dist/chunk-ktbe458z.js +0 -2
  96. package/dist/chunk-r73fanrm.js +0 -1
  97. package/dist/chunk-smh39yy2.js +0 -1
  98. package/dist/chunk-w9tnd1q2.js +0 -1
  99. package/dist/chunk-zz9rax72.js +0 -1
  100. package/dist/web/assets/ChatView-YFotW0KS.js +0 -7
@@ -1,4 +1,4 @@
1
- import{fe as YO}from"./chunk-jyeas4p9.js";import{je as XO}from"./chunk-77z6x1zb.js";import{bf as qO,df as S,gf as y}from"./chunk-r561wfcz.js";import{nf as K}from"./chunk-dbb20rxh.js";import{Gf as n}from"./chunk-1y52h772.js";import{Pf as r}from"./chunk-kmeccj99.js";import{Rf as w}from"./chunk-fasxw5bb.js";var N;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(N||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import _ from"node:path";import{nanoid as z}from"nanoid";var C={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import jO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import h from"node:path";import{Mutex as WO}from"async-mutex";import SO from"write-file-atomic";var k=1,GO=1048576,VO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function LO(O){let q={};for(let Q of Object.values(N)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(N))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(LO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new WO;filePath;constructor(O=h.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let J;try{J=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let W=J.projects[Z];if(!W)return{...X,state:"untrusted"};return{...X,state:W.digest===$?"trusted":"modified",trustedDigest:W.digest,trustedAt:W.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:k,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>GO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==k)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!h.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!VO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:k,projects:Z}}async writeStore(O){let q=h.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await SO(this.filePath,`${JSON.stringify(O,null,2)}
1
+ import{je as YO}from"./chunk-sr2stcda.js";import{ne as XO}from"./chunk-djh79rde.js";import{ff as qO,hf as S,kf as y}from"./chunk-9ka0bdry.js";import{rf as K}from"./chunk-kvd5nexw.js";import{Kf as n}from"./chunk-h0q03x9f.js";import{Tf as r}from"./chunk-czjbz0fp.js";import{Vf as w}from"./chunk-c7zk9zj2.js";var N;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(N||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import _ from"node:path";import{nanoid as z}from"nanoid";var C={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import jO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import h from"node:path";import{Mutex as WO}from"async-mutex";import SO from"write-file-atomic";var k=1,GO=1048576,VO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function LO(O){let q={};for(let Q of Object.values(N)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(N))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(LO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new WO;filePath;constructor(O=h.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let J;try{J=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let W=J.projects[Z];if(!W)return{...X,state:"untrusted"};return{...X,state:W.digest===$?"trusted":"modified",trustedDigest:W.digest,trustedAt:W.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:k,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>GO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==k)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!h.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!VO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:k,projects:Z}}async writeStore(O){let q=h.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await SO(this.filePath,`${JSON.stringify(O,null,2)}
2
2
  `,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(zO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(BO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(AO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function zO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function BO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function AO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var KO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),PO=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),_O=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),UO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),NO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),MO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),wO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),CO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),EO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([KO,PO,_O,UO,bO,NO,MO,TO,wO,CO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(EO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",J=Q?.failureBehavior||"ignore",W=`Invalid hook output JSON: ${X}`;if(J==="deny")return{success:!1,blocking:!0,error:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(J==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${W}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:W,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class l{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class u{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:J}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),W=new l(this.MAX_STDOUT_SIZE),G=new l(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{W.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await J.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,R)=>{let F=!1,V=!1,B,P=()=>{return B??=J.terminate(),B},b=null,H=()=>{if(b&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",b),b=null},I=setTimeout(()=>{F=!0,P()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),F)await P();L({stdout:W.getContent(),stderr:G.getContent(),exitCode:F?124:f??1,timedOut:F})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),R(f)}),Q.abortSignal){if(b=()=>{if(V)return;V=!0,clearTimeout(I),H(),P().then(()=>{L({stdout:W.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",b),Q.abortSignal.aborted)b()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),DO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new u;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},J=await this.executeHook($,X,Q);if(!J.success){if(J.blocking)return{decision:"deny",reason:J.error};if(J.needsConfirmation)return{decision:"ask",reason:J.warning||J.error};if(J.warning)Y.push(J.warning);continue}let W=J.output?.hookSpecificOutput;if(W&&"permissionDecision"in W){switch(W.permissionDecision){case"deny":return{decision:"deny",reason:W.permissionDecisionReason};case"ask":return{decision:"ask",reason:W.permissionDecisionReason};case"allow":break}if("updatedInput"in W&&W.updatedInput)Z={...Z,...W.updatedInput}}}catch(X){let J=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${J}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:J};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${J}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
3
3
  `):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,J=[];for(let W of Y){if(!W.success&&W.warning){J.push(W.warning);continue}let G=W.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
4
4
 
@@ -25,7 +25,7 @@ import{fe as YO}from"./chunk-jyeas4p9.js";import{je as XO}from"./chunk-77z6x1zb.
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-303cba4k.js"),{createChatServiceAsync:J}=await import("./chunk-efkqwhff.js"),{resolveModelConfig:W}=await import("./chunk-6v4dwkw7.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-c23c1vn6.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-k7p4qwdr.js"),{createChatServiceAsync:J}=await import("./chunk-txqccp76.js"),{resolveModelConfig:W}=await import("./chunk-1ejj4jvg.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-rbwntemj.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -42,4 +42,4 @@ ${O.prompt}
42
42
  `+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
43
43
  `+`- 如果没有发现问题,使用 "approve"
44
44
  `+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let q=O.trim(),Q=q.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Q)return Q[1].trim();return q}async executeHooksConcurrently(O,q,Q,Z){let Y=[],$=new Set;for(let X of O){if($.size>=Z)await Promise.race($);let J=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),W=J.then(()=>{$.delete(W)}).catch(()=>{$.delete(W)});$.add(W),Y.push(J)}return Promise.all(Y)}}async function yO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:J}=await Q.read();if(J)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var HO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class i{matches(O,q){if(!O)return!0;if(O.tools&&q.toolName){if(!this.matchTools(O.tools,q))return!1}if(O.paths){let Q=q.filePaths??(q.filePath?[q.filePath]:[]);if(Q.length===0||!Q.some((Z)=>this.matchPaths(O.paths,Z)))return!1}if(O.commands&&q.command){if(!this.matchCommands(O.commands,q.command))return!1}return!0}matchTools(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchToolWithParams(Q,q));return this.matchToolWithParams(O,q)}matchPaths(O,q){if(Array.isArray(O))return O.some((Z)=>{return a(Z)(q)});return a(O)(q)}matchCommands(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchPattern(q,Q));return this.matchPattern(q,O)}matchToolWithParams(O,q){let{toolName:Q,command:Z,filePath:Y}=q,$=HO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,J]=$;if(!this.matchPattern(Q,X))return!1;let W=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(W.length===0)return!1;return W.some((G)=>this.matchGlobOrPattern(G,J))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}class U{static instance=null;config=C;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new Map;sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!U.instance)U.instance=new U;return U.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){let Z=this.sessionConfigKey(O,q[0]??K()),Y=this.disabledSessions.has(Z);for(let $ of q){let X=this.sessionConfigKey(O,$);if(Y||=this.disabledSessions.has(X),this.sessionStateAliases.set(X,Z),this.sessionConfigs.set(X,this.snapshotConfig(Q)),X!==Z)this.disabledSessions.delete(X)}if(Y)this.disabledSessions.add(Z)}async unbindSessionModelResources(O,q){let Q=new Set;for(let Z of q){let Y=this.sessionConfigKey(O,Z);Q.add(this.sessionStateAliases.get(Y)??Y),this.sessionConfigs.delete(Y),this.sessionStateAliases.delete(Y),this.disabledSessions.delete(Y)}for(let Z of Q)this.disabledSessions.delete(Z);await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){U.instance?.cleanup(),U.instance=null}loadConfig(O,q=K()){let Q=E(C,O),Z=c();Q=E(Q,Z);let Y=_.resolve(q);if(Y===_.resolve(K()))this.config=Q;this.projectConfigs.set(Y,Q)}isEnabled(O=K(),q){if(!(q?this.getExecutionConfig(q,O):this.getConfig(O)).enabled)return!1;if(this.processDisabled)return!1;if(q&&this.disabledSessions.has(this.sessionStateKey(q,O)))return!1;return!0}disable(){this.processDisabled=!0,console.log("[HookManager] Hooks disabled for this process")}enable(){this.processDisabled=!1,console.log("[HookManager] Hooks enabled for this process")}disableSession(O,q){this.disabledSessions.add(this.sessionStateKey(O,q))}enableSession(O,q){this.disabledSessions.delete(this.sessionStateKey(O,q))}isSessionEnabled(O,q){return this.isEnabled(q,O)}isSessionPaused(O,q){return this.disabledSessions.has(this.sessionStateKey(O,q))}getConfig(O=K()){let q=_.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===_.resolve(K()))return this.config;return{...C,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}isExecutionEnabled(O,q,Q){return O.enabled===!0&&!this.processDisabled&&!this.disabledSessions.has(this.sessionStateKey(q,Q))}sessionStateKey(O,q){let Q=this.sessionConfigKey(O,q);return this.sessionStateAliases.get(Q)??Q}sessionConfigKey(O,q){return`${O}\x00${_.resolve(q)}`}snapshotConfig(O){let q=E(C,O);for(let Q of Object.values(N))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}inheritProjectConfig(O,q){this.projectConfigs.set(_.resolve(q),this.getConfig(O))}getTrustStatus(O=K()){return A.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=K(),q){return A.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=K()){return A.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let J=_.resolve(Z.projectDir),W=this.getConfig(J),G=W[O]??[];return W[O]=[...G,$],this.projectConfigs.set(J,W),()=>{let L=W[O];if(!L)return;W[O]=L.filter((R)=>R!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let J=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=J.filter((W)=>W!==$)}}async reloadConfig(O=K()){let q=await import("node:fs/promises"),Q=await import("node:path");try{let Z=Q.join(O,".blade","settings.local.json"),Y=await q.readFile(Z,"utf-8"),$=JSON.parse(Y);if($.hooks)this.loadConfig($.hooks,O)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let W=await this.executor.executePreToolHooks(X,$,J);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(W.decision==="deny")return W;return{decision:"allow",modifiedInput:W.modifiedInput,warning:W.warning,reason:W.reason}}return W}catch(W){return console.error("[HookManager] Error executing PreToolUse hooks:",W),{decision:"allow",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(J,X,W);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let J={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,J)}catch(W){return console.error("[HookManager] Error executing PermissionRequest hooks:",W),{decision:"ask",warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:z(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:z(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},J=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(J.length===0)return{};let W={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(J,X,W)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{suppress:!1,message:q};let Y={hook_event_name:"Notification",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,notification_type:O,title:Q.title,message:q},$=this.getMatchingHooks("Notification",{},Z);if($.length===0)return{suppress:!1,message:q};let X={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeNotificationHooks($,Y,X)}catch(J){return console.error("[HookManager] Error executing Notification hooks:",J),{suppress:!1,message:q,warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"Elicitation",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:z(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll(),this.disabledSessions.clear(),this.sessionStateAliases.clear()}}
45
- export{N as be,o as ce,U as de};
45
+ export{N as fe,o as ge,U as he};
@@ -1,4 +1,4 @@
1
- import{ka as H}from"./chunk-4tkn9bky.js";import"./chunk-095x2ykj.js";import{$c as $,fd as T}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as k}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ka as H}from"./chunk-70jrd752.js";import"./chunk-4dnvydyv.js";import{dd as $,jd as T}from"./chunk-q8f1k8ns.js";import"./chunk-wax3nm7t.js";import"./chunk-xjqcc0nt.js";import"./chunk-hpgee5s3.js";import"./chunk-sr2stcda.js";import"./chunk-djh79rde.js";import"./chunk-nfm5j63c.js";import"./chunk-gcsygn5a.js";import"./chunk-9ka0bdry.js";import"./chunk-vc2c8wkx.js";import{rf as k}from"./chunk-kvd5nexw.js";import"./chunk-8472vz3s.js";import"./chunk-f9tahtz6.js";import"./chunk-tffagd03.js";import"./chunk-698qsvyb.js";import"./chunk-h0q03x9f.js";import"./chunk-czjbz0fp.js";import"./chunk-c7zk9zj2.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -0,0 +1 @@
1
+ import{$c as g,Vc as a,Wc as b,Xc as c,Yc as d,Zc as e,_c as f,ad as h,bd as i,cd as j,dd as k,ed as l,fd as m,gd as n,hd as o,id as p,jd as q}from"./chunk-q8f1k8ns.js";import"./chunk-wax3nm7t.js";import"./chunk-xjqcc0nt.js";import"./chunk-djh79rde.js";import"./chunk-nfm5j63c.js";import"./chunk-gcsygn5a.js";import"./chunk-9ka0bdry.js";import"./chunk-vc2c8wkx.js";import"./chunk-kvd5nexw.js";import"./chunk-8472vz3s.js";import"./chunk-f9tahtz6.js";import"./chunk-tffagd03.js";import"./chunk-698qsvyb.js";import"./chunk-h0q03x9f.js";import"./chunk-czjbz0fp.js";import"./chunk-c7zk9zj2.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,6 +1,6 @@
1
- import{zc as I}from"./chunk-k106g2p6.js";import{Sc as A}from"./chunk-whftbz4b.js";import{je as h}from"./chunk-77z6x1zb.js";import{Ne as f,Re as T,Se as w,Te as M,Ue as P,Xe as k,Ye as E}from"./chunk-mvc0tad6.js";import{Ze as c,_e as y}from"./chunk-ah8hky46.js";import{bf as S,df as n,gf as p}from"./chunk-r561wfcz.js";import{lf as O}from"./chunk-dbb20rxh.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]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=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:p(["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(m),timeout:n.Optional(m),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(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),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(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["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(r),ask:n.Optional(r),deny:n.Optional(r)})),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 a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}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 l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.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),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}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 l=await k.getInstance().initialize(i),s=E(l,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(`
1
+ import{Dc as I}from"./chunk-hjvdsrzb.js";import{Wc as A}from"./chunk-q8f1k8ns.js";import{ne as h}from"./chunk-djh79rde.js";import{$e as k,Re as f,Ve as T,We as w,Xe as M,Ye as P,af as E}from"./chunk-nfm5j63c.js";import{bf as c,cf as y}from"./chunk-gcsygn5a.js";import{ff as S,hf as n,kf as p}from"./chunk-9ka0bdry.js";import{pf as O}from"./chunk-kvd5nexw.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]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=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:p(["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(m),timeout:n.Optional(m),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(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),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(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["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(r),ask:n.Optional(r),deny:n.Optional(r)})),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 a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}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 l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.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),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}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 l=await k.getInstance().initialize(i),s=E(l,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
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
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.jsonSchema&&o.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((o.jsonSchema||o.outputSchema)&&!o.print&&!o.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");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 wc,g as xc,v as yc};
6
+ export{Z as Ac,g as Bc,v as Cc};
@@ -0,0 +1,2 @@
1
+ import{ne as o}from"./chunk-djh79rde.js";import{hf as J,if as $,jf as O,kf as K}from"./chunk-9ka0bdry.js";import{lf as v,mf as S,nf as l}from"./chunk-vc2c8wkx.js";import{Tf as n}from"./chunk-czjbz0fp.js";var G=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],a={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},f=new Map;function D(Q,Z,W){let B=new Set;for(let X of Q.split(",")){let[Y,k]=X.split("/"),V=k?Number.parseInt(k,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=W;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[U,i]=Y.split("-");j=Number.parseInt(U,10),H=Number.parseInt(i,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>W||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let U=j;U<=H;U+=V)B.add(U)}return B}function C(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[W,B,X,Y,k]=Z,V=D(k,G[4].min,G[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(W,G[0].min,G[0].max),hours:D(B,G[1].min,G[1].max),daysOfMonth:D(X,G[2].min,G[2].max),months:D(Y,G[3].min,G[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:k.trim()!=="*"}}function t(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let W=f.get(Z);if(!W)W=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),f.set(Z,W);let B=Object.fromEntries(W.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:a[B.weekday]??-1}}function r(Q,Z,W){let B=t(Z,W);if(!Q.minutes.has(B.minute))return!1;if(!Q.hours.has(B.hour))return!1;if(!Q.months.has(B.month))return!1;let X=Q.daysOfMonth.has(B.dayOfMonth),Y=Q.daysOfWeek.has(B.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function T(Q,Z,W){let B=C(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(r(B,X,W))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var E={s:1000,m:60000,h:3600000,d:86400000};function DJ(Q){let W=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!W)return null;let B=Number.parseInt(W[1],10);if(!Number.isInteger(B)||B<=0)return null;let X=W[2]||"m";return B*E[X]}function y(Q){for(let Z of["d","h","m","s"]){let W=E[Z];if(Q%W===0)return`${Q/W}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,W){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return T(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((W??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let B=new Date(Q.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>Z.getTime()?B:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(C(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function FJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?y(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as bJ,readFile as wJ}from"node:fs/promises";import s from"node:path";import{nanoid as LJ}from"nanoid";import PJ from"write-file-atomic";var w=$(K(["default","autoEdit","yolo","plan"]));var N=$(K(["user","assistant","system","tool"])),p=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),h=J.Union([J.String(),J.Array(p)]),NJ=$(J.Object({id:J.String(),role:N,content:h,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),e=$(K(["queued","running","completed","failed","cancelled","interrupted"])),F=$(K(["local","worktree"])),JJ=$(K(["applied","discarded","conflicted"])),QJ=$(J.Object({status:JJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),ZJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),$J=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),qJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array($J,{maxItems:100}),truncated:J.Boolean()})),BJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),KJ=$(J.Object({name:J.String(),type:K(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(BJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(K(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),xJ=$(J.Object({serverName:J.String(),mode:K(["form","url"]),message:J.String(),fields:J.Optional(J.Array(KJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),WJ=$(J.Object({type:K(["permission","question","elicitation"]),requestId:J.String()})),XJ=$(J.Object({code:K(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean()})),L=$(K(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(K(["auto","standard","fast","flex"])),M=$(K(["auto","low","medium","high"])),b=$(J.Union([K(["auto","pragmatic","friendly","explanatory"]),J.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(K(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:O(e,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(XJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional(QJ),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(ZJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(WJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),fJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),CJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),EJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),RJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:K(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:K(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),u=$(J.Object({role:N,content:h,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),SJ=$(J.Object({session:z,messages:J.Array(u)})),d=$(K(["conversation","code","both"])),YJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),lJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:O(d,"conversation")})),hJ=$(J.Object({checkpoint:YJ,mode:d,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(u)})),HJ=K(["running","completed","failed","cancelled"]),R=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:HJ,rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),restartRecovery:J.Optional(J.Object({outcome:K(["completed","interrupted","failed"]),recoveredAt:J.Number()})),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(K(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),uJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),dJ=$(J.Object({source:R,session:R})),mJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),cJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),gJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),nJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),m=J.Object({type:K(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:S})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),c=J.Record(J.String(),J.Unknown()),oJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),sJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:K(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),iJ=$(J.Object({action:K(["apply","discard"])})),q=$(J.Object({kind:K(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),jJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default")})),x=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,dispatch:jJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(K(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),enabled:O(J.Boolean(),!0)})),tJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(q),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),rJ=$(J.Object({schedules:J.Array(x)})),TJ=$(J.Object({content:J.String({maxLength:l}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),UJ=K(["completed","failed","aborted","timed_out","spawn_error"]),kJ=$(J.Object({version:J.Literal(1),command:J.String(),status:UJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),yJ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),pJ=$(J.Object({executionId:J.String(),messageId:J.String(),record:kJ,auxiliary:J.Boolean(),delivery:J.Optional(K(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),eJ=$(J.Object({projectPath:J.String(),kind:K(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),JQ=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),QQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),ZQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(K(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:K(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),VJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:K(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),$Q=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(K(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(K(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(K(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(VJ,{maxItems:36})),input:J.Optional(J.Array(K(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),BQ=$(K(["vs-dark","vs-light","hc-black"])),GJ=$(K(["light","dark","system"])),OJ=$(J.Object({language:J.String(),theme:J.String(),uiTheme:GJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),KQ=$(J.Partial(OJ));var g=o("Service"),MJ=1;function IJ(){return s.join(n(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=IJ()){this.filePath=Q}async readFile(){try{let Q=await wJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let W=[],B=0;for(let X of Z.schedules){let Y=x.safeParse(X);if(Y.success)W.push(Y.data);else B+=1}if(B>0)g.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return W}catch(Q){let Z=Q;if(Z.code!=="ENOENT")g.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await bJ(s.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:MJ,schedules:Q};await PJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((W)=>W.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,W=_(Z);if(W)throw Error(W);let B=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let X=B.toISOString(),Y=A(Z,B),k={id:LJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(k),await this.writeFile(V),k})}async update(Q,Z){return this.serializeWrite(async()=>{let W=await this.readFile(),B=W.findIndex((H)=>H.id===Q);if(B===-1)return;let X=W[B];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,U=_(H);if(U)throw Error(U);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},k=!X.enabled,V=Y.enabled,j=Z.trigger!==void 0;if((j||k&&V)&&Z.nextRunAt===void 0){let H=new Date,U=A(Y.trigger,H);if(Y.nextRunAt=U?U.toISOString():null,j)Y.expiresAt=null}return W[B]=Y,await this.writeFile(W),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),W=Z.filter((B)=>B.id!==Q);if(W.length===Z.length)return!1;return await this.writeFile(W),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var LQ=I.getInstance();
2
+ export{DJ as la,A as ma,_ as na,FJ as oa,qJ as pa,z as qa,lJ as ra,uJ as sa,oJ as ta,sJ as ua,iJ as va,x as wa,aJ as xa,tJ as ya,rJ as za,TJ as Aa,yJ as Ba,eJ as Ca,I as Da,LQ as Ea};
@@ -1,2 +1,2 @@
1
- import{td as B}from"./chunk-5chec8rs.js";import{sf as Y}from"./chunk-w5m418w5.js";import{vf as Z,yf as $}from"./chunk-9wqr1sbq.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
- export{K as pd,O as qd,E as rd};
1
+ import{xd as B}from"./chunk-m27w377p.js";import{wf as Y}from"./chunk-8472vz3s.js";import{Cf as $,zf as Z}from"./chunk-f9tahtz6.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
+ export{K as td,O as ud,E as vd};
@@ -1,2 +1,2 @@
1
1
  import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
2
- export{N as kf,D as lf,P as mf,V as nf};
2
+ export{N as of,D as pf,P as qf,V as rf};
@@ -1,2 +1,2 @@
1
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 sd,g as td};
2
+ export{s as wd,g as xd};
@@ -1,2 +1,2 @@
1
- import{C as o}from"./chunk-ryhk5qmv.js";import{bc as i}from"./chunk-1p5822w7.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
1
+ import{C as o}from"./chunk-46nbyp0r.js";import{fc as i}from"./chunk-ak7v70sy.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
2
2
  export{m as s};
@@ -0,0 +1 @@
1
+ import{ac as a,bc as b,cc as c,dc as d,ec as e,fc as f}from"./chunk-ak7v70sy.js";import"./chunk-vypake1a.js";import"./chunk-m27w377p.js";import"./chunk-5sw8j9ae.js";import"./chunk-sr2stcda.js";import"./chunk-djh79rde.js";import"./chunk-vc2c8wkx.js";import"./chunk-kvd5nexw.js";import"./chunk-f9tahtz6.js";import"./chunk-tffagd03.js";import"./chunk-czjbz0fp.js";import"./chunk-c7zk9zj2.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
@@ -1,4 +1,4 @@
1
- import{$e as Zn,af as Jn}from"./chunk-ah8hky46.js";import{bf as rn,cf as D,df as m}from"./chunk-r561wfcz.js";import{hf as pn,if as Nn}from"./chunk-0qayfsc9.js";import{nf as b}from"./chunk-dbb20rxh.js";import{pf as Dn,sf as H}from"./chunk-w5m418w5.js";import{Af as fn,Bf as En}from"./chunk-wxqkpvqw.js";import{Ff as P}from"./chunk-jahf977w.js";import{Pf as un}from"./chunk-kmeccj99.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 _ of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[_]!==void 0)throw Error(`MCP OAuth "${_}" 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((_)=>_.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 M=t.scopes?.map((_)=>_.trim());if(M){if(M.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(M.some((_)=>!_||_.length>128||!Qn.test(_)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(M).size!==M.length)throw Error("MCP OAuth scopes must not contain duplicates")}let o=t.callbackPort;if(o!==void 0&&(!Number.isInteger(o)||o<1024||o>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},...M?.length?{scopes:M}:{},...o!==void 0?{callbackPort:o}:{}}}import{randomUUID as J}from"node:crypto";import st from"node:http";import{auth as _n}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}),ot=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}),_t=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}),on=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(ot),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(_t),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),on)},{additionalProperties:!1});function l(n,t){return n instanceof Error&&"code"in n&&n.code===t}function it(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return l(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 y(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:y(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(on,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(l(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)}
1
+ import{df as Zn,ef as Jn}from"./chunk-gcsygn5a.js";import{ff as rn,gf as D,hf as m}from"./chunk-9ka0bdry.js";import{lf as pn,mf as Nn}from"./chunk-vc2c8wkx.js";import{rf as b}from"./chunk-kvd5nexw.js";import{tf as Dn,wf as H}from"./chunk-8472vz3s.js";import{Ef as fn,Ff as En}from"./chunk-tffagd03.js";import{Jf as P}from"./chunk-698qsvyb.js";import{Tf as un}from"./chunk-czjbz0fp.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 _ of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[_]!==void 0)throw Error(`MCP OAuth "${_}" 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((_)=>_.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 M=t.scopes?.map((_)=>_.trim());if(M){if(M.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(M.some((_)=>!_||_.length>128||!Qn.test(_)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(M).size!==M.length)throw Error("MCP OAuth scopes must not contain duplicates")}let o=t.callbackPort;if(o!==void 0&&(!Number.isInteger(o)||o<1024||o>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},...M?.length?{scopes:M}:{},...o!==void 0?{callbackPort:o}:{}}}import{randomUUID as J}from"node:crypto";import st from"node:http";import{auth as _n}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}),ot=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}),_t=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}),on=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(ot),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(_t),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),on)},{additionalProperties:!1});function l(n,t){return n instanceof Error&&"code"in n&&n.code===t}function it(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return l(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 y(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:y(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(on,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(l(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
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
3
  `,"utf8"),await r.close(),async()=>{try{if(JSON.parse(await A.readFile(n,"utf8")).token===t)await A.unlink(n)}catch(u){if(!l(u,"ENOENT"))throw u}}}catch(r){if(!l(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(!it(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 cn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ft(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -41,4 +41,4 @@ ${e.map((r)=>` - ${r}`).join(`
41
41
  ]
42
42
  }
43
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 le,q as me,x as ne,Q as oe,cn as pe,L as qe,Tn as re,se,K as te,fe as ue,Ee as ve,ce as we,wn as xe,dt as ye,ae as ze,xt as Ae,Te as Be,Rn as Ce,be as De,Pe as Ee,de as Fe,xe as Ge,Le as He,ln as Ie,he as Je,Ce as Ke,$e as Le,Ie as Me,f as Ne,w as Oe,N as Pe,G as Qe,zn as Re,Gn as Se,Hn as Te,qn as Ue,On as Ve,Yn as We,C as Xe,Mu as Ye};
44
+ export{B as pe,q as qe,x as re,Q as se,cn as te,L as ue,Tn as ve,se as we,K as xe,fe as ye,Ee as ze,ce as Ae,wn as Be,dt as Ce,ae as De,xt as Ee,Te as Fe,Rn as Ge,be as He,Pe as Ie,de as Je,xe as Ke,Le,ln as Me,he as Ne,Ce as Oe,$e as Pe,Ie as Qe,f as Re,w as Se,N as Te,G as Ue,zn as Ve,Gn as We,Hn as Xe,qn as Ye,On as Ze,Yn as _e,C as $e,Mu as af};
@@ -1,4 +1,4 @@
1
- import{b as uJ,c as lJ,d as dJ}from"./chunk-2ygqbd1z.js";import{j as e9,k as $J}from"./chunk-jhzk287k.js";import{r as p8}from"./chunk-a1ztrwjb.js";import{$ as g4,F as _$,H as C4,I as I4,L as J8,M as WJ,N as LJ,Q as BJ,R as wJ,W as w6,X as b6,Y as ZY,Z as E4,ba as U6,t as q6,w as s2,x as a2,y as e4,z as YY}from"./chunk-ryhk5qmv.js";import{fa as I9,ga as T9,ha as f9,ka as JY}from"./chunk-4tkn9bky.js";import"./chunk-ktbe458z.js";import{Va as l4,hb as u2}from"./chunk-72ztan96.js";import{sb as X8}from"./chunk-095x2ykj.js";import{Hb as m4,Pb as k4,Qb as x2,Rb as v4,Tb as D8,_b as Q8,bc as P0}from"./chunk-1p5822w7.js";import"./chunk-vprpk6q1.js";import{zc as cJ}from"./chunk-k106g2p6.js";import{Ac as G8,Bc as c8,Dc as T1}from"./chunk-edphxwj1.js";import"./chunk-65kbckpt.js";import{Hc as C$,Ic as d0,Jc as s1,Kc as RQ,Lc as D$,Mc as V8,Nc as o6,Oc as uQ,Pc as d9,Qc as n6,Rc as k$,Sc as Q1,Tc as $Y,Uc as r0,Vc as pJ,Wc as b2,Xc as Y8,_c as j4,fd as g0}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-sj2w24fe.js";import{rd as lQ}from"./chunk-afhdpen9.js";import"./chunk-5chec8rs.js";import"./chunk-4ypy5bk8.js";import{Ad as W6,Dd as kJ,Jd as HJ,Pd as QY}from"./chunk-g7p165yz.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import{be as IQ,de as U1}from"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import{ge as tJ,je as n1}from"./chunk-77z6x1zb.js";import{Ne as sJ,Xe as FJ,Ye as eJ}from"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import{hf as V$,if as j8,jf as TQ}from"./chunk-0qayfsc9.js";import{nf as x0}from"./chunk-dbb20rxh.js";import{of as n9,pf as t9,sf as V1}from"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import{Ef as g9}from"./chunk-wxqkpvqw.js";import{Ff as sQ}from"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import{Rf as CQ}from"./chunk-fasxw5bb.js";import{useMemoizedFn as k2}from"ahooks";import{useEffect as jX,useState as v2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as q$}from"ink";import{useEffect as U$,useMemo as TX,useRef as I2}from"react";import{useShallow as GY}from"zustand/react/shallow";import{useStore as XY}from"zustand";function s($){return XY(k$,$)}var KY=[],v$=()=>s(($)=>$.session.sessionId),I1=()=>s(($)=>$.session.workspaceRoot),eQ=()=>s(($)=>$.session.messages),$4=()=>s(($)=>$.session.clearCount),Q4=()=>s(($)=>$.session.isCompacting),J4=()=>s(($)=>$.session.tokenUsage.estimatedCostUsd),Y4=()=>s(($)=>$.session.providerRetry),Z4=()=>s(($)=>$.session.providerStall),a1=()=>s(($)=>$.session.actions),X4=()=>s(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),G4=()=>s(($)=>$.app.initializationStatus),K4=()=>s(($)=>$.app.initializationError),P8=()=>s(($)=>$.app.activeModal),q4=()=>s(($)=>$.app.tasks),U4=()=>s(($)=>$.app.modelEditorTarget),z4=()=>s(($)=>$.app.sessionSelectorData),O4=()=>s(($)=>$.app.awaitingSecondCtrlC),i1=()=>s(($)=>$.app.actions),y8=()=>s(($)=>$.app.initializationStatus==="ready"),_4=()=>s(($)=>$.app.tasks.length>0),S$=()=>s(($)=>$.config.config?.permissionMode||"default"),N4=()=>s(($)=>$.config.config?.models??KY),R8=()=>s(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),M8=()=>s(($)=>$.config.config?.currentModelId),A0=()=>s(($)=>{return d0.getTheme()}),F4=()=>s(($)=>$.config.config?.theme??"default"),$1=()=>s(($)=>$.focus.currentFocus),H4=()=>s(($)=>$.focus.actions),o1=()=>s(($)=>$.command.isProcessing),W4=()=>s(($)=>$.command.actions),C8=()=>s(($)=>$.command.pendingCommands),L4=()=>s(($)=>$.command.recoveredSteeringCount),I8=()=>s(($)=>$.app.thinkingModeEnabled),T8=()=>s(($)=>$.app.reasoningEffort),f8=()=>s(($)=>$.app.serviceTier),k8=()=>s(($)=>$.app.responseVerbosity),v8=()=>s(($)=>$.app.communicationStyle),B4=()=>s(($)=>$.session.currentThinkingContent),w4=()=>s(($)=>$.session.thinkingExpanded),b4=()=>s(($)=>$.session.currentStreamingMessageId),A4=()=>s(GY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),P4=()=>s(($)=>$.session.finalizingStreamingMessageId),y4=()=>s(($)=>$.session.historyExpanded),R4=()=>s(($)=>$.session.expandedMessageCount);import{useMemoizedFn as h$}from"ahooks";import{useEffect as p2,useRef as u4}from"react";function qY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let G=JSON.parse(J.responseBody)?.error?.message;if(G){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${G}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function UY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function zY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function S8($){let Q=UY($),Y=zY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=qY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as OY,mkdirSync as _Y,writeFileSync as NY}from"node:fs";import FY from"node:os";import j2 from"node:path";var M4=null;function HY(){let $=process.env.BLADE_STORAGE_ROOT||j2.join(FY.homedir(),".blade");return j2.join($,"logs","stream-debug.log")}function WY($){if(M4===$)return;let Q=j2.dirname($);_Y(Q,{recursive:!0,mode:493}),NY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{b as uJ,c as lJ,d as dJ}from"./chunk-zj651nrm.js";import{j as e9,k as $J}from"./chunk-abtq0kjb.js";import{r as p8}from"./chunk-tw0eh910.js";import{$ as g4,F as _$,H as C4,I as I4,L as J8,M as WJ,N as LJ,Q as BJ,R as wJ,W as w6,X as b6,Y as ZY,Z as E4,ba as U6,t as q6,w as s2,x as a2,y as e4,z as YY}from"./chunk-46nbyp0r.js";import{fa as I9,ga as T9,ha as f9,ka as JY}from"./chunk-70jrd752.js";import"./chunk-kky5ydtw.js";import{$a as l4,ib as u2}from"./chunk-0affe05f.js";import{tb as X8}from"./chunk-4dnvydyv.js";import{Lb as m4,Tb as k4,Ub as x2,Vb as v4,Xb as D8,cc as Q8,fc as P0}from"./chunk-ak7v70sy.js";import"./chunk-vypake1a.js";import{Dc as cJ}from"./chunk-hjvdsrzb.js";import{Ec as G8,Fc as c8,Hc as T1}from"./chunk-8efpk2z9.js";import"./chunk-9m80tr4t.js";import{$c as Y8,Lc as C$,Mc as d0,Nc as s1,Oc as RQ,Pc as D$,Qc as V8,Rc as o6,Sc as uQ,Tc as d9,Uc as n6,Vc as k$,Wc as Q1,Xc as $Y,Yc as r0,Zc as pJ,_c as b2,cd as j4,jd as g0}from"./chunk-q8f1k8ns.js";import"./chunk-wax3nm7t.js";import"./chunk-xjqcc0nt.js";import"./chunk-rxfmqnf7.js";import{vd as lQ}from"./chunk-ksm02qjh.js";import"./chunk-m27w377p.js";import"./chunk-yann89nx.js";import{Ed as W6,Hd as kJ,Nd as HJ,Td as QY}from"./chunk-2j3d4ykq.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import{fe as IQ,he as U1}from"./chunk-hpgee5s3.js";import"./chunk-sr2stcda.js";import{ke as tJ,ne as n1}from"./chunk-djh79rde.js";import{$e as FJ,Re as sJ,af as eJ}from"./chunk-nfm5j63c.js";import"./chunk-gcsygn5a.js";import"./chunk-9ka0bdry.js";import{lf as V$,mf as j8,nf as TQ}from"./chunk-vc2c8wkx.js";import{rf as x0}from"./chunk-kvd5nexw.js";import{sf as n9,tf as t9,wf as V1}from"./chunk-8472vz3s.js";import"./chunk-f9tahtz6.js";import{If as g9}from"./chunk-tffagd03.js";import{Jf as sQ}from"./chunk-698qsvyb.js";import"./chunk-h0q03x9f.js";import"./chunk-czjbz0fp.js";import{Vf as CQ}from"./chunk-c7zk9zj2.js";import{useMemoizedFn as k2}from"ahooks";import{useEffect as jX,useState as v2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as q$}from"ink";import{useEffect as U$,useMemo as TX,useRef as I2}from"react";import{useShallow as GY}from"zustand/react/shallow";import{useStore as XY}from"zustand";function s($){return XY(k$,$)}var KY=[],v$=()=>s(($)=>$.session.sessionId),I1=()=>s(($)=>$.session.workspaceRoot),eQ=()=>s(($)=>$.session.messages),$4=()=>s(($)=>$.session.clearCount),Q4=()=>s(($)=>$.session.isCompacting),J4=()=>s(($)=>$.session.tokenUsage.estimatedCostUsd),Y4=()=>s(($)=>$.session.providerRetry),Z4=()=>s(($)=>$.session.providerStall),a1=()=>s(($)=>$.session.actions),X4=()=>s(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),G4=()=>s(($)=>$.app.initializationStatus),K4=()=>s(($)=>$.app.initializationError),P8=()=>s(($)=>$.app.activeModal),q4=()=>s(($)=>$.app.tasks),U4=()=>s(($)=>$.app.modelEditorTarget),z4=()=>s(($)=>$.app.sessionSelectorData),O4=()=>s(($)=>$.app.awaitingSecondCtrlC),i1=()=>s(($)=>$.app.actions),y8=()=>s(($)=>$.app.initializationStatus==="ready"),_4=()=>s(($)=>$.app.tasks.length>0),S$=()=>s(($)=>$.config.config?.permissionMode||"default"),N4=()=>s(($)=>$.config.config?.models??KY),R8=()=>s(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),M8=()=>s(($)=>$.config.config?.currentModelId),A0=()=>s(($)=>{return d0.getTheme()}),F4=()=>s(($)=>$.config.config?.theme??"default"),$1=()=>s(($)=>$.focus.currentFocus),H4=()=>s(($)=>$.focus.actions),o1=()=>s(($)=>$.command.isProcessing),W4=()=>s(($)=>$.command.actions),C8=()=>s(($)=>$.command.pendingCommands),L4=()=>s(($)=>$.command.recoveredSteeringCount),I8=()=>s(($)=>$.app.thinkingModeEnabled),T8=()=>s(($)=>$.app.reasoningEffort),f8=()=>s(($)=>$.app.serviceTier),k8=()=>s(($)=>$.app.responseVerbosity),v8=()=>s(($)=>$.app.communicationStyle),B4=()=>s(($)=>$.session.currentThinkingContent),w4=()=>s(($)=>$.session.thinkingExpanded),b4=()=>s(($)=>$.session.currentStreamingMessageId),A4=()=>s(GY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),P4=()=>s(($)=>$.session.finalizingStreamingMessageId),y4=()=>s(($)=>$.session.historyExpanded),R4=()=>s(($)=>$.session.expandedMessageCount);import{useMemoizedFn as h$}from"ahooks";import{useEffect as p2,useRef as u4}from"react";function qY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let G=JSON.parse(J.responseBody)?.error?.message;if(G){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${G}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function UY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function zY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function S8($){let Q=UY($),Y=zY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=qY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as OY,mkdirSync as _Y,writeFileSync as NY}from"node:fs";import FY from"node:os";import j2 from"node:path";var M4=null;function HY(){let $=process.env.BLADE_STORAGE_ROOT||j2.join(FY.homedir(),".blade");return j2.join($,"logs","stream-debug.log")}function WY($){if(M4===$)return;let Q=j2.dirname($);_Y(Q,{recursive:!0,mode:493}),NY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),M4=$}function h2($,Q,Y){try{let J=HY();WY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",G=`[${Z}] [${$}] ${Q}${X}
3
3
  `;OY(J,G)}catch{}}var $8=n1("UI");function T4($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,h2("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$8.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),h2("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),G=$.getStreamingMessageId();if(G){if(Z)D$(G,Z);V8(G)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="scheduled"||J.phase==="attempt"?X:null);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===D8)break;if($8.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),G=C4(Z.function.name,X);$.sessionActions.addToolMessage(G,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:G,params:X})}catch(X){$8.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===D8)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",G=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(G,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:G});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===D8)break;$8.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=I4(Z.function.name,J.result);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":$8.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-zj651nrm.js";import"./chunk-c7zk9zj2.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};