blade-code 0.10.36 → 0.10.38

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 (85) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-qwrdss51.js → chunk-0b3fnxry.js} +3 -3
  3. package/dist/{chunk-qvdcesry.js → chunk-0dw58ycv.js} +2 -2
  4. package/dist/{chunk-1t8ebwsp.js → chunk-0tdc8pg9.js} +1 -1
  5. package/dist/chunk-13bzyvs2.js +1 -0
  6. package/dist/chunk-169rpaqn.js +1 -0
  7. package/dist/{chunk-1raz6s2b.js → chunk-199as76m.js} +2 -2
  8. package/dist/chunk-2mkdj63h.js +1 -0
  9. package/dist/chunk-4mpx8rad.js +1 -0
  10. package/dist/chunk-572gdsjd.js +1 -0
  11. package/dist/{chunk-q15qd9x4.js → chunk-5xfef98g.js} +1 -1
  12. package/dist/{chunk-acw8q8w9.js → chunk-6aw2ts3m.js} +1 -1
  13. package/dist/{chunk-95n8g52h.js → chunk-6t2bkj8s.js} +1 -1
  14. package/dist/chunk-7t97xngf.js +160 -0
  15. package/dist/chunk-8xp6djrk.js +1 -0
  16. package/dist/chunk-921c6fm5.js +1 -0
  17. package/dist/{chunk-7c5tnz4y.js → chunk-9yd3av82.js} +1 -1
  18. package/dist/{chunk-ekzck3x7.js → chunk-9zfr1ydk.js} +1 -1
  19. package/dist/{chunk-9g6rzbcv.js → chunk-a1shhh83.js} +1 -1
  20. package/dist/{chunk-cc7dmst6.js → chunk-a9r3w0t9.js} +2 -2
  21. package/dist/{chunk-6jpspf3v.js → chunk-ahkpjvaq.js} +1 -1
  22. package/dist/{chunk-qxvk42rf.js → chunk-ak37gg0n.js} +1 -1
  23. package/dist/{chunk-g510tpqt.js → chunk-asqah231.js} +1 -1
  24. package/dist/{chunk-phgqzja3.js → chunk-atdb1pks.js} +1 -1
  25. package/dist/{chunk-gy8esxaa.js → chunk-aw4r1zhr.js} +2 -2
  26. package/dist/{chunk-cnctwxqn.js → chunk-b9zfq3et.js} +1 -1
  27. package/dist/{chunk-2mvp3rqw.js → chunk-cm4t4cz6.js} +2 -2
  28. package/dist/{chunk-4bbnytq5.js → chunk-e6ttz45s.js} +1 -1
  29. package/dist/{chunk-n4555gej.js → chunk-e8wpd0s4.js} +1 -1
  30. package/dist/{chunk-xrhtwcd0.js → chunk-fj6frvhd.js} +1 -1
  31. package/dist/chunk-fjpqxdct.js +1 -0
  32. package/dist/{chunk-0m4s8r87.js → chunk-g7v01gjg.js} +3 -3
  33. package/dist/chunk-gc7bk6v0.js +1 -0
  34. package/dist/{chunk-95k17p11.js → chunk-gh0vdddb.js} +1 -1
  35. package/dist/{chunk-6gcmfvfj.js → chunk-gvx3707k.js} +1 -1
  36. package/dist/chunk-h4k801hr.js +6 -0
  37. package/dist/chunk-hcrfkqc1.js +1 -0
  38. package/dist/chunk-hkrbsqsw.js +6 -0
  39. package/dist/{chunk-rshbnfr8.js → chunk-htvt9e1j.js} +3 -3
  40. package/dist/chunk-jd764yqg.js +5 -0
  41. package/dist/{chunk-m2w03hpc.js → chunk-jpzrwcm7.js} +1 -1
  42. package/dist/{chunk-4s0c6tkd.js → chunk-jtjcg93t.js} +1 -1
  43. package/dist/chunk-jtv91ez8.js +2 -0
  44. package/dist/{chunk-250vpvr5.js → chunk-kw543czm.js} +1 -1
  45. package/dist/{chunk-y990fa4r.js → chunk-kzr5n83y.js} +41 -41
  46. package/dist/{chunk-0dj2qm8a.js → chunk-m0a2zdm8.js} +1 -1
  47. package/dist/{chunk-09qkatb5.js → chunk-m3yb3rek.js} +1 -1
  48. package/dist/chunk-n5nj8d8f.js +1 -0
  49. package/dist/{chunk-y9nq48st.js → chunk-qc5qwgpt.js} +2 -2
  50. package/dist/{chunk-ck5tvxkj.js → chunk-r863t0fx.js} +1 -1
  51. package/dist/{chunk-e23sz81n.js → chunk-rfec0k27.js} +1 -1
  52. package/dist/{chunk-5xc50n8e.js → chunk-rj1z55m8.js} +1 -1
  53. package/dist/{chunk-m6dh31kb.js → chunk-tczrjn95.js} +2 -2
  54. package/dist/chunk-ts8h7mx5.js +44 -0
  55. package/dist/{chunk-hq1wrf1g.js → chunk-vxpj2jgx.js} +1 -1
  56. package/dist/chunk-vxxhd72z.js +1 -0
  57. package/dist/{chunk-8ft7j7aw.js → chunk-y3sb4wda.js} +1 -1
  58. package/dist/{chunk-99ywfge1.js → chunk-ydy9bvcp.js} +1 -1
  59. package/dist/web/assets/{ChatView-Dx9j7CGg.js → ChatView-BB4nYdEf.js} +12 -12
  60. package/dist/web/assets/{CodeBlockHighlighter-CZADKR6S.js → CodeBlockHighlighter-CAFugWXU.js} +1 -1
  61. package/dist/web/assets/{FilePreview-BOIDa_oJ.js → FilePreview-O5aDfFS4.js} +1 -1
  62. package/dist/web/assets/{MarkdownRenderer-DXsfHVUX.js → MarkdownRenderer-C_qekwq_.js} +3 -3
  63. package/dist/web/assets/{SettingsModal-lQveNhC6.js → SettingsModal-FADlD0Da.js} +1 -1
  64. package/dist/web/assets/{TaskSwitcher-BSrmpJ2u.js → TaskSwitcher-D3k3tRpI.js} +1 -1
  65. package/dist/web/assets/{TerminalPanel-BFre9Shc.js → TerminalPanel-DBmKVVbI.js} +1 -1
  66. package/dist/web/assets/{index-DGZjm9wT.js → index-CMIW4J1Q.js} +3 -3
  67. package/dist/web/index.html +1 -1
  68. package/package.json +1 -1
  69. package/dist/chunk-3pxn6gcj.js +0 -1
  70. package/dist/chunk-4f1g8f6q.js +0 -1
  71. package/dist/chunk-4vq34v09.js +0 -5
  72. package/dist/chunk-515mkr66.js +0 -44
  73. package/dist/chunk-5c5qh3ab.js +0 -1
  74. package/dist/chunk-5vkxcjn1.js +0 -1
  75. package/dist/chunk-738a282r.js +0 -1
  76. package/dist/chunk-8m87dnk2.js +0 -1
  77. package/dist/chunk-e5yage6p.js +0 -1
  78. package/dist/chunk-hh158y4e.js +0 -6
  79. package/dist/chunk-j2tmdkmw.js +0 -1
  80. package/dist/chunk-psgt2pq7.js +0 -6
  81. package/dist/chunk-q3r0zfec.js +0 -1
  82. package/dist/chunk-rv6kca90.js +0 -1
  83. package/dist/chunk-s4enbe93.js +0 -160
  84. package/dist/chunk-ve7kp9rr.js +0 -1
  85. package/dist/chunk-xf2kjb9a.js +0 -1
@@ -0,0 +1 @@
1
+ import{jg as a,kg as b,lg as c,mg as d,ng as e,og as f}from"./chunk-aw4r1zhr.js";import"./chunk-jtjcg93t.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -0,0 +1 @@
1
+ import{Ad as l,Bd as m,Cd as n,Dd as o,Ed as p,Fd as q,pd as a,qd as b,rd as c,sd as d,td as e,ud as f,vd as g,wd as h,xd as i,yd as j,zd as k}from"./chunk-rfec0k27.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-ts8h7mx5.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-jtv91ez8.js";import"./chunk-0dw58ycv.js";import"./chunk-cm4t4cz6.js";import"./chunk-asqah231.js";import"./chunk-aw4r1zhr.js";import"./chunk-tczrjn95.js";import"./chunk-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.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,4 +1,4 @@
1
- import{Ab as Xt,Bb as bn,Cb as Tn,Db as fn}from"./chunk-5cgyevqj.js";import{Bc as jt}from"./chunk-qgez5vw6.js";import{Ee as Bt}from"./chunk-cc7dmst6.js";import{$e as wn,Je as xt,Ke as tn,Le as en,Me as zt,Ne as U,Oe as rn,Pe as gt,Qe as mt,Se as dn,Te as En,Ue as B,Ve as on,We as pn,Xe as un,Ye as lt,Ze as cn,_e as Mn,bf as S,ef as yn,ff as Ht,gf as Ut,hf as R,if as qt}from"./chunk-515mkr66.js";import{Bf as X,Df as x}from"./chunk-93jx06kq.js";import{Nf as vt}from"./chunk-6360fg4j.js";import{dg as nn,eg as sn}from"./chunk-gy8esxaa.js";import{ug as ss}from"./chunk-4s0c6tkd.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{Ab as Xt,Bb as bn,Cb as Tn,Db as fn}from"./chunk-5cgyevqj.js";import{Bc as jt}from"./chunk-qgez5vw6.js";import{Ee as Bt}from"./chunk-a9r3w0t9.js";import{$e as wn,Je as xt,Ke as tn,Le as en,Me as zt,Ne as U,Oe as rn,Pe as gt,Qe as mt,Se as dn,Te as En,Ue as B,Ve as on,We as pn,Xe as un,Ye as lt,Ze as cn,_e as Mn,bf as S,ef as yn,ff as Ht,gf as Ut,hf as R,if as qt}from"./chunk-ts8h7mx5.js";import{Bf as X,Df as x}from"./chunk-93jx06kq.js";import{Nf as vt}from"./chunk-6360fg4j.js";import{kg as nn,lg as sn}from"./chunk-aw4r1zhr.js";import{Bg as ss}from"./chunk-jtjcg93t.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-m2w03hpc.js";import{L as M,S as y}from"./chunk-0m4s8r87.js";import"./chunk-7c5tnz4y.js";import"./chunk-95k17p11.js";import{ib as h,rb as A}from"./chunk-y990fa4r.js";import"./chunk-5cgyevqj.js";import{jc as w,xc as U}from"./chunk-6gcmfvfj.js";import"./chunk-qgez5vw6.js";import"./chunk-phgqzja3.js";import{Uc as C}from"./chunk-1t8ebwsp.js";import{Wc as I,Xc as S,Yc as v}from"./chunk-hh158y4e.js";import{Zc as O}from"./chunk-qggnvzkc.js";import"./chunk-0evyrnx0.js";import{ud as P}from"./chunk-e23sz81n.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-4vq34v09.js";import"./chunk-6jpspf3v.js";import"./chunk-3rjmkaey.js";import"./chunk-acw8q8w9.js";import"./chunk-9g6rzbcv.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-cc7dmst6.js";import"./chunk-v11r4ahz.js";import"./chunk-515mkr66.js";import{Af as F}from"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as z}from"./chunk-6360fg4j.js";import"./chunk-qvdcesry.js";import"./chunk-2mvp3rqw.js";import"./chunk-g510tpqt.js";import"./chunk-gy8esxaa.js";import"./chunk-m6dh31kb.js";import"./chunk-0dj2qm8a.js";import"./chunk-y9nq48st.js";import"./chunk-4s0c6tkd.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-jpzrwcm7.js";import{L as M,S as y}from"./chunk-g7v01gjg.js";import"./chunk-9yd3av82.js";import"./chunk-gh0vdddb.js";import{ib as h,rb as A}from"./chunk-kzr5n83y.js";import"./chunk-5cgyevqj.js";import{jc as w,xc as U}from"./chunk-gvx3707k.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import{Uc as C}from"./chunk-0tdc8pg9.js";import{Wc as I,Xc as S,Yc as v}from"./chunk-h4k801hr.js";import{Zc as O}from"./chunk-qggnvzkc.js";import"./chunk-0evyrnx0.js";import{ud as P}from"./chunk-rfec0k27.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-jd764yqg.js";import"./chunk-ahkpjvaq.js";import"./chunk-3rjmkaey.js";import"./chunk-6aw2ts3m.js";import"./chunk-a1shhh83.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-a9r3w0t9.js";import"./chunk-v11r4ahz.js";import"./chunk-ts8h7mx5.js";import{Af as F}from"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as z}from"./chunk-6360fg4j.js";import"./chunk-jtv91ez8.js";import"./chunk-0dw58ycv.js";import"./chunk-cm4t4cz6.js";import"./chunk-asqah231.js";import"./chunk-aw4r1zhr.js";import"./chunk-tczrjn95.js";import"./chunk-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1,4 +1,4 @@
1
- import{re as L1,se as Z0,te as G1}from"./chunk-hq18c6r9.js";import{xe as $O,ye as HO}from"./chunk-zwt7f9ab.js";import{Be as Y1}from"./chunk-ckfc7j7m.js";import{Ce as B0,Ee as M0}from"./chunk-cc7dmst6.js";import{nf as V0,of as o1,yf as S0}from"./chunk-515mkr66.js";import{Bf as u,Df as W,Gf as R1}from"./chunk-93jx06kq.js";import{Nf as b}from"./chunk-6360fg4j.js";import{Rf as h,Sf as z}from"./chunk-qvdcesry.js";import{dg as p0}from"./chunk-gy8esxaa.js";import{ig as w}from"./chunk-m6dh31kb.js";import J1 from"node:path";import Y$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import zO from"yaml";var u$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function c$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
1
+ import{re as L1,se as Z0,te as G1}from"./chunk-hq18c6r9.js";import{xe as $O,ye as HO}from"./chunk-zwt7f9ab.js";import{Be as Y1}from"./chunk-ckfc7j7m.js";import{Ce as B0,Ee as M0}from"./chunk-a9r3w0t9.js";import{nf as V0,of as o1,yf as S0}from"./chunk-ts8h7mx5.js";import{Bf as u,Df as W,Gf as R1}from"./chunk-93jx06kq.js";import{Nf as b}from"./chunk-6360fg4j.js";import{Yf as h,Zf as z}from"./chunk-0dw58ycv.js";import{kg as p0}from"./chunk-aw4r1zhr.js";import{pg as w}from"./chunk-tczrjn95.js";import J1 from"node:path";import Y$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import zO from"yaml";var u$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function c$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -1,4 +1,4 @@
1
- import{Ie as YO}from"./chunk-v11r4ahz.js";import{Bf as qO,Df as S,Gf as y}from"./chunk-93jx06kq.js";import{Nf as K}from"./chunk-6360fg4j.js";import{Rf as XO}from"./chunk-qvdcesry.js";import{jg as n}from"./chunk-0dj2qm8a.js";import{sg as r}from"./chunk-y9nq48st.js";import{ug as w}from"./chunk-4s0c6tkd.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{Ie as YO}from"./chunk-v11r4ahz.js";import{Bf as qO,Df as S,Gf as y}from"./chunk-93jx06kq.js";import{Nf as K}from"./chunk-6360fg4j.js";import{Yf as XO}from"./chunk-0dw58ycv.js";import{qg as n}from"./chunk-m0a2zdm8.js";import{zg as r}from"./chunk-qc5qwgpt.js";import{Bg as w}from"./chunk-jtjcg93t.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{Ie as YO}from"./chunk-v11r4ahz.js";import{Bf as qO,Df as S,Gf as y}from".
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-e5yage6p.js"),{createChatServiceAsync:J}=await import("./chunk-8m87dnk2.js"),{resolveModelConfig:W}=await import("./chunk-j2tmdkmw.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-5vkxcjn1.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-921c6fm5.js"),{createChatServiceAsync:J}=await import("./chunk-vxxhd72z.js"),{resolveModelConfig:W}=await import("./chunk-4mpx8rad.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-13bzyvs2.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}
@@ -1,2 +1,2 @@
1
- import{Sd as B}from"./chunk-3rjmkaey.js";import{Xf as Y}from"./chunk-2mvp3rqw.js";import{_f as Z,bg as $}from"./chunk-g510tpqt.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}}
1
+ import{Sd as B}from"./chunk-3rjmkaey.js";import{cg as Y}from"./chunk-cm4t4cz6.js";import{fg as Z,ig as $}from"./chunk-asqah231.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
2
  export{K as Od,O as Pd,E as Qd};
@@ -1,2 +1,2 @@
1
- import{Xf as o}from"./chunk-2mvp3rqw.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
1
+ import{cg as o}from"./chunk-cm4t4cz6.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
2
2
  export{e as j,i as k};
@@ -1,2 +1,2 @@
1
1
  var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
2
- export{f as Yf,p as Zf,u as _f,S as $f,c as ag,l as bg};
2
+ export{f as dg,p as eg,u as fg,S as gg,c as hg,l as ig};
@@ -1,4 +1,4 @@
1
- import{Rf as i}from"./chunk-qvdcesry.js";import{kg as o,mg as C,og as L,sg as j,tg as n}from"./chunk-y9nq48st.js";import{ug as I}from"./chunk-4s0c6tkd.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
1
+ import{Yf as i}from"./chunk-0dw58ycv.js";import{Ag as n,rg as o,tg as C,vg as L,zg as j}from"./chunk-qc5qwgpt.js";import{Bg as I}from"./chunk-jtjcg93t.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
2
2
  `),W=!_.endsWith(`
3
3
  `),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
4
4
  `)}
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as a}from"node:path";import{fileURLToPath as u}from"node:url";var t={name:"blade-code",version:"0.10.36",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(u(import.meta.url));for(let n=0;n<5;n++){try{let e=JSON.parse(l(a(i,"package.json"),"utf8"));if(e.name===t.name&&typeof e.version==="string"&&typeof e.description==="string")return s=e,s}catch{}i=o(i)}return s={name:t.name,version:process.env.BLADE_VERSION??t.version,description:t.description},s}function v(){return{...r()}}function p(){return r().version}function h(){return r().name}function w(){return r().description}function f(){return`v${p()}`}function g(){return`v${p()} © 2025 Blade Code`}
2
- export{v as cg,p as dg,h as eg,w as fg,f as gg,g as hg};
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as a}from"node:path";import{fileURLToPath as u}from"node:url";var t={name:"blade-code",version:"0.10.38",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(u(import.meta.url));for(let n=0;n<5;n++){try{let e=JSON.parse(l(a(i,"package.json"),"utf8"));if(e.name===t.name&&typeof e.version==="string"&&typeof e.description==="string")return s=e,s}catch{}i=o(i)}return s={name:t.name,version:process.env.BLADE_VERSION??t.version,description:t.description},s}function v(){return{...r()}}function p(){return r().version}function h(){return r().name}function w(){return r().description}function f(){return`v${p()}`}function g(){return`v${p()} © 2025 Blade Code`}
2
+ export{v as jg,p as kg,h as lg,w as mg,f as ng,g as og};
@@ -1 +1 @@
1
- import{rc as a,sc as b,tc as c,uc as d,vc as e,wc as f,xc as g}from"./chunk-6gcmfvfj.js";import"./chunk-qgez5vw6.js";import"./chunk-phgqzja3.js";import"./chunk-3rjmkaey.js";import"./chunk-zwt7f9ab.js";import"./chunk-v11r4ahz.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-qvdcesry.js";import"./chunk-g510tpqt.js";import"./chunk-gy8esxaa.js";import"./chunk-y9nq48st.js";import"./chunk-4s0c6tkd.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
1
+ import{rc as a,sc as b,tc as c,uc as d,vc as e,wc as f,xc as g}from"./chunk-gvx3707k.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import"./chunk-3rjmkaey.js";import"./chunk-zwt7f9ab.js";import"./chunk-v11r4ahz.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-0dw58ycv.js";import"./chunk-asqah231.js";import"./chunk-aw4r1zhr.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1,3 +1,3 @@
1
- import{Zf as N,ag as M}from"./chunk-g510tpqt.js";import{sg as H}from"./chunk-y9nq48st.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
1
+ import{eg as N,hg as M}from"./chunk-asqah231.js";import{zg as H}from"./chunk-qc5qwgpt.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
2
2
  `,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
3
- export{K as Tf,X as Uf,J as Vf,L as Wf,hu as Xf};
3
+ export{K as _f,X as $f,J as ag,L as bg,hu as cg};
@@ -1,3 +1,3 @@
1
- import{rg as $,sg as F}from"./chunk-y9nq48st.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
1
+ import{yg as $,zg as F}from"./chunk-qc5qwgpt.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
2
2
  `,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
3
3
  export{_ as l};
@@ -1 +1 @@
1
- import{La as J,sa as V,ua as W,va as O}from"./chunk-95k17p11.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as Q}from"./chunk-6360fg4j.js";import"./chunk-qvdcesry.js";import"./chunk-y9nq48st.js";import"./chunk-4s0c6tkd.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
1
+ import{La as J,sa as V,ua as W,va as O}from"./chunk-gh0vdddb.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as Q}from"./chunk-6360fg4j.js";import"./chunk-0dw58ycv.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
@@ -1,3 +1,3 @@
1
- import{l as i}from"./chunk-4bbnytq5.js";import{Nf as s}from"./chunk-6360fg4j.js";import"./chunk-y9nq48st.js";import"./chunk-4s0c6tkd.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{l as i}from"./chunk-e6ttz45s.js";import{Nf as s}from"./chunk-6360fg4j.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -0,0 +1 @@
1
+ import{pg as a}from"./chunk-tczrjn95.js";import"./chunk-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";export{a as WorkspaceTrustService};
@@ -1,4 +1,4 @@
1
- import{ja as R,ka as i0,pa as TJ,qa as H9,ra as u0}from"./chunk-7c5tnz4y.js";import{La as H3,sa as G3,ua as z3,va as h4}from"./chunk-95k17p11.js";import{Ma as w$,Na as U1,Oa as o8,Pa as p$,Qa as d8,Ra as p9,Va as K0,Xa as v2,Ya as e8,Za as $9,_a as Z9,bb as i2,db as d6,eb as r2,fb as n2,ib as J$,ob as K5,pb as _J,qb as g7,wb as T9,zb as M9}from"./chunk-y990fa4r.js";import{Fb as z0,Gb as D1,Hb as v$,Ib as Y2,Jb as l4,Kb as c2,Lb as l2,Vb as X5,Wb as F0,Xb as o0,ec as i4,fc as d0,gc as W1,hc as e7,ic as $J,lc as LJ,pc as j9,uc as ZJ,vc as JJ,xc as n}from"./chunk-6gcmfvfj.js";import{Ac as n9,Bc as P2,yc as h,zc as r9}from"./chunk-qgez5vw6.js";import{Cc as O3,Fc as _3,Nc as F3,Tc as q3}from"./chunk-phgqzja3.js";import{cd as yZ,dd as vZ}from"./chunk-0evyrnx0.js";import{Ad as A9,Fd as Y1,pd as a2,qd as B0,rd as k,ud as O0,vd as I2,wd as V1,xd as A$,yd as e6,zd as g$}from"./chunk-e23sz81n.js";import{Gd as z$}from"./chunk-atsw605q.js";import{Md as VJ,Nd as y2}from"./chunk-4vq34v09.js";import{Pd as R0,Qd as f$}from"./chunk-6jpspf3v.js";import{Rd as qJ}from"./chunk-3rjmkaey.js";import{Td as n7,Ud as a7,Vd as t7}from"./chunk-acw8q8w9.js";import{$d as R$,Wd as u2,Xd as d2,Zd as m2,_d as p2,ae as e9,ce as I0,de as M3,ee as x0,fe as r0,ge as f5,he as U5,ie as W$,je as o$,ke as s$,le as s7,me as D4,oe as U0,pe as x2,qe as XJ}from"./chunk-9g6rzbcv.js";import{se as K1,ue as Z$,ve as N2}from"./chunk-hq18c6r9.js";import{Ae as xZ,we as yJ,ye as o7,ze as Y5}from"./chunk-zwt7f9ab.js";import{Ce as f4,Ee as N0}from"./chunk-cc7dmst6.js";import{Fe as a1,Ge as c4,He as t1,Ie as e$}from"./chunk-v11r4ahz.js";import{Ke as LZ,Pe as bZ,Re as M4,We as jJ,_e as NZ,af as c7,cf as a8,df as t8,jf as i$,mf as c8,of as GZ,qf as UJ,rf as r7,sf as _9,tf as F9,uf as q9,vf as D9,wf as E9,xf as w9,yf as X0}from"./chunk-515mkr66.js";import{Bf as U2,Cf as C5,Df as B,Ef as $7,Ff as S,Gf as c}from"./chunk-93jx06kq.js";import{If as x7,Jf as h7}from"./chunk-thstqcg3.js";import{Lf as z2,Nf as C}from"./chunk-6360fg4j.js";import{Rf as r}from"./chunk-qvdcesry.js";import{Wf as l7,Xf as i7}from"./chunk-2mvp3rqw.js";import{$f as vJ,Yf as hJ}from"./chunk-g510tpqt.js";import{dg as mJ}from"./chunk-gy8esxaa.js";import{ig as k0}from"./chunk-m6dh31kb.js";import{lg as J2,ng as c$,pg as p7,qg as XZ,sg as w0}from"./chunk-y9nq48st.js";import{ug as X$}from"./chunk-4s0c6tkd.js";import{randomUUID as j5}from"crypto";import{randomUUID as v3}from"node:crypto";var R3=String.raw`
1
+ import{ja as R,ka as i0,pa as TJ,qa as H9,ra as u0}from"./chunk-9yd3av82.js";import{La as H3,sa as G3,ua as z3,va as h4}from"./chunk-gh0vdddb.js";import{Ma as w$,Na as U1,Oa as o8,Pa as p$,Qa as d8,Ra as p9,Va as K0,Xa as v2,Ya as e8,Za as $9,_a as Z9,bb as i2,db as d6,eb as r2,fb as n2,ib as J$,ob as K5,pb as _J,qb as g7,wb as T9,zb as M9}from"./chunk-kzr5n83y.js";import{Fb as z0,Gb as D1,Hb as v$,Ib as Y2,Jb as l4,Kb as c2,Lb as l2,Vb as X5,Wb as F0,Xb as o0,ec as i4,fc as d0,gc as W1,hc as e7,ic as $J,lc as LJ,pc as j9,uc as ZJ,vc as JJ,xc as n}from"./chunk-gvx3707k.js";import{Ac as n9,Bc as P2,yc as h,zc as r9}from"./chunk-qgez5vw6.js";import{Cc as O3,Fc as _3,Nc as F3,Tc as q3}from"./chunk-atdb1pks.js";import{cd as yZ,dd as vZ}from"./chunk-0evyrnx0.js";import{Ad as A9,Fd as Y1,pd as a2,qd as B0,rd as k,ud as O0,vd as I2,wd as V1,xd as A$,yd as e6,zd as g$}from"./chunk-rfec0k27.js";import{Gd as z$}from"./chunk-atsw605q.js";import{Md as VJ,Nd as y2}from"./chunk-jd764yqg.js";import{Pd as R0,Qd as f$}from"./chunk-ahkpjvaq.js";import{Rd as qJ}from"./chunk-3rjmkaey.js";import{Td as n7,Ud as a7,Vd as t7}from"./chunk-6aw2ts3m.js";import{$d as R$,Wd as u2,Xd as d2,Zd as m2,_d as p2,ae as e9,ce as I0,de as M3,ee as x0,fe as r0,ge as f5,he as U5,ie as W$,je as o$,ke as s$,le as s7,me as D4,oe as U0,pe as x2,qe as XJ}from"./chunk-a1shhh83.js";import{se as K1,ue as Z$,ve as N2}from"./chunk-hq18c6r9.js";import{Ae as xZ,we as yJ,ye as o7,ze as Y5}from"./chunk-zwt7f9ab.js";import{Ce as f4,Ee as N0}from"./chunk-a9r3w0t9.js";import{Fe as a1,Ge as c4,He as t1,Ie as e$}from"./chunk-v11r4ahz.js";import{Ke as LZ,Pe as bZ,Re as M4,We as jJ,_e as NZ,af as c7,cf as a8,df as t8,jf as i$,mf as c8,of as GZ,qf as UJ,rf as r7,sf as _9,tf as F9,uf as q9,vf as D9,wf as E9,xf as w9,yf as X0}from"./chunk-ts8h7mx5.js";import{Bf as U2,Cf as C5,Df as B,Ef as $7,Ff as S,Gf as c}from"./chunk-93jx06kq.js";import{If as x7,Jf as h7}from"./chunk-thstqcg3.js";import{Lf as z2,Nf as C}from"./chunk-6360fg4j.js";import{Yf as r}from"./chunk-0dw58ycv.js";import{bg as l7,cg as i7}from"./chunk-cm4t4cz6.js";import{dg as hJ,gg as vJ}from"./chunk-asqah231.js";import{kg as mJ}from"./chunk-aw4r1zhr.js";import{pg as k0}from"./chunk-tczrjn95.js";import{sg as J2,ug as c$,wg as p7,xg as XZ,zg as w0}from"./chunk-qc5qwgpt.js";import{Bg as X$}from"./chunk-jtjcg93t.js";import{randomUUID as j5}from"crypto";import{randomUUID as v3}from"node:crypto";var R3=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -776,7 +776,7 @@ ${$0}
776
776
  </approved-plan>
777
777
 
778
778
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof H==="string")J0=H+v;else J0=[...H,{type:"text",text:v}]}P=yield*this.runLoop(J0,O,{...M,inputMessageId:void 0})}if(!this.sessionRuntime||!A)return P;let y=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0});if(y)yield{kind:"goal_updated",goal:y};if(!P.success||O.signal?.aborted){if(y=await this.sessionRuntime.pauseActiveGoal(O.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),y)yield{kind:"goal_updated",goal:y}}if(P.success&&!O.signal?.aborted&&L<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(A,O.signal);let l=P.success&&!O.signal?.aborted&&L<20;if(b=await this.sessionRuntime.finishTurn(A,{continuePending:l,outcome:P.success&&!O.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:O.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),b){L++,_=!0,F=!1,D=null,H="",E=void 0,q=j(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:T()};continue}if(!P.success||O.signal?.aborted)return P;if(y=await this.sessionRuntime.getGoal(),!y||y.status!=="active"&&y.status!=="verifying")return P;if(D=await this.sessionRuntime.beginGoalContinuation(),!D)return P;b=await this.sessionRuntime.beginTurn("goal"),_=!1,F=!0,H=Y6(D),E=void 0,q=void 0,yield{kind:"goal_continuation_started",goal:D,continuation:D.continuationCount},yield{kind:"goal_updated",goal:D}}}finally{if(this.sessionRuntime&&b)await this.sessionRuntime.finishTurn(b)}}let K=typeof Q==="string"?Q:Q.filter((H)=>H.type==="text").map((H)=>H.text).join(`
779
- `),G={id:this.generateTaskId(),type:"simple",prompt:K};return{success:!0,finalMessage:(await this.executeTask(G)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-ve7kp9rr.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await u$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=T1($);else{let U=$.filter((W)=>W.type==="text");if(U.length>0){let W=U[0];X=$.map((Q)=>Q===W?{type:"text",text:T1(W.text)}:Q)}else X=[{type:"text",text:T1("")},...$]}return yield*this.executeLoop(X,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await u$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return M9(X,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},X=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,U=J.error===void 0,W=J.output,Q={success:U,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...X?{metadata:X}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],K=T9(Y,Q);if(K)V.push(K);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of Y)Z.unregister(X.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await u$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await h2({sessionId:"default",configDir:R9.join(C9.homedir(),".blade"),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await H2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new j1(`legacy-${sU()}`)});this.legacyMcpRegistry=Z;for(let[U,W]of Object.entries($))try{p.debug(`Connecting to MCP server: ${U}`),await Z.registerServer(U,W),p.debug(`MCP server "${U}" connected`)}catch(Q){p.warn(`Warning: MCP server "${U}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(S1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(U)=>{J.replaceMcpTools(U.tools,U)}),Z.on("contentCatalogChanged",(U)=>{J.queueMcpContentChange(U)}),Z.on("resourceUpdated",(U)=>{J.queueMcpResourceUpdated(U)}),Z.on("connectionLifecycleChanged",(U)=>{J.queueMcpConnectionChange(U)}),Z.on("log",(U)=>{J.queueMcpLog(U)}),Z.on("instructionsChanged",(U)=>{J.queueMcpInstructionsChange({revision:U.revision,reason:U.reason,replace:!1,instructions:U.action==="added"&&U.instruction?[{serverName:U.serverName,...U.instruction}]:[],removed:U.action==="removed"?[U.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((U)=>U.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await U0(C());if(this.agentResources=x2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((X)=>{if(X===Y.name)return!0;let U=X.match(/^(\w+)\(.*\)$/);if(U&&U[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
779
+ `),G={id:this.generateTaskId(),type:"simple",prompt:K};return{success:!0,finalMessage:(await this.executeTask(G)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-hcrfkqc1.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await u$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=T1($);else{let U=$.filter((W)=>W.type==="text");if(U.length>0){let W=U[0];X=$.map((Q)=>Q===W?{type:"text",text:T1(W.text)}:Q)}else X=[{type:"text",text:T1("")},...$]}return yield*this.executeLoop(X,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await u$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return M9(X,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},X=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,U=J.error===void 0,W=J.output,Q={success:U,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...X?{metadata:X}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],K=T9(Y,Q);if(K)V.push(K);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of Y)Z.unregister(X.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await u$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await h2({sessionId:"default",configDir:R9.join(C9.homedir(),".blade"),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await H2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new j1(`legacy-${sU()}`)});this.legacyMcpRegistry=Z;for(let[U,W]of Object.entries($))try{p.debug(`Connecting to MCP server: ${U}`),await Z.registerServer(U,W),p.debug(`MCP server "${U}" connected`)}catch(Q){p.warn(`Warning: MCP server "${U}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(S1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(U)=>{J.replaceMcpTools(U.tools,U)}),Z.on("contentCatalogChanged",(U)=>{J.queueMcpContentChange(U)}),Z.on("resourceUpdated",(U)=>{J.queueMcpResourceUpdated(U)}),Z.on("connectionLifecycleChanged",(U)=>{J.queueMcpConnectionChange(U)}),Z.on("log",(U)=>{J.queueMcpLog(U)}),Z.on("instructionsChanged",(U)=>{J.queueMcpInstructionsChange({revision:U.revision,reason:U.reason,replace:!1,instructions:U.action==="added"&&U.instruction?[{serverName:U.serverName,...U.instruction}]:[],removed:U.action==="removed"?[U.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((U)=>U.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await U0(C());if(this.agentResources=x2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((X)=>{if(X===Y.name)return!0;let U=X.match(/^(\w+)\(.*\)$/);if(U&&U[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
780
780
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let X=this.buildAttachmentText(Y);if(!X)return $;return[...$,{type:"text",text:X}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let X of $)if(X.type==="file"){let U=X.metadata?.lineRange?` (lines ${X.metadata.lineRange.start}${X.metadata.lineRange.end?`-${X.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${X.path}"${U?` range="${U}"`:""}>`,X.content,"</file>")}else if(X.type==="directory")Z.push(`<directory path="${X.path}">`,X.content,"</directory>");else if(X.type==="error")J.push(`- @${X.path}: ${X.error}`);let Y="";if(Z.length>0)Y+=`
781
781
 
782
782
  <system-reminder>
@@ -1574,7 +1574,7 @@ ${J}
1574
1574
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1575
1575
  `)}}case"create":{let Q=FG(U);if("error"in Q)return Y.sendMessage(`创建失败:${Q.error}`),{success:!1,error:Q.error};let V={prompt:Q.prompt,projectPath:W,trigger:Q.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let K=await $.create(V),G=K.nextRunAt?new Date(K.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${K.id}\`
1576
1576
  ${h4(K.trigger)} · 下次运行: ${G}`),{success:!0,message:`Schedule ${K.id} created`}}catch(K){let G=K instanceof Error?K.message:String(K);return Y.sendMessage(`创建失败:${G}`),{success:!1,error:G}}}case"remove":case"rm":{let Q=U[0];if(!Q)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(Q);return Y.sendMessage(V?`[OK] 已删除 \`${Q}\``:`未找到 \`${Q}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let Q=U[0];if(!Q)return Y.sendMessage(`用法:/schedule ${X} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(Q,X==="enable");return Y.sendMessage(V?`[OK] 已${X==="enable"?"启用":"停用"} \`${Q}\``:`未找到 \`${Q}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let Q=U[0];if(!Q)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await qG(Q),Y.sendMessage(`[OK] 已触发 \`${Q}\``),{success:!0,message:"Schedule triggered"}}catch(V){let K=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${K}`),{success:!1,error:K}}}default:return Y.sendMessage(`未知子命令: ${X}
1577
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var B3=DG();import*as F1 from"node:fs/promises";import*as q1 from"node:path";async function D3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:X,storagePath:U}=Z,W=U??J2(X??C());if(!U){let H=await EG($,X??C(),J,Y);if(H)return H}let Q;try{Q=(await F1.readdir(W)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>q1.join(W,O))}catch{return[]}let K=(await Promise.all(Q.map(async(H)=>{try{let O=await F1.stat(H);return{path:H,mtime:O.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,O)=>O.mtime-H.mtime).map((H)=>H.path),G=[],z=Y?$:$.toLowerCase();for(let H of K){if(G.length>=J)break;let O=q1.basename(H,".jsonl"),_=await wG(H,z,Y,O);if(G.push(..._),G.length>=J){G.length=J;break}}return G}async function EG($,Z,J,Y){try{let{syncAll:X}=await import("./chunk-5xc50n8e.js"),U=await F3();if(!U)return null;let{SessionService:W}=await import("./chunk-cnctwxqn.js");await X(U,W.projectionDeriverForSearch());let Q=q1.resolve(Z),V=q3(U,$,Q,J*4),K=Y?$:$.toLowerCase(),G=[];for(let z of V){if(z.role!=="user"&&z.role!=="assistant")continue;let H=g4(z.text,K,Y,z.session_id,z.role,z.timestamp??void 0,0);if(H)G.push(H);if(G.length>=J)break}return G}catch{return null}}async function wG($,Z,J,Y){try{let X=await F1.readFile($,"utf8"),W=X.split(`
1577
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var B3=DG();import*as F1 from"node:fs/promises";import*as q1 from"node:path";async function D3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:X,storagePath:U}=Z,W=U??J2(X??C());if(!U){let H=await EG($,X??C(),J,Y);if(H)return H}let Q;try{Q=(await F1.readdir(W)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>q1.join(W,O))}catch{return[]}let K=(await Promise.all(Q.map(async(H)=>{try{let O=await F1.stat(H);return{path:H,mtime:O.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,O)=>O.mtime-H.mtime).map((H)=>H.path),G=[],z=Y?$:$.toLowerCase();for(let H of K){if(G.length>=J)break;let O=q1.basename(H,".jsonl"),_=await wG(H,z,Y,O);if(G.push(..._),G.length>=J){G.length=J;break}}return G}async function EG($,Z,J,Y){try{let{syncAll:X}=await import("./chunk-rj1z55m8.js"),U=await F3();if(!U)return null;let{SessionService:W}=await import("./chunk-b9zfq3et.js");await X(U,W.projectionDeriverForSearch());let Q=q1.resolve(Z),V=q3(U,$,Q,J*4),K=Y?$:$.toLowerCase(),G=[];for(let z of V){if(z.role!=="user"&&z.role!=="assistant")continue;let H=g4(z.text,K,Y,z.session_id,z.role,z.timestamp??void 0,0);if(H)G.push(H);if(G.length>=J)break}return G}catch{return null}}async function wG($,Z,J,Y){try{let X=await F1.readFile($,"utf8"),W=X.split(`
1578
1578
  `).flatMap((z,H)=>{if(!z.trim())return[];try{return[{event:JSON.parse(z),index:H}]}catch{return[]}});if(!W.some(({event:z})=>z.type==="session_created"))return LG(W,Z,J,Y);let V=new Map(W.flatMap(({event:z,index:H})=>typeof z.id==="string"?[[z.id,H+1]]:[])),K=O3(_3(X,$)),G=new Map;for(let z of K){if(z.type==="message_created"&&(z.data.role==="user"||z.data.role==="assistant"))G.set(z.data.messageId,{role:z.data.role,content:[],timestamp:z.timestamp,lineNumber:V.get(z.id)??0});if(z.type==="part_created"&&z.data.partType==="text"){let H=G.get(z.data.messageId),O=z.data.payload.text;if(H&&typeof O==="string")H.content.push(O)}}return[...G.values()].flatMap((z)=>{let H=g4(z.content.join(" "),Z,J,Y,z.role,z.timestamp,z.lineNumber);return H?[H]:[]})}catch{return[]}}function LG($,Z,J,Y){return $.flatMap(({event:X,index:U})=>{if(X.type!=="message")return[];let W=X.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let Q=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((K)=>typeof K==="object"&&K!==null&&K.type==="text"&&typeof K.text==="string").map((K)=>K.text).join(" "):"",V=g4(Q,Z,J,Y,W.role,typeof X.timestamp==="string"?X.timestamp:void 0,U+1);return V?[V]:[]})}function g4($,Z,J,Y,X,U,W){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let V=Q.indexOf(Z),K=Math.max(0,V-80),G=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:X,content:(K>0?"...":"")+$.slice(K,G).replace(/\n/g," ")+(G<$.length?"...":""),timestamp:U,lineNumber:W}}function E3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1579
1579
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",X=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${X} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1580
1580
  `)}var bG={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=I(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let X=await D3(Y,{maxResults:15,projectPath:Z.cwd}),U=E3(X);return J.sendMessage(U),{success:!0,message:`found ${X.length} results`,data:{matches:X.length}}}catch(X){let U=X instanceof Error?X.message:"未知错误";return J.sendMessage(`搜索失败: ${U}`),{success:!1,error:U}}}},w3=bG;var NG={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await I0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),s$(Z.workspaceRoot??Z.cwd),await o$(Z.workspaceRoot??Z.cwd),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return k().addAssistantMessage(Y),{success:!1,error:Y}}}},L3=NG;import AG from"node:path";function q5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function b3($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function N3($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function jG($,Z){let J=I(Z),Y=$[0],X=t.getInstance(),U=Z0.getInstance(),W=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:AG.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let O=$[1],_=$.slice(2).join(" ").trim();if(!O||!_)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let F=await Z.subagents.resume(O,_),q=`Resumed \`${O}\` as \`${F.session.id}\` (depth ${F.session.resumeDepth}).`;return J.sendMessage(q),{success:!0,message:q,data:{action:"subagent_resumed",sourceAgentId:O,subagent:F.session}}}if(Y==="clean"){let O=U.cleanupExpiredSessionsForParent(Q??W,0);return J.sendMessage(`已清理 ${O} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${O} agent sessions`}}let V=[`**后台任务列表**
@@ -0,0 +1 @@
1
+ import{Wc as a,Xc as b,Yc as c}from"./chunk-h4k801hr.js";import"./chunk-qggnvzkc.js";import"./chunk-rfec0k27.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-ckfc7j7m.js";import"./chunk-ts8h7mx5.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-jtv91ez8.js";import"./chunk-0dw58ycv.js";import"./chunk-cm4t4cz6.js";import"./chunk-asqah231.js";import"./chunk-aw4r1zhr.js";import"./chunk-tczrjn95.js";import"./chunk-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};