blade-code 0.10.76 → 0.10.78

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 (88) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-9fm80wbr.js → chunk-0141jad7.js} +1 -1
  3. package/dist/chunk-03k5c0e3.js +1 -0
  4. package/dist/{chunk-aq15mcwm.js → chunk-091qx62q.js} +1 -1
  5. package/dist/{chunk-fmkntp49.js → chunk-0a0sj79a.js} +2 -2
  6. package/dist/{chunk-9x141v5g.js → chunk-0ra945vt.js} +2 -2
  7. package/dist/chunk-0vr244p2.js +1 -0
  8. package/dist/{chunk-yhyqcmh1.js → chunk-16wxxkev.js} +1 -1
  9. package/dist/{chunk-db2v383v.js → chunk-1j4smrfy.js} +1 -1
  10. package/dist/{chunk-yg7cacsc.js → chunk-1mc7nfb4.js} +1 -1
  11. package/dist/{chunk-wx9zxzgm.js → chunk-33bpwkyk.js} +2 -2
  12. package/dist/{chunk-chmf8s1j.js → chunk-3bmsp8yv.js} +2 -2
  13. package/dist/{chunk-gpxvyxz1.js → chunk-3cbfykzb.js} +1 -1
  14. package/dist/{chunk-ttbq1xmz.js → chunk-5m8x01n9.js} +2 -2
  15. package/dist/{chunk-68stvfdj.js → chunk-5nezhmnq.js} +2 -2
  16. package/dist/chunk-6adxyred.js +1 -0
  17. package/dist/{chunk-gx1wx7z5.js → chunk-72mk2y5d.js} +1 -1
  18. package/dist/chunk-7az90ak3.js +1 -0
  19. package/dist/{chunk-n5d0d6q7.js → chunk-7nx0pzfk.js} +1 -1
  20. package/dist/chunk-89yq5n68.js +10 -0
  21. package/dist/chunk-91w5bqyx.js +1 -0
  22. package/dist/{chunk-625krpnt.js → chunk-96ye1aqq.js} +4 -4
  23. package/dist/chunk-9vrtjw9f.js +1 -0
  24. package/dist/{chunk-8bsse16j.js → chunk-b9nhnzaj.js} +1 -1
  25. package/dist/{chunk-z37v80c1.js → chunk-b9vm7gns.js} +2 -2
  26. package/dist/chunk-bxks9zbr.js +168 -0
  27. package/dist/{chunk-vpn2e8tj.js → chunk-d4z4kpvk.js} +2 -2
  28. package/dist/{chunk-qnj3dajb.js → chunk-eeb2945p.js} +1 -1
  29. package/dist/{chunk-9dspha54.js → chunk-ezs65v1m.js} +2 -2
  30. package/dist/{chunk-h0ys86rn.js → chunk-fdcn0thm.js} +1 -1
  31. package/dist/{chunk-ehks2r00.js → chunk-fsm3fb2m.js} +1 -1
  32. package/dist/chunk-fyd1v6c0.js +1 -0
  33. package/dist/{chunk-xmty01x3.js → chunk-g6fw4y71.js} +1 -1
  34. package/dist/chunk-gn6ftvjy.js +1 -0
  35. package/dist/{chunk-tnaxxgje.js → chunk-gre57x9m.js} +1 -1
  36. package/dist/{chunk-8chhdkg2.js → chunk-gwbanhxq.js} +10 -5
  37. package/dist/{chunk-bvhbc0wr.js → chunk-h0fh3j9w.js} +1 -1
  38. package/dist/{chunk-zwd5q6dt.js → chunk-h3w814js.js} +1 -1
  39. package/dist/{chunk-vn1r6z64.js → chunk-h6a0nct6.js} +1 -1
  40. package/dist/{chunk-ckvq6z49.js → chunk-h9xayrwp.js} +1 -1
  41. package/dist/{chunk-r8ayexxd.js → chunk-jdb2mwbn.js} +1 -1
  42. package/dist/{chunk-ts96epcd.js → chunk-jswmz4fk.js} +1 -1
  43. package/dist/{chunk-vdtma2yq.js → chunk-jwx10h5z.js} +1 -1
  44. package/dist/{chunk-c80pzvhs.js → chunk-jzvbjn6e.js} +1 -1
  45. package/dist/{chunk-eesa8c5h.js → chunk-ky9q53m7.js} +1 -1
  46. package/dist/chunk-m3vqjtz7.js +1 -0
  47. package/dist/{chunk-tssmnn37.js → chunk-m4avjqx5.js} +2 -2
  48. package/dist/{chunk-kxgr18gy.js → chunk-m7xfm75q.js} +2 -2
  49. package/dist/{chunk-js4vqnds.js → chunk-mygw13zd.js} +1 -1
  50. package/dist/chunk-n60hs2m0.js +1 -0
  51. package/dist/{chunk-j67n7v73.js → chunk-nmh9b40p.js} +1 -1
  52. package/dist/{chunk-zvpr8s8r.js → chunk-nykkq8c2.js} +1 -1
  53. package/dist/{chunk-9ra452yc.js → chunk-pfvgkexe.js} +1 -1
  54. package/dist/{chunk-js4aekf1.js → chunk-qxn5bg5k.js} +1 -1
  55. package/dist/chunk-reakyamv.js +2 -0
  56. package/dist/chunk-rpbyc2k4.js +1 -0
  57. package/dist/{chunk-cgd0vjw2.js → chunk-s3r32avd.js} +1 -1
  58. package/dist/chunk-s56p9w29.js +1 -0
  59. package/dist/{chunk-01k69v34.js → chunk-seamt0j3.js} +2 -2
  60. package/dist/{chunk-426sb4tk.js → chunk-shq0pkxq.js} +1 -1
  61. package/dist/{chunk-79cxktz1.js → chunk-sj0k8cdf.js} +1 -1
  62. package/dist/{chunk-vwa2kczj.js → chunk-szhzvb57.js} +1 -1
  63. package/dist/{chunk-zk34d9mm.js → chunk-tqjpaaa0.js} +1 -1
  64. package/dist/{chunk-6h3x4jv0.js → chunk-tzq6155m.js} +28 -28
  65. package/dist/{chunk-90yjhvjb.js → chunk-vkz1vhbp.js} +1 -1
  66. package/dist/{chunk-9k3tg2hs.js → chunk-w1zk41np.js} +3 -3
  67. package/dist/{chunk-abzn9eba.js → chunk-wbap76bk.js} +1 -1
  68. package/dist/chunk-wy9c9jj6.js +1 -0
  69. package/dist/chunk-yd7bc0cm.js +6 -0
  70. package/dist/{chunk-psy247es.js → chunk-zkhb55jz.js} +1 -1
  71. package/package.json +1 -1
  72. package/dist/chunk-0z6fn1mt.js +0 -1
  73. package/dist/chunk-25q79gk4.js +0 -6
  74. package/dist/chunk-2nnfx3s7.js +0 -1
  75. package/dist/chunk-5b0tejhz.js +0 -1
  76. package/dist/chunk-66w68q81.js +0 -168
  77. package/dist/chunk-6r150c8y.js +0 -1
  78. package/dist/chunk-9eah1889.js +0 -1
  79. package/dist/chunk-9tcrrjzg.js +0 -1
  80. package/dist/chunk-bpf84msg.js +0 -1
  81. package/dist/chunk-c074qee7.js +0 -1
  82. package/dist/chunk-d8gn6hw5.js +0 -1
  83. package/dist/chunk-egv5k7t5.js +0 -1
  84. package/dist/chunk-et3d69av.js +0 -1
  85. package/dist/chunk-mjq7rrq1.js +0 -1
  86. package/dist/chunk-t1bvxk3s.js +0 -2
  87. package/dist/chunk-tppvhg2n.js +0 -1
  88. package/dist/chunk-zjfdj7be.js +0 -10
@@ -1,4 +1,4 @@
1
- import{ma as F,oa as L}from"./chunk-8chhdkg2.js";import{Lc as $,Nc as B,Vc as Q}from"./chunk-6h3x4jv0.js";import{Se as y}from"./chunk-vpn2e8tj.js";import{Lg as V}from"./chunk-9fm80wbr.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{ma as F,oa as L}from"./chunk-gwbanhxq.js";import{Lc as $,Nc as B,Vc as Q}from"./chunk-tzq6155m.js";import{Ve as y}from"./chunk-d4z4kpvk.js";import{Og as V}from"./chunk-0141jad7.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as m,I as n,M as o,R as p,_ as q,C as r};
@@ -1,4 +1,4 @@
1
- import{sf as YO}from"./chunk-psy247es.js";import{Bg as S,Eg as y,zg as qO}from"./chunk-js4aekf1.js";import{Lg as P}from"./chunk-9fm80wbr.js";import{lh as XO}from"./chunk-z37v80c1.js";import{Hh as n}from"./chunk-79cxktz1.js";import{Rh as r}from"./chunk-9x141v5g.js";import{Th as w}from"./chunk-bvhbc0wr.js";var b;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(b||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import C from"node:path";import{LRUCache as fO}from"lru-cache";import{nanoid as R}from"nanoid";var N={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import DO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import k from"node:path";import{Mutex as SO}from"async-mutex";import GO from"write-file-atomic";var h=1,VO=1048576,LO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function zO(O){let q={};for(let Q of Object.values(b)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(b))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(zO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new SO;filePath;constructor(O=k.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let W;try{W=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let J=W.projects[Z];if(!J)return{...X,state:"untrusted"};return{...X,state:J.digest===$?"trusted":"modified",trustedDigest:J.digest,trustedAt:J.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:h,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>VO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==h)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!k.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!LO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:h,projects:Z}}async writeStore(O){let q=k.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await GO(this.filePath,`${JSON.stringify(O,null,2)}
1
+ import{vf as YO}from"./chunk-zkhb55jz.js";import{Cg as qO,Eg as S,Hg as y}from"./chunk-qxn5bg5k.js";import{Og as P}from"./chunk-0141jad7.js";import{oh as XO}from"./chunk-b9vm7gns.js";import{Kh as n}from"./chunk-sj0k8cdf.js";import{Uh as r}from"./chunk-0ra945vt.js";import{Wh as w}from"./chunk-h0fh3j9w.js";var b;((V)=>{V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.PostToolUseFailure="PostToolUseFailure";V.PermissionRequest="PermissionRequest";V.Elicitation="Elicitation";V.ElicitationResult="ElicitationResult";V.UserPromptSubmit="UserPromptSubmit";V.SessionStart="SessionStart";V.SessionEnd="SessionEnd";V.Stop="Stop";V.SubagentStop="SubagentStop";V.Notification="Notification";V.Compaction="Compaction"})(b||={});var v;((Z)=>{Z.Approve="approve";Z.Block="block";Z.Async="async"})(v||={});var m;((Z)=>{Z.Allow="allow";Z.Deny="deny";Z.Ask="ask"})(m||={});import C from"node:path";import{LRUCache as fO}from"lru-cache";import{nanoid as R}from"nanoid";var N={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,httpPolicy:{},PreToolUse:[],PostToolUse:[{name:"builtin:code-review-sensor",matcher:{tools:"Edit|Write"},hooks:[{type:"prompt",prompt:"审查此代码变更,重点检查:"+"1) 安全漏洞(命令注入、XSS、SQL 注入、硬编码密钥/密码)"+"2) 明显的逻辑错误(无限循环、off-by-one、空引用)"+"3) 类型安全问题。"+"如果发现严重问题,将问题描述放在 hookSpecificOutput.additionalContext 中。"+"如果没有严重问题,返回 approve。",model:void 0,timeout:15}]}],PostToolUseFailure:[],PermissionRequest:[],Elicitation:[],ElicitationResult:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]};function E(O,q){return{...O,...q,PreToolUse:q.PreToolUse??O.PreToolUse,PostToolUse:q.PostToolUse??O.PostToolUse,PostToolUseFailure:q.PostToolUseFailure??O.PostToolUseFailure,PermissionRequest:q.PermissionRequest??O.PermissionRequest,Elicitation:q.Elicitation??O.Elicitation,ElicitationResult:q.ElicitationResult??O.ElicitationResult,UserPromptSubmit:q.UserPromptSubmit??O.UserPromptSubmit,SessionStart:q.SessionStart??O.SessionStart,SessionEnd:q.SessionEnd??O.SessionEnd,Stop:q.Stop??O.Stop,SubagentStop:q.SubagentStop??O.SubagentStop,Notification:q.Notification??O.Notification,Compaction:q.Compaction??O.Compaction}}function c(){let O={};if(process.env.BLADE_DISABLE_HOOKS==="true")O.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let q=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(q)&&q>0)O.defaultTimeout=q}return O}class d{executedHooks=new Map;canExecute(O,q){if(!this.executedHooks.has(O))this.executedHooks.set(O,new Set);if(this.executedHooks.get(O).has(q))return console.warn(`[HookGuard] Hook ${q} for tool ${O} already executed, skipping`),!1;return!0}markExecuted(O,q){let Q=this.executedHooks.get(O);if(Q)Q.add(q)}cleanup(O){this.executedHooks.delete(O)}cleanupAll(){this.executedHooks.clear()}}import DO from"node:path";import{createHash as JO}from"node:crypto";import{constants as s,promises as j}from"node:fs";import k from"node:path";import{Mutex as SO}from"async-mutex";import GO from"write-file-atomic";var h=1,VO=1048576,LO=/^sha256:[0-9a-f]{64}$/;class o extends Error{constructor(){super("Hook configuration changed after review; reload before trusting");this.name="HookTrustDigestMismatchError"}}function D(O){return O!==null&&typeof O==="object"&&!Array.isArray(O)}function M(O){if(O===void 0||typeof O==="function")return;if(Array.isArray(O))return O.map(M).filter((Q)=>Q!==void 0);if(!D(O))return O;if(O.type==="function")return;let q={};for(let Q of Object.keys(O).sort()){let Z=M(O[Q]);if(Z!==void 0)q[Q]=Z}return q}function zO(O){let q={};for(let Q of Object.values(b)){let Y=(O[Q]??[]).map(($)=>M({...$,hooks:$.hooks.map((X)=>X.source?{...X,source:{kind:X.source.kind,pluginName:X.source.pluginName,pluginSource:X.source.pluginSource}}:X)})).filter(($)=>$!==void 0);if(Y.length>0)q[Q]=Y}return{defaultTimeout:O.defaultTimeout,timeoutBehavior:O.timeoutBehavior,failureBehavior:O.failureBehavior,maxConcurrentHooks:O.maxConcurrentHooks,httpPolicy:M(O.httpPolicy??{}),events:q}}function FO(O){if(O.type==="command")return O.command.slice(0,2048);if(O.type==="prompt")return O.prompt.slice(0,512);if(O.type==="http")try{let q=new URL(O.url);return`${q.origin}${q.pathname}`.slice(0,2048)}catch{return O.url.slice(0,2048)}return"in-process function"}function t(O){let q=[];for(let Q of Object.values(b))for(let Z of O[Q]??[]){let Y=Z.matcher?JSON.stringify(M(Z.matcher)):void 0;for(let $ of Z.hooks){if($.type==="function")continue;q.push({event:Q,matcher:Y,name:Z.name,type:$.type,target:FO($),...$.source?{pluginName:$.source.pluginName,pluginSource:$.source.pluginSource}:{}})}}return q}function RO(O){if(t(O).length===0)return null;let q=JSON.stringify(M(zO(O)));return`sha256:${JO("sha256").update(q).digest("hex")}`}class A{static instance=null;mutex=new SO;filePath;constructor(O=k.join(r(),"hook-trust.json")){this.filePath=O}static getInstance(){if(!A.instance)A.instance=new A;return A.instance}static resetInstance(){A.instance=null}async getStatus(O,q){let{projectPath:Q,trustRoot:Z}=await n(O),Y=t(q),$=RO(q),X={projectPath:Q,trustRoot:Z,enabled:q.enabled===!0,configuredHooks:Y.length,currentDigest:$,definitions:Y};if(!q.enabled)return{...X,state:"disabled"};if(!$)return{...X,state:"not_required"};let W;try{W=await this.readStore()}catch(G){return{...X,state:"error",error:G instanceof Error?G.message:"Hook trust store is unavailable"}}let J=W.projects[Z];if(!J)return{...X,state:"untrusted"};return{...X,state:J.digest===$?"trusted":"modified",trustedDigest:J.digest,trustedAt:J.trustedAt}}async trust(O,q,Q){return this.mutex.runExclusive(async()=>{let Z=await this.getStatus(O,q);if(!Z.currentDigest)throw Error("No configured external hooks require trust");if(Q!==void 0&&Q!==Z.currentDigest)throw new o;let Y=await this.readStore();return Y.projects[Z.trustRoot]={digest:Z.currentDigest,trustedAt:new Date().toISOString()},await this.writeStore(Y),this.getStatus(O,q)})}async revoke(O,q){return this.mutex.runExclusive(async()=>{let Q=await this.getStatus(O,q),Z=await this.readStore();if(Q.trustRoot in Z.projects)delete Z.projects[Q.trustRoot],await this.writeStore(Z);return this.getStatus(O,q)})}async readStore(){let O;try{O=await j.open(this.filePath,s.O_RDONLY|s.O_NOFOLLOW)}catch(Y){if(Y.code==="ENOENT")return{version:h,projects:{}};throw Error("Hook trust store must be a regular file")}let q;try{let Y=await O.stat();if(!Y.isFile())throw Error("Hook trust store must be a regular file");if(Y.size>VO)throw Error("Hook trust store exceeds the maximum supported size");if(process.getuid&&Y.uid!==process.getuid())throw Error("Hook trust store must be owned by the current user");if((Y.mode&511)!==384)throw Error("Hook trust store permissions must be 0600");q=await O.readFile("utf8")}finally{await O.close()}let Q=JSON.parse(q);if(!D(Q)||Q.version!==h)throw Error("Hook trust store version must be 1");if(Object.keys(Q).some((Y)=>Y!=="version"&&Y!=="projects")||!D(Q.projects))throw Error("Hook trust store contains unsupported fields");let Z={};for(let[Y,$]of Object.entries(Q.projects)){if(!k.isAbsolute(Y)||!D($)||typeof $.digest!=="string"||!LO.test($.digest)||typeof $.trustedAt!=="string"||!Number.isFinite(Date.parse($.trustedAt))||Object.keys($).some((X)=>X!=="digest"&&X!=="trustedAt"))throw Error("Hook trust store contains an invalid project entry");Z[Y]={digest:$.digest,trustedAt:$.trustedAt}}return{version:h,projects:Z}}async writeStore(O){let q=k.dirname(this.filePath);await j.mkdir(q,{recursive:!0,mode:448}),await j.chmod(q,448),await GO(this.filePath,`${JSON.stringify(O,null,2)}
2
2
  `,{mode:384}),await j.chmod(this.filePath,384)}}class T extends Error{constructor(O){super(O);this.name="HttpHookSecurityError"}}function e(O,q={}){let Q;try{Q=new URL(O)}catch{throw new T(`Invalid URL: ${O}`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw new T(`Only http/https supported, got: ${Q.protocol}`);let Z=Q.hostname.toLowerCase();if(BO(Z,q.allowedHosts))return;if(Q.protocol==="http:"&&!q.allowHttp)throw new T(`HTTP (non-TLS) blocked for ${Z}; use https:// or add to allowedHosts`);if(AO(Z)&&!q.allowLoopback)throw new T(`Loopback address blocked: ${Z}; enable policy.allowLoopback or add to allowedHosts`);if(PO(Z)&&!q.allowPrivateRanges)throw new T(`Private/link-local address blocked: ${Z}; enable policy.allowPrivateRanges or add to allowedHosts`)}function BO(O,q){if(!q||q.length===0)return!1;return q.some((Q)=>{let Z=Q.toLowerCase();if(Z===O)return!0;if(Z.startsWith("*.")){let Y=Z.slice(1);return O.endsWith(Y)&&O.length>Y.length}return!1})}function AO(O){if(O==="localhost")return!0;if(O==="::1"||O==="[::1]")return!0;if(/^127\.\d+\.\d+\.\d+$/.test(O))return!0;return!1}function PO(O){let q=O.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(!q)return!1;let[Q,Z]=q.slice(1).map(Number);if(Q===10)return!0;if(Q===172&&Z>=16&&Z<=31)return!0;if(Q===192&&Z===168)return!0;if(Q===169&&Z===254)return!0;return!1}function OO(O){if(!O)return{};let q={};for(let[Q,Z]of Object.entries(O))q[Q]=Z.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(Y,$)=>{return process.env[$]??`\${${$}}`});return q}var UO=S.Object({hookEventName:S.Literal("PreToolUse"),permissionDecision:S.Optional(S.Enum(m)),permissionDecisionReason:S.Optional(S.String()),updatedInput:S.Optional(S.Record(S.String(),S.Unknown()))}),_O=S.Object({hookEventName:S.Literal("PostToolUse"),additionalContext:S.Optional(S.String()),updatedOutput:S.Optional(S.Unknown())}),KO=S.Object({hookEventName:S.Literal("Stop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String())}),bO=S.Object({hookEventName:S.Literal("SubagentStop"),continue:S.Optional(S.Boolean()),continueReason:S.Optional(S.String()),additionalContext:S.Optional(S.String())}),NO=S.Object({hookEventName:S.Literal("PermissionRequest"),permissionDecision:S.Optional(y(["approve","deny","ask"])),permissionDecisionReason:S.Optional(S.String())}),QO=S.Record(S.String(),S.Union([S.String(),S.Number(),S.Boolean(),S.Array(S.String(),{maxItems:100})]),{maxProperties:32}),MO=S.Object({hookEventName:S.Literal("Elicitation"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),TO=S.Object({hookEventName:S.Literal("ElicitationResult"),action:S.Optional(y(["accept","decline","cancel"])),content:S.Optional(QO)}),wO=S.Object({hookEventName:S.Literal("UserPromptSubmit"),updatedPrompt:S.Optional(S.String()),contextInjection:S.Optional(S.String())}),CO=S.Object({hookEventName:S.Literal("SessionStart"),env:S.Optional(S.Record(S.String(),S.String()))}),EO=S.Object({hookEventName:S.Literal("Compaction"),blockCompaction:S.Optional(S.Boolean()),blockReason:S.Optional(S.String())}),jO=S.Object({decision:S.Optional(S.Object({behavior:S.Enum(v)})),systemMessage:S.Optional(S.String()),hookSpecificOutput:S.Optional(S.Union([UO,_O,KO,bO,NO,MO,TO,wO,CO,EO])),suppressOutput:S.Optional(S.Boolean())});function ZO(O){return qO(jO,O)}class p{parse(O,q,Q){if(O.timedOut){let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let Z=this.tryParseJSON(O.stdout);if(Z){let Y=ZO(Z);if(!Y.success){let X="error"in Y?Y.error.message:"Unknown validation error",W=Q?.failureBehavior||"ignore",J=`Invalid hook output JSON: ${X}`;if(W==="deny")return{success:!1,blocking:!0,error:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else if(W==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};else return{success:!1,blocking:!1,warning:J,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}let $=Y.data;if($.decision?.behavior==="block")return{success:!1,blocking:!0,error:$.systemMessage||"Hook blocked execution",output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};if($.decision?.behavior==="async")return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q};return{success:!0,output:$,stdout:O.stdout,stderr:O.stderr,exitCode:O.exitCode,hook:q}}return this.parseByExitCode(O,q,Q)}parseByExitCode(O,q,Q){let Z=O.exitCode;switch(Z){case 0:return{success:!0,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 2:return{success:!1,blocking:!0,error:O.stderr||O.stdout||"Hook returned exit code 2",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};case 124:{let Y=Q?.timeoutBehavior||"ignore",$="Hook timeout";if(Y==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}default:{let Y=Q?.failureBehavior||"ignore",$=O.stderr||O.stdout||`Hook failed with exit code ${Z}`;if(Y==="deny")return{success:!1,blocking:!0,error:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else if(Y==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${$}. Continue?`,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q};else return{success:!1,blocking:!1,warning:$,stdout:O.stdout,stderr:O.stderr,exitCode:Z,hook:q}}}}tryParseJSON(O){try{let q=O.trim();if(!q)return null;let Q=q.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Q)return null;return JSON.parse(Q[1])}catch{return null}}}class u{content="";maxSize;constructor(O){this.maxSize=O}append(O){if(this.content.length<this.maxSize){let q=this.maxSize-this.content.length;this.content+=O.substring(0,q)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class l{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute(O,q,Q,Z){let Y=JSON.stringify(q);if(Y.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Y.length} bytes (max ${this.MAX_INPUT_SIZE})`);let $=this.createSafeEnv(q,Q.environment),{child:X,processTree:W}=YO(O,[],{shell:!0,env:$,cwd:Q.projectDir}),J=new u(this.MAX_STDOUT_SIZE),G=new u(this.MAX_STDERR_SIZE);X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(L)=>{J.append(L)}),X.stderr?.on("data",(L)=>{G.append(L)});try{X.stdin?.write(Y),X.stdin?.end()}catch(L){throw await W.terminate(),Error(`Failed to write hook input: ${L}`)}return new Promise((L,F)=>{let z=!1,V=!1,B,U=()=>{return B??=W.terminate(),B},K=null,H=()=>{if(K&&Q.abortSignal)Q.abortSignal.removeEventListener("abort",K),K=null},I=setTimeout(()=>{z=!0,U()},Z);if(X.on("close",async(f)=>{if(V)return;if(V=!0,clearTimeout(I),H(),z)await U();L({stdout:J.getContent(),stderr:G.getContent(),exitCode:z?124:f??1,timedOut:z})}),X.on("error",(f)=>{if(V)return;V=!0,clearTimeout(I),H(),F(f)}),Q.abortSignal){if(K=()=>{if(V)return;V=!0,clearTimeout(I),H(),U().then(()=>{L({stdout:J.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})},Q.abortSignal.addEventListener("abort",K),Q.abortSignal.aborted)K()}})}createSafeEnv(O,q={}){return{...q,PATH:q.PATH??process.env.PATH??"",HOME:q.HOME??process.env.HOME??"",USER:q.USER??process.env.USER??"",SHELL:q.SHELL??process.env.SHELL??"/bin/sh",BLADE_PROJECT_DIR:O.project_dir,BLADE_SESSION_ID:O.session_id,BLADE_HOOK_EVENT:O.hook_event_name,BLADE_TOOL_NAME:"tool_name"in O?O.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in O?O.tool_use_id:""}}}var $O=XO("Execution"),yO={PreToolUse:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "...", "updatedInput": { ... } }',PostToolUse:'{ "additionalContext": "注入到工具结果的额外信息", "updatedOutput": "修改后的工具输出" }',Stop:'{ "continue": true, "continueReason": "继续执行的原因" } // continue: true 表示阻止停止',SubagentStop:'{ "continue": true, "continueReason": "...", "additionalContext": "..." }',PermissionRequest:'{ "permissionDecision": "approve" | "deny" | "ask", "permissionDecisionReason": "..." }',Elicitation:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',ElicitationResult:'{ "action": "accept" | "decline" | "cancel", "content": { "field": "value" } }',UserPromptSubmit:'{ "updatedPrompt": "修改后的提示词", "contextInjection": "注入的上下文" }',Compaction:'{ "blockCompaction": true, "blockReason": "阻止压缩的原因" }'};class x{processExecutor=new l;outputParser=new p;chatServiceCache=new Map;sessionModelResources=new Map;sessionEnvironments=new Map;trustWarnings=new Set;bindSessionModelResources(O,q,Q){for(let Z of q)this.sessionModelResources.set(this.sessionResourceKey(O,Z),Q),this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q.config.env)}bindSessionEnvironment(O,q,Q){for(let Z of q)this.sessionEnvironments.set(this.sessionResourceKey(O,Z),Q)}async unbindSessionModelResources(O,q){for(let Q of q){let Z=this.sessionResourceKey(O,Q);this.sessionModelResources.delete(Z),this.sessionEnvironments.delete(Z);let Y=`${Z}\x00`;for(let[$,X]of this.chatServiceCache){if(!$.startsWith(Y))continue;this.chatServiceCache.delete($),await X.dispose?.()}}}async executePreToolHooks(O,q,Q){if(O.length===0)return{decision:"allow"};let Z="tool_input"in q?q.tool_input:{},Y=[];for(let $ of O)try{let X={...q,...Z&&{tool_input:Z}},W=await this.executeHook($,X,Q);if(!W.success){if(W.blocking)return{decision:"deny",reason:W.error};if(W.needsConfirmation)return{decision:"ask",reason:W.warning||W.error};if(W.warning)Y.push(W.warning);continue}let J=W.output?.hookSpecificOutput;if(J&&"permissionDecision"in J){switch(J.permissionDecision){case"deny":return{decision:"deny",reason:J.permissionDecisionReason};case"ask":return{decision:"ask",reason:J.permissionDecisionReason};case"allow":break}if("updatedInput"in J&&J.updatedInput)Z={...Z,...J.updatedInput}}}catch(X){let W=X instanceof Error?X.message:String(X);if(Y.push(`Hook failed: ${W}`),Q.config.failureBehavior==="deny")return{decision:"deny",reason:W};else if(Q.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${W}. Continue?`}}return{decision:"allow",modifiedInput:Z,warning:Y.length>0?Y.join(`
3
3
  `):void 0}}async executePostToolHooks(O,q,Q){if(O.length===0)return{};let Z=Q.config.maxConcurrentHooks||5,Y=await this.executeHooksConcurrently(O,q,Q,Z),$=[],X=void 0,W=[];for(let J of Y){if(!J.success&&J.warning){W.push(J.warning);continue}let G=J.output?.hookSpecificOutput;if(G&&"additionalContext"in G){if(G.additionalContext)$.push(G.additionalContext);if("updatedOutput"in G&&G.updatedOutput!==void 0)X=G.updatedOutput}}return{additionalContext:$.length>0?$.join(`
4
4
 
@@ -25,7 +25,7 @@ import{sf as YO}from"./chunk-psy247es.js";import{Bg as S,Eg as y,zg as qO}from".
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-9eah1889.js"),{createChatServiceAsync:W}=await import("./chunk-2nnfx3s7.js"),{resolveModelConfig:J}=await import("./chunk-mjq7rrq1.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-bpf84msg.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-s56p9w29.js"),{createChatServiceAsync:W}=await import("./chunk-gn6ftvjy.js"),{resolveModelConfig:J}=await import("./chunk-rpbyc2k4.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-03k5c0e3.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -42,4 +42,4 @@ ${O.prompt}
42
42
  `+`- 只输出 JSON,不要包含 markdown 代码块或其他文本
43
43
  `+`- 如果没有发现问题,使用 "approve"
44
44
  `+'- 只在发现严重问题时使用 "block"'}extractJsonFromLLMResponse(O){let q=O.trim(),Q=q.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);if(Q)return Q[1].trim();return q}async executeHooksConcurrently(O,q,Q,Z){let Y=[],$=new Set;for(let X of O){if($.size>=Z)await Promise.race($);let W=this.executeHook(X,q,Q).catch((G)=>({success:!1,blocking:!1,error:G instanceof Error?G.message:String(G),hook:X})),J=W.then(()=>{$.delete(J)}).catch(()=>{$.delete(J)});$.add(J),Y.push(W)}return Promise.all(Y)}}async function HO(O,q){let Q=O.body?.getReader();if(!Q)return"";let Z=new TextDecoder,Y=0,$="";while(!0){let{value:X,done:W}=await Q.read();if(W)break;if(Y+=X.byteLength,Y>q){try{Q.cancel()}catch{}$+=Z.decode(X.slice(0,q-(Y-X.byteLength)));break}$+=Z.decode(X,{stream:!0})}return $+=Z.decode(),$}import a from"picomatch";var IO=/^([A-Za-z0-9_|]+)\((.+)\)$/;class i{matches(O,q){if(!O)return!0;if(O.tools&&q.toolName){if(!this.matchTools(O.tools,q))return!1}if(O.paths){let Q=q.filePaths??(q.filePath?[q.filePath]:[]);if(Q.length===0||!Q.some((Z)=>this.matchPaths(O.paths,Z)))return!1}if(O.commands&&q.command){if(!this.matchCommands(O.commands,q.command))return!1}return!0}matchTools(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchToolWithParams(Q,q));return this.matchToolWithParams(O,q)}matchPaths(O,q){if(Array.isArray(O))return O.some((Z)=>{return a(Z)(q)});return a(O)(q)}matchCommands(O,q){if(Array.isArray(O))return O.some((Q)=>this.matchPattern(q,Q));return this.matchPattern(q,O)}matchToolWithParams(O,q){let{toolName:Q,command:Z,filePath:Y}=q,$=IO.exec(O);if(!$)return this.matchPattern(Q,O);let[,X,W]=$;if(!this.matchPattern(Q,X))return!1;let J=this.getArgValues(Q,Z,q.filePaths??(Y?[Y]:[]));if(J.length===0)return!1;return J.some((G)=>this.matchGlobOrPattern(G,W))}getArgValues(O,q,Q=[]){if(O==="Bash"||O==="BashTool")return q?[q]:[];if(["Read","Edit","Write","ApplyPatch","Glob","Grep"].includes(O))return Q;return q?[q]:Q}matchGlobOrPattern(O,q){if(/[*?[\]{}!]/.test(q))try{return a(q,{bash:!0,dot:!0})(O)}catch{}if(q.endsWith("*")){let Q=q.slice(0,-1);return O.startsWith(Q)}return O===q}matchPattern(O,q){if(q==="*")return!0;if(!q.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(q))return O===q;if(q.includes("|"))return q.split("|").map((Z)=>Z.trim()).includes(O);try{return new RegExp(q).test(O)}catch{return O===q}}}var WO=64;class _{static instance=null;config=N;executor=new x;guard=new d;matcher=new i;processDisabled=!1;disabledSessions=new Set;sessionStateAliases=new Map;projectConfigs=new fO({max:WO});sessionConfigs=new Map;managedFunctionMatchers={};constructor(){}static getInstance(){if(!_.instance)_.instance=new _;return _.instance}bindSessionModelResources(O,q,Q){this.executor.bindSessionModelResources(O,q,Q)}bindSessionEnvironment(O,q,Q){this.executor.bindSessionEnvironment(O,q,Q)}bindSessionConfig(O,q,Q){let Z=this.sessionConfigKey(O,q[0]??P()),Y=this.disabledSessions.has(Z);for(let $ of q){let X=this.sessionConfigKey(O,$);if(Y||=this.disabledSessions.has(X),this.sessionStateAliases.set(X,Z),this.sessionConfigs.set(X,this.snapshotConfig(Q)),X!==Z)this.disabledSessions.delete(X)}if(Y)this.disabledSessions.add(Z)}async unbindSessionModelResources(O,q){let Q=`${O}\x00`;for(let Z of this.sessionConfigs.keys()){if(!Z.startsWith(Q))continue;this.sessionConfigs.delete(Z)}for(let Z of this.sessionStateAliases.keys()){if(!Z.startsWith(Q))continue;this.sessionStateAliases.delete(Z)}for(let Z of this.disabledSessions){if(!Z.startsWith(Q))continue;this.disabledSessions.delete(Z)}await this.executor.unbindSessionModelResources(O,q)}static resetInstance(){_.instance?.cleanup(),_.instance=null}loadConfig(O,q=P()){let Q=E(N,O),Z=c();Q=E(Q,Z),this.storeProjectConfig(q,Q)}isEnabled(O=P(),q){if(!(q?this.getExecutionConfig(q,O):this.getConfig(O)).enabled)return!1;if(this.processDisabled)return!1;if(q&&this.disabledSessions.has(this.sessionStateKey(q,O)))return!1;return!0}disable(){this.processDisabled=!0,console.log("[HookManager] Hooks disabled for this process")}enable(){this.processDisabled=!1,console.log("[HookManager] Hooks enabled for this process")}disableSession(O,q){this.disabledSessions.add(this.sessionStateKey(O,q))}enableSession(O,q){this.disabledSessions.delete(this.sessionStateKey(O,q))}isSessionEnabled(O,q){return this.isEnabled(q,O)}isSessionPaused(O,q){return this.disabledSessions.has(this.sessionStateKey(O,q))}getConfig(O=P()){let q=C.resolve(O),Q=this.projectConfigs.get(q);if(Q)return Q;if(q===C.resolve(P()))return this.config;return{...N,enabled:!1}}getExecutionConfig(O,q){return this.sessionConfigs.get(this.sessionConfigKey(O,q))??this.getConfig(q)}isExecutionEnabled(O,q,Q){return O.enabled===!0&&!this.processDisabled&&!this.disabledSessions.has(this.sessionStateKey(q,Q))}sessionStateKey(O,q){let Q=this.sessionConfigKey(O,q);return this.sessionStateAliases.get(Q)??Q}sessionConfigKey(O,q){return`${O}\x00${C.resolve(q)}`}snapshotConfig(O){let q=E(N,O);for(let Q of Object.values(b))q[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((Y)=>({...Y}))}));return q}storeProjectConfig(O,q){let Q=C.resolve(O);if(Q===C.resolve(P())){this.config=q,this.projectConfigs.delete(Q);return}this.projectConfigs.set(Q,q)}inheritProjectConfig(O,q,Q){let Z=Q?this.getExecutionConfig(Q,O):this.getConfig(O);if(this.storeProjectConfig(q,this.snapshotConfig(Z)),!Q)return;let Y=this.sessionConfigKey(Q,O),$=this.sessionConfigKey(Q,q),X=this.sessionStateAliases.get(Y)??Y,W=this.disabledSessions.has(X)||this.disabledSessions.has($);if(this.sessionConfigs.set($,this.snapshotConfig(Z)),this.sessionStateAliases.set($,X),$!==X)this.disabledSessions.delete($);if(W)this.disabledSessions.add(X)}getResidencyStats(){return{projectCapacity:WO,projectConfigs:this.projectConfigs.size,sessionConfigs:this.sessionConfigs.size,sessionAliases:this.sessionStateAliases.size}}getTrustStatus(O=P()){return A.getInstance().getStatus(O,this.getConfig(O))}trustProject(O=P(),q){return A.getInstance().trust(O,this.getConfig(O),q)}revokeProjectTrust(O=P()){return A.getInstance().revoke(O,this.getConfig(O))}registerFunction(O,q,Q,Z){let Y={type:"function",handler:Q,timeout:Z?.timeout},$={name:Z?.name??`inline-${O}-${Date.now()}`,matcher:q,hooks:[Y]};if(Z?.projectDir){let W=C.resolve(Z.projectDir),J=this.getConfig(W),G=J[O]??[];return J[O]=[...G,$],this.storeProjectConfig(W,J),()=>{let L=J[O];if(!L)return;J[O]=L.filter((F)=>F!==$)}}let X=this.managedFunctionMatchers[O]??[];return this.managedFunctionMatchers[O]=[...X,$],()=>{let W=this.managedFunctionMatchers[O]??[];this.managedFunctionMatchers[O]=W.filter((J)=>J!==$)}}async reloadConfig(O=P()){let q=await import("node:fs/promises"),Q=await import("node:path");try{let Z=Q.join(O,".blade","settings.local.json"),Y=await q.readFile(Z,"utf-8"),$=JSON.parse(Y);if($.hooks)this.loadConfig($.hooks,O)}catch{}}async executePreToolHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"allow"};if(Z.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(q,"PreToolUse"))return{decision:"allow"};let $={hook_event_name:"PreToolUse",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PreToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"allow"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{let J=await this.executor.executePreToolHooks(X,$,W);if(this.guard.markExecuted(q,"PreToolUse"),Z.permissionMode==="yolo"){if(J.decision==="deny")return J;return{decision:"allow",modifiedInput:J.modifiedInput,warning:J.warning,reason:J.reason}}return J}catch(J){return console.error("[HookManager] Error executing PreToolUse hooks:",J),{decision:"allow",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executePostToolHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};if(Y.permissionMode==="plan")return{};if(!this.guard.canExecute(q,"PostToolUse"))return{};let X={hook_event_name:"PostToolUse",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,tool_response:Z,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUse",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{let G=await this.executor.executePostToolHooks(W,X,J);return this.guard.markExecuted(q,"PostToolUse"),G}catch(G){return console.error("[HookManager] Error executing PostToolUse hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}finally{this.guard.cleanup(q)}}async executeStopHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{shouldStop:!0};let Q={hook_event_name:"Stop",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,reason:O.reason},Z=this.getMatchingHooks("Stop",{},q);if(Z.length===0)return{shouldStop:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeStopHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing Stop hooks:",$),{shouldStop:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSubagentStopHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{shouldStop:!0};let Z={hook_event_name:"SubagentStop",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,agent_type:O,task_description:q.taskDescription,success:q.success,result_summary:q.resultSummary,error:q.error},Y=this.getMatchingHooks("SubagentStop",{},Q);if(Y.length===0)return{shouldStop:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSubagentStopHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing SubagentStop hooks:",X),{shouldStop:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePermissionRequestHooks(O,q,Q,Z){let Y=this.getExecutionConfig(Z.sessionId,Z.projectDir);if(!this.isExecutionEnabled(Y,Z.sessionId,Z.projectDir))return{decision:"ask"};let $={hook_event_name:"PermissionRequest",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,project_dir:Z.projectDir,session_id:Z.sessionId,permission_mode:Z.permissionMode},X=this.getMatchingHooks("PermissionRequest",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},Y);if(X.length===0)return{decision:"ask"};let W={projectDir:Z.projectDir,sessionId:Z.sessionId,permissionMode:Z.permissionMode,config:Y,abortSignal:Z.abortSignal};try{return await this.executor.executePermissionRequestHooks(X,$,W)}catch(J){return console.error("[HookManager] Error executing PermissionRequest hooks:",J),{decision:"ask",warning:`Hook execution failed: ${J instanceof Error?J.message:String(J)}`}}}async executeUserPromptSubmitHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{proceed:!0};let Z={hook_event_name:"UserPromptSubmit",hook_execution_id:R(),timestamp:new Date().toISOString(),user_prompt:O,has_images:q.hasImages,image_count:q.imageCount,project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode},Y=this.getMatchingHooks("UserPromptSubmit",{},Q);if(Y.length===0)return{proceed:!0};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeUserPromptSubmitHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing UserPromptSubmit hooks:",X),{proceed:!0,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeSessionStartHooks(O){let q=this.getExecutionConfig(O.sessionId,O.projectDir);if(!this.isExecutionEnabled(q,O.sessionId,O.projectDir))return{proceed:!0};let Q={hook_event_name:"SessionStart",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:O.projectDir,session_id:O.sessionId,permission_mode:O.permissionMode,is_resume:O.isResume,resume_session_id:O.resumeSessionId},Z=this.getMatchingHooks("SessionStart",{},q);if(Z.length===0)return{proceed:!0};let Y={projectDir:O.projectDir,sessionId:O.sessionId,permissionMode:O.permissionMode,config:q,abortSignal:O.abortSignal};try{return await this.executor.executeSessionStartHooks(Z,Q,Y)}catch($){return console.error("[HookManager] Error executing SessionStart hooks:",$),{proceed:!0,warning:`Hook execution failed: ${$ instanceof Error?$.message:String($)}`}}}async executeSessionEndHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"SessionEnd",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,reason:O},Y=this.getMatchingHooks("SessionEnd",{},Q);if(Y.length===0)return{};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeSessionEndHooks(Y,Z,$),{}}catch(X){return console.error("[HookManager] Error executing SessionEnd hooks:",X),{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executePostToolUseFailureHooks(O,q,Q,Z,Y){let $=this.getExecutionConfig(Y.sessionId,Y.projectDir);if(!this.isExecutionEnabled($,Y.sessionId,Y.projectDir))return{};let X={hook_event_name:"PostToolUseFailure",hook_execution_id:R(),timestamp:new Date().toISOString(),tool_name:O,tool_use_id:q,tool_input:Q,error:Z,error_type:Y.errorType,is_interrupt:Y.isInterrupt,is_timeout:Y.isTimeout,project_dir:Y.projectDir,session_id:Y.sessionId,permission_mode:Y.permissionMode},W=this.getMatchingHooks("PostToolUseFailure",{toolName:O,filePath:this.extractFilePaths(Q)[0],filePaths:this.extractFilePaths(Q),command:this.extractCommand(O,Q)},$);if(W.length===0)return{};let J={projectDir:Y.projectDir,sessionId:Y.sessionId,permissionMode:Y.permissionMode,config:$,abortSignal:Y.abortSignal};try{return await this.executor.executePostToolUseFailureHooks(W,X,J)}catch(G){return console.error("[HookManager] Error executing PostToolUseFailure hooks:",G),{warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executeNotificationHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{suppress:!1,message:q};let Y={hook_event_name:"Notification",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,notification_type:O,title:Q.title,message:q},$=this.getMatchingHooks("Notification",{},Z);if($.length===0)return{suppress:!1,message:q};let X={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeNotificationHooks($,Y,X)}catch(W){return console.error("[HookManager] Error executing Notification hooks:",W),{suppress:!1,message:q,warning:`Hook execution failed: ${W instanceof Error?W.message:String(W)}`}}}async executeElicitationHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{};let Z={hook_event_name:"Elicitation",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,server_name:O.serverName,mode:O.mode,message:O.message,requested_schema:O.requestedSchema,url:O.url,elicitation_id:O.elicitationId};return this.executeElicitationHookChain("Elicitation",Z,q,Q)}async executeElicitationResultHooks(O,q,Q){let Z=this.getExecutionConfig(Q.sessionId,Q.projectDir);if(!this.isExecutionEnabled(Z,Q.sessionId,Q.projectDir))return{};let Y={hook_event_name:"ElicitationResult",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode,server_name:O.serverName,mode:O.mode,elicitation_id:O.elicitationId,action:q.action,content:q.content};return this.executeElicitationHookChain("ElicitationResult",Y,Q,Z)}async executeElicitationHookChain(O,q,Q,Z){let Y=this.getMatchingHooks(O,{},Z);if(Y.length===0)return{};let $={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:Z,abortSignal:Q.abortSignal};try{return await this.executor.executeElicitationHooks(Y,q,$)}catch(X){return{warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}async executeCompactionHooks(O,q){let Q=this.getExecutionConfig(q.sessionId,q.projectDir);if(!this.isExecutionEnabled(Q,q.sessionId,q.projectDir))return{blockCompaction:!1};let Z={hook_event_name:"Compaction",hook_execution_id:R(),timestamp:new Date().toISOString(),project_dir:q.projectDir,session_id:q.sessionId,permission_mode:q.permissionMode,trigger:O,messages_before:q.messagesBefore,tokens_before:q.tokensBefore},Y=this.getMatchingHooks("Compaction",{},Q);if(Y.length===0)return{blockCompaction:!1};let $={projectDir:q.projectDir,sessionId:q.sessionId,permissionMode:q.permissionMode,config:Q,abortSignal:q.abortSignal};try{return await this.executor.executeCompactionHooks(Y,Z,$)}catch(X){return console.error("[HookManager] Error executing Compaction hooks:",X),{blockCompaction:!1,warning:`Hook execution failed: ${X instanceof Error?X.message:String(X)}`}}}getMatchingHooks(O,q,Q){let Z=[...Q[O]??[],...this.managedFunctionMatchers[O]??[]],Y=[];for(let $ of Z)if(this.matcher.matches($.matcher,q))Y.push(...$.hooks);return Y}extractFilePaths(O){let q=[],Q=["file_path","path","filePath","source","target"];for(let Z of Q){let Y=O[Z];if(typeof Y==="string")q.push(Y)}if(typeof O.patch==="string"){for(let Z of O.patch.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm))if(Z[1])q.push(Z[1]);for(let Z of O.patch.matchAll(/^\*\*\* Move to: (.+)$/gm))if(Z[1])q.push(Z[1])}return[...new Set(q)]}extractCommand(O,q){if(O==="Bash"||O==="BashTool"){let Q=q.command;if(typeof Q==="string")return Q}return}cleanup(){this.guard.cleanupAll(),this.config=N,this.processDisabled=!1,this.disabledSessions.clear(),this.sessionStateAliases.clear(),this.projectConfigs.clear(),this.sessionConfigs.clear(),this.managedFunctionMatchers={}}}
45
- export{b as mf,o as nf,_ as of};
45
+ export{b as pf,o as qf,_ as rf};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-xmty01x3.js";import"./chunk-kxgr18gy.js";import"./chunk-bvhbc0wr.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-g6fw4y71.js";import"./chunk-m7xfm75q.js";import"./chunk-h0fh3j9w.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -0,0 +1 @@
1
+ import{Ab as k,Hb as l,Ib as m,Jb as n,Kb as o,Mb as p,Nb as q,Ob as r,mb as a,nb as b,pb as c,tb as d,ub as e,vb as f,wb as g,xb as h,yb as i,zb as j}from"./chunk-bxks9zbr.js";import"./chunk-r8wbvxn7.js";import"./chunk-tzq6155m.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-mygw13zd.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-w1zk41np.js";import"./chunk-zkhb55jz.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-m7xfm75q.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.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};
@@ -0,0 +1,6 @@
1
+ import{m as fH,n as yH,o as SH,p as TH,q as bH,r as RH}from"./chunk-vkz1vhbp.js";import{A as JH,v as MH,w as t,x as e,y as HH,z as d}from"./chunk-fdcn0thm.js";import{Q as xH,S as UH,T as _H,V as ZH,Y as GH}from"./chunk-gwbanhxq.js";import"./chunk-s3r32avd.js";import"./chunk-ky9q53m7.js";import{Eb as jH,jb as s,vb as WH}from"./chunk-bxks9zbr.js";import"./chunk-r8wbvxn7.js";import{Kc as O,Vc as a,vc as DH,zc as LH}from"./chunk-tzq6155m.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{rd as FH}from"./chunk-tqjpaaa0.js";import{td as EH,ud as zH,vd as AH}from"./chunk-szhzvb57.js";import{wd as PH}from"./chunk-jdb2mwbn.js";import"./chunk-h3w814js.js";import{Wd as QH}from"./chunk-16wxxkev.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-5m8x01n9.js";import"./chunk-d4z4kpvk.js";import{hf as VH}from"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import"./chunk-w1zk41np.js";import"./chunk-zkhb55jz.js";import"./chunk-m4avjqx5.js";import{Ag as BH}from"./chunk-pfvgkexe.js";import{Cg as NH,Eg as H,Fg as KH,Hg as N}from"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as g}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-m7xfm75q.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";import fJ from"yargs";import{hideBin as yJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function mH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function cH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await mH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>cH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var $H=1;function D(K){return H.Object({event_version:H.Literal($H),...K})}var uH=D({type:H.Literal("content_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking_delta"),delta:H.String()}),pH=D({type:H.Literal("thinking"),content:H.String()}),vH=D({type:H.Literal("stream_end")}),lH=D({type:H.Literal("content"),content:H.String()}),aH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),sH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),iH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),oH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(sH)}),rH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),nH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(rH)}),tH=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),eH=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),HJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),JJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),KJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),VJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),ZJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),$J=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),qJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),XJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),YJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),BJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),NJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),QJ=D({type:H.Literal("task_update"),tasks:H.Array(ZH)}),DJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(VH)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),LJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),WJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),jJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(N(["circuit_open","context_exhausted","deterministic","empty_exhausted","transient_exhausted"]))}),xJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),UJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),GJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),PJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),FJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),EJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),zJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),AJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),MJ=D({type:H.Literal("error"),message:H.String()}),iJ=KH(H.Union([uH,dH,pH,vH,lH,aH,iH,oH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,UJ,_J,xJ,GJ,PJ,FJ,EJ,zJ,AJ,MJ]));function qH(K,V){return{event_version:$H,type:K,...V}}function SJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;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 TJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var bJ=N(["text","jsonl"]),RJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(BH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(bJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class IH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function IJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function gJ(K){let V=NH(RJ,K);if(!V.success)throw Error(`Invalid headless options: ${IJ(V.error)}`);return V.data}function CJ(K){return K.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 Q=await cJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
2
+ `)}function kJ(K){return`[task] [${K.status}] ${K.subject}`}function hJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function OJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function wJ(K){return K==="jsonl"?"jsonl":"text"}function XH(K,V){let Q=(...q)=>{for(let J of q){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function mJ(K,V,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))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 YH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify(qH(J,Z))}
3
+ `)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
4
+ `);if(J)K.stdout.write(`
5
+ `)},content(J){if(V==="jsonl"){q("content",{content:J});return}L(K.stdout,J)},structuredOutput(J){if(V==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}L(K.stdout,JSON.stringify(J.output))},toolStart(J,Z,W,x){if(V==="jsonl"){q("tool_start",{tool_name:J,summary:Z,target:W,tool_kind:x});return}L(K.stderr,`[tool:start] ${Z}`)},toolProgress(J,Z,W,x,j){if(V==="jsonl"){q("tool_progress",{tool_name:J,message:Z,progress:W,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}L(K.stderr,`[tool:progress] ${J}: ${Z}`)},toolResult(J,Z,W,x,j){if(V==="jsonl"){q("tool_result",{tool_name:J,summary:Z,target:W,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}L(K.stderr,`[tool:result] ${Z}`)},mcpCatalogChanged(J){if(V==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(V==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(V==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}L(K.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(V==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}L(K.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(V==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}L(K.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(V==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}L(K.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(V==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}L(K.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(V==="jsonl"){q("project_rules_loaded",{files:J.files.map((Z)=>({id:Z.id,relative_path:Z.relativePath,source:Z.source,conditional:Z.conditional,content_sha256:Z.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}L(K.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,Z,W){if(V==="jsonl"){q("user_shell_started",{execution_id:J,command:Z,auxiliary:W});return}L(K.stderr,`[user-shell:start] ${Z}`)},userShellOutput(J,Z,W,x){if(V==="jsonl"){q("user_shell_output",{execution_id:J,stream:Z,chunk:W,stream_truncated:x});return}(Z==="stderr"?K.stderr:K.stdout).write(W)},userShellCompleted(J){if(V==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}L(K.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,Z,W,x={}){if(V==="jsonl"){q("phase",{phase:J,status:Z,message:W,turn:x.turn,tool_name:x.toolName,target:x.target});return}L(K.stderr,`[phase:${J}] ${W}`)},toolDetail(J,Z){if(V==="jsonl"){q("tool_detail",{tool_name:J,detail:Z});return}L(K.stderr,Z)},taskUpdate(J){if(V==="jsonl"){q("task_update",{tasks:J});return}for(let Z of J)L(K.stderr,kJ(Z))},goal(J){if(V==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount});return}if(J.goal)L(K.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else L(K.stderr,"[goal:cleared]")},subagent(J){let Z=J.kind==="subagent_spawned";if(V==="jsonl"){q("subagent",{state:Z?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:Z?void 0:J.success,summary:Z?void 0:J.summary,verification_verdict:Z?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}L(K.stderr,`[subagent:${Z?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(V==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}L(K.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let Z=J.phase==="start";if(V==="jsonl"){q("compacting",{state:Z?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,input_reductions:J.inputReductions,messages_omitted:J.messagesOmitted,files_omitted:J.filesOmitted,failure_reason:J.failureReason});return}L(K.stderr,Z?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}${J.inputReductions?` with ${J.inputReductions} input reduction${J.inputReductions===1?"":"s"}`:""}`)},providerAdmission(J){if(V==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}L(K.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(V==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let Z=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";L(K.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${Z}`)},providerCircuit(J){if(V==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let Z=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";L(K.stderr,`[provider-circuit:${J.phase}] ${J.reason}${Z}`)},providerStall(J){if(V==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}L(K.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},actionStationarity(J){if(V==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}L(K.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(V==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}L(K.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(V==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}L(K.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(V==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}L(K.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,Z=0){if(V==="jsonl"){q("output",{content:J,exit_code:Z});return}L(Z===0?K.stdout:K.stderr,J)},error(J){if(V==="jsonl"){q("error",{message:J});return}L(K.stderr,J)}}}async function cJ(K,V={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new IH,Z={targetLocked:!1},W,x,j,G=TJ(Q),f=!1,F=new v(V,{signal:G.signal,onFailure:(Y)=>{f=!0,G.abort(Y)}}),w={stdout:{write:(Y)=>F.write("stdout",Y)},stderr:{write:(Y)=>F.write("stderr",Y)}},B=YH(w,q),m=async()=>{try{return await F.flush(),!f}catch{return!1}},y=async(Y)=>{return x?.(),x=void 0,j?.(),j=void 0,await m()?Y:1};try{let Y=gJ(K);q=wJ(Y.outputFormat);let S=await bH(Y);B=YH(w,q,Boolean(S)),await fH();let i=Y.forkSession!==!0&&(Y.continue===!0||typeof Y.resume==="string"&&Y.resume.length>0)?await SH({message:Y.message,_:Y._,stdin:Q?.stdin}):await yH({...Y,stdin:Q?.stdin}),R=i===void 0,P=R?{mode:"agent",content:""}:await TH(i);if(P.mode==="output"){if(P.content)B.output(P.content,P.exitCode??0);return await y(P.exitCode??0)}let C=P.content.trimStart().startsWith("!")?P.content.trimStart().slice(1).trim():void 0;if(C!==void 0&&Y.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(C!==void 0&&S)throw Error("Output schemas cannot be combined with user shell commands");if(Y.taskIsolation&&(Y.continue||Y.resume||Y.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:_,messages:o,metadata:r}=await RH({sessionId:Y.sessionId,continue:Y.continue,resume:Y.resume,forkSession:Y.forkSession,fallbackSessionPrefix:"headless"}),I=Y.permissionMode??r?.permissionMode??"yolo",n=Y.model&&Y.model!=="inherit"?Y.model:QH()?.id,U=Y.taskIsolation?await MH.createSessionTask({sessionId:_,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,dispatch:{version:1,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,permissionMode:I,...n?{modelId:n}:{},...S?{outputSchema:S}:{}}}):void 0,E=U?.metadata.projectPath??r?.projectPath??g();if(j=s.subscribe((X)=>{if(X.type!=="subagent.provider.admission"||X.sessionId!==_||X.projectPath!==E)return;let $=X.properties,z=["queued","admitted","rejected"],A=["foreground","background","internal"],M=["stream","pending_count","pending_bytes"],b=["global","domain","owner","class"],wH=["capacity","queue_full","wait_timeout","closed"];if(!z.includes($.phase)||!A.includes($.requestClass)||!M.includes($.resource)||!b.includes($.scope)||$.reason!==void 0&&!wH.includes($.reason)||typeof $.queuePosition!=="number"||typeof $.queueDepth!=="number"||typeof $.inFlight!=="number"||typeof $.limit!=="number"||typeof $.waitMs!=="number"||typeof $.maxWaitMs!=="number"||$.recoveryRemainingMs!==void 0&&typeof $.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}})}),!U)await a.setSessionPermissionMode(_,E,I);let gH=U?!1:await jH.cancelPendingNonInteractive(E,_);if(U)B.taskSession({sessionId:_,projectPath:E,sourceProjectPath:U.metadata.taskSourceProjectPath??g(),isolation:Y.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=s.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==_||X.projectPath!==E||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let CH={messages:gH?await a.loadSessionModelContext(_,E):[...o],userId:"cli-user",sessionId:_,workspaceRoot:E,permissionMode:I,signal:G.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:hJ()};W=await xH.create({sessionId:_,workspaceRoot:E,modelId:Y.model,permissionMode:I,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig,agents:Y.agents?PH(Y.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...o.length>0?{sessionStart:{isResume:!0,resumeSessionId:_}}:{}});let k=R&&W.getPendingSteeringCount()>0,h=R&&!k?await W.getGoal():null,c=h?.status==="active"||h?.status==="verifying",T=R&&!k&&!c?await W.getRecoveredFinalResponse():void 0;if(R&&!k&&!c){if(!T)throw Error("No unfinished turn or active goal to resume");if(h)B.goal({kind:"goal_updated",goal:h});if(T.structuredOutput&&T.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:T.structuredOutput,schemaDigest:T.structuredOutputSchemaDigest});else B.content(T.content);return B.phase("completed","done","Recovered headless run completed"),await y(0)}if(C!==void 0){let X=await W.executeUserShellCommand(C,{signal:G.signal,onEvent:async($)=>{if($.type==="started")B.userShellStarted($.executionId,$.command,$.auxiliary);else if($.type==="output")B.userShellOutput($.executionId,$.stream,$.chunk,$.streamTruncated);await m()}});return B.userShellCompleted(X),await y(X.record.status==="completed"?0:X.record.status==="aborted"?130:X.record.exitCode??1)}let kH=Y.maxTurns??W.getConfig().maxTurns,hH=U?.taskWorktree?[...new Set([...Y.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:Y.disallowedTools,OH=await GH.createWithRuntime(W,{sessionId:_,systemPrompt:Y.systemPrompt,appendSystemPrompt:Y.appendSystemPrompt,maxTurns:Y.maxTurns,modelId:Y.model,permissionMode:I,toolWhitelist:Y.allowedTools,toolBlacklist:hH,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig}),u=await WH(OH.chatStream(P.content,CH,{stream:!0,signal:G.signal,maxTurns:Y.maxTurns,builtinVerification:Y.verificationAgent!==!1,outputSchema:S,pendingInputOnly:k,goalContinuationOnly:c,...kH===-1?{onTurnLimitReached:async(X)=>{return B.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":if(!S||q==="jsonl")J.markAssistantContent();B.contentDelta(X.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta(X.delta,J.hasOpenThinking()));break;case"stream_end":{let $=J.completeStream();B.streamEnd($.wroteAssistantContent,$.openedThinking);break}case"tool_start":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;if(["TaskCreate","TaskUpdate","TaskList"].includes($.function.name))break;try{let z=JSON.parse($.function.arguments),A=UH($.function.name,z),M=XH($.function.name,z),b=mJ($.function.name,A,M,Z);if(b.shouldLockTarget)Z.targetLocked=!0;B.phase(b.phase,b.status,b.message,{toolName:$.function.name,target:M}),B.toolStart($.function.name,A,M,X.toolKind)}catch{B.phase(Z.targetLocked?"executing":"searching",Z.targetLocked?"hit":"ongoing",Z.targetLocked?`Working within target: ${$.function.name}`:`Still searching: ${$.function.name}`,{toolName:$.function.name}),B.toolStart($.function.name,$.function.name,void 0,X.toolKind)}break}case"tool_progress":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;B.toolProgress($.function.name,X.update.message,X.update.progress,X.update.total,X.update.admission);break}case"tool_result":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;let z;try{let M=JSON.parse($.function.arguments);z=XH($.function.name,M)}catch{z=void 0}let A=LH(_H($.function.name,X.result),DH);if(B.toolResult($.function.name,A.summary,z,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message,background:SJ(X.result.metadata)}),A.detail)B.toolDetail($.function.name,A.detail);break}case"token_usage":B.tokenUsage(X.usage);break;case"compaction":B.compacting(X);break;case"task_update":B.taskUpdate(X.tasks);break;case"structured_output":B.structuredOutput(X);break;case"mcp_catalog_changed":B.mcpCatalogChanged(X);break;case"mcp_content_changed":B.mcpContentChanged(X);break;case"mcp_resource_updated":B.mcpResourceUpdated(X);break;case"mcp_connection_changed":B.mcpConnectionChanged(X);break;case"mcp_log":B.mcpLog(X);break;case"mcp_instructions_changed":B.mcpInstructionsChanged(X);break;case"mcp_task_changed":B.mcpTaskChanged(X);break;case"project_rules_loaded":B.projectRulesLoaded(X);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":B.goal(X);break;case"subagent_spawned":case"subagent_completed":B.subagent(X);break;case"model_fallback":break;case"provider_admission":B.providerAdmission(X);break;case"provider_retry":B.providerRetry(X);break;case"provider_circuit":B.providerCircuit(X);break;case"provider_stall":B.providerStall(X);break;case"action_stationarity":B.actionStationarity(X);break;case"turn_start":if(X.turn===1)Z.targetLocked=!1;B.phase("turn",Z.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let $=X}}await m()});if(u.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!u.success)return B.error(`Error: ${u.error?.message??"Agent execution failed"}`),await y(1);return B.phase("completed","done","Headless run completed"),await y(0)}catch(Y){if(!f){if(J.hasOpenThinking()&&q==="text")w.stderr.write(`
6
+ `);B.error(`Error: ${OJ(Y)}`)}return await y(1)}finally{x?.(),j?.();try{await W?.dispose()}finally{F.close(),G.dispose()}}}async function PK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":Z,"max-turns":W,...x}=FH,j=fJ(yJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([zH,EH,AH]);return CJ(j),await j.parse(),!0}export{cJ as runHeadless,PK as handleHeadlessMode,RJ as HeadlessOptionsSchema};
@@ -1,2 +1,2 @@
1
1
  import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
2
- export{G as pf,F as qf,R as rf,v as sf};
2
+ export{G as sf,F as tf,R as uf,v as vf};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.76",
3
+ "version": "0.10.78",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{Ab as k,Hb as l,Ib as m,Jb as n,Kb as o,Mb as p,Nb as q,Ob as r,mb as a,nb as b,pb as c,tb as d,ub as e,vb as f,wb as g,xb as h,yb as i,zb as j}from"./chunk-66w68q81.js";import"./chunk-r8wbvxn7.js";import"./chunk-6h3x4jv0.js";import"./chunk-skw3b17a.js";import"./chunk-vdtma2yq.js";import"./chunk-c9e0fbyh.js";import"./chunk-01k69v34.js";import"./chunk-js4vqnds.js";import"./chunk-c80pzvhs.js";import"./chunk-n5d0d6q7.js";import"./chunk-9k3tg2hs.js";import"./chunk-psy247es.js";import"./chunk-9ra452yc.js";import"./chunk-js4aekf1.js";import"./chunk-t1bvxk3s.js";import"./chunk-9fm80wbr.js";import"./chunk-qnj3dajb.js";import"./chunk-z37v80c1.js";import"./chunk-68stvfdj.js";import"./chunk-vn1r6z64.js";import"./chunk-kxgr18gy.js";import"./chunk-79cxktz1.js";import"./chunk-9x141v5g.js";import"./chunk-bvhbc0wr.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,6 +0,0 @@
1
- import{m as fH,n as yH,o as SH,p as TH,q as bH,r as RH}from"./chunk-90yjhvjb.js";import{A as JH,v as MH,w as t,x as e,y as HH,z as d}from"./chunk-h0ys86rn.js";import{Q as xH,S as UH,T as _H,V as ZH,Y as GH}from"./chunk-8chhdkg2.js";import"./chunk-cgd0vjw2.js";import"./chunk-eesa8c5h.js";import{Eb as jH,jb as s,vb as WH}from"./chunk-66w68q81.js";import"./chunk-r8wbvxn7.js";import{Kc as O,Vc as a,vc as DH,zc as LH}from"./chunk-6h3x4jv0.js";import"./chunk-skw3b17a.js";import"./chunk-vdtma2yq.js";import{rd as FH}from"./chunk-zk34d9mm.js";import{td as EH,ud as zH,vd as AH}from"./chunk-vwa2kczj.js";import{wd as PH}from"./chunk-r8ayexxd.js";import"./chunk-zwd5q6dt.js";import{Wd as QH}from"./chunk-yhyqcmh1.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-01k69v34.js";import"./chunk-wx9zxzgm.js";import"./chunk-js4vqnds.js";import"./chunk-ttbq1xmz.js";import"./chunk-vpn2e8tj.js";import{ef as VH}from"./chunk-c80pzvhs.js";import"./chunk-n5d0d6q7.js";import"./chunk-8bsse16j.js";import"./chunk-9k3tg2hs.js";import"./chunk-psy247es.js";import"./chunk-tssmnn37.js";import{xg as BH}from"./chunk-9ra452yc.js";import{Bg as H,Cg as KH,Eg as N,zg as NH}from"./chunk-js4aekf1.js";import"./chunk-t1bvxk3s.js";import{Lg as g}from"./chunk-9fm80wbr.js";import"./chunk-qnj3dajb.js";import"./chunk-z37v80c1.js";import"./chunk-68stvfdj.js";import"./chunk-vn1r6z64.js";import"./chunk-kxgr18gy.js";import"./chunk-fmkntp49.js";import"./chunk-79cxktz1.js";import"./chunk-9x141v5g.js";import"./chunk-bvhbc0wr.js";import fJ from"yargs";import{hideBin as yJ}from"yargs/helpers";function p(K,V,Q){if(K.off){K.off(V,Q);return}K.removeListener?.(V,Q)}function mH(K,V){if(!K.once&&!K.on||!K.off&&!K.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,Z=()=>{p(K,"drain",x),p(K,"error",j),V.removeEventListener("abort",G)},W=(F)=>{if(J)return;J=!0,Z(),F()},x=()=>W(Q),j=(F)=>W(()=>q(F??Error("Writable emitted an error"))),G=()=>W(()=>q(V.reason??Error("Writable drain aborted")));if(V.aborted){G();return}let f=K.once?.bind(K)??K.on?.bind(K);f?.("drain",x),f?.("error",j),V.addEventListener("abort",G,{once:!0})})}async function cH(K,V,Q){if(K.destroyed||K.writableEnded)throw Error("Writable is already closed");if(K.write(V)===!1)await mH(K,Q)}class v{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new d("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(K,V={}){this.options=V;let Q=(q)=>new JH({maxPendingItems:V.maxPendingItems??t,maxPendingBytes:V.maxPendingBytes??e,writeTimeoutMs:V.writeTimeoutMs??HH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,Z)=>cH(K[q],J,Z),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(K.stdout),K.stderr!==K.stdout)this.observeSinkErrors(K.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write(K,V){return this.queues[K].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(K){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(K){if(!K.on||!K.off&&!K.removeListener)return;let V=(Q)=>{this.fail(new d("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};K.on("error",V),this.sinkErrorListeners.push({writer:K,listener:V})}fail(K){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(K),this.queues.stderr.close(K),this.options.onFailure?.(K)}removeSinkErrorListeners(){for(let{writer:K,listener:V}of this.sinkErrorListeners.splice(0))p(K,"error",V)}}var $H=1;function D(K){return H.Object({event_version:H.Literal($H),...K})}var uH=D({type:H.Literal("content_delta"),delta:H.String()}),dH=D({type:H.Literal("thinking_delta"),delta:H.String()}),pH=D({type:H.Literal("thinking"),content:H.String()}),vH=D({type:H.Literal("stream_end")}),lH=D({type:H.Literal("content"),content:H.String()}),aH=D({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),l=N(["readonly","write","execute"]),sH=H.Object({kind:l,scope:N(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),iH=D({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l)}),oH=D({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(sH)}),rH=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:N(["local","acp"])}),nH=D({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(l),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(rH)}),tH=D({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),eH=D({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:N(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),HJ=D({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),JJ=D({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:N(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),KJ=D({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:N(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),VJ=D({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:N(["added","removed"]),reason:N(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),ZJ=D({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:N(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),$J=D({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:N(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),qJ=D({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),XJ=D({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:N(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),YJ=D({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:N(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),BJ=D({type:H.Literal("phase"),phase:N(["turn","searching","inspecting","target_hit","executing","completed"]),status:N(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),NJ=D({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),QJ=D({type:H.Literal("task_update"),tasks:H.Array(ZH)}),DJ=D({type:H.Literal("goal"),state:N(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(N(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(N(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(N(VH)),premature_stop_count:H.Optional(H.Integer({minimum:1}))}),LJ=D({type:H.Literal("subagent"),state:N(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(N(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),WJ=D({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:N(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),jJ=D({type:H.Literal("compacting"),state:N(["started","completed"]),reason:H.Optional(N(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(N(["llm","fallback","snip"])),outcome:H.Optional(N(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0}))}),xJ=D({type:H.Literal("provider_retry"),phase:N(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:N(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(N(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(N(["attempt_limit","recovery_budget"]))}),UJ=D({type:H.Literal("provider_admission"),phase:N(["queued","admitted","rejected"]),request_class:N(["foreground","background","internal"]),resource:N(["stream","pending_count","pending_bytes"]),scope:N(["global","domain","owner","class"]),reason:H.Optional(N(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),_J=D({type:H.Literal("provider_circuit"),phase:N(["opened","waiting","probe","closed","reopened","rejected"]),reason:N(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),GJ=D({type:H.Literal("provider_stall"),phase:N(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),PJ=D({type:H.Literal("action_stationarity"),phase:N(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),FJ=D({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),EJ=D({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:N(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),zJ=D({type:H.Literal("task_admission"),state:N(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),AJ=D({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),MJ=D({type:H.Literal("error"),message:H.String()}),iJ=KH(H.Union([uH,dH,pH,vH,lH,aH,iH,oH,nH,tH,eH,HJ,JJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,UJ,_J,xJ,GJ,PJ,FJ,EJ,zJ,AJ,MJ]));function qH(K,V){return{event_version:$H,type:K,...V}}function SJ(K){if(!K||typeof K!=="object"||Array.isArray(K))return;let V=K;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 TJ(K){let V=new AbortController,Q=(Z)=>{if(!V.signal.aborted)V.abort(Z)},q=()=>Q("interrupt"),J=()=>Q(K?.signal?.reason);if(K?.signal){if(K.signal.addEventListener("abort",J,{once:!0}),K.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:V.signal,abort:Q,dispose:()=>{K?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var bJ=N(["text","jsonl"]),RJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(K)=>K===-1||K>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(BH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(N(["local","worktree"])),outputFormat:H.Optional(bJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class IH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(K){this.openedThinking=K}hasOpenThinking(){return this.openedThinking}completeStream(){let K={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,K}}function IJ(K){return K.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function gJ(K){let V=NH(RJ,K);if(!V.success)throw Error(`Invalid headless options: ${IJ(V.error)}`);return V.data}function CJ(K){return K.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 Q=await cJ(V);process.exit(Q)})}function L(K,V=""){K.write(`${V}
2
- `)}function kJ(K){return`[task] [${K.status}] ${K.subject}`}function hJ(){return{requestConfirmation:async(K)=>K.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:K.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function OJ(K){if(!(K instanceof Error))return"Unknown error";let q=K.lastError??K;if(q.responseBody)try{let W=JSON.parse(q.responseBody)?.error?.message;if(W)return q.statusCode?`${W} (HTTP ${q.statusCode})`:W}catch{}let J=K.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return K.message}function wJ(K){return K==="jsonl"?"jsonl":"text"}function XH(K,V){let Q=(...q)=>{for(let J of q){let Z=V[J];if(typeof Z==="string"&&Z.trim()!=="")return Z}return};switch(K){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function mJ(K,V,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),Z=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(K)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${V}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(J.has(K))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Z.has(K))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 YH(K,V,Q=!1){let q=(J,Z)=>{K.stdout.write(`${JSON.stringify(qH(J,Z))}
3
- `)};return{contentDelta(J){if(V==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;K.stdout.write(J)},thinkingDelta(J,Z){if(V==="jsonl")return q("thinking_delta",{delta:J}),Z;if(!Z)K.stderr.write("[thinking] ");return K.stderr.write(J),!0},thinking(J){if(V==="jsonl"){q("thinking",{content:J});return}L(K.stderr,`[thinking] ${J}`)},streamEnd(J,Z){if(V==="jsonl"){q("stream_end",{});return}if(Z)K.stderr.write(`
4
- `);if(J)K.stdout.write(`
5
- `)},content(J){if(V==="jsonl"){q("content",{content:J});return}L(K.stdout,J)},structuredOutput(J){if(V==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}L(K.stdout,JSON.stringify(J.output))},toolStart(J,Z,W,x){if(V==="jsonl"){q("tool_start",{tool_name:J,summary:Z,target:W,tool_kind:x});return}L(K.stderr,`[tool:start] ${Z}`)},toolProgress(J,Z,W,x,j){if(V==="jsonl"){q("tool_progress",{tool_name:J,message:Z,progress:W,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}L(K.stderr,`[tool:progress] ${J}: ${Z}`)},toolResult(J,Z,W,x,j){if(V==="jsonl"){q("tool_result",{tool_name:J,summary:Z,target:W,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}L(K.stderr,`[tool:result] ${Z}`)},mcpCatalogChanged(J){if(V==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(V==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}L(K.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(V==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}L(K.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(V==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}L(K.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(V==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}L(K.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(V==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}L(K.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(V==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}L(K.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(V==="jsonl"){q("project_rules_loaded",{files:J.files.map((Z)=>({id:Z.id,relative_path:Z.relativePath,source:Z.source,conditional:Z.conditional,content_sha256:Z.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}L(K.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,Z,W){if(V==="jsonl"){q("user_shell_started",{execution_id:J,command:Z,auxiliary:W});return}L(K.stderr,`[user-shell:start] ${Z}`)},userShellOutput(J,Z,W,x){if(V==="jsonl"){q("user_shell_output",{execution_id:J,stream:Z,chunk:W,stream_truncated:x});return}(Z==="stderr"?K.stderr:K.stdout).write(W)},userShellCompleted(J){if(V==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}L(K.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,Z,W,x={}){if(V==="jsonl"){q("phase",{phase:J,status:Z,message:W,turn:x.turn,tool_name:x.toolName,target:x.target});return}L(K.stderr,`[phase:${J}] ${W}`)},toolDetail(J,Z){if(V==="jsonl"){q("tool_detail",{tool_name:J,detail:Z});return}L(K.stderr,Z)},taskUpdate(J){if(V==="jsonl"){q("task_update",{tasks:J});return}for(let Z of J)L(K.stderr,kJ(Z))},goal(J){if(V==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount});return}if(J.goal)L(K.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else L(K.stderr,"[goal:cleared]")},subagent(J){let Z=J.kind==="subagent_spawned";if(V==="jsonl"){q("subagent",{state:Z?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:Z?void 0:J.success,summary:Z?void 0:J.summary,verification_verdict:Z?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}L(K.stderr,`[subagent:${Z?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(V==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}L(K.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let Z=J.phase==="start";if(V==="jsonl"){q("compacting",{state:Z?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,post_tokens:J.postTokens});return}L(K.stderr,Z?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}`)},providerAdmission(J){if(V==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}L(K.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(V==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let Z=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";L(K.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${Z}`)},providerCircuit(J){if(V==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let Z=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";L(K.stderr,`[provider-circuit:${J.phase}] ${J.reason}${Z}`)},providerStall(J){if(V==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}L(K.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},actionStationarity(J){if(V==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}L(K.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(V==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}L(K.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(V==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}L(K.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(V==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}L(K.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,Z=0){if(V==="jsonl"){q("output",{content:J,exit_code:Z});return}L(Z===0?K.stdout:K.stderr,J)},error(J){if(V==="jsonl"){q("error",{message:J});return}L(K.stderr,J)}}}async function cJ(K,V={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new IH,Z={targetLocked:!1},W,x,j,G=TJ(Q),f=!1,F=new v(V,{signal:G.signal,onFailure:(Y)=>{f=!0,G.abort(Y)}}),w={stdout:{write:(Y)=>F.write("stdout",Y)},stderr:{write:(Y)=>F.write("stderr",Y)}},B=YH(w,q),m=async()=>{try{return await F.flush(),!f}catch{return!1}},y=async(Y)=>{return x?.(),x=void 0,j?.(),j=void 0,await m()?Y:1};try{let Y=gJ(K);q=wJ(Y.outputFormat);let S=await bH(Y);B=YH(w,q,Boolean(S)),await fH();let i=Y.forkSession!==!0&&(Y.continue===!0||typeof Y.resume==="string"&&Y.resume.length>0)?await SH({message:Y.message,_:Y._,stdin:Q?.stdin}):await yH({...Y,stdin:Q?.stdin}),R=i===void 0,P=R?{mode:"agent",content:""}:await TH(i);if(P.mode==="output"){if(P.content)B.output(P.content,P.exitCode??0);return await y(P.exitCode??0)}let C=P.content.trimStart().startsWith("!")?P.content.trimStart().slice(1).trim():void 0;if(C!==void 0&&Y.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(C!==void 0&&S)throw Error("Output schemas cannot be combined with user shell commands");if(Y.taskIsolation&&(Y.continue||Y.resume||Y.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:_,messages:o,metadata:r}=await RH({sessionId:Y.sessionId,continue:Y.continue,resume:Y.resume,forkSession:Y.forkSession,fallbackSessionPrefix:"headless"}),I=Y.permissionMode??r?.permissionMode??"yolo",n=Y.model&&Y.model!=="inherit"?Y.model:QH()?.id,U=Y.taskIsolation?await MH.createSessionTask({sessionId:_,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,dispatch:{version:1,prompt:P.content,sourceProjectPath:g(),isolation:Y.taskIsolation,permissionMode:I,...n?{modelId:n}:{},...S?{outputSchema:S}:{}}}):void 0,E=U?.metadata.projectPath??r?.projectPath??g();if(j=s.subscribe((X)=>{if(X.type!=="subagent.provider.admission"||X.sessionId!==_||X.projectPath!==E)return;let $=X.properties,z=["queued","admitted","rejected"],A=["foreground","background","internal"],M=["stream","pending_count","pending_bytes"],b=["global","domain","owner","class"],wH=["capacity","queue_full","wait_timeout","closed"];if(!z.includes($.phase)||!A.includes($.requestClass)||!M.includes($.resource)||!b.includes($.scope)||$.reason!==void 0&&!wH.includes($.reason)||typeof $.queuePosition!=="number"||typeof $.queueDepth!=="number"||typeof $.inFlight!=="number"||typeof $.limit!=="number"||typeof $.waitMs!=="number"||typeof $.maxWaitMs!=="number"||$.recoveryRemainingMs!==void 0&&typeof $.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}})}),!U)await a.setSessionPermissionMode(_,E,I);let gH=U?!1:await jH.cancelPendingNonInteractive(E,_);if(U)B.taskSession({sessionId:_,projectPath:E,sourceProjectPath:U.metadata.taskSourceProjectPath??g(),isolation:Y.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=s.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==_||X.projectPath!==E||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let CH={messages:gH?await a.loadSessionModelContext(_,E):[...o],userId:"cli-user",sessionId:_,workspaceRoot:E,permissionMode:I,signal:G.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:hJ()};W=await xH.create({sessionId:_,workspaceRoot:E,modelId:Y.model,permissionMode:I,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig,agents:Y.agents?PH(Y.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...o.length>0?{sessionStart:{isResume:!0,resumeSessionId:_}}:{}});let k=R&&W.getPendingSteeringCount()>0,h=R&&!k?await W.getGoal():null,c=h?.status==="active"||h?.status==="verifying",T=R&&!k&&!c?await W.getRecoveredFinalResponse():void 0;if(R&&!k&&!c){if(!T)throw Error("No unfinished turn or active goal to resume");if(h)B.goal({kind:"goal_updated",goal:h});if(T.structuredOutput&&T.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:T.structuredOutput,schemaDigest:T.structuredOutputSchemaDigest});else B.content(T.content);return B.phase("completed","done","Recovered headless run completed"),await y(0)}if(C!==void 0){let X=await W.executeUserShellCommand(C,{signal:G.signal,onEvent:async($)=>{if($.type==="started")B.userShellStarted($.executionId,$.command,$.auxiliary);else if($.type==="output")B.userShellOutput($.executionId,$.stream,$.chunk,$.streamTruncated);await m()}});return B.userShellCompleted(X),await y(X.record.status==="completed"?0:X.record.status==="aborted"?130:X.record.exitCode??1)}let kH=Y.maxTurns??W.getConfig().maxTurns,hH=U?.taskWorktree?[...new Set([...Y.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:Y.disallowedTools,OH=await GH.createWithRuntime(W,{sessionId:_,systemPrompt:Y.systemPrompt,appendSystemPrompt:Y.appendSystemPrompt,maxTurns:Y.maxTurns,modelId:Y.model,permissionMode:I,toolWhitelist:Y.allowedTools,toolBlacklist:hH,mcpConfig:Y.mcpConfig,strictMcpConfig:Y.strictMcpConfig}),u=await WH(OH.chatStream(P.content,CH,{stream:!0,signal:G.signal,maxTurns:Y.maxTurns,builtinVerification:Y.verificationAgent!==!1,outputSchema:S,pendingInputOnly:k,goalContinuationOnly:c,...kH===-1?{onTurnLimitReached:async(X)=>{return B.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":if(!S||q==="jsonl")J.markAssistantContent();B.contentDelta(X.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta(X.delta,J.hasOpenThinking()));break;case"stream_end":{let $=J.completeStream();B.streamEnd($.wroteAssistantContent,$.openedThinking);break}case"tool_start":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;if(["TaskCreate","TaskUpdate","TaskList"].includes($.function.name))break;try{let z=JSON.parse($.function.arguments),A=UH($.function.name,z),M=XH($.function.name,z),b=mJ($.function.name,A,M,Z);if(b.shouldLockTarget)Z.targetLocked=!0;B.phase(b.phase,b.status,b.message,{toolName:$.function.name,target:M}),B.toolStart($.function.name,A,M,X.toolKind)}catch{B.phase(Z.targetLocked?"executing":"searching",Z.targetLocked?"hit":"ongoing",Z.targetLocked?`Working within target: ${$.function.name}`:`Still searching: ${$.function.name}`,{toolName:$.function.name}),B.toolStart($.function.name,$.function.name,void 0,X.toolKind)}break}case"tool_progress":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;B.toolProgress($.function.name,X.update.message,X.update.progress,X.update.total,X.update.admission);break}case"tool_result":{let $=X.toolCall;if(!("function"in $))break;if($.function.name===O)break;let z;try{let M=JSON.parse($.function.arguments);z=XH($.function.name,M)}catch{z=void 0}let A=LH(_H($.function.name,X.result),DH);if(B.toolResult($.function.name,A.summary,z,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message,background:SJ(X.result.metadata)}),A.detail)B.toolDetail($.function.name,A.detail);break}case"token_usage":B.tokenUsage(X.usage);break;case"compaction":B.compacting(X);break;case"task_update":B.taskUpdate(X.tasks);break;case"structured_output":B.structuredOutput(X);break;case"mcp_catalog_changed":B.mcpCatalogChanged(X);break;case"mcp_content_changed":B.mcpContentChanged(X);break;case"mcp_resource_updated":B.mcpResourceUpdated(X);break;case"mcp_connection_changed":B.mcpConnectionChanged(X);break;case"mcp_log":B.mcpLog(X);break;case"mcp_instructions_changed":B.mcpInstructionsChanged(X);break;case"mcp_task_changed":B.mcpTaskChanged(X);break;case"project_rules_loaded":B.projectRulesLoaded(X);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":B.goal(X);break;case"subagent_spawned":case"subagent_completed":B.subagent(X);break;case"model_fallback":break;case"provider_admission":B.providerAdmission(X);break;case"provider_retry":B.providerRetry(X);break;case"provider_circuit":B.providerCircuit(X);break;case"provider_stall":B.providerStall(X);break;case"action_stationarity":B.actionStationarity(X);break;case"turn_start":if(X.turn===1)Z.targetLocked=!1;B.phase("turn",Z.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let $=X}}await m()});if(u.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!u.success)return B.error(`Error: ${u.error?.message??"Agent execution failed"}`),await y(1);return B.phase("completed","done","Headless run completed"),await y(0)}catch(Y){if(!f){if(J.hasOpenThinking()&&q==="text")w.stderr.write(`
6
- `);B.error(`Error: ${OJ(Y)}`)}return await y(1)}finally{x?.(),j?.();try{await W?.dispose()}finally{F.close(),G.dispose()}}}async function PK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":Z,"max-turns":W,...x}=FH,j=fJ(yJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([zH,EH,AH]);return CJ(j),await j.parse(),!0}export{cJ as runHeadless,PK as handleHeadlessMode,RJ as HeadlessOptionsSchema};
@@ -1 +0,0 @@
1
- import{me as a}from"./chunk-01k69v34.js";import"./chunk-qnj3dajb.js";import"./chunk-z37v80c1.js";import"./chunk-68stvfdj.js";import"./chunk-vn1r6z64.js";import"./chunk-9x141v5g.js";import"./chunk-bvhbc0wr.js";export{a as createChatServiceAsync};
@@ -1 +0,0 @@
1
- import{Ah as c,Bh as d,Ch as e,Dh as f,yh as a,zh as b}from"./chunk-kxgr18gy.js";import"./chunk-bvhbc0wr.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};