blade-code 0.10.37 → 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 (41) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-q0mwwhpw.js → chunk-0b3fnxry.js} +1 -1
  3. package/dist/{chunk-y5jxkynb.js → chunk-0tdc8pg9.js} +1 -1
  4. package/dist/{chunk-15w4crsc.js → chunk-13bzyvs2.js} +1 -1
  5. package/dist/chunk-169rpaqn.js +1 -0
  6. package/dist/{chunk-61h0d0gq.js → chunk-199as76m.js} +2 -2
  7. package/dist/chunk-2mkdj63h.js +1 -0
  8. package/dist/{chunk-m377j9bs.js → chunk-572gdsjd.js} +1 -1
  9. package/dist/{chunk-dgks1che.js → chunk-5xfef98g.js} +1 -1
  10. package/dist/{chunk-46r1m8yn.js → chunk-6aw2ts3m.js} +1 -1
  11. package/dist/{chunk-232bcv23.js → chunk-6t2bkj8s.js} +1 -1
  12. package/dist/chunk-7t97xngf.js +160 -0
  13. package/dist/{chunk-qzn3rb8r.js → chunk-8xp6djrk.js} +1 -1
  14. package/dist/{chunk-e6frdh2s.js → chunk-921c6fm5.js} +1 -1
  15. package/dist/{chunk-0nvc6y56.js → chunk-9yd3av82.js} +1 -1
  16. package/dist/{chunk-0e4nc00e.js → chunk-9zfr1ydk.js} +1 -1
  17. package/dist/{chunk-rtzd076h.js → chunk-a1shhh83.js} +1 -1
  18. package/dist/{chunk-r48jmc74.js → chunk-a9r3w0t9.js} +1 -1
  19. package/dist/{chunk-b6ve4vyt.js → chunk-aw4r1zhr.js} +1 -1
  20. package/dist/{chunk-jz6esh56.js → chunk-b9zfq3et.js} +1 -1
  21. package/dist/{chunk-g5429yjs.js → chunk-g7v01gjg.js} +3 -3
  22. package/dist/{chunk-8bczq0xe.js → chunk-gc7bk6v0.js} +1 -1
  23. package/dist/{chunk-d63dczf8.js → chunk-gvx3707k.js} +1 -1
  24. package/dist/{chunk-xsew6530.js → chunk-h4k801hr.js} +1 -1
  25. package/dist/{chunk-xfrdwxde.js → chunk-hcrfkqc1.js} +1 -1
  26. package/dist/{chunk-s3xfr72w.js → chunk-hkrbsqsw.js} +1 -1
  27. package/dist/{chunk-r9pz4z1p.js → chunk-htvt9e1j.js} +1 -1
  28. package/dist/{chunk-fqcf0n0h.js → chunk-jpzrwcm7.js} +1 -1
  29. package/dist/{chunk-9hjhbsna.js → chunk-kzr5n83y.js} +1 -1
  30. package/dist/{chunk-njb4rjhs.js → chunk-m3yb3rek.js} +1 -1
  31. package/dist/{chunk-mznx9gg6.js → chunk-n5nj8d8f.js} +1 -1
  32. package/dist/{chunk-x4yfhp8j.js → chunk-r863t0fx.js} +1 -1
  33. package/dist/{chunk-5cjy9yj1.js → chunk-rfec0k27.js} +1 -1
  34. package/dist/{chunk-vk3e2w5h.js → chunk-ts8h7mx5.js} +1 -1
  35. package/dist/{chunk-qavfq2vp.js → chunk-vxpj2jgx.js} +1 -1
  36. package/dist/{chunk-jsd6d2f5.js → chunk-y3sb4wda.js} +1 -1
  37. package/dist/{chunk-v2wka1pq.js → chunk-ydy9bvcp.js} +1 -1
  38. package/package.json +1 -1
  39. package/dist/chunk-5ckfx738.js +0 -1
  40. package/dist/chunk-73pqjvxk.js +0 -1
  41. package/dist/chunk-8pcfmzq0.js +0 -160
@@ -1 +1 @@
1
- import{jg as a,kg as b,lg as c,mg as d,ng as e,og as f}from"./chunk-b6ve4vyt.js";import"./chunk-jtjcg93t.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
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};
@@ -1 +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-5cjy9yj1.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-vk3e2w5h.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-b6ve4vyt.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
+ 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-r48jmc74.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-vk3e2w5h.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-b6ve4vyt.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} 个错误):
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-fqcf0n0h.js";import{L as M,S as y}from"./chunk-g5429yjs.js";import"./chunk-0nvc6y56.js";import"./chunk-gh0vdddb.js";import{ib as h,rb as A}from"./chunk-9hjhbsna.js";import"./chunk-5cgyevqj.js";import{jc as w,xc as U}from"./chunk-d63dczf8.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import{Uc as C}from"./chunk-y5jxkynb.js";import{Wc as I,Xc as S,Yc as v}from"./chunk-xsew6530.js";import{Zc as O}from"./chunk-qggnvzkc.js";import"./chunk-0evyrnx0.js";import{ud as P}from"./chunk-5cjy9yj1.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-jd764yqg.js";import"./chunk-ahkpjvaq.js";import"./chunk-3rjmkaey.js";import"./chunk-46r1m8yn.js";import"./chunk-rtzd076h.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-r48jmc74.js";import"./chunk-v11r4ahz.js";import"./chunk-vk3e2w5h.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-b6ve4vyt.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)}
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-r48jmc74.js";import{nf as V0,of as o1,yf as S0}from"./chunk-vk3e2w5h.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-b6ve4vyt.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
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
@@ -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-e6frdh2s.js"),{createChatServiceAsync:J}=await import("./chunk-vxxhd72z.js"),{resolveModelConfig:W}=await import("./chunk-4mpx8rad.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-15w4crsc.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{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.37",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`}
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
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-d63dczf8.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-b6ve4vyt.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
+ 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,4 +1,4 @@
1
- import{ja as R,ka as i0,pa as TJ,qa as H9,ra as u0}from"./chunk-0nvc6y56.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-9hjhbsna.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-d63dczf8.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-5cjy9yj1.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-46r1m8yn.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-rtzd076h.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-r48jmc74.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-vk3e2w5h.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-b6ve4vyt.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`
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-xfrdwxde.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-rj1z55m8.js"),U=await F3();if(!U)return null;let{SessionService:W}=await import("./chunk-jz6esh56.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=[`**后台任务列表**
@@ -1 +1 @@
1
- import{Wc as a,Xc as b,Yc as c}from"./chunk-xsew6530.js";import"./chunk-qggnvzkc.js";import"./chunk-5cjy9yj1.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-ckfc7j7m.js";import"./chunk-vk3e2w5h.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-b6ve4vyt.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};
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};
@@ -1,4 +1,4 @@
1
- import{Cc as u,Dc as Hf,Ec as C$,Fc as Yf,Gc as I,Hc as N$,Ic as Wf,Jc as G$,Kc as _$,Lc as x$,Nc as g0,Qc as J$,Rc as Uf}from"./chunk-atdb1pks.js";import{Rd as V0}from"./chunk-3rjmkaey.js";import{we as Z0}from"./chunk-zwt7f9ab.js";import{Ie as i$}from"./chunk-v11r4ahz.js";import{Hf as Qf,If as Xf}from"./chunk-thstqcg3.js";import{Nf as A$}from"./chunk-6360fg4j.js";import{Yf as U0}from"./chunk-0dw58ycv.js";import{dg as x0,gg as J0}from"./chunk-asqah231.js";import{kg as p}from"./chunk-b6ve4vyt.js";import{rg as Ff,sg as q0,tg as Kf,ug as A,vg as m,xg as G0,yg as c,zg as C0}from"./chunk-qc5qwgpt.js";import{readdir as L$,readFile as a,rm as $0,stat as E0}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as yf,randomUUID as Sf}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as Mf}from"node:child_process";import{createHash as gf}from"node:crypto";import{readFileSync as Ef}from"node:fs";var bf=/^[a-f0-9]{64}$/;function Y$($){if(!$||typeof $!=="object")return!1;let f=$;return(f.platform==="linux"||f.platform==="darwin"||f.platform==="win32")&&typeof f.fingerprint==="string"&&bf.test(f.fingerprint)}var W$={readFile:($)=>Ef($,"utf8"),execFile:($,f)=>Mf($,f,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},wf=($)=>{try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}};function u0($,f){return{platform:$,fingerprint:gf("sha256").update(`${$}\x00${f}`).digest("hex")}}function kf($,f){let T=f.readFile(`/proc/${$}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function Q0($,f=process.platform,T=W$){if(!Number.isInteger($)||$<=1)return;try{if(f==="linux")return u0(f,kf($,T));if(f==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String($)]).trim();return q?u0(f,q):void 0}if(f==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0(f,B):void 0}}catch{return}return}function U$($,f){return Q0($,f.platform)?.fingerprint===f.fingerprint}function o1($,f,T=W$,q=wf){if(!Number.isInteger($)||$<=1)return!1;let B=Q0($,f.platform,T);if(B)return B.fingerprint===f.fingerprint;return!q($)}var z$=1;function jf($,f){let T=yf("sha256").update(f).digest("hex");return H0.join(q0($),".locks",`${T}.lock`)}function X0($,f){return $ instanceof Error&&"code"in $&&$.code===f}async function P0($){try{let f=JSON.parse(await v.readFile($,"utf8"));if(f.version!==z$||typeof f.sessionId!=="string"||typeof f.ownerId!=="string"||!Number.isInteger(f.pid)||(f.pid??0)<=0||f.processIdentity!==void 0&&!Y$(f.processIdentity)||typeof f.acquiredAt!=="string")return;return f}catch{return}}async function D$($){let f=await P0($);if(f)return f;return await new Promise((T)=>setTimeout(T,10)),P0($)}function mf($){try{return process.kill($,0),!0}catch(f){return X0(f,"EPERM")}}async function R$($,f){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(f)}
1
+ import{Cc as u,Dc as Hf,Ec as C$,Fc as Yf,Gc as I,Hc as N$,Ic as Wf,Jc as G$,Kc as _$,Lc as x$,Nc as g0,Qc as J$,Rc as Uf}from"./chunk-atdb1pks.js";import{Rd as V0}from"./chunk-3rjmkaey.js";import{we as Z0}from"./chunk-zwt7f9ab.js";import{Ie as i$}from"./chunk-v11r4ahz.js";import{Hf as Qf,If as Xf}from"./chunk-thstqcg3.js";import{Nf as A$}from"./chunk-6360fg4j.js";import{Yf as U0}from"./chunk-0dw58ycv.js";import{dg as x0,gg as J0}from"./chunk-asqah231.js";import{kg as p}from"./chunk-aw4r1zhr.js";import{rg as Ff,sg as q0,tg as Kf,ug as A,vg as m,xg as G0,yg as c,zg as C0}from"./chunk-qc5qwgpt.js";import{readdir as L$,readFile as a,rm as $0,stat as E0}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as yf,randomUUID as Sf}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as Mf}from"node:child_process";import{createHash as gf}from"node:crypto";import{readFileSync as Ef}from"node:fs";var bf=/^[a-f0-9]{64}$/;function Y$($){if(!$||typeof $!=="object")return!1;let f=$;return(f.platform==="linux"||f.platform==="darwin"||f.platform==="win32")&&typeof f.fingerprint==="string"&&bf.test(f.fingerprint)}var W$={readFile:($)=>Ef($,"utf8"),execFile:($,f)=>Mf($,f,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},wf=($)=>{try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}};function u0($,f){return{platform:$,fingerprint:gf("sha256").update(`${$}\x00${f}`).digest("hex")}}function kf($,f){let T=f.readFile(`/proc/${$}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function Q0($,f=process.platform,T=W$){if(!Number.isInteger($)||$<=1)return;try{if(f==="linux")return u0(f,kf($,T));if(f==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String($)]).trim();return q?u0(f,q):void 0}if(f==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0(f,B):void 0}}catch{return}return}function U$($,f){return Q0($,f.platform)?.fingerprint===f.fingerprint}function o1($,f,T=W$,q=wf){if(!Number.isInteger($)||$<=1)return!1;let B=Q0($,f.platform,T);if(B)return B.fingerprint===f.fingerprint;return!q($)}var z$=1;function jf($,f){let T=yf("sha256").update(f).digest("hex");return H0.join(q0($),".locks",`${T}.lock`)}function X0($,f){return $ instanceof Error&&"code"in $&&$.code===f}async function P0($){try{let f=JSON.parse(await v.readFile($,"utf8"));if(f.version!==z$||typeof f.sessionId!=="string"||typeof f.ownerId!=="string"||!Number.isInteger(f.pid)||(f.pid??0)<=0||f.processIdentity!==void 0&&!Y$(f.processIdentity)||typeof f.acquiredAt!=="string")return;return f}catch{return}}async function D$($){let f=await P0($);if(f)return f;return await new Promise((T)=>setTimeout(T,10)),P0($)}function mf($){try{return process.kill($,0),!0}catch(f){return X0(f,"EPERM")}}async function R$($,f){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(f)}
2
2
  `,"utf8"),!0}catch(q){if(X0(q,"EEXIST"))return!1;if(T)await v.unlink($).catch(()=>{return});throw q}finally{await T?.close().catch(()=>{return})}}class h extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class n{filePath;record;released=!1;constructor($,f){this.filePath=$;this.record=f}static async acquire($,f=A$()){let T=jf(f,$),q={version:z$,sessionId:$,ownerId:Sf(),pid:process.pid,processIdentity:Q0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(H0.dirname(T),{recursive:!0,mode:448}),await R$(T,q))return new n(T,q);let B=await D$(T);if(B&&mf(B.pid)&&(!B.processIdentity||U$(B.pid,B.processIdentity)))throw new h(B.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await R$(T,q))return new n(T,q);throw new h((await D$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await P0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((f)=>{if(!X0(f,"ENOENT"))throw f})}}var TT=1;function h0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function If($){if(!h0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&h0($.image_url)&&typeof $.image_url.url==="string"}function vf($){if(!h0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(If)}function M$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let f=JSON.stringify($);if(Buffer.byteLength(f)>16777216)return;let T=JSON.parse(f);if(!Array.isArray(T)||!T.every(vf))return;return T}function qT($){let f=M$($);if(!f)throw Error("Compaction replacement context is invalid or exceeds limits");return f}function g$($){return M$($)}function uf($,f){for(let T of $){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let q=T.data.payload;if(!q||typeof q!=="object"||Array.isArray(q))continue;let B=q;if(B.toolCallId===f||T.data.partId===f||T.data.messageId===f)return B}return}function E$($){let f=u($),T=new Map;for(let q of f){if(q.type==="interaction_requested"){T.set(q.data.requestId,{request:q.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(q.type==="interaction_responded"){let B=T.get(q.data.requestId);if(B)B.response=q.data;continue}if(q.type==="interaction_recovered"){let B=T.get(q.data.requestId);if(B)B.recovery=q.data}}for(let q of T.values()){let B=uf(f,q.request.toolCallId);q.hasToolResult=B!==void 0;let L=B?.metadata&&typeof B.metadata==="object"?B.metadata:void 0;q.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===q.request.requestId}return[...T.values()]}function b$($){return E$($).reverse().find((f)=>!f.response&&!f.recovery)}function OT($){let f=new Map;for(let T of E$($))f.set(T.request.toolCallId,T);return[...f.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function w$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function Y0($){let f=new Map,T=[];for(let q of $){if(q.type==="review_started"){if(!f.has(q.data.reviewId))T.push(q.data.reviewId),f.set(q.data.reviewId,{start:q.data});continue}if(q.type!=="review_completed")continue;let B=f.get(q.data.reviewId);if(B&&B.completion===void 0)B.completion=q.data}return T.map((q)=>f.get(q)).filter((q)=>q!==void 0)}function NT($){return Y0($).reverse().find((f)=>f.completion===void 0)}function n0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function k$($,f){let T=["## Code Review","",`Target: ${$.target.label}`,`Status: ${n0(f.status)}`,"",f.overallExplanation||"No overall explanation was provided."];if(f.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[q,B]of f.findings.entries()){let L=B.codeLocation.lineStart===B.codeLocation.lineEnd?`${B.codeLocation.lineStart}`:`${B.codeLocation.lineStart}-${B.codeLocation.lineEnd}`;T.push("",`${q+1}. ${B.title}`,` ${B.codeLocation.path}:L${L} · confidence ${B.confidenceScore.toFixed(2)}`,` ${B.body}`)}}if(f.error)T.push("",`Error: ${f.error}`);return T.join(`
3
3
  `)}function y$($,f){return{reviewId:$.reviewId,phase:"completed",status:f.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:f.overallExplanation,findings:f.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...f.error?{error:f.error}:{}}}var l0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Pf($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function hf($){let f=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(f))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(f))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(f))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(f))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(f))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(f))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(f))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(f))return"unsupported_input";return"runtime"}function nf($){return{code:$,...l0[$]}}function c0($){return nf(hf(Pf($)))}function p0($){if(!$||typeof $!=="object")return!1;let f=$;if(typeof f.code!=="string"||!(f.code in l0))return!1;let T=l0[f.code];return f.message===T.message&&f.retryable===T.retryable}import{promises as L0,realpathSync as cf}from"node:fs";import W0 from"node:path";import*as r from"fs/promises";import*as H from"path";var S$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,f){super($);this.code=f;this.name="PathSecurityError"}}class i0{static normalize($,f){let T=H.isAbsolute($)?$:H.resolve(f,$),q=H.normalize(T),B=H.normalize(f);if(!this.isWithinWorkspace(q,B))throw new d(`Path outside workspace: ${$} (resolved to ${q}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return q}static checkRestricted($){let f=$.split(H.sep);for(let T of S$)if(f.includes(T))throw new d(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,f){this.checkTraversal($);let T=this.normalize($,f);this.checkRestricted(T);try{await r.access(T)}catch(q){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,f){try{let T=await r.realpath($),q=await r.realpath(f);if(!this.isWithinWorkspace(T,q))throw new d(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return $}}static getRelativePath($,f){return H.relative(f,$)}static isWithinWorkspace($,f){let T=H.resolve($),q=H.resolve(f),B=H.relative(q,T);return B===""||B!==".."&&!B.startsWith(`..${H.sep}`)&&!H.isAbsolute(B)}static async isWithinWorkspaceResolved($,f){let T=H.resolve(f),q=H.isAbsolute($)?H.resolve($):H.resolve(T,$);if(!this.isWithinWorkspace(q,T))return!1;let B;try{B=await r.realpath(T)}catch{return!1}let L=q;while(!0){try{let C=await r.realpath(L);return this.isWithinWorkspace(C,B)}catch(C){let _=C.code;if(_!=="ENOENT"&&_!=="ENOTDIR")return!1}let O=H.dirname(L);if(O===L)return!1;L=O}}static isRestricted($){let f=$.split(H.sep);return S$.some((T)=>f.includes(T))}}var B0=U0("Tool");class l{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}async recordFileRead($,f){try{let T=await L0.stat($),q={filePath:W0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:f,lastOperation:"read"};this.setRecord(q),await this.recordAliases($,q.filePath),B0.debug(`记录文件读取: ${$}`)}catch(T){B0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,f,T="edit"){try{let q=await L0.stat($),B={filePath:W0.resolve($),accessTime:Date.now(),mtime:q.mtimeMs,sessionId:f,lastOperation:T};this.setRecord(B),await this.recordAliases($,B.filePath),B0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(q){B0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${$}`,q)}}hasFileBeenRead($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return!1;return f?T.has(f):T.size>0}async checkFileModification($,f){let T=this.getFileRecord($,f);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(Math.abs(q.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${q.mtime.toISOString()})`};return{modified:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${B.message}`}}}async checkExternalModification($,f){let T=this.getFileRecord($,f);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(q.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${q.mtime.toISOString()})`};return{isExternal:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${$}`,q),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(f)return T.get(f);return[...T.values()].sort((q,B)=>B.accessTime-q.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,f){let T=this.resolveTrackedPath($);if(!f){this.accessedFiles.delete(T),this.removeAliases(T);return}let q=this.accessedFiles.get(T);if(q?.delete(f),q?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,f){for(let[T,q]of this.accessedFiles.entries()){if(f&&!i0.isWithinWorkspace(T,f))continue;if(q.delete($),q.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.instance=null}setRecord($){let f=this.accessedFiles.get($.filePath);if(!f)f=new Map,this.accessedFiles.set($.filePath,f);f.set($.sessionId,$)}async recordAliases($,f){this.pathAliases.set(W0.resolve($),f);let T=await L0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,f)}resolveTrackedPath($){let f=W0.resolve($);if(this.accessedFiles.has(f))return f;let T=this.pathAliases.get(f);if(T)return T;try{let q=cf.native(f);return this.pathAliases.get(q)??q}catch{return f}}removeAliases($){for(let[f,T]of this.pathAliases)if(T===$)this.pathAliases.delete(f)}}import*as O0 from"node:crypto";import{promises as F}from"node:fs";import*as Q from"node:path";import d0 from"write-file-atomic";var j$="missing";class D0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(A($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!Q.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?Q.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let f=C0();this.snapshotDir=Q.join(f,"file-history",this.sessionId),this.manifestPath=Q.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await F.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=C0(),f=await F.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=O0.createHash("sha256").update(f).digest("hex").slice(0,24),q=Q.join($,"file-history",this.sessionId),B=Q.join($,"file-history","workspaces",T,this.sessionId),L=Q.join(B,"manifest.json");try{await F.access(L)}catch{await this.migrateLegacySnapshotDir(q,B,f)}this.snapshotDir=B,this.manifestPath=L}async migrateLegacySnapshotDir($,f,T){let q;try{q=JSON.parse(await F.readFile(Q.join($,"manifest.json"),"utf8"))}catch{return}if(q.schemaVersion!==1||!Array.isArray(q.snapshots)||!q.snapshots.every((B)=>this.isWithinWorkspace(B.filePath,T)))return;await F.mkdir(Q.dirname(f),{recursive:!0,mode:493});try{await F.rename($,f)}catch(B){let L=B.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw B}}isWithinWorkspace($,f){if(!Q.isAbsolute($))return!1;let T=Q.relative(f,Q.resolve($));return T===""||T!==".."&&!T.startsWith(`..${Q.sep}`)&&!Q.isAbsolute(T)}async createSnapshot($,f){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity($),q=!0;try{await F.access(T)}catch{q=!1}let B=this.trackedFileBackups.get(T),L=B?B.version+1:1,O=this.generateFileHash(T,L),C=this.getSnapshotPath(O,L),_=new Date;if(q){let G=await F.readFile(T);await F.writeFile(C,G)}let N={backupFileName:O,version:L,backupTime:_};return this.trackedFileBackups.set(T,N),this.snapshots.push({messageId:f,backupFileName:O,timestamp:_,filePath:T,version:L,existedBefore:q}),await this.cleanupOldSnapshots(T),await this.persistManifest(),N}async recordPostEditState($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)throw Error(`未找到待完成的快照: ${T}`);q.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)return;this.removeSnapshot(q),await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let f=await this.resolveFileIdentity($),T=this.snapshots.slice().reverse().find((L)=>L.filePath===f&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${f}`);if(await this.hashFile(f)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${f}`);let B=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(f),{recursive:!0}),await F.writeFile(f,L)}else await F.rm(f,{force:!0});return this.removeSnapshot(T),await F.rm(B,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,f){let T=await this.resolveFileIdentity($),q=this.snapshots.slice().reverse().find((L)=>L.messageId===f&&L.filePath===T);if(!q)throw Error(`未找到快照: messageId=${f}, filePath=${T}`);let B=this.getSnapshotPath(q.backupFileName,q.version);if(q.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(T),{recursive:!0}),await F.writeFile(T,L)}else await F.rm(T,{force:!0})}async listSnapshots($){let f=await this.resolveFileIdentity($);return this.snapshots.filter((T)=>T.filePath===f)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let f=this.buildRewindPlan($);return{files:f.map((T)=>T.filePath),snapshotCount:f.reduce((T,q)=>T+q.selected.length,0)}}async rewindSnapshots($){let f=this.buildRewindPlan($);if(f.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let B of f){let L,O=!0;try{L=await F.readFile(B.filePath)}catch(_){if(_.code!=="ENOENT")throw _;O=!1}if((L?O0.createHash("sha256").update(L).digest("hex"):j$)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(T.set(B.filePath,{existed:O,content:L}),B.target.existedBefore)await F.access(this.getSnapshotPath(B.target.backupFileName,B.target.version))}let q=[...this.snapshots];try{for(let L of f)if(L.target.existedBefore){let O=await F.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await F.mkdir(Q.dirname(L.filePath),{recursive:!0}),await d0(L.filePath,O)}else await F.rm(L.filePath,{force:!0});let B=new Set(f.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!B.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...B].map((L)=>F.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(B){this.snapshots=q,this.rebuildTrackedFileBackups();let L=[];for(let[O,C]of T)try{if(C.existed&&C.content)await d0(O,C.content);else await F.rm(O,{force:!0})}catch(_){L.push(_)}if(L.length>0)throw AggregateError([B,...L],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:f.map((B)=>B.filePath),snapshotCount:f.reduce((B,L)=>B+L.selected.length,0)}}async commitSnapshots($){let f=this.buildRewindPlan($),T=new Set(f.flatMap((B)=>B.selected));if(T.size===0)return{files:[],snapshotCount:0};let q=[...this.snapshots];this.snapshots=this.snapshots.filter((B)=>!T.has(B)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(B){throw this.snapshots=q,this.rebuildTrackedFileBackups(),B}return await Promise.all([...T].map((B)=>F.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return}))),{files:f.map((B)=>B.filePath),snapshotCount:T.size}}buildRewindPlan($){let f=new Set($),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),q=T.filter((L)=>f.has(L.messageId));return[...new Set(q.map((L)=>L.filePath))].sort().map((L)=>{let O=T.filter((G)=>G.filePath===L),C=O.filter((G)=>f.has(G.messageId)),_=O.indexOf(C[0]),N=O.slice(_);if(N.length!==C.length||N.some((G)=>!f.has(G.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:C,target:C[0],latest:C.at(-1)}})}async loadManifest(){try{let $=await F.readFile(this.manifestPath,"utf-8"),f=JSON.parse($);if(f.schemaVersion!==1||!Array.isArray(f.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(f.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await F.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((f)=>({...f,timestamp:f.timestamp.toISOString()}))};await d0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let T=this.snapshots.filter((q)=>q.filePath===$).slice(0,-this.maxSnapshots);for(let q of T)await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),this.removeSnapshot(q)}async cleanup($=0){let f=this.snapshots.slice().sort((q,B)=>B.timestamp.getTime()-q.timestamp.getTime()),T=new Set(f.slice(0,$));for(let q of this.snapshots)if(!T.has(q))await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0});this.snapshots=f.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,f){return Q.join(this.snapshotDir,`${$}@v${f}`)}async resolveFileIdentity($){let f=Q.resolve($),T=[],q=f;while(!0){try{let L=await F.realpath(q);return Q.join(L,...T.reverse())}catch(L){let O=L.code;if(O!=="ENOENT"&&O!=="ENOTDIR")throw L}let B=Q.dirname(q);if(B===q)return f;T.push(Q.basename(q)),q=B}}async hashFile($){try{let f=await F.readFile($);return O0.createHash("sha256").update(f).digest("hex")}catch(f){if(f.code==="ENOENT")return j$;throw f}}removeSnapshot($){let f=this.snapshots.indexOf($);if(f>=0)this.snapshots.splice(f,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let f=this.trackedFileBackups.get($.filePath);if(!f||f.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,f){let T=O0.createHash("md5");return T.update(`${$}:${f}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var DT=1200,RT=2000,AT=2000,zT=2000;function I$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function pf($){if(typeof $==="string"&&$.length>0)return $;if(I$($)&&typeof $.message==="string")return $.message;return}function df($,f){if($===null||$===void 0)return f??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function v$($){let f=$.error!==null&&$.error!==void 0,T=f?pf($.error)??"Tool execution failed":void 0,q=I$($.metadata)?$.metadata:void 0;return{success:!f,llmContent:df($.output,T),...T?{error:{type:"execution_error",message:T}}:{},...q?{metadata:q}:{}}}function o0($,f){if($.length<=f)return $;let T=Math.max(0,f);if(T>0&&T<$.length&&/[\uD800-\uDBFF]/.test($.charAt(T-1)))T-=1;return $.slice(0,T)}function m$($,f){if($.length<=f)return $;let T=Math.max(0,$.length-f);if(T<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(T)))T+=1;return $.slice(T)}function r0($,f){if($.length<=f)return $;if(f<=0)return"";let T=`
4
4
  ... (display clipped) ...
@@ -1,4 +1,4 @@
1
- import{Zc as T}from"./chunk-qggnvzkc.js";import{qd as P}from"./chunk-5cjy9yj1.js";import{kf as K,lf as G,nf as b,sf as D,tf as I,uf as R,vf as U,yf as E,zf as M}from"./chunk-vk3e2w5h.js";import{Af as x}from"./chunk-a7pvtxvz.js";import{Bf as y,Df as k,Gf as Z}from"./chunk-93jx06kq.js";import{Lf as X}from"./chunk-6360fg4j.js";import{Pf as h,Qf as L}from"./chunk-jtv91ez8.js";import{Yf as A}from"./chunk-0dw58ycv.js";import{promises as f}from"node:fs";import C from"node:path";var F=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],_=new Set([...Object.keys(b),...F]),Y=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),$=k.Array(k.String()),S=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(Y),timeout:k.Optional(Y),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(Y),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(Y),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:K,maximum:G})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:L})])),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(Y),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(x)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:D,maximum:I})),maxQueuedTasks:k.Optional(k.Integer({minimum:R,maximum:U})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional($),ask:k.Optional($),deny:k.Optional($)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),c=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function Q(q,B){let w;try{w=JSON.parse(q)}catch(J){let W=J instanceof Error?`: ${J.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${W}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let J of Object.keys(w))if(!_.has(J))throw Error(`Unknown --settings field: ${J}`);let V=y(S,w);if(!V.success){let J=V.error.issues.map((W)=>`${W.path.join(".")||"settings"}: ${W.message}`).join("; ");throw Error(`Invalid --settings value: ${J}`)}return V.data}async function j(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return Q(B,"inline JSON");let w=C.resolve(X(),B),V;try{V=await f.readFile(w,"utf8")}catch(J){let W=J instanceof Error?`: ${J.message}`:"";throw Error(`Unable to read --settings file ${w}${W}`)}return Q(V,w)}function O(q,B){if(!B)return;let w=B;for(let[V,J]of c){if(V==="permissionMode"&&q.yolo===!0)continue;if(q[J]===void 0&&w[V]!==void 0)q[J]=w[V]}}var H=A("General"),qk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},wk=async(q)=>{let B=await j(typeof q.settings==="string"?q.settings:void 0);if(O(q,B),typeof q.agents==="string")T(q.agents);N(q);try{let V=await E.getInstance().initialize(B),J=M(V,q);if(P().config.actions.setConfig(J),q.debug)H.info("[CLI] 配置已加载到 Store")}catch(w){H.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{Zc as T}from"./chunk-qggnvzkc.js";import{qd as P}from"./chunk-rfec0k27.js";import{kf as K,lf as G,nf as b,sf as D,tf as I,uf as R,vf as U,yf as E,zf as M}from"./chunk-ts8h7mx5.js";import{Af as x}from"./chunk-a7pvtxvz.js";import{Bf as y,Df as k,Gf as Z}from"./chunk-93jx06kq.js";import{Lf as X}from"./chunk-6360fg4j.js";import{Pf as h,Qf as L}from"./chunk-jtv91ez8.js";import{Yf as A}from"./chunk-0dw58ycv.js";import{promises as f}from"node:fs";import C from"node:path";var F=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],_=new Set([...Object.keys(b),...F]),Y=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),$=k.Array(k.String()),S=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(Y),timeout:k.Optional(Y),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(Y),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(Y),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:K,maximum:G})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:L})])),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(Y),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(x)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:D,maximum:I})),maxQueuedTasks:k.Optional(k.Integer({minimum:R,maximum:U})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional($),ask:k.Optional($),deny:k.Optional($)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),c=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function Q(q,B){let w;try{w=JSON.parse(q)}catch(J){let W=J instanceof Error?`: ${J.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${W}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let J of Object.keys(w))if(!_.has(J))throw Error(`Unknown --settings field: ${J}`);let V=y(S,w);if(!V.success){let J=V.error.issues.map((W)=>`${W.path.join(".")||"settings"}: ${W.message}`).join("; ");throw Error(`Invalid --settings value: ${J}`)}return V.data}async function j(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return Q(B,"inline JSON");let w=C.resolve(X(),B),V;try{V=await f.readFile(w,"utf8")}catch(J){let W=J instanceof Error?`: ${J.message}`:"";throw Error(`Unable to read --settings file ${w}${W}`)}return Q(V,w)}function O(q,B){if(!B)return;let w=B;for(let[V,J]of c){if(V==="permissionMode"&&q.yolo===!0)continue;if(q[J]===void 0&&w[V]!==void 0)q[J]=w[V]}}var H=A("General"),qk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},wk=async(q)=>{let B=await j(typeof q.settings==="string"?q.settings:void 0);if(O(q,B),typeof q.agents==="string")T(q.agents);N(q);try{let V=await E.getInstance().initialize(B),J=M(V,q);if(P().config.actions.setConfig(J),q.debug)H.info("[CLI] 配置已加载到 Store")}catch(w){H.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1 +1 @@
1
- import{$a as a,ab as b,cb as c,gb as d,hb as e,ib as f,jb as g,kb as h,lb as i,mb as j,nb as k,sb as l,tb as m,ub as n,vb as o,xb as p,yb as q,zb as r}from"./chunk-9hjhbsna.js";import"./chunk-5cgyevqj.js";import"./chunk-d63dczf8.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import"./chunk-atsw605q.js";import"./chunk-jd764yqg.js";import"./chunk-3rjmkaey.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-r48jmc74.js";import"./chunk-v11r4ahz.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-b6ve4vyt.js";import"./chunk-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
1
+ import{$a as a,ab as b,cb as c,gb as d,hb as e,ib as f,jb as g,kb as h,lb as i,mb as j,nb as k,sb as l,tb as m,ub as n,vb as o,xb as p,yb as q,zb as r}from"./chunk-kzr5n83y.js";import"./chunk-5cgyevqj.js";import"./chunk-gvx3707k.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import"./chunk-atsw605q.js";import"./chunk-jd764yqg.js";import"./chunk-3rjmkaey.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-a9r3w0t9.js";import"./chunk-v11r4ahz.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-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,4 +1,4 @@
1
- import{m as fq,n as Eq,o as Iq,p as Lq,q as Wq,r as Sq}from"./chunk-fqcf0n0h.js";import{t as Jq,u as o,v as n,w as t,x as m,y as e}from"./chunk-dgks1che.js";import{L as Uq,N as _q,O as Mq,Q as Zq,S as Pq}from"./chunk-g5429yjs.js";import"./chunk-0nvc6y56.js";import"./chunk-gh0vdddb.js";import{Va as zq,ib as jq,rb as Hq}from"./chunk-9hjhbsna.js";import"./chunk-5cgyevqj.js";import{Zb as Gq,bc as Dq,mc as g,xc as v}from"./chunk-d63dczf8.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import{Uc as Aq}from"./chunk-y5jxkynb.js";import{Wc as xq,Xc as Rq,Yc as bq}from"./chunk-xsew6530.js";import{Zc as Nq}from"./chunk-qggnvzkc.js";import"./chunk-0evyrnx0.js";import{xd as Bq}from"./chunk-5cjy9yj1.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-jd764yqg.js";import"./chunk-ahkpjvaq.js";import"./chunk-3rjmkaey.js";import"./chunk-46r1m8yn.js";import"./chunk-rtzd076h.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-r48jmc74.js";import"./chunk-v11r4ahz.js";import"./chunk-vk3e2w5h.js";import{Af as Xq}from"./chunk-a7pvtxvz.js";import{Bf as Kq,Df as q,Ef as qq,Gf as z}from"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as h}from"./chunk-6360fg4j.js";import"./chunk-jtv91ez8.js";import"./chunk-0dw58ycv.js";import"./chunk-cm4t4cz6.js";import"./chunk-asqah231.js";import"./chunk-b6ve4vyt.js";import"./chunk-tczrjn95.js";import"./chunk-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";import RZ from"yargs";import{hideBin as bZ}from"yargs/helpers";function p($,V,D){if($.off){$.off(V,D);return}$.removeListener?.(V,D)}function Tq($,V){if(!$.once&&!$.on||!$.off&&!$.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((D,Q)=>{let Z=!1,Y=()=>{p($,"drain",M),p($,"error",_),V.removeEventListener("abort",x)},H=(b)=>{if(Z)return;Z=!0,Y(),b()},M=()=>H(D),_=(b)=>H(()=>Q(b??Error("Writable emitted an error"))),x=()=>H(()=>Q(V.reason??Error("Writable drain aborted")));if(V.aborted){x();return}let R=$.once?.bind($)??$.on?.bind($);R?.("drain",M),R?.("error",_),V.addEventListener("abort",x,{once:!0})})}async function gq($,V,D){if($.destroyed||$.writableEnded)throw Error("Writable is already closed");if($.write(V)===!1)await Tq($,D)}class u{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new m("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor($,V={}){this.options=V;let D=(Q)=>new e({maxPendingItems:V.maxPendingItems??o,maxPendingBytes:V.maxPendingBytes??n,writeTimeoutMs:V.writeTimeoutMs??t,sizeOf:(Z)=>Buffer.byteLength(Z),write:(Z,Y)=>gq($[Q],Z,Y),onFailure:(Z)=>this.fail(Z)});if(this.queues={stdout:D("stdout"),stderr:D("stderr")},this.observeSinkErrors($.stdout),$.stderr!==$.stdout)this.observeSinkErrors($.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write($,V){return this.queues[$].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close($){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close($),this.queues.stderr.close($)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors($){if(!$.on||!$.off&&!$.removeListener)return;let V=(D)=>{this.fail(new m("write_failed","Headless writable failed",{cause:D??Error("Writable emitted an error")}))};$.on("error",V),this.sinkErrorListeners.push({writer:$,listener:V})}fail($){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close($),this.queues.stderr.close($),this.options.onFailure?.($)}removeSinkErrorListeners(){for(let{writer:$,listener:V}of this.sinkErrorListeners.splice(0))p($,"error",V)}}var $q=1;function j($){return q.Object({event_version:q.Literal($q),...$})}var wq=j({type:q.Literal("content_delta"),delta:q.String()}),cq=j({type:q.Literal("thinking_delta"),delta:q.String()}),dq=j({type:q.Literal("thinking"),content:q.String()}),mq=j({type:q.Literal("stream_end")}),pq=j({type:q.Literal("content"),content:q.String()}),uq=j({type:q.Literal("structured_output"),output:q.Record(q.String(),q.Unknown()),schema_digest:q.String({pattern:"^[a-f0-9]{64}$"})}),l=z(["readonly","write","execute"]),lq=q.Object({kind:l,scope:z(["global","session"]),queue_position:q.Integer({minimum:1}),in_flight:q.Integer({minimum:0}),limit:q.Integer({minimum:1})}),vq=j({type:q.Literal("tool_start"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(l)}),sq=j({type:q.Literal("tool_progress"),tool_name:q.String(),message:q.String(),progress:q.Optional(q.Number()),total:q.Optional(q.Number()),admission:q.Optional(lq)}),iq=q.Object({auto_backgrounded:q.Literal(!0),background_reason:q.Literal("foreground_budget"),foreground_budget_ms:q.Integer({minimum:1}),shell_id:q.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:q.Optional(q.Integer({minimum:1})),terminal_transport:z(["local","acp"])}),aq=j({type:q.Literal("tool_result"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(l),success:q.Optional(q.Boolean()),error_type:q.Optional(q.String()),error_message:q.Optional(q.String()),background:q.Optional(iq)}),rq=j({type:q.Literal("mcp_catalog_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),oq=j({type:q.Literal("mcp_content_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),content_kind:z(["resources","resource_templates","prompts"]),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),nq=j({type:q.Literal("mcp_resource_updated"),revision:q.Integer({minimum:1}),server_name:q.String(),uri:q.String()}),tq=j({type:q.Literal("mcp_connection_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),phase:z(["reconnecting","recovered","failed"]),reason:q.String(),attempt:q.Integer({minimum:0}),max_attempts:q.Integer({minimum:0}),next_retry_at:q.Optional(q.Integer({minimum:0})),error:q.Optional(q.String())}),eq=j({type:q.Literal("mcp_log"),revision:q.Integer({minimum:1}),server_name:q.String(),level:z(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:q.Optional(q.String()),message:q.String(),projected_bytes:q.Integer({minimum:0}),data_sha256:q.String(),truncated:q.Boolean(),details_omitted:q.Boolean(),timestamp:q.Integer({minimum:0}),synthetic:q.Optional(q.Boolean())}),qZ=j({type:q.Literal("mcp_instructions_changed"),revision:q.Integer({minimum:0}),server_name:q.String(),action:z(["added","removed"]),reason:z(["snapshot","connection","disconnection"]),text:q.Optional(q.String()),source_bytes:q.Optional(q.Integer({minimum:0})),projected_bytes:q.Optional(q.Integer({minimum:0})),sha256:q.Optional(q.String()),truncated:q.Optional(q.Boolean()),details_omitted:q.Optional(q.Boolean())}),ZZ=j({type:q.Literal("mcp_task_changed"),revision:q.Integer({minimum:0}),task_id:q.String(),server_name:q.String(),tool_name:q.String(),status:z(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:q.Optional(q.String()),created_at:q.Integer({minimum:0}),updated_at:q.Integer({minimum:0}),completed_at:q.Optional(q.Integer({minimum:0})),has_result:q.Boolean(),error:q.Optional(q.String())}),$Z=j({type:q.Literal("project_rules_loaded"),files:q.Array(q.Object({id:q.String(),relative_path:q.String(),source:z(["project","local"]),conditional:q.Boolean(),content_sha256:q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:q.Array(q.String()),blocked_write:q.Boolean()}),VZ=j({type:q.Literal("user_shell_started"),execution_id:q.String(),command:q.String(),auxiliary:q.Boolean()}),YZ=j({type:q.Literal("user_shell_output"),execution_id:q.String(),stream:z(["stdout","stderr"]),chunk:q.String(),stream_truncated:q.Boolean()}),QZ=j({type:q.Literal("user_shell_completed"),execution_id:q.String(),message_id:q.String(),status:z(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:q.Union([q.Integer(),q.Null()]),duration_ms:q.Number({minimum:0}),stdout:q.String(),stderr:q.String(),truncated:q.Boolean(),auxiliary:q.Boolean()}),XZ=j({type:q.Literal("phase"),phase:z(["turn","searching","inspecting","target_hit","executing","completed"]),status:z(["ongoing","hit","done"]),message:q.String(),turn:q.Optional(q.Number()),tool_name:q.Optional(q.String()),target:q.Optional(q.String())}),KZ=j({type:q.Literal("tool_detail"),tool_name:q.String(),detail:q.String()}),BZ=j({type:q.Literal("task_update"),tasks:q.Array(Zq)}),GZ=j({type:q.Literal("goal"),state:z(["updated","cleared"]),goal_id:q.Optional(q.String()),status:q.Optional(z(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:q.Optional(q.Integer({minimum:1})),verification_status:q.Optional(z(["pending","pass","fail","partial"])),verifier_session_id:q.Optional(q.String()),verification_evidence_sha256:q.Optional(q.String({pattern:"^[a-f0-9]{64}$"}))}),DZ=j({type:q.Literal("subagent"),state:z(["spawned","completed"]),session_id:q.String(),subagent_type:q.Optional(q.String()),success:q.Optional(q.Boolean()),summary:q.Optional(q.String()),verification_verdict:q.Optional(z(["pass","fail","partial"])),resumed_from:q.Optional(q.String()),root_agent_id:q.Optional(q.String()),resume_depth:q.Optional(q.Integer({minimum:0}))}),zZ=j({type:q.Literal("token_usage"),input_tokens:q.Number(),output_tokens:q.Number(),total_tokens:q.Number(),max_context_tokens:q.Number(),cache_read_tokens:q.Optional(q.Number()),cache_write_tokens:q.Optional(q.Number()),cost_usd:q.Optional(q.Number())}),jZ=j({type:q.Literal("compacting"),state:z(["started","completed"]),reason:q.Optional(z(["threshold","context_limit","turn_limit","manual"])),strategy:q.Optional(z(["llm","fallback","snip"])),outcome:q.Optional(z(["completed","fallback","failed"])),pre_tokens:q.Optional(q.Number({minimum:0})),post_tokens:q.Optional(q.Number({minimum:0}))}),HZ=j({type:q.Literal("provider_retry"),phase:z(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:q.Integer({minimum:0}),max_retries:q.Integer({minimum:0}),reason:z(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:q.Optional(q.Integer({minimum:100,maximum:599})),delay_ms:q.Optional(q.Integer({minimum:0})),next_retry_at:q.Optional(q.Integer({minimum:0})),mode:q.Optional(z(["standard","bounded_foreground"])),recovery_budget_ms:q.Optional(q.Integer({minimum:0})),recovery_elapsed_ms:q.Optional(q.Integer({minimum:0})),recovery_remaining_ms:q.Optional(q.Integer({minimum:0})),exhausted_by:q.Optional(z(["attempt_limit","recovery_budget"]))}),UZ=j({type:q.Literal("provider_stall"),phase:z(["detected","recovered"]),stall_count:q.Integer({minimum:1}),duration_ms:q.Integer({minimum:0}),warning_after_ms:q.Integer({minimum:1}),timeout_ms:q.Integer({minimum:1}),output_started:q.Boolean()}),_Z=j({type:q.Literal("action_stationarity"),phase:z(["detected","recovered","halted"]),tool_name:q.String(),run_length:q.Integer({minimum:1}),nudge_threshold:q.Integer({minimum:1}),halt_threshold:q.Integer({minimum:1}),progress_aware:q.Boolean()}),MZ=j({type:q.Literal("turn_limit"),turns_count:q.Number(),action:q.Literal("continue")}),PZ=j({type:q.Literal("task_session"),session_id:q.String(),project_path:q.String(),source_project_path:q.String(),isolation:z(["local","worktree"]),worktree_branch:q.Optional(q.String()),base_commit:q.Optional(q.String())}),NZ=j({type:q.Literal("task_admission"),state:z(["queued","running"]),queue_position:q.Optional(q.Integer({minimum:1})),queue_depth:q.Integer({minimum:0}),in_flight:q.Integer({minimum:0}),max_concurrent_tasks:q.Integer({minimum:1})}),AZ=j({type:q.Literal("output"),content:q.String(),exit_code:q.Number()}),xZ=j({type:q.Literal("error"),message:q.String()}),pZ=qq(q.Union([wq,cq,dq,mq,pq,uq,vq,sq,aq,rq,oq,nq,tq,eq,qZ,ZZ,$Z,VZ,YZ,QZ,XZ,KZ,BZ,GZ,DZ,zZ,jZ,HZ,UZ,_Z,MZ,PZ,NZ,AZ,xZ]));function Vq($,V){return{event_version:$q,type:$,...V}}function JZ($){if(!$||typeof $!=="object"||Array.isArray($))return;let V=$;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function fZ($){let V=new AbortController,D=(Y)=>{if(!V.signal.aborted)V.abort(Y)},Q=()=>D("interrupt"),Z=()=>D($?.signal?.reason);if($?.signal){if($.signal.addEventListener("abort",Z,{once:!0}),$.signal.aborted)Z()}else process.once("SIGINT",Q),process.once("SIGTERM",Q);return{signal:V.signal,abort:D,dispose:()=>{$?.signal?.removeEventListener("abort",Z),process.removeListener("SIGINT",Q),process.removeListener("SIGTERM",Q)}}}var EZ=z(["text","jsonl"]),IZ=q.Object({headless:q.Optional(q.Boolean()),message:q.Optional(q.String()),_:q.Optional(q.Array(q.Union([q.String(),q.Number()]))),model:q.Optional(q.String()),systemPrompt:q.Optional(q.String()),appendSystemPrompt:q.Optional(q.String()),verificationAgent:q.Optional(q.Boolean()),maxTurns:q.Optional(q.Refine(q.Integer(),($)=>$===-1||$>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:q.Optional(q.Enum(Xq)),mcpConfig:q.Optional(q.Array(q.String())),strictMcpConfig:q.Optional(q.Boolean()),sessionId:q.Optional(q.String()),allowedTools:q.Optional(q.Array(q.String())),disallowedTools:q.Optional(q.Array(q.String())),agents:q.Optional(q.String()),continue:q.Optional(q.Boolean()),resume:q.Optional(q.Union([q.String(),q.Boolean()])),forkSession:q.Optional(q.Boolean()),taskIsolation:q.Optional(z(["local","worktree"])),outputFormat:q.Optional(EZ),jsonSchema:q.Optional(q.String()),outputSchema:q.Optional(q.String())});class Cq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened($){this.openedThinking=$}hasOpenThinking(){return this.openedThinking}completeStream(){let $={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,$}}function LZ($){return $.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function WZ($){let V=Kq(IZ,$);if(!V.success)throw Error(`Invalid headless options: ${LZ(V.error)}`);return V.data}function SZ($){return $.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).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("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let D=await yZ(V);process.exit(D)})}function U($,V=""){$.write(`${V}
1
+ import{m as fq,n as Eq,o as Iq,p as Lq,q as Wq,r as Sq}from"./chunk-jpzrwcm7.js";import{t as Jq,u as o,v as n,w as t,x as m,y as e}from"./chunk-5xfef98g.js";import{L as Uq,N as _q,O as Mq,Q as Zq,S as Pq}from"./chunk-g7v01gjg.js";import"./chunk-9yd3av82.js";import"./chunk-gh0vdddb.js";import{Va as zq,ib as jq,rb as Hq}from"./chunk-kzr5n83y.js";import"./chunk-5cgyevqj.js";import{Zb as Gq,bc as Dq,mc as g,xc as v}from"./chunk-gvx3707k.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import{Uc as Aq}from"./chunk-0tdc8pg9.js";import{Wc as xq,Xc as Rq,Yc as bq}from"./chunk-h4k801hr.js";import{Zc as Nq}from"./chunk-qggnvzkc.js";import"./chunk-0evyrnx0.js";import{xd as Bq}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 Xq}from"./chunk-a7pvtxvz.js";import{Bf as Kq,Df as q,Ef as qq,Gf as z}from"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as h}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 RZ from"yargs";import{hideBin as bZ}from"yargs/helpers";function p($,V,D){if($.off){$.off(V,D);return}$.removeListener?.(V,D)}function Tq($,V){if(!$.once&&!$.on||!$.off&&!$.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((D,Q)=>{let Z=!1,Y=()=>{p($,"drain",M),p($,"error",_),V.removeEventListener("abort",x)},H=(b)=>{if(Z)return;Z=!0,Y(),b()},M=()=>H(D),_=(b)=>H(()=>Q(b??Error("Writable emitted an error"))),x=()=>H(()=>Q(V.reason??Error("Writable drain aborted")));if(V.aborted){x();return}let R=$.once?.bind($)??$.on?.bind($);R?.("drain",M),R?.("error",_),V.addEventListener("abort",x,{once:!0})})}async function gq($,V,D){if($.destroyed||$.writableEnded)throw Error("Writable is already closed");if($.write(V)===!1)await Tq($,D)}class u{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new m("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor($,V={}){this.options=V;let D=(Q)=>new e({maxPendingItems:V.maxPendingItems??o,maxPendingBytes:V.maxPendingBytes??n,writeTimeoutMs:V.writeTimeoutMs??t,sizeOf:(Z)=>Buffer.byteLength(Z),write:(Z,Y)=>gq($[Q],Z,Y),onFailure:(Z)=>this.fail(Z)});if(this.queues={stdout:D("stdout"),stderr:D("stderr")},this.observeSinkErrors($.stdout),$.stderr!==$.stdout)this.observeSinkErrors($.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write($,V){return this.queues[$].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close($){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close($),this.queues.stderr.close($)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors($){if(!$.on||!$.off&&!$.removeListener)return;let V=(D)=>{this.fail(new m("write_failed","Headless writable failed",{cause:D??Error("Writable emitted an error")}))};$.on("error",V),this.sinkErrorListeners.push({writer:$,listener:V})}fail($){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close($),this.queues.stderr.close($),this.options.onFailure?.($)}removeSinkErrorListeners(){for(let{writer:$,listener:V}of this.sinkErrorListeners.splice(0))p($,"error",V)}}var $q=1;function j($){return q.Object({event_version:q.Literal($q),...$})}var wq=j({type:q.Literal("content_delta"),delta:q.String()}),cq=j({type:q.Literal("thinking_delta"),delta:q.String()}),dq=j({type:q.Literal("thinking"),content:q.String()}),mq=j({type:q.Literal("stream_end")}),pq=j({type:q.Literal("content"),content:q.String()}),uq=j({type:q.Literal("structured_output"),output:q.Record(q.String(),q.Unknown()),schema_digest:q.String({pattern:"^[a-f0-9]{64}$"})}),l=z(["readonly","write","execute"]),lq=q.Object({kind:l,scope:z(["global","session"]),queue_position:q.Integer({minimum:1}),in_flight:q.Integer({minimum:0}),limit:q.Integer({minimum:1})}),vq=j({type:q.Literal("tool_start"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(l)}),sq=j({type:q.Literal("tool_progress"),tool_name:q.String(),message:q.String(),progress:q.Optional(q.Number()),total:q.Optional(q.Number()),admission:q.Optional(lq)}),iq=q.Object({auto_backgrounded:q.Literal(!0),background_reason:q.Literal("foreground_budget"),foreground_budget_ms:q.Integer({minimum:1}),shell_id:q.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:q.Optional(q.Integer({minimum:1})),terminal_transport:z(["local","acp"])}),aq=j({type:q.Literal("tool_result"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(l),success:q.Optional(q.Boolean()),error_type:q.Optional(q.String()),error_message:q.Optional(q.String()),background:q.Optional(iq)}),rq=j({type:q.Literal("mcp_catalog_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),oq=j({type:q.Literal("mcp_content_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),content_kind:z(["resources","resource_templates","prompts"]),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),nq=j({type:q.Literal("mcp_resource_updated"),revision:q.Integer({minimum:1}),server_name:q.String(),uri:q.String()}),tq=j({type:q.Literal("mcp_connection_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),phase:z(["reconnecting","recovered","failed"]),reason:q.String(),attempt:q.Integer({minimum:0}),max_attempts:q.Integer({minimum:0}),next_retry_at:q.Optional(q.Integer({minimum:0})),error:q.Optional(q.String())}),eq=j({type:q.Literal("mcp_log"),revision:q.Integer({minimum:1}),server_name:q.String(),level:z(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:q.Optional(q.String()),message:q.String(),projected_bytes:q.Integer({minimum:0}),data_sha256:q.String(),truncated:q.Boolean(),details_omitted:q.Boolean(),timestamp:q.Integer({minimum:0}),synthetic:q.Optional(q.Boolean())}),qZ=j({type:q.Literal("mcp_instructions_changed"),revision:q.Integer({minimum:0}),server_name:q.String(),action:z(["added","removed"]),reason:z(["snapshot","connection","disconnection"]),text:q.Optional(q.String()),source_bytes:q.Optional(q.Integer({minimum:0})),projected_bytes:q.Optional(q.Integer({minimum:0})),sha256:q.Optional(q.String()),truncated:q.Optional(q.Boolean()),details_omitted:q.Optional(q.Boolean())}),ZZ=j({type:q.Literal("mcp_task_changed"),revision:q.Integer({minimum:0}),task_id:q.String(),server_name:q.String(),tool_name:q.String(),status:z(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:q.Optional(q.String()),created_at:q.Integer({minimum:0}),updated_at:q.Integer({minimum:0}),completed_at:q.Optional(q.Integer({minimum:0})),has_result:q.Boolean(),error:q.Optional(q.String())}),$Z=j({type:q.Literal("project_rules_loaded"),files:q.Array(q.Object({id:q.String(),relative_path:q.String(),source:z(["project","local"]),conditional:q.Boolean(),content_sha256:q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:q.Array(q.String()),blocked_write:q.Boolean()}),VZ=j({type:q.Literal("user_shell_started"),execution_id:q.String(),command:q.String(),auxiliary:q.Boolean()}),YZ=j({type:q.Literal("user_shell_output"),execution_id:q.String(),stream:z(["stdout","stderr"]),chunk:q.String(),stream_truncated:q.Boolean()}),QZ=j({type:q.Literal("user_shell_completed"),execution_id:q.String(),message_id:q.String(),status:z(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:q.Union([q.Integer(),q.Null()]),duration_ms:q.Number({minimum:0}),stdout:q.String(),stderr:q.String(),truncated:q.Boolean(),auxiliary:q.Boolean()}),XZ=j({type:q.Literal("phase"),phase:z(["turn","searching","inspecting","target_hit","executing","completed"]),status:z(["ongoing","hit","done"]),message:q.String(),turn:q.Optional(q.Number()),tool_name:q.Optional(q.String()),target:q.Optional(q.String())}),KZ=j({type:q.Literal("tool_detail"),tool_name:q.String(),detail:q.String()}),BZ=j({type:q.Literal("task_update"),tasks:q.Array(Zq)}),GZ=j({type:q.Literal("goal"),state:z(["updated","cleared"]),goal_id:q.Optional(q.String()),status:q.Optional(z(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:q.Optional(q.Integer({minimum:1})),verification_status:q.Optional(z(["pending","pass","fail","partial"])),verifier_session_id:q.Optional(q.String()),verification_evidence_sha256:q.Optional(q.String({pattern:"^[a-f0-9]{64}$"}))}),DZ=j({type:q.Literal("subagent"),state:z(["spawned","completed"]),session_id:q.String(),subagent_type:q.Optional(q.String()),success:q.Optional(q.Boolean()),summary:q.Optional(q.String()),verification_verdict:q.Optional(z(["pass","fail","partial"])),resumed_from:q.Optional(q.String()),root_agent_id:q.Optional(q.String()),resume_depth:q.Optional(q.Integer({minimum:0}))}),zZ=j({type:q.Literal("token_usage"),input_tokens:q.Number(),output_tokens:q.Number(),total_tokens:q.Number(),max_context_tokens:q.Number(),cache_read_tokens:q.Optional(q.Number()),cache_write_tokens:q.Optional(q.Number()),cost_usd:q.Optional(q.Number())}),jZ=j({type:q.Literal("compacting"),state:z(["started","completed"]),reason:q.Optional(z(["threshold","context_limit","turn_limit","manual"])),strategy:q.Optional(z(["llm","fallback","snip"])),outcome:q.Optional(z(["completed","fallback","failed"])),pre_tokens:q.Optional(q.Number({minimum:0})),post_tokens:q.Optional(q.Number({minimum:0}))}),HZ=j({type:q.Literal("provider_retry"),phase:z(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:q.Integer({minimum:0}),max_retries:q.Integer({minimum:0}),reason:z(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:q.Optional(q.Integer({minimum:100,maximum:599})),delay_ms:q.Optional(q.Integer({minimum:0})),next_retry_at:q.Optional(q.Integer({minimum:0})),mode:q.Optional(z(["standard","bounded_foreground"])),recovery_budget_ms:q.Optional(q.Integer({minimum:0})),recovery_elapsed_ms:q.Optional(q.Integer({minimum:0})),recovery_remaining_ms:q.Optional(q.Integer({minimum:0})),exhausted_by:q.Optional(z(["attempt_limit","recovery_budget"]))}),UZ=j({type:q.Literal("provider_stall"),phase:z(["detected","recovered"]),stall_count:q.Integer({minimum:1}),duration_ms:q.Integer({minimum:0}),warning_after_ms:q.Integer({minimum:1}),timeout_ms:q.Integer({minimum:1}),output_started:q.Boolean()}),_Z=j({type:q.Literal("action_stationarity"),phase:z(["detected","recovered","halted"]),tool_name:q.String(),run_length:q.Integer({minimum:1}),nudge_threshold:q.Integer({minimum:1}),halt_threshold:q.Integer({minimum:1}),progress_aware:q.Boolean()}),MZ=j({type:q.Literal("turn_limit"),turns_count:q.Number(),action:q.Literal("continue")}),PZ=j({type:q.Literal("task_session"),session_id:q.String(),project_path:q.String(),source_project_path:q.String(),isolation:z(["local","worktree"]),worktree_branch:q.Optional(q.String()),base_commit:q.Optional(q.String())}),NZ=j({type:q.Literal("task_admission"),state:z(["queued","running"]),queue_position:q.Optional(q.Integer({minimum:1})),queue_depth:q.Integer({minimum:0}),in_flight:q.Integer({minimum:0}),max_concurrent_tasks:q.Integer({minimum:1})}),AZ=j({type:q.Literal("output"),content:q.String(),exit_code:q.Number()}),xZ=j({type:q.Literal("error"),message:q.String()}),pZ=qq(q.Union([wq,cq,dq,mq,pq,uq,vq,sq,aq,rq,oq,nq,tq,eq,qZ,ZZ,$Z,VZ,YZ,QZ,XZ,KZ,BZ,GZ,DZ,zZ,jZ,HZ,UZ,_Z,MZ,PZ,NZ,AZ,xZ]));function Vq($,V){return{event_version:$q,type:$,...V}}function JZ($){if(!$||typeof $!=="object"||Array.isArray($))return;let V=$;if(V.auto_backgrounded!==!0||V.background_reason!=="foreground_budget"||!Number.isSafeInteger(V.foreground_budget_ms)||V.foreground_budget_ms<=0||typeof V.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(V.shell_id)||V.shell_id.length>128||V.terminal_transport!=="local"&&V.terminal_transport!=="acp"||V.pid!==void 0&&(!Number.isSafeInteger(V.pid)||V.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:V.foreground_budget_ms,shell_id:V.shell_id,...V.pid===void 0?{}:{pid:V.pid},terminal_transport:V.terminal_transport}}function fZ($){let V=new AbortController,D=(Y)=>{if(!V.signal.aborted)V.abort(Y)},Q=()=>D("interrupt"),Z=()=>D($?.signal?.reason);if($?.signal){if($.signal.addEventListener("abort",Z,{once:!0}),$.signal.aborted)Z()}else process.once("SIGINT",Q),process.once("SIGTERM",Q);return{signal:V.signal,abort:D,dispose:()=>{$?.signal?.removeEventListener("abort",Z),process.removeListener("SIGINT",Q),process.removeListener("SIGTERM",Q)}}}var EZ=z(["text","jsonl"]),IZ=q.Object({headless:q.Optional(q.Boolean()),message:q.Optional(q.String()),_:q.Optional(q.Array(q.Union([q.String(),q.Number()]))),model:q.Optional(q.String()),systemPrompt:q.Optional(q.String()),appendSystemPrompt:q.Optional(q.String()),verificationAgent:q.Optional(q.Boolean()),maxTurns:q.Optional(q.Refine(q.Integer(),($)=>$===-1||$>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:q.Optional(q.Enum(Xq)),mcpConfig:q.Optional(q.Array(q.String())),strictMcpConfig:q.Optional(q.Boolean()),sessionId:q.Optional(q.String()),allowedTools:q.Optional(q.Array(q.String())),disallowedTools:q.Optional(q.Array(q.String())),agents:q.Optional(q.String()),continue:q.Optional(q.Boolean()),resume:q.Optional(q.Union([q.String(),q.Boolean()])),forkSession:q.Optional(q.Boolean()),taskIsolation:q.Optional(z(["local","worktree"])),outputFormat:q.Optional(EZ),jsonSchema:q.Optional(q.String()),outputSchema:q.Optional(q.String())});class Cq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened($){this.openedThinking=$}hasOpenThinking(){return this.openedThinking}completeStream(){let $={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,$}}function LZ($){return $.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function WZ($){let V=Kq(IZ,$);if(!V.success)throw Error(`Invalid headless options: ${LZ(V.error)}`);return V.data}function SZ($){return $.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).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("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(V)=>{if(!V.headless)return;let D=await yZ(V);process.exit(D)})}function U($,V=""){$.write(`${V}
2
2
  `)}function CZ($){return`[task] [${$.status}] ${$.subject}`}function OZ(){return{requestConfirmation:async($)=>$.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:$.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function hZ($){if(!($ instanceof Error))return"Unknown error";let Q=$.lastError??$;if(Q.responseBody)try{let H=JSON.parse(Q.responseBody)?.error?.message;if(H)return Q.statusCode?`${H} (HTTP ${Q.statusCode})`:H}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function kZ($){return $==="jsonl"?"jsonl":"text"}function Yq($,V){let D=(...Q)=>{for(let Z of Q){let Y=V[Z];if(typeof Y==="string"&&Y.trim()!=="")return Y}return};switch($){case"Read":case"Edit":case"Write":case"UndoEdit":return D("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return D("notebook_path");case"Grep":return D("path","pattern");case"Glob":return D("pattern");case"WebFetch":return D("url");case"WebSearch":return D("query");case"Bash":return D("command","description");case"Task":return D("description");case"LSP":return D("filePath","operation");case"EnterWorktree":return D("name");case"ExitWorktree":return D("action");default:return}}function FZ($,V,D,Q){let Z=new Set(["Glob","Grep","WebSearch","LS"]),Y=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has($)&&!Q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(Q.targetLocked)return{phase:"executing",status:"hit",message:D?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(Z.has($))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Y.has($))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:Q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function Qq($,V,D=!1){let Q=(Z,Y)=>{$.stdout.write(`${JSON.stringify(Vq(Z,Y))}
3
3
  `)};return{contentDelta(Z){if(V==="jsonl"){Q("content_delta",{delta:Z});return}if(D)return;$.stdout.write(Z)},thinkingDelta(Z,Y){if(V==="jsonl")return Q("thinking_delta",{delta:Z}),Y;if(!Y)$.stderr.write("[thinking] ");return $.stderr.write(Z),!0},thinking(Z){if(V==="jsonl"){Q("thinking",{content:Z});return}U($.stderr,`[thinking] ${Z}`)},streamEnd(Z,Y){if(V==="jsonl"){Q("stream_end",{});return}if(Y)$.stderr.write(`
4
4
  `);if(Z)$.stdout.write(`
@@ -1,4 +1,4 @@
1
- import{j as n4,k as t4}from"./chunk-ak37gg0n.js";import{l as h$}from"./chunk-e6ttz45s.js";import{s as k0}from"./chunk-232bcv23.js";import{t as L4,u as S1,v as f1,w as y1,x as n0,y as m1}from"./chunk-dgks1che.js";import{$ as u4,A as zO,D as D4,E as Y$,F as V1,G as S$,H as $1,I as T0,J as O1,K as r0,L as F$,O as A$,P as M$,R as _4,S as B4,T as S4,U as f4,V as y4,W as m4,X as h4,Y as g4,Z as v4,_ as p4,aa as o4,da as MO,ia as KO}from"./chunk-g5429yjs.js";import{la as o1,ra as N0}from"./chunk-0nvc6y56.js";import{Aa as WO,Ba as N1,Ca as FO,Da as d0,Ea as s4,Fa as e4,Ga as $O,Ha as M4,Ia as E4,Ja as T4,Ka as k1,La as D1,ta as l$,wa as NO,xa as GO,ya as w4,za as A4}from"./chunk-gh0vdddb.js";import{Sa as I0,Ta as h,Va as j,Wa as H4,ib as e$,rb as p0}from"./chunk-9hjhbsna.js";import{Ab as V4}from"./chunk-5cgyevqj.js";import{$b as L$,Tb as N4,Vb as f$,ac as Y1,bc as w$,dc as G4,jc as W4,kc as F4,mc as O$,pc as t$,uc as U4,vc as r$,wc as s$,xc as C}from"./chunk-d63dczf8.js";import{Fd as _0,ud as $0,yd as s1}from"./chunk-5cjy9yj1.js";import{Gd as n$}from"./chunk-atsw605q.js";import{Sd as z4}from"./chunk-3rjmkaey.js";import{Ud as P$}from"./chunk-46r1m8yn.js";import{be as ZO,ce as YO,fe as P4,je as G$,ke as W$,oe as W0}from"./chunk-rtzd076h.js";import{ye as e1,ze as K4}from"./chunk-zwt7f9ab.js";import{De as l1,Ee as s0}from"./chunk-r48jmc74.js";import{We as a1,nf as c1,yf as N$}from"./chunk-vk3e2w5h.js";import{Bf as m,Df as D,Gf as V0}from"./chunk-93jx06kq.js";import{If as y$}from"./chunk-thstqcg3.js";import{Nf as g}from"./chunk-6360fg4j.js";import{Yf as d}from"./chunk-0dw58ycv.js";import{cg as g0}from"./chunk-cm4t4cz6.js";import{eg as t1,fg as x4,hg as r1,ig as X4}from"./chunk-asqah231.js";import{kg as t0}from"./chunk-b6ve4vyt.js";import{pg as U1}from"./chunk-tczrjn95.js";import{ug as C$,yg as g1}from"./chunk-qc5qwgpt.js";import{Bg as G1}from"./chunk-jtjcg93t.js";var C5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function k5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as H1,readFileSync as q$}from"node:fs";import{createServer as X5}from"node:http";import{networkInterfaces as z5}from"node:os";import{dirname as K5,extname as V5,join as y0}from"node:path";import{fileURLToPath as N5}from"node:url";import{brotliCompressSync as G5,gzipSync as W5,constants as F5}from"node:zlib";import{Hono as U5}from"hono";import{cors as D5}from"hono/cors";import{WebSocketServer as H5}from"ws";var a0=d("Service"),PO=30000,SO=new Set(["completed","failed","cancelled","interrupted"]);class c${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??k1.getInstance(),this.tickMs=$.tickMs??PO}start(){if(this.timer)return;a0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=j.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!SO.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,a0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){a0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),a0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let Y=await this.dispatch({prompt:$.prompt,title:$.title??fO($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),z=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:z?z.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),j.publish({sessionId:Y.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),a0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let z=Y instanceof Error?Y.message:String(Y);a0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,Y);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:z,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let Y=(await this.store.list()).find((z)=>z.lastRunSessionId===$);if(!Y)return;await this.store.update(Y.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function fO($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class e extends Error{code;statusCode;constructor($,O,J=500){super(O);this.code=$;this.statusCode=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class f extends e{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends e{constructor($){super("BAD_REQUEST",$,400)}}class k extends e{constructor($){super("CONFLICT",$,409)}}class o0 extends e{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class h0 extends e{constructor($="Server is shutting down"){super("SERVICE_UNAVAILABLE",$,503)}}class H0 extends e{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class a extends e{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var g5=D.Object({error:D.Object({code:D.String(),message:D.String()})});import{Hono as yO}from"hono";var i$=d("Service"),mO=D.Object({updates:D.Record(D.String(),D.Any()),options:D.Optional(D.Object({scope:D.Optional(V0(["local","project","global"])),immediate:D.Optional(D.Boolean())}))});function hO($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,codeTheme:$.codeTheme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks}}var I1=()=>{let $=new yO;return $.get("/",async(O)=>{try{let J=$0();return O.json(J?hO(J):{})}catch(J){return i$.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=m(mO,J);if(!Z.success)throw new _("Invalid config update format");let{updates:Y,options:z}=Z.data;return await _0().updateConfig(Y,z),O.json({success:!0,updates:Y})}catch(J){throw i$.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=$0();return O.json(J?.permissions||{})}catch(J){return i$.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as gO}from"hono";import{streamSSE as vO}from"hono/streaming";function P1($){let O="";if($.id!==void 0)O+=`id: ${$.id}
1
+ import{j as n4,k as t4}from"./chunk-ak37gg0n.js";import{l as h$}from"./chunk-e6ttz45s.js";import{s as k0}from"./chunk-6t2bkj8s.js";import{t as L4,u as S1,v as f1,w as y1,x as n0,y as m1}from"./chunk-5xfef98g.js";import{$ as u4,A as zO,D as D4,E as Y$,F as V1,G as S$,H as $1,I as T0,J as O1,K as r0,L as F$,O as A$,P as M$,R as _4,S as B4,T as S4,U as f4,V as y4,W as m4,X as h4,Y as g4,Z as v4,_ as p4,aa as o4,da as MO,ia as KO}from"./chunk-g7v01gjg.js";import{la as o1,ra as N0}from"./chunk-9yd3av82.js";import{Aa as WO,Ba as N1,Ca as FO,Da as d0,Ea as s4,Fa as e4,Ga as $O,Ha as M4,Ia as E4,Ja as T4,Ka as k1,La as D1,ta as l$,wa as NO,xa as GO,ya as w4,za as A4}from"./chunk-gh0vdddb.js";import{Sa as I0,Ta as h,Va as j,Wa as H4,ib as e$,rb as p0}from"./chunk-kzr5n83y.js";import{Ab as V4}from"./chunk-5cgyevqj.js";import{$b as L$,Tb as N4,Vb as f$,ac as Y1,bc as w$,dc as G4,jc as W4,kc as F4,mc as O$,pc as t$,uc as U4,vc as r$,wc as s$,xc as C}from"./chunk-gvx3707k.js";import{Fd as _0,ud as $0,yd as s1}from"./chunk-rfec0k27.js";import{Gd as n$}from"./chunk-atsw605q.js";import{Sd as z4}from"./chunk-3rjmkaey.js";import{Ud as P$}from"./chunk-6aw2ts3m.js";import{be as ZO,ce as YO,fe as P4,je as G$,ke as W$,oe as W0}from"./chunk-a1shhh83.js";import{ye as e1,ze as K4}from"./chunk-zwt7f9ab.js";import{De as l1,Ee as s0}from"./chunk-a9r3w0t9.js";import{We as a1,nf as c1,yf as N$}from"./chunk-ts8h7mx5.js";import{Bf as m,Df as D,Gf as V0}from"./chunk-93jx06kq.js";import{If as y$}from"./chunk-thstqcg3.js";import{Nf as g}from"./chunk-6360fg4j.js";import{Yf as d}from"./chunk-0dw58ycv.js";import{cg as g0}from"./chunk-cm4t4cz6.js";import{eg as t1,fg as x4,hg as r1,ig as X4}from"./chunk-asqah231.js";import{kg as t0}from"./chunk-aw4r1zhr.js";import{pg as U1}from"./chunk-tczrjn95.js";import{ug as C$,yg as g1}from"./chunk-qc5qwgpt.js";import{Bg as G1}from"./chunk-jtjcg93t.js";var C5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function k5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as H1,readFileSync as q$}from"node:fs";import{createServer as X5}from"node:http";import{networkInterfaces as z5}from"node:os";import{dirname as K5,extname as V5,join as y0}from"node:path";import{fileURLToPath as N5}from"node:url";import{brotliCompressSync as G5,gzipSync as W5,constants as F5}from"node:zlib";import{Hono as U5}from"hono";import{cors as D5}from"hono/cors";import{WebSocketServer as H5}from"ws";var a0=d("Service"),PO=30000,SO=new Set(["completed","failed","cancelled","interrupted"]);class c${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??k1.getInstance(),this.tickMs=$.tickMs??PO}start(){if(this.timer)return;a0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=j.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!SO.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,a0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){a0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),a0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let Y=await this.dispatch({prompt:$.prompt,title:$.title??fO($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),z=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:z?z.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),j.publish({sessionId:Y.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),a0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let z=Y instanceof Error?Y.message:String(Y);a0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,Y);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:l$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:z,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let Y=(await this.store.list()).find((z)=>z.lastRunSessionId===$);if(!Y)return;await this.store.update(Y.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function fO($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class e extends Error{code;statusCode;constructor($,O,J=500){super(O);this.code=$;this.statusCode=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class f extends e{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends e{constructor($){super("BAD_REQUEST",$,400)}}class k extends e{constructor($){super("CONFLICT",$,409)}}class o0 extends e{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class h0 extends e{constructor($="Server is shutting down"){super("SERVICE_UNAVAILABLE",$,503)}}class H0 extends e{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class a extends e{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var g5=D.Object({error:D.Object({code:D.String(),message:D.String()})});import{Hono as yO}from"hono";var i$=d("Service"),mO=D.Object({updates:D.Record(D.String(),D.Any()),options:D.Optional(D.Object({scope:D.Optional(V0(["local","project","global"])),immediate:D.Optional(D.Boolean())}))});function hO($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,codeTheme:$.codeTheme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks}}var I1=()=>{let $=new yO;return $.get("/",async(O)=>{try{let J=$0();return O.json(J?hO(J):{})}catch(J){return i$.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=m(mO,J);if(!Z.success)throw new _("Invalid config update format");let{updates:Y,options:z}=Z.data;return await _0().updateConfig(Y,z),O.json({success:!0,updates:Y})}catch(J){throw i$.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=$0();return O.json(J?.permissions||{})}catch(J){return i$.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as gO}from"hono";import{streamSSE as vO}from"hono/streaming";function P1($){let O="";if($.id!==void 0)O+=`id: ${$.id}
2
2
  `;if($.event!==void 0)O+=`event: ${$.event}
3
3
  `;for(let J of $.data.split(/\r\n|\r|\n/))O+=`data: ${J}
4
4
  `;if($.retry!==void 0)O+=`retry: ${$.retry}