blade-code 0.10.37 → 0.10.39

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 (86) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-1kbn1ypd.js +1 -0
  3. package/dist/{chunk-rj1z55m8.js → chunk-22pmyhp9.js} +1 -1
  4. package/dist/{chunk-qc5qwgpt.js → chunk-29abk8tj.js} +2 -2
  5. package/dist/chunk-3m0c6znc.js +44 -0
  6. package/dist/{chunk-46r1m8yn.js → chunk-4eg9qnxt.js} +1 -1
  7. package/dist/{chunk-x4yfhp8j.js → chunk-4yxavv7j.js} +1 -1
  8. package/dist/{chunk-e6ttz45s.js → chunk-56vs8ewy.js} +1 -1
  9. package/dist/chunk-59v0kdc9.js +160 -0
  10. package/dist/{chunk-atdb1pks.js → chunk-5ajyr2am.js} +1 -1
  11. package/dist/{chunk-ahkpjvaq.js → chunk-6yd3j5v5.js} +1 -1
  12. package/dist/{chunk-fj6frvhd.js → chunk-79gk29st.js} +1 -1
  13. package/dist/{chunk-jz6esh56.js → chunk-7b68psjh.js} +1 -1
  14. package/dist/{chunk-qavfq2vp.js → chunk-7ptkstyx.js} +1 -1
  15. package/dist/chunk-83mfrs3p.js +5 -0
  16. package/dist/chunk-99n3w3tg.js +1 -0
  17. package/dist/chunk-9q7v4ad9.js +1 -0
  18. package/dist/{chunk-0e4nc00e.js → chunk-9s2c9awb.js} +1 -1
  19. package/dist/{chunk-v2wka1pq.js → chunk-a14dy6yc.js} +1 -1
  20. package/dist/chunk-a51m3ysp.js +1 -0
  21. package/dist/{chunk-d63dczf8.js → chunk-aesdm7cg.js} +1 -1
  22. package/dist/{chunk-y5jxkynb.js → chunk-b1pz71cr.js} +1 -1
  23. package/dist/{chunk-9hjhbsna.js → chunk-b5g5mfq1.js} +3 -3
  24. package/dist/chunk-bvdk0hb2.js +2 -0
  25. package/dist/{chunk-0dw58ycv.js → chunk-byekf2bq.js} +2 -2
  26. package/dist/{chunk-q0mwwhpw.js → chunk-bzymtpc8.js} +19 -19
  27. package/dist/{chunk-asqah231.js → chunk-e09g9a7d.js} +1 -1
  28. package/dist/{chunk-e6frdh2s.js → chunk-ekfxm6g8.js} +1 -1
  29. package/dist/{chunk-r48jmc74.js → chunk-f3xwk6be.js} +2 -2
  30. package/dist/{chunk-cm4t4cz6.js → chunk-fjcmx039.js} +2 -2
  31. package/dist/chunk-g2m6y08q.js +1 -0
  32. package/dist/{chunk-fqcf0n0h.js → chunk-g9a3ht1x.js} +1 -1
  33. package/dist/{chunk-b6ve4vyt.js → chunk-gkc69333.js} +2 -2
  34. package/dist/chunk-gq29vpef.js +6 -0
  35. package/dist/chunk-gsx7sw92.js +6 -0
  36. package/dist/chunk-gvkb3mrd.js +1 -0
  37. package/dist/{chunk-njb4rjhs.js → chunk-jc498kjk.js} +1 -1
  38. package/dist/{chunk-jtjcg93t.js → chunk-kah7p2zm.js} +1 -1
  39. package/dist/{chunk-gh0vdddb.js → chunk-kbmw1can.js} +1 -1
  40. package/dist/{chunk-dgks1che.js → chunk-ksd1532x.js} +1 -1
  41. package/dist/{chunk-5cjy9yj1.js → chunk-kth1ra8z.js} +3 -3
  42. package/dist/{chunk-r9pz4z1p.js → chunk-m6mp65n0.js} +4 -4
  43. package/dist/chunk-m88j03bm.js +1 -0
  44. package/dist/{chunk-0nvc6y56.js → chunk-mjcgy285.js} +1 -1
  45. package/dist/{chunk-jsd6d2f5.js → chunk-n52vvqfj.js} +1 -1
  46. package/dist/{chunk-tczrjn95.js → chunk-nh43dgpd.js} +2 -2
  47. package/dist/chunk-p2t4gj7w.js +1 -0
  48. package/dist/{chunk-kw543czm.js → chunk-qp6k78yb.js} +1 -1
  49. package/dist/{chunk-e8wpd0s4.js → chunk-r1wyfnk8.js} +1 -1
  50. package/dist/{chunk-rtzd076h.js → chunk-sd8ptaz2.js} +1 -1
  51. package/dist/{chunk-61h0d0gq.js → chunk-shxg223c.js} +2 -2
  52. package/dist/chunk-skxst3ya.js +1 -0
  53. package/dist/{chunk-g5429yjs.js → chunk-tdqz02hf.js} +3 -3
  54. package/dist/{chunk-232bcv23.js → chunk-xs8v8nhj.js} +1 -1
  55. package/dist/{chunk-ak37gg0n.js → chunk-xvgfbahj.js} +1 -1
  56. package/dist/chunk-ya6xazne.js +1 -0
  57. package/dist/{chunk-m0a2zdm8.js → chunk-zg6drp32.js} +1 -1
  58. package/dist/chunk-zjzz2mh9.js +1 -0
  59. package/dist/web/assets/{ChatView-BB4nYdEf.js → ChatView-BY2JoPwW.js} +14 -14
  60. package/dist/web/assets/{CodeBlockHighlighter-CAFugWXU.js → CodeBlockHighlighter-BIeXOc6N.js} +1 -1
  61. package/dist/web/assets/{FilePreview-O5aDfFS4.js → FilePreview-CLfqslxP.js} +1 -1
  62. package/dist/web/assets/{MarkdownRenderer-C_qekwq_.js → MarkdownRenderer-D-iAfBPN.js} +3 -3
  63. package/dist/web/assets/{SettingsModal-FADlD0Da.js → SettingsModal-D9SfF3HV.js} +1 -1
  64. package/dist/web/assets/{TaskSwitcher-D3k3tRpI.js → TaskSwitcher-CKYCrKc2.js} +1 -1
  65. package/dist/web/assets/{TerminalPanel-DBmKVVbI.js → TerminalPanel-Bj4qKgM6.js} +1 -1
  66. package/dist/web/assets/{index-CMIW4J1Q.js → index-Dwm-v3BV.js} +4 -4
  67. package/dist/web/assets/{session-events-Dk20sSDo.js → session-events-Yagzv-3E.js} +4 -4
  68. package/dist/web/index.html +2 -2
  69. package/package.json +1 -1
  70. package/dist/chunk-15w4crsc.js +0 -1
  71. package/dist/chunk-4mpx8rad.js +0 -1
  72. package/dist/chunk-5ckfx738.js +0 -1
  73. package/dist/chunk-73pqjvxk.js +0 -1
  74. package/dist/chunk-8bczq0xe.js +0 -1
  75. package/dist/chunk-8pcfmzq0.js +0 -160
  76. package/dist/chunk-fjpqxdct.js +0 -1
  77. package/dist/chunk-jd764yqg.js +0 -5
  78. package/dist/chunk-jtv91ez8.js +0 -2
  79. package/dist/chunk-m377j9bs.js +0 -1
  80. package/dist/chunk-mznx9gg6.js +0 -1
  81. package/dist/chunk-qzn3rb8r.js +0 -1
  82. package/dist/chunk-s3xfr72w.js +0 -6
  83. package/dist/chunk-vk3e2w5h.js +0 -44
  84. package/dist/chunk-vxxhd72z.js +0 -1
  85. package/dist/chunk-xfrdwxde.js +0 -1
  86. package/dist/chunk-xsew6530.js +0 -6
@@ -1,4 +1,4 @@
1
- import{Yf as i}from"./chunk-0dw58ycv.js";import{Ag as n,rg as o,tg as C,vg as L,zg as j}from"./chunk-qc5qwgpt.js";import{Bg as I}from"./chunk-jtjcg93t.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
1
+ import{ag as i}from"./chunk-byekf2bq.js";import{Dg as j,Eg as n,vg as o,xg as C,zg as L}from"./chunk-29abk8tj.js";import{Fg as I}from"./chunk-kah7p2zm.js";import{stat as d}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var s=50,t=100,e=/^[A-Za-z0-9_-]+$/,__=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function E_(_){return typeof _==="string"&&__.test(_)&&Number.isFinite(Date.parse(_))}function P(_){return typeof _==="string"&&U.isAbsolute(_)}function R_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function W_(_){try{if(!e.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||P(R.cwd))||!E_(R.lastMessageTime)||!P(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function y(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function $_(_){if(!_.cursor)return;let E=W_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function z_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?s:W;if(!Number.isInteger(k)||k<1||k>t)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function k_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=$_(E);if(W)R=R.filter((k)=>k_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:R_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function H_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:c(_,E),createdAt:R.data.createdAt}}function c(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!H_(k)})}function w(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function q_(_){let E=w(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:c(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function y_(_,E){let R=w(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as f from"node:fs";import{createReadStream as M_}from"node:fs";import*as V from"node:fs/promises";import*as O from"node:path";import{createInterface as Q_}from"node:readline";var m=65536;function x(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function V_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
2
2
  `),W=!_.endsWith(`
3
3
  `),$=[];for(let[H,k]of R.entries())try{let M=V_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await V.mkdir(O.dirname(this.filePath),{recursive:!0,mode:493});let E=await V.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map(x).join(`
4
4
  `)}
@@ -1,2 +1,2 @@
1
- import{Sd as B}from"./chunk-3rjmkaey.js";import{cg as Y}from"./chunk-cm4t4cz6.js";import{fg as Z,ig as $}from"./chunk-asqah231.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
1
+ import{Sd as B}from"./chunk-3rjmkaey.js";import{gg as Y}from"./chunk-fjcmx039.js";import{jg as Z,mg as $}from"./chunk-e09g9a7d.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,providerCircuitBreakerOpenMs:z.providerCircuitBreakerOpenMs,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
2
  export{K as Od,O as Pd,E as Qd};
@@ -1,3 +1,3 @@
1
- import{l as i}from"./chunk-e6ttz45s.js";import{Nf as s}from"./chunk-6360fg4j.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{l as i}from"./chunk-56vs8ewy.js";import{Nf as s}from"./chunk-6360fg4j.js";import"./chunk-29abk8tj.js";import"./chunk-kah7p2zm.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -1 +1 @@
1
- import{rc as a,sc as b,tc as c,uc as d,vc as e,wc as f,xc as g}from"./chunk-d63dczf8.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import"./chunk-3rjmkaey.js";import"./chunk-zwt7f9ab.js";import"./chunk-v11r4ahz.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-0dw58ycv.js";import"./chunk-asqah231.js";import"./chunk-b6ve4vyt.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
1
+ import{rc as a,sc as b,tc as c,uc as d,vc as e,wc as f,xc as g}from"./chunk-aesdm7cg.js";import"./chunk-qgez5vw6.js";import"./chunk-5ajyr2am.js";import"./chunk-3rjmkaey.js";import"./chunk-zwt7f9ab.js";import"./chunk-v11r4ahz.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-byekf2bq.js";import"./chunk-e09g9a7d.js";import"./chunk-gkc69333.js";import"./chunk-29abk8tj.js";import"./chunk-kah7p2zm.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1,4 +1,4 @@
1
- import{ra as H}from"./chunk-0nvc6y56.js";import"./chunk-5cgyevqj.js";import"./chunk-qgez5vw6.js";import{Fd as T,zd as $}from"./chunk-5cjy9yj1.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-r48jmc74.js";import"./chunk-v11r4ahz.js";import"./chunk-vk3e2w5h.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as k}from"./chunk-6360fg4j.js";import"./chunk-jtv91ez8.js";import"./chunk-0dw58ycv.js";import"./chunk-cm4t4cz6.js";import"./chunk-asqah231.js";import"./chunk-b6ve4vyt.js";import"./chunk-tczrjn95.js";import"./chunk-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ra as H}from"./chunk-mjcgy285.js";import"./chunk-5cgyevqj.js";import"./chunk-qgez5vw6.js";import{Fd as T,zd as $}from"./chunk-kth1ra8z.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-f3xwk6be.js";import"./chunk-v11r4ahz.js";import"./chunk-3m0c6znc.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as k}from"./chunk-6360fg4j.js";import"./chunk-bvdk0hb2.js";import"./chunk-byekf2bq.js";import"./chunk-fjcmx039.js";import"./chunk-e09g9a7d.js";import"./chunk-gkc69333.js";import"./chunk-nh43dgpd.js";import"./chunk-zg6drp32.js";import"./chunk-29abk8tj.js";import"./chunk-kah7p2zm.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -0,0 +1,5 @@
1
+ import{Rf as et,Sf as Ee,Tf as Pe,Uf as tt,Vf as fe,Xf as xe}from"./chunk-bvdk0hb2.js";import{ag as V}from"./chunk-byekf2bq.js";import{eg as Ue,gg as oe}from"./chunk-fjcmx039.js";import{jg as Je}from"./chunk-e09g9a7d.js";var _t={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},le=(e)=>_t[e]||{};var Mt=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function te(e){return typeof e==="string"&&Mt.has(e)}function yt(e){if(!e.aborted)return;if(te(e.reason))return e.reason;return"user-cancel"}function nn(e){if(te(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function Ie(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let n=AbortSignal;if(typeof n.any==="function")return n.any(t);for(let f of t)if(f.aborted)return f;let u=new AbortController,o=new Map;for(let f of t){let p=()=>{u.abort(f.reason);for(let[_,h]of o)_.removeEventListener("abort",h)};o.set(f,p)}for(let[f,p]of o)f.addEventListener("abort",p,{once:!0});return u.signal}function K(e,t,n){let u=n?.throwOnAbort??!1;if(t?.aborted){if(u)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((o,f)=>{let p,_=setTimeout(()=>{if(t&&p)t.removeEventListener("abort",p);o()},e);if(t)p=()=>{if(clearTimeout(_),u)f(new DOMException("Aborted","AbortError"));else o()},t.addEventListener("abort",p,{once:!0})})}var Et=V("Chat"),Pt={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function ne(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
2
+ `)}function bt(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return Et.warn("[PiAIChatService] Invalid historical tool arguments",{value:e}),{}}}function st(e){let t=e.match(/^data:([^;,]+);base64,(.+)$/s);return t?{mimeType:t[1],data:t[2]}:void 0}async function ct(e,t){let n=st(e);if(n)return{type:"image",...n};if(!/^https?:\/\//i.test(e))return{type:"text",text:`[Unsupported image source: ${e}]`};let u=await fetch(e,{signal:t});if(!u.ok)throw Error(`Failed to load image ${e}: HTTP ${u.status}`);return{type:"image",mimeType:u.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await u.arrayBuffer()).toString("base64")}}async function Oe(e,t,n,u,o){let f=e.filter((h)=>h.role==="system").map((h)=>ne(h.content)).filter(Boolean).join(`
3
+
4
+ `),p=[];for(let h of e){if(h.role==="system")continue;if(h.role==="user"){let x=t.input.includes("image"),M=typeof h.content==="string"?h.content:await Promise.all(h.content.map((P)=>P.type==="text"?Promise.resolve({type:"text",text:P.text}):x?ct(P.image_url.url,u):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));p.push({role:"user",content:M,timestamp:Date.now()});continue}if(h.role==="assistant"){let x=[];if(h.reasoningContent?.trim())x.push({type:"thinking",thinking:h.reasoningContent});let M=ne(h.content);if(M)x.push({type:"text",text:M});for(let P of h.tool_calls??[]){if(!("function"in P))continue;x.push({type:"toolCall",id:P.id,name:P.function.name,arguments:bt(P.function.arguments)})}p.push({role:"assistant",content:x,api:t.api,provider:t.provider,model:t.id,usage:Pt,stopReason:h.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}p.push({role:"toolResult",toolCallId:h.tool_call_id??"",toolName:h.name??"unknown",content:[{type:"text",text:ne(h.content)}],isError:!1,timestamp:Date.now()})}let _=n?.filter((h)=>!o||h.name===o).map((h)=>({name:h.name,description:h.description,parameters:h.parameters,constrainedSampling:h.constrainedSampling}));return{...f?{systemPrompt:f}:{},messages:p,..._?.length?{tools:_}:{}}}function De(e){let t=[];for(let n=0;n<e.length;n++){let u=e[n];if(u.role==="tool")continue;let o=u.role==="assistant"&&u.tool_calls?.length?u.tool_calls:void 0;if(!o){t.push(u);continue}let f=[],p=n+1;while(p<e.length&&e[p].role==="tool")f.push(e[p++]);let _=new Set(o.map((M)=>M.id)),h=f.filter((M)=>M.tool_call_id&&_.has(M.tool_call_id)),x=new Set(h.map((M)=>M.tool_call_id));if(_.size===o.length&&h.length===_.size&&x.size===_.size)t.push(u,...h);n=p-1}return t}function ke(e){return e.some((t)=>t.role==="assistant"&&Boolean(t.tool_calls?.length)&&!t.reasoningContent?.trim())}function je(e,t){return{...e,...t.baseUrl?{baseUrl:Ue(e.api,t.baseUrl)}:{},...t.maxOutputTokens?{maxTokens:t.maxOutputTokens}:{}}}function ue(e){let t=e.modelCatalog??oe();return{models:t.models,model:je(t.getModel(e.provider,e.model),e)}}function Ne(e,t){let n=e.modelCatalog??oe();return je(n.getModel(t.provider,t.model),e)}import{createHmac as mt,randomBytes as Tt}from"node:crypto";var at=60000,Ct=4,Rt=0.8;var F=300000,de=600000;var Be=128,Ve=256,At=1800000,Ye=50;class Z extends Error{circuit;code="PROVIDER_CIRCUIT_OPEN";constructor(e){super(`Provider circuit open; retry after ${e.retryAfterMs??0}ms`);this.circuit=e;this.name="ProviderCircuitOpenError"}}function he(e){return e instanceof Z||e!==null&&typeof e==="object"&&"code"in e&&e.code==="PROVIDER_CIRCUIT_OPEN"}function Y(e,t){return e!==void 0&&Number.isSafeInteger(e)&&e>0?e:t}function gt(e,t){return e!==void 0&&Number.isFinite(e)&&e>0&&e<=1?e:t}function lt(e){try{let t=new URL(e);if(t.hash="",t.hostname=t.hostname.toLowerCase(),t.searchParams.sort(),t.pathname!=="/")t.pathname=t.pathname.replace(/\/+$/,"");return t.toString()}catch{return e.trim().replace(/\/+$/,"")}}function It(e){if(!e)return[];return Object.entries(e).map(([t,n])=>[t.trim().toLowerCase(),n.trim()]).sort(([t],[n])=>t.localeCompare(n))}function St(e,t){let n=JSON.stringify([e.provider.trim(),String(e.api).trim(),lt(e.baseUrl),e.model.trim(),e.serviceTier?.trim()??"",e.apiVersion?.trim()??"",e.apiKey??"",It(e.customHeaders),e.openDurationMs]);return mt("sha256",Buffer.from(t)).update(n).digest("hex")}function J(e){let t=0;for(let n of e)if(n.failure)t++;return t}function we(e){return e!==void 0&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function ze(e){if(e===void 0||!Number.isFinite(e)||e<0)return;return Math.min(Math.ceil(e),xe)}class We{#e=new Map;#o=new WeakMap;#p;#n;#u;#t;constructor(e={}){this.#p=e.processSecret?new Uint8Array(e.processSecret):Tt(32),this.#n=e.now??(()=>performance.now()),this.#u=e.wallNow??e.now??Date.now,this.#t={maxEntries:Math.min(Y(e.maxEntries,Be),Be),maxWindowEntries:Math.min(Y(e.maxWindowEntries,Ve),Ve),windowMs:Y(e.windowMs,at),minSamples:Y(e.minSamples,Ct),errorRateThreshold:gt(e.errorRateThreshold,Rt),idleTtlMs:Y(e.idleTtlMs,At)}}get size(){return this.#e.size}get(e){if(e.openDurationMs===0)return this.#f();let t=this.#n();this.#R(t);let n=St(e,this.#p),u=this.#e.get(n);if(u)return u.lastTouchedAt=t,this.#_(u,e.probeLeaseMs);if(this.#e.size>=this.#t.maxEntries)this.#A();if(this.#e.size>=this.#t.maxEntries)return this.#f();let o={key:n,state:"closed",samples:[],generation:0,nextAttemptId:1,nextProbeLeaseId:1,configuredOpenDurationMs:e.openDurationMs,effectiveOpenDurationMs:e.openDurationMs,lastTouchedAt:t,detached:!1};return this.#e.set(n,o),this.#_(o,e.probeLeaseMs)}#_(e,t){let n=this,u=Math.max(F,Math.min(Y(t,F),de));return{check:()=>n.#c(e,u),recordSuccess:(o)=>n.#d(o,"success"),recordFailure:(o,f)=>n.#d(o,"failure",f),recordNeutral:(o)=>n.#d(o,"neutral"),abandon:(o)=>n.#b(o),snapshot:()=>n.#C(e)}}#f(){let e=this;return{check:()=>{let t=Object.freeze({kind:"noop"});return e.#o.set(t,{generation:0,attemptId:0,kind:"noop",settled:!1}),{allowed:!0,probe:!1,token:t}},recordSuccess:(t)=>e.#x(t),recordFailure:(t)=>e.#x(t),recordNeutral:(t)=>e.#x(t),abandon:(t)=>e.#b(t),snapshot:()=>({state:"closed",sampleCount:0,failureCount:0,noop:!0,detached:!1})}}#x(e){let t=this.#o.get(e);if(t?.kind==="noop")t.settled=!0;return}#c(e,t){let n=this.#n();if(e.detached)return this.#f().check();if(e.lastTouchedAt=n,this.#h(e,n),e.state==="closed")return this.#M(e,"regular");if(e.state==="open"){let o=e.nextProbeAt??n;if(n<o)return this.#E(e,o-n);e.state="half_open",e.generation++,e.probeLeaseId=void 0,e.probeLeaseExpiresAt=void 0}if(e.probeLeaseId===void 0||e.probeLeaseExpiresAt!==void 0&&n>=e.probeLeaseExpiresAt)return this.#m(e,n,t);let u=Math.max(1,(e.probeLeaseExpiresAt??n+Ye)-n);return this.#E(e,Math.min(Ye,u))}#M(e,t,n){let u=Object.freeze({kind:t});return this.#o.set(u,{entry:e,generation:e.generation,attemptId:e.nextAttemptId++,kind:t,...n!==void 0?{probeLeaseId:n}:{},settled:!1}),{allowed:!0,probe:t==="probe",token:u}}#m(e,t,n){let u=e.nextProbeLeaseId++;e.probeLeaseId=u,e.probeLeaseExpiresAt=t+n,e.lastTouchedAt=t;let o=this.#M(e,"probe",u),f=e.lastFailure??{reason:"server_error"};return{...o,reason:f.reason,...f.statusCode!==void 0?{statusCode:f.statusCode}:{},openDurationMs:e.effectiveOpenDurationMs,sampleCount:e.samples.length,failureCount:J(e.samples)}}#E(e,t){let n=e.lastFailure??{reason:"server_error"};return{allowed:!1,state:e.state==="open"?"open":"half_open",reason:n.reason,...n.statusCode!==void 0?{statusCode:n.statusCode}:{},retryAfterMs:Math.max(0,Math.ceil(t)),nextProbeAt:this.#u()+Math.max(0,Math.ceil(t)),openDurationMs:e.effectiveOpenDurationMs,sampleCount:e.samples.length,failureCount:J(e.samples)}}#d(e,t,n){let u=this.#o.get(e);if(!u||u.settled)return;if(u.settled=!0,u.kind==="noop"||!u.entry)return;let o=u.entry;if(o.detached||u.generation!==o.generation||u.kind==="regular"&&o.state!=="closed"||u.kind==="probe"&&(o.state!=="half_open"||u.probeLeaseId!==o.probeLeaseId))return;let f=this.#n();if(o.lastTouchedAt=f,u.kind==="probe"){if(t==="failure"&&n)return this.#P(o,n,f,"reopened");return this.#T(o)}if(t==="neutral")return;if(this.#a(o,t==="failure",f),t!=="failure"||!n)return;let p=J(o.samples),_=o.samples.length===0?0:p/o.samples.length;if(o.samples.length>=this.#t.minSamples&&_>=this.#t.errorRateThreshold)return this.#P(o,n,f,"opened");return}#P(e,t,n,u){let o={reason:t.reason,...we(t.statusCode)!==void 0?{statusCode:we(t.statusCode)}:{},...ze(t.retryAfterMs)!==void 0?{retryAfterMs:ze(t.retryAfterMs)}:{}},f=o.retryAfterMs??0,p=Math.max(e.configuredOpenDurationMs,f);return e.state="open",e.generation++,e.probeLeaseId=void 0,e.probeLeaseExpiresAt=void 0,e.effectiveOpenDurationMs=p,e.nextProbeAt=n+p,e.lastFailure=o,{phase:u,reason:o.reason,...o.statusCode!==void 0?{statusCode:o.statusCode}:{},retryAfterMs:p,nextProbeAt:this.#u()+p,openDurationMs:p,sampleCount:e.samples.length,failureCount:J(e.samples)}}#T(e){let t=e.lastFailure??{reason:"server_error"};return e.state="closed",e.generation++,e.samples=[],e.probeLeaseId=void 0,e.probeLeaseExpiresAt=void 0,e.nextProbeAt=void 0,e.effectiveOpenDurationMs=e.configuredOpenDurationMs,{phase:"closed",reason:t.reason,...t.statusCode!==void 0?{statusCode:t.statusCode}:{},openDurationMs:e.effectiveOpenDurationMs,sampleCount:0,failureCount:0}}#b(e){let t=this.#o.get(e);if(!t||t.settled)return!1;if(t.settled=!0,t.kind==="noop")return!0;let n=t.entry;if(!n||n.detached||t.kind!=="probe"||t.generation!==n.generation||t.probeLeaseId!==n.probeLeaseId)return!1;return n.probeLeaseId=void 0,n.probeLeaseExpiresAt=void 0,n.lastTouchedAt=this.#n(),!0}#a(e,t,n){if(this.#h(e,n),e.samples.length>=this.#t.maxWindowEntries)e.samples.shift();e.samples.push({at:n,failure:t})}#h(e,t){let n=t-this.#t.windowMs,u=0;while(u<e.samples.length&&e.samples[u].at<n)u++;if(u>0)e.samples.splice(0,u)}#C(e){if(!e.detached)this.#h(e,this.#n());return{state:e.state,sampleCount:e.samples.length,failureCount:J(e.samples),...e.nextProbeAt!==void 0?{nextProbeAt:e.nextProbeAt}:{},noop:!1,detached:e.detached}}#R(e){for(let[t,n]of this.#e)if(n.state==="closed"&&e-n.lastTouchedAt>this.#t.idleTtlMs)this.#s(t,n)}#A(){let e;for(let t of this.#e.values())if(t.state==="closed"&&(!e||t.lastTouchedAt<e.lastTouchedAt))e=t;if(e)this.#s(e.key,e)}#s(e,t){t.detached=!0,this.#e.delete(e)}}var re;function Xe(){return re??=new We,re}var Ge=new WeakSet;class Q extends Error{budgetMs;elapsedMs;code="PROVIDER_RECOVERY_BUDGET_EXCEEDED";constructor(e,t){super(`Provider recovery budget exhausted after ${e}ms`);this.budgetMs=e;this.elapsedMs=t;this.name="ProviderRecoveryBudgetExceededError"}}var Ot=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],Dt=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],kt=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function $e(e){return(e instanceof Error?e.message:String(e)).toLowerCase()}function Ut(e){let t=$e(e);return Dt.some((n)=>t.includes(n))}function pe(e){if(e!==null&&typeof e==="object")Ge.add(e)}function cn(e){return e!==null&&typeof e==="object"&&Ge.has(e)}function jt(e){return e!==null&&typeof e==="object"&&"code"in e?e.code:void 0}function Nt(e){if(e===null||typeof e!=="object")return;let t=e;for(let n of["status","statusCode"]){let u=t[n];if(typeof u==="number"&&Number.isInteger(u))return u}return}function Bt(e){let t=e.match(/^(?:error:\s*)?(\d{3})\b/),n=e.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),u=Number(t?.[1]??n?.[1]);return Number.isInteger(u)?u:void 0}function w(e,t){let n=$e(e),u=jt(e);if(u==="STREAM_IDLE_TIMEOUT"||u==="PROVIDER_RECOVERY_BUDGET_EXCEEDED"||e instanceof Error&&e.name==="AbortError"||n.includes("request aborted")||n==="aborted")return{retryable:!1};if(Ot.some((f)=>n.includes(f))||Ut(e))return{retryable:!1};if(t?.shouldRetry==="false")return{retryable:!1,statusCode:t.statusCode};let o=t?.statusCode??Nt(e)??Bt(n);if(t?.shouldRetry==="true")return{retryable:!0,reason:o===429?"rate_limit":o===408||o===409?"timeout":"server_error",statusCode:o};if(o===429)return{retryable:!0,reason:"rate_limit",statusCode:o};if(o===408||o===409)return{retryable:!0,reason:"timeout",statusCode:o};if(o!==void 0&&o>=500&&o<=599)return{retryable:!0,reason:"server_error",statusCode:o};if(u==="PROVIDER_STREAM_CLOSED"||n.includes("stream closed before completion")||n.includes("ended without")||n.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:o};if(kt.some((f)=>n.includes(f)))return{retryable:!0,reason:"transport",statusCode:o};if(n.includes("timeout")||n.includes("timed out")||n.includes("temporarily unavailable")||n.includes("upstream_error")||n.includes("overloaded")||n.includes("rate limit")||n.includes("too many requests")||n.includes("service unavailable")||n.includes("server error")||n.includes("internal error")||n.includes("please retry")||n.includes("try your request again"))return{retryable:!0,reason:n.includes("rate")||n.includes("too many")?"rate_limit":n.includes("timeout")||n.includes("timed out")?"timeout":"server_error",statusCode:o};return{retryable:!1,statusCode:o}}function _e(e,t){if(!e)return;if(e.retryAfterMs!==void 0){let o=Number.parseFloat(e.retryAfterMs);if(Number.isFinite(o))return Math.max(0,o)}if(e.retryAfter===void 0)return;let n=Number.parseFloat(e.retryAfter);if(Number.isFinite(n))return Math.max(0,n*1000);let u=Date.parse(e.retryAfter);return Number.isFinite(u)?Math.max(0,u-t):void 0}function He(e,t,n={}){let u=n.now??Date.now(),o=n.maxDelayMs??60000,f=_e(t,u);if(f!==void 0)return Math.min(Math.ceil(f),o);let p=Math.max(0,e-1),_=n.maxExponentialDelayMs??8000,h=Math.min(500*2**p,_),x=Math.max(0,Math.min(1,n.random??Math.random())),M=h*(0.75+x*0.25);return Math.min(Math.round(M),o)}function Ze(e,t){let n=e.onPayload;e.onPayload=async(u,o)=>{let f=n?await n(u,o):u;return t(f===void 0?u:f,o)}}function Vt(e){if(!e.reasoningEnabled)return;return e.reasoningEffort??e.reasoningLevel??"high"}function Yt(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function wt(e,t,n,u){let o=u?void 0:Vt(n);if(!o){if(t.api==="anthropic-messages")e.thinkingEnabled=!1;if(t.api==="google-generative-ai"||t.api==="google-vertex")e.thinking={enabled:!1};return}switch(t.api){case"anthropic-messages":e.thinkingEnabled=!0,e.effort=o;break;case"google-generative-ai":case"google-vertex":e.thinking={enabled:!0,level:Yt(o)};break;case"mistral-conversations":e.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":e.reasoning=o;break;default:e.reasoningEffort=o}}function zt(e,t,n){if(!n)return;switch(t){case"anthropic-messages":case"bedrock-converse-stream":e.toolChoice={type:"tool",name:n};break;case"openai-completions":case"mistral-conversations":case"pi-messages":e.toolChoice={type:"function",function:{name:n}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":e.toolChoice={type:"function",name:n};break;case"google-generative-ai":case"google-vertex":e.toolChoice="any";break}}function rt(e,t,n){let u=n.serviceTier;if(!u)return;if(t.api==="openai-responses"||t.api==="openai-codex-responses"||t.api==="azure-openai-responses"){e.serviceTier=u;return}if(t.api!=="openai-completions"&&!(t.api==="anthropic-messages"&&u==="fast"))return;Ze(e,(o)=>{if(!o||typeof o!=="object"||Array.isArray(o))return o;return t.api==="anthropic-messages"?{...o,speed:"fast"}:{...o,service_tier:u}})}function Wt(e,t,n){let u=n.responseVerbosity;if(!u)return;if(Je(t,u),t.api==="openai-codex-responses"){e.textVerbosity=u;return}Ze(e,(o)=>{if(!o||typeof o!=="object"||Array.isArray(o))return o;if(t.api==="openai-completions")return{...o,verbosity:u};let f="text"in o&&o.text&&typeof o.text==="object"&&!Array.isArray(o.text)?o.text:{};return{...o,text:{...f,verbosity:u}}})}function Qe(e,t,n,u,o=!1){let f={apiKey:e.apiKey,headers:e.customHeaders,signal:n,temperature:u?.temperature??e.temperature??0,maxTokens:u?.maxOutputTokens??e.maxOutputTokens,timeoutMs:e.timeout,maxRetries:0,cacheRetention:e.enablePromptCaching?"short":"none"};if(wt(f,t,e,o),zt(f,t.api,u?.toolChoice?.toolName),rt(f,t,e),Wt(f,t,e),t.api==="azure-openai-responses")f.azureBaseUrl=e.baseUrl,f.azureApiVersion=e.apiVersion,f.azureDeploymentName=t.id;return f}function Ke(e,t){let n=t.get("x-should-retry");return{statusCode:e,...t.get("retry-after")!==null?{retryAfter:t.get("retry-after")??void 0}:{},...t.get("retry-after-ms")!==null?{retryAfterMs:t.get("retry-after-ms")??void 0}:{},...n==="true"||n==="false"?{shouldRetry:n}:{}}}var Xt=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function Le(e,t,n){let u=e.onResponse;if(e.onResponse=async(f,p)=>{let _=new Headers(f.headers);n(Ke(f.status,_)),await u?.(f,p)},!Xt.has(t.api)||typeof globalThis.fetch!=="function")return;let o=typeof e.fetch==="function"?e.fetch:globalThis.fetch.bind(globalThis);e.fetch=async(f,p)=>{let _=await o(f,p);return n(Ke(_.status,_.headers)),_}}function ie(e){return{promptTokens:e.input+e.cacheRead+e.cacheWrite,completionTokens:e.output,totalTokens:e.totalTokens,costUsd:e.cost.total,...e.reasoning!==void 0?{reasoningTokens:e.reasoning}:{},...e.cacheWrite>0?{cacheCreationInputTokens:e.cacheWrite}:{},...e.cacheRead>0?{cacheReadInputTokens:e.cacheRead}:{}}}var v=300000,Gt=30000;class qe extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(e){super(`Provider stream idle timeout after ${e}ms without an event`);this.timeoutMs=e;this.name="StreamIdleTimeoutError"}}class Fe extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function Me(e){return e.reason instanceof Error?e.reason:new DOMException("Aborted","AbortError")}function $t(e){return e.idleTimeoutMs&&e.idleTimeoutMs>0?e.idleTimeoutMs:v}function Ht(e,t){if(t===0)return;let n=t!==void 0&&t>0?t:Gt;return Math.max(1,Math.min(n,Math.floor(e/2)))}function Kt(e,t,n){if(n?.aborted)return Promise.reject(Me(n));return new Promise((u,o)=>{let f=!1,p=()=>{clearTimeout(M),n?.removeEventListener("abort",x)},_=(P)=>{if(f)return;f=!0,p(),u(P)},h=(P)=>{if(f)return;f=!0,p(),o(P instanceof Error?P:Error(String(P)))},x=()=>{if(n)h(Me(n))},M=setTimeout(()=>_({kind:"timer"}),Math.max(0,t));if(n?.addEventListener("abort",x,{once:!0}),n?.aborted){x();return}e.then((P)=>_({kind:"next",result:P}),h)})}async function*Jt(e,t,n){let u=$t(t),o=Ht(u,t.stallWarningMs);if(t.signal?.aborted)throw Me(t.signal);let f=Date.now(),p=Promise.resolve().then(()=>e.next()),_;for(;;){let x=await Kt(p,(_?u:o??u)-(Date.now()-f),t.signal);if(x.kind==="next"){if(_)yield{..._,phase:"recovered",durationMs:Math.max(_.durationMs,Date.now()-f)};return x.result}if(!_&&o!==void 0){n.stallCount++,_={phase:"detected",stallCount:n.stallCount,durationMs:o,warningAfterMs:o,timeoutMs:u,outputStarted:n.outputStarted},yield _;continue}let M=new qe(u);throw t.abort?.(M),M}}async function*ve(e,t,n,u,o={}){let p=e.stream(t,n,u)[Symbol.asyncIterator](),_=0,h=!1,x={stallCount:0,outputStarted:!1};try{while(!0){let M=Jt(p,o,x),P=await M.next();while(!P.done)yield{providerStall:P.value},P=await M.next();let C=P.value;if(C.done)throw new Fe;let s=C.value;switch(s.type){case"text_delta":x.outputStarted=!0,yield{content:s.delta};break;case"thinking_delta":x.outputStarted=!0,yield{reasoningContent:s.delta};break;case"toolcall_end":x.outputStarted=!0,yield{toolCalls:[{index:_++,id:s.toolCall.id,type:"function",function:{name:s.toolCall.name,arguments:JSON.stringify(s.toolCall.arguments)}}]};break;case"done":h=!0,yield{finishReason:s.reason,usage:ie(s.message.usage)};return;case"error":throw Error(s.error.errorMessage??`Request ${s.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!h)Promise.resolve(p.return?.()).catch(()=>{return})}}var ye=V("Chat");function Zt(e){return Boolean(e&&e.role==="user"&&Array.isArray(e.content)&&e.content.some((t)=>t.type==="image_url"))}function Qt(e,t){let n=w(e,t);if(!n.retryable||!n.reason)return;let u=n.statusCode;switch(n.reason){case"rate_limit":if(u!==429)return;break;case"server_error":if(u===void 0||u<500||u>599)return;break;case"transport":case"stream_closed":break;case"timeout":return}let o=_e(t,Date.now());return{reason:n.reason,...u!==void 0?{statusCode:u}:{},...o!==void 0?{retryAfterMs:o}:{}}}function Lt(e){return e!==null&&typeof e==="object"&&"code"in e&&e.code==="STREAM_IDLE_TIMEOUT"}class be{config;models;model;constructor(e){let t=ue(e);this.config={...e,maxContextTokens:t.model.contextWindow,maxOutputTokens:e.maxOutputTokens??t.model.maxTokens},this.models=t.models,this.model=t.model,ye.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(e,t,n,u){let o="",f="",p=[],_,h;for await(let x of this.streamChat(e,t,n,u)){o+=x.content??"",f+=x.reasoningContent??"";for(let M of x.toolCalls??[])if(M.id&&M.type==="function"&&M.function?.name)p.push(M);_=x.usage??_,h=x.finishReason??h}return{content:o,...f?{reasoningContent:f}:{},...p.length>0?{toolCalls:p}:{},usage:_,finishReason:h}}async*streamChat(e,t,n,u){let o=u?.toolChoice?.toolName;if(o&&!t?.some((d)=>d.name===o))throw Error(`Required tool is unavailable: ${o}`);let f=De(e);if(f.some((d)=>Zt(d))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let p=Boolean(o)||ke(f),_=await Oe(f,this.model,t,n,o),h=u?.providerRecovery;if(h&&!tt(h.budgetMs))throw Error("Invalid bounded foreground Provider recovery budget");let x=h?.mode==="bounded_foreground"&&h.budgetMs>0?{budgetMs:h.budgetMs,startedAt:void 0}:void 0,M=x?"bounded_foreground":"standard",P=this.config.maxRetries??2,C=this.config.maxRetries??(x?et:2),s=x!==void 0&&this.config.maxRetries===void 0,O=0,k,nt=this.config.providerCircuitRegistry??Xe(),se=this.config.providerCircuitBreakerOpenMs??fe,ot=Math.max(F,Math.min(this.config.streamIdleTimeout??v,de)),ut=(d)=>nt.get({provider:d.provider,api:d.api,baseUrl:d.baseUrl??this.config.baseUrl??"",model:d.id,serviceTier:this.config.serviceTier,apiVersion:this.config.apiVersion,apiKey:this.config.apiKey,customHeaders:this.config.customHeaders,openDurationMs:se,probeLeaseMs:ot}),A=(d=Date.now())=>{if(!x)return;let b=x.startedAt===void 0?0:Math.min(x.budgetMs,Math.max(0,d-x.startedAt));return{recoveryBudgetMs:x.budgetMs,recoveryElapsedMs:b,recoveryRemainingMs:Math.max(0,x.budgetMs-b)}},D=()=>({mode:M,...A()??{}}),ce=()=>{if(x&&x.startedAt===void 0)x.startedAt=Date.now()},z=()=>{let d=A();return new Q(x?.budgetMs??0,d?.recoveryElapsedMs??0)},r=()=>!s||O<C+1,ft=(d)=>{if(!r())throw z();if(s)O++;k=void 0;let b=new AbortController,g=n?Ie(n,b.signal):b.signal,a;if(x?.startedAt!==void 0){let m=A()?.recoveryRemainingMs??0;if(m<=0)throw z();let S=new Q(x.budgetMs,x.budgetMs);a=setTimeout(()=>b.abort(S),m),a.unref?.()}let U=Qe(this.config,d,g,u,p);Le(U,d,(m)=>{k=m});let j=ve(this.models,d,_,U,{idleTimeoutMs:this.config.streamIdleTimeout??v,signal:g,abort:(m)=>b.abort(m)});return async function*(){try{yield*j}finally{if(a)clearTimeout(a)}}()},me=this,B=(d)=>({phase:d.phase,reason:d.reason,...d.statusCode!==void 0?{statusCode:d.statusCode}:{},...d.retryAfterMs!==void 0?{retryAfterMs:d.retryAfterMs}:{},...d.nextProbeAt!==void 0?{nextProbeAt:d.nextProbeAt}:{},openDurationMs:d.openDurationMs,sampleCount:d.sampleCount,failureCount:d.failureCount,...A()?{recoveryRemainingMs:A()?.recoveryRemainingMs}:{}}),Te=(d,b)=>({phase:d,reason:b.reason,...b.statusCode!==void 0?{statusCode:b.statusCode}:{},retryAfterMs:b.retryAfterMs,...b.nextProbeAt!==void 0?{nextProbeAt:b.nextProbeAt}:{},openDurationMs:b.openDurationMs,sampleCount:b.sampleCount,failureCount:b.failureCount,...A()?{recoveryRemainingMs:A()?.recoveryRemainingMs}:{}}),xt=(d)=>({phase:"probe",reason:d.reason??"server_error",...d.statusCode!==void 0?{statusCode:d.statusCode}:{},openDurationMs:d.openDurationMs??se,...d.sampleCount!==void 0?{sampleCount:d.sampleCount}:{},...d.failureCount!==void 0?{failureCount:d.failureCount}:{},...A()?{recoveryRemainingMs:A()?.recoveryRemainingMs}:{}}),ae=(d,b,g)=>({providerRetry:{phase:"exhausted",attempt:d,maxRetries:C,reason:b,...g!==void 0?{statusCode:g}:{},...D(),exhaustedBy:"recovery_budget"}}),Ce=async function*(d,b,g,a){let U,j=!1,m,S,N=ut(d);for(let l=0;l<=g;l++){if(!r())break;let R=N.check();while(!R.allowed){if(m=R.reason,S=R.statusCode,!x||!a){let E=Te("rejected",R);throw yield{providerCircuit:E},new Z(E)}ce();let c=A()?.recoveryRemainingMs??0;if(c<=0){let E=z();throw yield ae(s?Math.max(0,O-1):l,R.reason,R.statusCode),E}yield{providerCircuit:Te("waiting",R)};let I=Math.min(Math.max(1,R.retryAfterMs),Ee,c);if(await K(I,n,{throwOnAbort:!0}),(A()?.recoveryRemainingMs??0)<=0){let E=z();throw yield ae(s?Math.max(0,O-1):l,R.reason,R.statusCode),E}R=N.check()}let W=R.token;if(R.probe)yield{providerCircuit:xt(R)};try{let T=!1,c=!1;for await(let I of ft(d)){if(I.providerStall){yield I;continue}let E=s?O-1:l;if(E>0&&m&&!T)T=!0,yield{providerRetry:{phase:"recovered",attempt:E,maxRetries:C,reason:m,...S!==void 0?{statusCode:S}:{},...D()}};if(!c){c=!0;let X=N.recordSuccess(W);if(X)yield{providerCircuit:B(X)}}j=!0,b(),yield I}if(!c){let I=N.recordSuccess(W);if(I)yield{providerCircuit:B(I)}}return}catch(T){if(U=T,me.logIdleTimeout(T,j,d),await me.handleAbort(n),T instanceof Q){if(j)throw pe(T),T;throw yield{providerRetry:{phase:"exhausted",attempt:s?Math.max(0,O-1):l,maxRetries:C,reason:m??"timeout",...S!==void 0?{statusCode:S}:{},...D(),exhaustedBy:"recovery_budget"}},T}let c=w(T,k);if(j)throw pe(T),T;let I=Qt(T,k),E=I?N.recordFailure(W,I):k&&!Lt(T)?N.recordNeutral(W):void 0;if(E)yield{providerCircuit:B(E)};if(!c.retryable||!c.reason){if(l>0&&m)yield{providerRetry:{phase:"exhausted",attempt:s?Math.max(0,O-1):l,maxRetries:C,reason:m,...S!==void 0?{statusCode:S}:{},...D()}};throw T}m=c.reason,S=c.statusCode;let X=l<g&&r();if(E&&E.phase!=="closed"&&X&&(!x||!a)){let G={...B(E),phase:"rejected"};throw yield{providerCircuit:G},new Z(G)}if(X){ce();let G=s?O:l+1,ht=He(G,k,x?{maxDelayMs:Pe,maxExponentialDelayMs:Pe}:void 0),Ae=E&&E.phase!=="closed"?E.retryAfterMs??0:0;if(x&&Ae>0&&E)yield{providerCircuit:{...B(E),phase:"waiting"}};let pt=A(),ee=Math.max(ht,Ae),$=x?Math.min(ee,pt?.recoveryRemainingMs??ee):ee,i={attempt:G,maxRetries:C,reason:c.reason,...c.statusCode!==void 0?{statusCode:c.statusCode}:{}};if(yield{providerRetry:{phase:"scheduled",...i,delayMs:$,nextRetryAt:Date.now()+$,...D()}},x){let H=$;while(H>0){let ge=Math.min(H,Ee);if(await K(ge,n,{throwOnAbort:!0}),H-=ge,(A()?.recoveryRemainingMs??0)<=0){let q=z();throw yield{providerRetry:{phase:"exhausted",...i,...D(),exhaustedBy:"recovery_budget"}},q}if(H>0){if(E&&E.phase!=="closed"&&E.nextProbeAt!==void 0){let q=Math.max(0,E.nextProbeAt-Date.now());if(q>0)yield{providerCircuit:{...B(E),phase:"waiting",retryAfterMs:q}}}yield{providerRetry:{phase:"waiting",...i,delayMs:$,nextRetryAt:Date.now()+H,...D()}}}}}else await K($,n,{throwOnAbort:!0});yield{providerRetry:{phase:"attempt",...i,...D()}}}else yield{providerRetry:{phase:"exhausted",attempt:s?Math.max(0,O-1):l,maxRetries:C,reason:c.reason,...c.statusCode!==void 0?{statusCode:c.statusCode}:{},...D(),...x&&(a||!r())?{exhaustedBy:"attempt_limit"}:{}}}}finally{N.abandon(W)}}throw U},y,Re=!1,L=this.config.fallbackModels??[],dt=x&&L.length>0?Math.min(P,C):C;try{for await(let d of Ce(this.model,()=>{Re=!0},dt,L.length===0))yield d;return}catch(d){if(y=d,Re||!he(d)&&!w(d,k).retryable)throw d}for(let[d,b]of L.entries()){if(!r())break;yield{modelFallback:!0};let g=!1;try{let a=Ne(this.config,b),U=d===L.length-1,j=x&&!U?Math.min(P,C):C;for await(let m of Ce(a,()=>{g=!0},j,U))yield m;return}catch(a){if(y=a,g||!he(a)&&!w(a,k).retryable)throw a}}throw y}async handleAbort(e){if(e?.aborted)await K(0,e,{throwOnAbort:!0})}logIdleTimeout(e,t,n){if(e===null||typeof e!=="object"||!("code"in e)||e.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in e)||typeof e.timeoutMs!=="number")return;ye.warn("[PiAIChatService] Provider stream idle timeout",{provider:n.provider,model:n.id,timeoutMs:e.timeoutMs,replayBoundaryCrossed:t})}getConfig(){return{...this.config}}updateConfig(e){let t={...this.config,...e},n=ue(t);this.config={...t,maxContextTokens:n.model.contextWindow,maxOutputTokens:t.maxOutputTokens??n.model.maxTokens},this.models=n.models,this.model=n.model}}var it=V("Service");async function zn(e){let t=e;if(t.provider){let n=le(t.provider);if(Object.keys(n).length>0)t={...t,customHeaders:{...n,...t.customHeaders}},it.debug(`Injected ${t.provider} specific headers:`,Object.keys(n))}return qt(t)}function qt(e){return new be(e)}
5
+ export{yt as Hd,nn as Id,Ie as Jd,Ut as Kd,cn as Ld,be as Md,zn as Nd};
@@ -0,0 +1 @@
1
+ import{ng as a,og as b,pg as c,qg as d,rg as e,sg as f}from"./chunk-gkc69333.js";import"./chunk-kah7p2zm.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -0,0 +1 @@
1
+ import{Wc as a,Xc as b,Yc as c}from"./chunk-gq29vpef.js";import"./chunk-qggnvzkc.js";import"./chunk-kth1ra8z.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-ckfc7j7m.js";import"./chunk-3m0c6znc.js";import"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import"./chunk-6360fg4j.js";import"./chunk-bvdk0hb2.js";import"./chunk-byekf2bq.js";import"./chunk-fjcmx039.js";import"./chunk-e09g9a7d.js";import"./chunk-gkc69333.js";import"./chunk-nh43dgpd.js";import"./chunk-zg6drp32.js";import"./chunk-29abk8tj.js";import"./chunk-kah7p2zm.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,4 +1,4 @@
1
- import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-fqcf0n0h.js";import{L as M,S as y}from"./chunk-g5429yjs.js";import"./chunk-0nvc6y56.js";import"./chunk-gh0vdddb.js";import{ib as h,rb as A}from"./chunk-9hjhbsna.js";import"./chunk-5cgyevqj.js";import{jc as w,xc as U}from"./chunk-d63dczf8.js";import"./chunk-qgez5vw6.js";import"./chunk-atdb1pks.js";import{Uc as C}from"./chunk-y5jxkynb.js";import{Wc as I,Xc as S,Yc as v}from"./chunk-xsew6530.js";import{Zc as O}from"./chunk-qggnvzkc.js";import"./chunk-0evyrnx0.js";import{ud as P}from"./chunk-5cjy9yj1.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-jd764yqg.js";import"./chunk-ahkpjvaq.js";import"./chunk-3rjmkaey.js";import"./chunk-46r1m8yn.js";import"./chunk-rtzd076h.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-r48jmc74.js";import"./chunk-v11r4ahz.js";import"./chunk-vk3e2w5h.js";import{Af as F}from"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as z}from"./chunk-6360fg4j.js";import"./chunk-jtv91ez8.js";import"./chunk-0dw58ycv.js";import"./chunk-cm4t4cz6.js";import"./chunk-asqah231.js";import"./chunk-b6ve4vyt.js";import"./chunk-tczrjn95.js";import"./chunk-m0a2zdm8.js";import"./chunk-qc5qwgpt.js";import"./chunk-jtjcg93t.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-g9a3ht1x.js";import{L as M,S as y}from"./chunk-tdqz02hf.js";import"./chunk-mjcgy285.js";import"./chunk-kbmw1can.js";import{ib as h,rb as A}from"./chunk-b5g5mfq1.js";import"./chunk-5cgyevqj.js";import{jc as w,xc as U}from"./chunk-aesdm7cg.js";import"./chunk-qgez5vw6.js";import"./chunk-5ajyr2am.js";import{Uc as C}from"./chunk-b1pz71cr.js";import{Wc as I,Xc as S,Yc as v}from"./chunk-gq29vpef.js";import{Zc as O}from"./chunk-qggnvzkc.js";import"./chunk-0evyrnx0.js";import{ud as P}from"./chunk-kth1ra8z.js";import"./chunk-v508x7cg.js";import"./chunk-atsw605q.js";import"./chunk-83mfrs3p.js";import"./chunk-6yd3j5v5.js";import"./chunk-3rjmkaey.js";import"./chunk-4eg9qnxt.js";import"./chunk-sd8ptaz2.js";import"./chunk-hq18c6r9.js";import"./chunk-zwt7f9ab.js";import"./chunk-ckfc7j7m.js";import"./chunk-f3xwk6be.js";import"./chunk-v11r4ahz.js";import"./chunk-3m0c6znc.js";import{Af as F}from"./chunk-a7pvtxvz.js";import"./chunk-93jx06kq.js";import"./chunk-thstqcg3.js";import{Nf as z}from"./chunk-6360fg4j.js";import"./chunk-bvdk0hb2.js";import"./chunk-byekf2bq.js";import"./chunk-fjcmx039.js";import"./chunk-e09g9a7d.js";import"./chunk-gkc69333.js";import"./chunk-nh43dgpd.js";import"./chunk-zg6drp32.js";import"./chunk-29abk8tj.js";import"./chunk-kah7p2zm.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1 +1 @@
1
- import{a as o}from"./chunk-jsd6d2f5.js";import"./chunk-b6ve4vyt.js";import"./chunk-jtjcg93t.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-n52vvqfj.js";import"./chunk-gkc69333.js";import"./chunk-kah7p2zm.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{Od as a,Pd as b,Qd as c}from"./chunk-6yd3j5v5.js";import"./chunk-3rjmkaey.js";import"./chunk-fjcmx039.js";import"./chunk-e09g9a7d.js";import"./chunk-29abk8tj.js";import"./chunk-kah7p2zm.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1,4 +1,4 @@
1
- import{Cc as u,Dc as Hf,Ec as C$,Fc as Yf,Gc as I,Hc as N$,Ic as Wf,Jc as G$,Kc as _$,Lc as x$,Nc as g0,Qc as J$,Rc as Uf}from"./chunk-atdb1pks.js";import{Rd as V0}from"./chunk-3rjmkaey.js";import{we as Z0}from"./chunk-zwt7f9ab.js";import{Ie as i$}from"./chunk-v11r4ahz.js";import{Hf as Qf,If as Xf}from"./chunk-thstqcg3.js";import{Nf as A$}from"./chunk-6360fg4j.js";import{Yf as U0}from"./chunk-0dw58ycv.js";import{dg as x0,gg as J0}from"./chunk-asqah231.js";import{kg as p}from"./chunk-b6ve4vyt.js";import{rg as Ff,sg as q0,tg as Kf,ug as A,vg as m,xg as G0,yg as c,zg as C0}from"./chunk-qc5qwgpt.js";import{readdir as L$,readFile as a,rm as $0,stat as E0}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as yf,randomUUID as Sf}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as Mf}from"node:child_process";import{createHash as gf}from"node:crypto";import{readFileSync as Ef}from"node:fs";var bf=/^[a-f0-9]{64}$/;function Y$($){if(!$||typeof $!=="object")return!1;let f=$;return(f.platform==="linux"||f.platform==="darwin"||f.platform==="win32")&&typeof f.fingerprint==="string"&&bf.test(f.fingerprint)}var W$={readFile:($)=>Ef($,"utf8"),execFile:($,f)=>Mf($,f,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},wf=($)=>{try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}};function u0($,f){return{platform:$,fingerprint:gf("sha256").update(`${$}\x00${f}`).digest("hex")}}function kf($,f){let T=f.readFile(`/proc/${$}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function Q0($,f=process.platform,T=W$){if(!Number.isInteger($)||$<=1)return;try{if(f==="linux")return u0(f,kf($,T));if(f==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String($)]).trim();return q?u0(f,q):void 0}if(f==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0(f,B):void 0}}catch{return}return}function U$($,f){return Q0($,f.platform)?.fingerprint===f.fingerprint}function o1($,f,T=W$,q=wf){if(!Number.isInteger($)||$<=1)return!1;let B=Q0($,f.platform,T);if(B)return B.fingerprint===f.fingerprint;return!q($)}var z$=1;function jf($,f){let T=yf("sha256").update(f).digest("hex");return H0.join(q0($),".locks",`${T}.lock`)}function X0($,f){return $ instanceof Error&&"code"in $&&$.code===f}async function P0($){try{let f=JSON.parse(await v.readFile($,"utf8"));if(f.version!==z$||typeof f.sessionId!=="string"||typeof f.ownerId!=="string"||!Number.isInteger(f.pid)||(f.pid??0)<=0||f.processIdentity!==void 0&&!Y$(f.processIdentity)||typeof f.acquiredAt!=="string")return;return f}catch{return}}async function D$($){let f=await P0($);if(f)return f;return await new Promise((T)=>setTimeout(T,10)),P0($)}function mf($){try{return process.kill($,0),!0}catch(f){return X0(f,"EPERM")}}async function R$($,f){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(f)}
1
+ import{Cc as u,Dc as Hf,Ec as C$,Fc as Yf,Gc as I,Hc as N$,Ic as Wf,Jc as G$,Kc as _$,Lc as x$,Nc as g0,Qc as J$,Rc as Uf}from"./chunk-5ajyr2am.js";import{Rd as V0}from"./chunk-3rjmkaey.js";import{we as Z0}from"./chunk-zwt7f9ab.js";import{Ie as i$}from"./chunk-v11r4ahz.js";import{Hf as Qf,If as Xf}from"./chunk-thstqcg3.js";import{Nf as A$}from"./chunk-6360fg4j.js";import{ag as U0}from"./chunk-byekf2bq.js";import{hg as x0,kg as J0}from"./chunk-e09g9a7d.js";import{og as p}from"./chunk-gkc69333.js";import{Bg as G0,Cg as c,Dg as C0,vg as Ff,wg as q0,xg as Kf,yg as A,zg as m}from"./chunk-29abk8tj.js";import{readdir as L$,readFile as a,rm as $0,stat as E0}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as yf,randomUUID as Sf}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as Mf}from"node:child_process";import{createHash as gf}from"node:crypto";import{readFileSync as Ef}from"node:fs";var bf=/^[a-f0-9]{64}$/;function Y$($){if(!$||typeof $!=="object")return!1;let f=$;return(f.platform==="linux"||f.platform==="darwin"||f.platform==="win32")&&typeof f.fingerprint==="string"&&bf.test(f.fingerprint)}var W$={readFile:($)=>Ef($,"utf8"),execFile:($,f)=>Mf($,f,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},wf=($)=>{try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}};function u0($,f){return{platform:$,fingerprint:gf("sha256").update(`${$}\x00${f}`).digest("hex")}}function kf($,f){let T=f.readFile(`/proc/${$}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function Q0($,f=process.platform,T=W$){if(!Number.isInteger($)||$<=1)return;try{if(f==="linux")return u0(f,kf($,T));if(f==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String($)]).trim();return q?u0(f,q):void 0}if(f==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0(f,B):void 0}}catch{return}return}function U$($,f){return Q0($,f.platform)?.fingerprint===f.fingerprint}function o1($,f,T=W$,q=wf){if(!Number.isInteger($)||$<=1)return!1;let B=Q0($,f.platform,T);if(B)return B.fingerprint===f.fingerprint;return!q($)}var z$=1;function jf($,f){let T=yf("sha256").update(f).digest("hex");return H0.join(q0($),".locks",`${T}.lock`)}function X0($,f){return $ instanceof Error&&"code"in $&&$.code===f}async function P0($){try{let f=JSON.parse(await v.readFile($,"utf8"));if(f.version!==z$||typeof f.sessionId!=="string"||typeof f.ownerId!=="string"||!Number.isInteger(f.pid)||(f.pid??0)<=0||f.processIdentity!==void 0&&!Y$(f.processIdentity)||typeof f.acquiredAt!=="string")return;return f}catch{return}}async function D$($){let f=await P0($);if(f)return f;return await new Promise((T)=>setTimeout(T,10)),P0($)}function mf($){try{return process.kill($,0),!0}catch(f){return X0(f,"EPERM")}}async function R$($,f){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(f)}
2
2
  `,"utf8"),!0}catch(q){if(X0(q,"EEXIST"))return!1;if(T)await v.unlink($).catch(()=>{return});throw q}finally{await T?.close().catch(()=>{return})}}class h extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class n{filePath;record;released=!1;constructor($,f){this.filePath=$;this.record=f}static async acquire($,f=A$()){let T=jf(f,$),q={version:z$,sessionId:$,ownerId:Sf(),pid:process.pid,processIdentity:Q0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(H0.dirname(T),{recursive:!0,mode:448}),await R$(T,q))return new n(T,q);let B=await D$(T);if(B&&mf(B.pid)&&(!B.processIdentity||U$(B.pid,B.processIdentity)))throw new h(B.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await R$(T,q))return new n(T,q);throw new h((await D$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await P0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((f)=>{if(!X0(f,"ENOENT"))throw f})}}var TT=1;function h0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function If($){if(!h0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&h0($.image_url)&&typeof $.image_url.url==="string"}function vf($){if(!h0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(If)}function M$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let f=JSON.stringify($);if(Buffer.byteLength(f)>16777216)return;let T=JSON.parse(f);if(!Array.isArray(T)||!T.every(vf))return;return T}function qT($){let f=M$($);if(!f)throw Error("Compaction replacement context is invalid or exceeds limits");return f}function g$($){return M$($)}function uf($,f){for(let T of $){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let q=T.data.payload;if(!q||typeof q!=="object"||Array.isArray(q))continue;let B=q;if(B.toolCallId===f||T.data.partId===f||T.data.messageId===f)return B}return}function E$($){let f=u($),T=new Map;for(let q of f){if(q.type==="interaction_requested"){T.set(q.data.requestId,{request:q.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(q.type==="interaction_responded"){let B=T.get(q.data.requestId);if(B)B.response=q.data;continue}if(q.type==="interaction_recovered"){let B=T.get(q.data.requestId);if(B)B.recovery=q.data}}for(let q of T.values()){let B=uf(f,q.request.toolCallId);q.hasToolResult=B!==void 0;let L=B?.metadata&&typeof B.metadata==="object"?B.metadata:void 0;q.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===q.request.requestId}return[...T.values()]}function b$($){return E$($).reverse().find((f)=>!f.response&&!f.recovery)}function OT($){let f=new Map;for(let T of E$($))f.set(T.request.toolCallId,T);return[...f.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function w$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function Y0($){let f=new Map,T=[];for(let q of $){if(q.type==="review_started"){if(!f.has(q.data.reviewId))T.push(q.data.reviewId),f.set(q.data.reviewId,{start:q.data});continue}if(q.type!=="review_completed")continue;let B=f.get(q.data.reviewId);if(B&&B.completion===void 0)B.completion=q.data}return T.map((q)=>f.get(q)).filter((q)=>q!==void 0)}function NT($){return Y0($).reverse().find((f)=>f.completion===void 0)}function n0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function k$($,f){let T=["## Code Review","",`Target: ${$.target.label}`,`Status: ${n0(f.status)}`,"",f.overallExplanation||"No overall explanation was provided."];if(f.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[q,B]of f.findings.entries()){let L=B.codeLocation.lineStart===B.codeLocation.lineEnd?`${B.codeLocation.lineStart}`:`${B.codeLocation.lineStart}-${B.codeLocation.lineEnd}`;T.push("",`${q+1}. ${B.title}`,` ${B.codeLocation.path}:L${L} · confidence ${B.confidenceScore.toFixed(2)}`,` ${B.body}`)}}if(f.error)T.push("",`Error: ${f.error}`);return T.join(`
3
3
  `)}function y$($,f){return{reviewId:$.reviewId,phase:"completed",status:f.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:f.overallExplanation,findings:f.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...f.error?{error:f.error}:{}}}var l0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Pf($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function hf($){let f=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(f))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(f))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(f))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(f))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(f))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(f))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(f))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(f))return"unsupported_input";return"runtime"}function nf($){return{code:$,...l0[$]}}function c0($){return nf(hf(Pf($)))}function p0($){if(!$||typeof $!=="object")return!1;let f=$;if(typeof f.code!=="string"||!(f.code in l0))return!1;let T=l0[f.code];return f.message===T.message&&f.retryable===T.retryable}import{promises as L0,realpathSync as cf}from"node:fs";import W0 from"node:path";import*as r from"fs/promises";import*as H from"path";var S$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,f){super($);this.code=f;this.name="PathSecurityError"}}class i0{static normalize($,f){let T=H.isAbsolute($)?$:H.resolve(f,$),q=H.normalize(T),B=H.normalize(f);if(!this.isWithinWorkspace(q,B))throw new d(`Path outside workspace: ${$} (resolved to ${q}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return q}static checkRestricted($){let f=$.split(H.sep);for(let T of S$)if(f.includes(T))throw new d(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,f){this.checkTraversal($);let T=this.normalize($,f);this.checkRestricted(T);try{await r.access(T)}catch(q){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,f){try{let T=await r.realpath($),q=await r.realpath(f);if(!this.isWithinWorkspace(T,q))throw new d(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return $}}static getRelativePath($,f){return H.relative(f,$)}static isWithinWorkspace($,f){let T=H.resolve($),q=H.resolve(f),B=H.relative(q,T);return B===""||B!==".."&&!B.startsWith(`..${H.sep}`)&&!H.isAbsolute(B)}static async isWithinWorkspaceResolved($,f){let T=H.resolve(f),q=H.isAbsolute($)?H.resolve($):H.resolve(T,$);if(!this.isWithinWorkspace(q,T))return!1;let B;try{B=await r.realpath(T)}catch{return!1}let L=q;while(!0){try{let C=await r.realpath(L);return this.isWithinWorkspace(C,B)}catch(C){let _=C.code;if(_!=="ENOENT"&&_!=="ENOTDIR")return!1}let O=H.dirname(L);if(O===L)return!1;L=O}}static isRestricted($){let f=$.split(H.sep);return S$.some((T)=>f.includes(T))}}var B0=U0("Tool");class l{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}async recordFileRead($,f){try{let T=await L0.stat($),q={filePath:W0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:f,lastOperation:"read"};this.setRecord(q),await this.recordAliases($,q.filePath),B0.debug(`记录文件读取: ${$}`)}catch(T){B0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,f,T="edit"){try{let q=await L0.stat($),B={filePath:W0.resolve($),accessTime:Date.now(),mtime:q.mtimeMs,sessionId:f,lastOperation:T};this.setRecord(B),await this.recordAliases($,B.filePath),B0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(q){B0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${$}`,q)}}hasFileBeenRead($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return!1;return f?T.has(f):T.size>0}async checkFileModification($,f){let T=this.getFileRecord($,f);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(Math.abs(q.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${q.mtime.toISOString()})`};return{modified:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${B.message}`}}}async checkExternalModification($,f){let T=this.getFileRecord($,f);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(q.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${q.mtime.toISOString()})`};return{isExternal:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${$}`,q),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(f)return T.get(f);return[...T.values()].sort((q,B)=>B.accessTime-q.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,f){let T=this.resolveTrackedPath($);if(!f){this.accessedFiles.delete(T),this.removeAliases(T);return}let q=this.accessedFiles.get(T);if(q?.delete(f),q?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,f){for(let[T,q]of this.accessedFiles.entries()){if(f&&!i0.isWithinWorkspace(T,f))continue;if(q.delete($),q.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.instance=null}setRecord($){let f=this.accessedFiles.get($.filePath);if(!f)f=new Map,this.accessedFiles.set($.filePath,f);f.set($.sessionId,$)}async recordAliases($,f){this.pathAliases.set(W0.resolve($),f);let T=await L0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,f)}resolveTrackedPath($){let f=W0.resolve($);if(this.accessedFiles.has(f))return f;let T=this.pathAliases.get(f);if(T)return T;try{let q=cf.native(f);return this.pathAliases.get(q)??q}catch{return f}}removeAliases($){for(let[f,T]of this.pathAliases)if(T===$)this.pathAliases.delete(f)}}import*as O0 from"node:crypto";import{promises as F}from"node:fs";import*as Q from"node:path";import d0 from"write-file-atomic";var j$="missing";class D0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(A($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!Q.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?Q.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let f=C0();this.snapshotDir=Q.join(f,"file-history",this.sessionId),this.manifestPath=Q.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await F.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=C0(),f=await F.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=O0.createHash("sha256").update(f).digest("hex").slice(0,24),q=Q.join($,"file-history",this.sessionId),B=Q.join($,"file-history","workspaces",T,this.sessionId),L=Q.join(B,"manifest.json");try{await F.access(L)}catch{await this.migrateLegacySnapshotDir(q,B,f)}this.snapshotDir=B,this.manifestPath=L}async migrateLegacySnapshotDir($,f,T){let q;try{q=JSON.parse(await F.readFile(Q.join($,"manifest.json"),"utf8"))}catch{return}if(q.schemaVersion!==1||!Array.isArray(q.snapshots)||!q.snapshots.every((B)=>this.isWithinWorkspace(B.filePath,T)))return;await F.mkdir(Q.dirname(f),{recursive:!0,mode:493});try{await F.rename($,f)}catch(B){let L=B.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw B}}isWithinWorkspace($,f){if(!Q.isAbsolute($))return!1;let T=Q.relative(f,Q.resolve($));return T===""||T!==".."&&!T.startsWith(`..${Q.sep}`)&&!Q.isAbsolute(T)}async createSnapshot($,f){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity($),q=!0;try{await F.access(T)}catch{q=!1}let B=this.trackedFileBackups.get(T),L=B?B.version+1:1,O=this.generateFileHash(T,L),C=this.getSnapshotPath(O,L),_=new Date;if(q){let G=await F.readFile(T);await F.writeFile(C,G)}let N={backupFileName:O,version:L,backupTime:_};return this.trackedFileBackups.set(T,N),this.snapshots.push({messageId:f,backupFileName:O,timestamp:_,filePath:T,version:L,existedBefore:q}),await this.cleanupOldSnapshots(T),await this.persistManifest(),N}async recordPostEditState($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)throw Error(`未找到待完成的快照: ${T}`);q.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)return;this.removeSnapshot(q),await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let f=await this.resolveFileIdentity($),T=this.snapshots.slice().reverse().find((L)=>L.filePath===f&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${f}`);if(await this.hashFile(f)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${f}`);let B=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(f),{recursive:!0}),await F.writeFile(f,L)}else await F.rm(f,{force:!0});return this.removeSnapshot(T),await F.rm(B,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,f){let T=await this.resolveFileIdentity($),q=this.snapshots.slice().reverse().find((L)=>L.messageId===f&&L.filePath===T);if(!q)throw Error(`未找到快照: messageId=${f}, filePath=${T}`);let B=this.getSnapshotPath(q.backupFileName,q.version);if(q.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(T),{recursive:!0}),await F.writeFile(T,L)}else await F.rm(T,{force:!0})}async listSnapshots($){let f=await this.resolveFileIdentity($);return this.snapshots.filter((T)=>T.filePath===f)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let f=this.buildRewindPlan($);return{files:f.map((T)=>T.filePath),snapshotCount:f.reduce((T,q)=>T+q.selected.length,0)}}async rewindSnapshots($){let f=this.buildRewindPlan($);if(f.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let B of f){let L,O=!0;try{L=await F.readFile(B.filePath)}catch(_){if(_.code!=="ENOENT")throw _;O=!1}if((L?O0.createHash("sha256").update(L).digest("hex"):j$)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(T.set(B.filePath,{existed:O,content:L}),B.target.existedBefore)await F.access(this.getSnapshotPath(B.target.backupFileName,B.target.version))}let q=[...this.snapshots];try{for(let L of f)if(L.target.existedBefore){let O=await F.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await F.mkdir(Q.dirname(L.filePath),{recursive:!0}),await d0(L.filePath,O)}else await F.rm(L.filePath,{force:!0});let B=new Set(f.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!B.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...B].map((L)=>F.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(B){this.snapshots=q,this.rebuildTrackedFileBackups();let L=[];for(let[O,C]of T)try{if(C.existed&&C.content)await d0(O,C.content);else await F.rm(O,{force:!0})}catch(_){L.push(_)}if(L.length>0)throw AggregateError([B,...L],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:f.map((B)=>B.filePath),snapshotCount:f.reduce((B,L)=>B+L.selected.length,0)}}async commitSnapshots($){let f=this.buildRewindPlan($),T=new Set(f.flatMap((B)=>B.selected));if(T.size===0)return{files:[],snapshotCount:0};let q=[...this.snapshots];this.snapshots=this.snapshots.filter((B)=>!T.has(B)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(B){throw this.snapshots=q,this.rebuildTrackedFileBackups(),B}return await Promise.all([...T].map((B)=>F.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return}))),{files:f.map((B)=>B.filePath),snapshotCount:T.size}}buildRewindPlan($){let f=new Set($),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),q=T.filter((L)=>f.has(L.messageId));return[...new Set(q.map((L)=>L.filePath))].sort().map((L)=>{let O=T.filter((G)=>G.filePath===L),C=O.filter((G)=>f.has(G.messageId)),_=O.indexOf(C[0]),N=O.slice(_);if(N.length!==C.length||N.some((G)=>!f.has(G.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:C,target:C[0],latest:C.at(-1)}})}async loadManifest(){try{let $=await F.readFile(this.manifestPath,"utf-8"),f=JSON.parse($);if(f.schemaVersion!==1||!Array.isArray(f.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(f.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await F.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((f)=>({...f,timestamp:f.timestamp.toISOString()}))};await d0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let T=this.snapshots.filter((q)=>q.filePath===$).slice(0,-this.maxSnapshots);for(let q of T)await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),this.removeSnapshot(q)}async cleanup($=0){let f=this.snapshots.slice().sort((q,B)=>B.timestamp.getTime()-q.timestamp.getTime()),T=new Set(f.slice(0,$));for(let q of this.snapshots)if(!T.has(q))await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0});this.snapshots=f.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,f){return Q.join(this.snapshotDir,`${$}@v${f}`)}async resolveFileIdentity($){let f=Q.resolve($),T=[],q=f;while(!0){try{let L=await F.realpath(q);return Q.join(L,...T.reverse())}catch(L){let O=L.code;if(O!=="ENOENT"&&O!=="ENOTDIR")throw L}let B=Q.dirname(q);if(B===q)return f;T.push(Q.basename(q)),q=B}}async hashFile($){try{let f=await F.readFile($);return O0.createHash("sha256").update(f).digest("hex")}catch(f){if(f.code==="ENOENT")return j$;throw f}}removeSnapshot($){let f=this.snapshots.indexOf($);if(f>=0)this.snapshots.splice(f,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let f=this.trackedFileBackups.get($.filePath);if(!f||f.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,f){let T=O0.createHash("md5");return T.update(`${$}:${f}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var DT=1200,RT=2000,AT=2000,zT=2000;function I$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function pf($){if(typeof $==="string"&&$.length>0)return $;if(I$($)&&typeof $.message==="string")return $.message;return}function df($,f){if($===null||$===void 0)return f??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function v$($){let f=$.error!==null&&$.error!==void 0,T=f?pf($.error)??"Tool execution failed":void 0,q=I$($.metadata)?$.metadata:void 0;return{success:!f,llmContent:df($.output,T),...T?{error:{type:"execution_error",message:T}}:{},...q?{metadata:q}:{}}}function o0($,f){if($.length<=f)return $;let T=Math.max(0,f);if(T>0&&T<$.length&&/[\uD800-\uDBFF]/.test($.charAt(T-1)))T-=1;return $.slice(0,T)}function m$($,f){if($.length<=f)return $;let T=Math.max(0,$.length-f);if(T<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(T)))T+=1;return $.slice(T)}function r0($,f){if($.length<=f)return $;if(f<=0)return"";let T=`
4
4
  ... (display clipped) ...
@@ -1,2 +1,2 @@
1
- import{kg as d,mg as h}from"./chunk-b6ve4vyt.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{og as d,qg as h}from"./chunk-gkc69333.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as Uc,w as Vc};
@@ -1,4 +1,4 @@
1
- import{Eb as WJ}from"./chunk-5cgyevqj.js";import{Fb as l0,Mb as q6,Nb as O6,Ob as e1,Pb as $2,Wb as W6,cc as C$,mc as U0,oc as q2,pc as X1,qc as O2,xc as f$}from"./chunk-d63dczf8.js";import{Cc as t,Fc as B6,Gc as G0}from"./chunk-atdb1pks.js";import{Gd as E6}from"./chunk-atsw605q.js";import{Hd as $J,Id as C0,Jd as n6,Kd as JJ,Ld as L2,Nd as Z6}from"./chunk-jd764yqg.js";import{re as v0,se as P0,ve as ZJ}from"./chunk-hq18c6r9.js";import{Ee as W$}from"./chunk-r48jmc74.js";import{Nf as a}from"./chunk-6360fg4j.js";import{Yf as O0}from"./chunk-0dw58ycv.js";import{kg as L6}from"./chunk-b6ve4vyt.js";import{Ag as j6,sg as H$,ug as n2,vg as z0,wg as H1,yg as w6}from"./chunk-qc5qwgpt.js";import{Bg as F8}from"./chunk-jtjcg93t.js";function J$($){return $.role==="system"&&Array.isArray($.content)}function $$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(J$);if(this._contextualSystemMessages=$.messages.filter($$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!J$(W)&&!$$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!$$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(J$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!J$(J)&&!$$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter($$),this._history=$.filter((J)=>!J$(J)&&!$$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function T2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function k2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function x2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var DJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),wJ=/^(LD_.+|DYLD_.+|PATH)$/,M2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function A$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(M2);if(!K)break;let H=K[1];if(!DJ.has(H))break;J=Y}return J}function g4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(M2);if(!K)break;let H=K[1];if(wJ.test(H))break;J=Y}return J}var jJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of jJ){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function s$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function h2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function P$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var LJ=new Set(["npm","pnpm","yarn","bun"]),R2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),qJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function OJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function GJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function yJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=P$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=i0.isAbsolute(K)?i0.resolve(K):i0.resolve(Z,K);if(!l0.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function Z$($,J){let Z=A$(GJ($)),W=s$(Z);if(!W||h2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:yJ(Z,W,J);if(!Y)return!1;let K=P$(Y);if(K.length===0||K.some((z)=>[...qJ].some((D)=>z===D||z.startsWith(`${D}=`))))return!1;let[H,X,Q]=K;if(LJ.has(H??""))return OJ(X==="run"?Q:X)||X==="--test";if((H==="npx"||H==="bunx")&&R2.has(X??""))return!0;if(R2.has(H??""))return!0;if(H==="node"&&X==="--test")return!0;if(H==="go"&&["build","test","vet"].includes(X??""))return!0;return H==="cargo"&&["build","check","clippy","test"].includes(X??"")}function i4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=O0("Agent"),UJ=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=UJ)return{action:"truncated"};if(T2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var FJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],_J=/```[\s\S]{50,}```/,C2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",bJ=2;function g1($,J,Z=!0){if(!$||J>=bJ)return{action:"none"};if(!Z&&_J.test($))return{action:"retry",prompt:C2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(FJ.some((H)=>H.test(W)))return{action:"retry",prompt:C2};return{action:"none"}}var NJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],I2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},SJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},AJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",PJ="Required verification did not run successfully before the retry limit.",EJ=3;function p2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&Z$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&Z$(K,W))$.add(K)}function m1($,J,Z){if(!$||!NJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(I2).filter((Q)=>I2[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((z)=>SJ[Q].test(z)));if(W.length>0?K.length===0:Y.some((Q)=>Z$(Q)))return{action:"none"};if(Z>=EJ)return{action:"fail",message:PJ};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${AJ}${X}`}}var fJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],g2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function m2($){return typeof $==="string"&&g2.some((J)=>J.test($))}var TJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],kJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function xJ($){if(typeof $!=="string")return;if(kJ.some((J)=>J.test($)))return"multiple-allowed";return TJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=xJ(J);if(Z!==void 0)return Z==="required"}return!1}var MJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",hJ="Required delegation did not complete before the retry limit.",RJ=3;function u2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=e$(W),K=!1;if(!Y)for(let H of W){if(g2.some((X)=>X.test(H)))break;if(fJ.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=RJ)return{action:"fail",message:hJ};return{action:"retry",prompt:MJ}}var CJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],IJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],vJ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function d2($){return vJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=d2($);return CJ.some((Z)=>Z.test(J))}var pJ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",gJ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",mJ="Required worktree lifecycle did not complete before the retry limit.",uJ=3;function c2($,J,Z){if(!$)return{action:"none"};let W=d2($);if(!$1(W))return{action:"none"};let Y=IJ.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=uJ)return{action:"fail",message:mJ};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?pJ:gJ}}var v2=30000;async function u1($){try{let Z=W$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),v2)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${v2}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function dJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var cJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function iJ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function lJ($){let J=$;for(let Q of cJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function i2($){return lJ(iJ($))}import{EventEmitter as rJ}from"events";import l2 from"node:path";function d1($){if(n2($.sessionId),!l2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l2.resolve($.projectPath)}}function r2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function W5($,J){return r2($)===r2(J)}class Y$ extends rJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!Y$.instance)Y$.instance=new Y$;return Y$.instance}publish($,J,Z,W){let Y=d1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var E$=Y$.getInstance();var M0=O0("Agent"),J1=new Set;async function nJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=i2(J);if(!K)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:K}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
1
+ import{Eb as WJ}from"./chunk-5cgyevqj.js";import{Fb as l0,Mb as q6,Nb as O6,Ob as e1,Pb as $2,Wb as W6,cc as C$,mc as U0,oc as q2,pc as X1,qc as O2,xc as f$}from"./chunk-aesdm7cg.js";import{Cc as t,Fc as B6,Gc as G0}from"./chunk-5ajyr2am.js";import{Gd as E6}from"./chunk-atsw605q.js";import{Hd as $J,Id as C0,Jd as n6,Kd as JJ,Ld as L2,Nd as Z6}from"./chunk-83mfrs3p.js";import{re as v0,se as P0,ve as ZJ}from"./chunk-hq18c6r9.js";import{Ee as W$}from"./chunk-f3xwk6be.js";import{Nf as a}from"./chunk-6360fg4j.js";import{ag as O0}from"./chunk-byekf2bq.js";import{og as L6}from"./chunk-gkc69333.js";import{Ag as H1,Cg as w6,Eg as j6,wg as H$,yg as n2,zg as z0}from"./chunk-29abk8tj.js";import{Fg as F8}from"./chunk-kah7p2zm.js";function J$($){return $.role==="system"&&Array.isArray($.content)}function $$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class a${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(J$);if(this._contextualSystemMessages=$.messages.filter($$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!J$(W)&&!$$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!$$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(J$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!J$(J)&&!$$(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter($$),this._history=$.filter((J)=>!J$(J)&&!$$(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function T2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function k2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function x2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import i0 from"node:path";var DJ=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),wJ=/^(LD_.+|DYLD_.+|PATH)$/,M2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function A$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(M2);if(!K)break;let H=K[1];if(!DJ.has(H))break;J=Y}return J}function g4($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(M2);if(!K)break;let H=K[1];if(wJ.test(H))break;J=Y}return J}var jJ=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function I1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of jJ){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function s$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function h2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function P$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let Q=$[H+1];if(Q&&'$`"\\'.includes(Q))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var LJ=new Set(["npm","pnpm","yarn","bun"]),R2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),qJ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function OJ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function GJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function yJ($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=P$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=i0.isAbsolute(K)?i0.resolve(K):i0.resolve(Z,K);if(!l0.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function Z$($,J){let Z=A$(GJ($)),W=s$(Z);if(!W||h2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:yJ(Z,W,J);if(!Y)return!1;let K=P$(Y);if(K.length===0||K.some((z)=>[...qJ].some((D)=>z===D||z.startsWith(`${D}=`))))return!1;let[H,X,Q]=K;if(LJ.has(H??""))return OJ(X==="run"?Q:X)||X==="--test";if((H==="npx"||H==="bunx")&&R2.has(X??""))return!0;if(R2.has(H??""))return!0;if(H==="node"&&X==="--test")return!0;if(H==="go"&&["build","test","vet"].includes(X??""))return!0;return H==="cargo"&&["build","check","clippy","test"].includes(X??"")}function i4($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!i0.isAbsolute($);let Z=i0.isAbsolute($)?i0.resolve($):i0.resolve(J,$);return l0.isWithinWorkspace(Z,J)}var v1=O0("Agent"),UJ=3;function p1($,J,Z){if($!=="length")return{action:"none"};if(J>=UJ)return{action:"truncated"};if(T2(Z)==="stop")return v1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var FJ=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],_J=/```[\s\S]{50,}```/,C2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",bJ=2;function g1($,J,Z=!0){if(!$||J>=bJ)return{action:"none"};if(!Z&&_J.test($))return{action:"retry",prompt:C2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(FJ.some((H)=>H.test(W)))return{action:"retry",prompt:C2};return{action:"none"}}var NJ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],I2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},SJ={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},AJ="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",PJ="Required verification did not run successfully before the retry limit.",EJ=3;function p2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&Z$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&Z$(K,W))$.add(K)}function m1($,J,Z){if(!$||!NJ.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(I2).filter((Q)=>I2[Q].test($)),Y=[...J],K=W.filter((Q)=>!Y.some((z)=>SJ[Q].test(z)));if(W.length>0?K.length===0:Y.some((Q)=>Z$(Q)))return{action:"none"};if(Z>=EJ)return{action:"fail",message:PJ};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${AJ}${X}`}}var fJ=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],g2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function m2($){return typeof $==="string"&&g2.some((J)=>J.test($))}var TJ=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],kJ=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function xJ($){if(typeof $!=="string")return;if(kJ.some((J)=>J.test($)))return"multiple-allowed";return TJ.some((J)=>J.test($))?"required":void 0}function e$($){for(let J of $){let Z=xJ(J);if(Z!==void 0)return Z==="required"}return!1}var MJ="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",hJ="Required delegation did not complete before the retry limit.",RJ=3;function u2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=e$(W),K=!1;if(!Y)for(let H of W){if(g2.some((X)=>X.test(H)))break;if(fJ.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=RJ)return{action:"fail",message:hJ};return{action:"retry",prompt:MJ}}var CJ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],IJ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],vJ=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function d2($){return vJ.reduce((J,Z)=>J.replace(Z," "),$)}function $1($){if(typeof $!=="string")return!1;let J=d2($);return CJ.some((Z)=>Z.test(J))}var pJ="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",gJ="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",mJ="Required worktree lifecycle did not complete before the retry limit.",uJ=3;function c2($,J,Z){if(!$)return{action:"none"};let W=d2($);if(!$1(W))return{action:"none"};let Y=IJ.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=uJ)return{action:"fail",message:mJ};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?pJ:gJ}}var v2=30000;async function u1($){try{let Z=W$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??a(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),v2)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return v1.warn(`[Loop] Stop hook 超时 (${v2}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return v1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function dJ($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var cJ=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function iJ($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function lJ($){let J=$;for(let Q of cJ)J=J.replace(Q," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function i2($){return lJ(iJ($))}import{EventEmitter as rJ}from"events";import l2 from"node:path";function d1($){if(n2($.sessionId),!l2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l2.resolve($.projectPath)}}function r2($){let J=d1($);return JSON.stringify([J.projectPath,J.sessionId])}function W5($,J){return r2($)===r2(J)}class Y$ extends rJ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!Y$.instance)Y$.instance=new Y$;return Y$.instance}publish($,J,Z,W){let Y=d1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var E$=Y$.getInstance();var M0=O0("Agent"),J1=new Set;async function nJ($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(J1.has(Z))return;if(J1.size>=5000)J1.clear();J1.add(Z);try{let W=$.workspaceRoot,Y=await f$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=i2(J);if(!K)return;await f$.updateSessionMetadata(Z,Y.projectPath,{title:K}),E$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){M0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var c1=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,r0="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",o2="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class K$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function n0($){return $.executionEngine?.getContextManager()}async function H0($,J,Z,W=null,Y,K={}){let H=K.required??$.executionEngine!==void 0;try{let X=n0($),Q=typeof Z==="string"?Z.trim()!=="":Z.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&J.sessionId&&Q){let z=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(H&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)nJ(J,Z);return z}if(H&&J.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(X){if(M0.warn("[Loop] 保存用户消息失败:",X),H)throw new K$("user_message",{cause:X})}return null}async function g($,J,Z,W,Y,K,H={}){let X=H.required??$.executionEngine!==void 0;try{let Q=n0($),z=Boolean(Z.trim()||Y?.trim());if(Q&&J.sessionId&&z){let D=await Q.saveMessage(J.sessionId,"assistant",Z,W,K,J.subagentInfo,Y);if(X&&!D)throw Error("Durable assistant-message commit returned no identity");return D}if(X&&J.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(M0.warn("[Loop] 保存助手消息失败:",Q),X)throw new K$("assistant_message",{cause:Q})}return null}async function a2($,J,Z){try{let W=n0($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",c1,Z,void 0,J.subagentInfo)}catch(W){M0.warn("[Loop] 保存中断边界失败:",W)}return null}async function s2($,J,Z,W,Y){try{let K=n0($);if(!K||!J.sessionId||Z.length===0)return null;return await K.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((H)=>({...H})))),triggerPaths:[...W]},J.subagentInfo)}catch(K){M0.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function i1($,J,Z,W,Y,K={}){try{let H=n0($);if(H&&J.sessionId){let X=await H.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo);if(K.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(K.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(H){if(M0.warn("[Loop] 保存工具调用失败:",H),K.required)throw H}return null}async function Z1($,J,Z,W,Y,K,H,X,Q,z={}){try{let D=n0($);if(D&&J.sessionId){let q=await D.saveToolResult(J.sessionId,Z,W,Y,K,H,J.subagentInfo,X,Q);if(z.required&&!q)throw Error("Durable tool-result commit returned no identity");return q}if(z.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(D){if(M0.warn("[Loop] 保存工具结果失败:",D),z.required)throw D}return null}async function T$($,J,Z,W,Y={}){try{let K=n0($);if(K&&J.sessionId){let H=await K.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!H)throw Error("Compaction checkpoint commit returned no identity");return H||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if(M0.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}import{createHash as y4}from"node:crypto";import{promises as Y8}from"node:fs";import K8 from"node:path";import{nanoid as R0}from"nanoid";import*as i from"node:fs/promises";import*as o0 from"node:path";var t2={enabled:!0,maxIndexLines:200};var oJ="memory",e2="MEMORY.md";class l1{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=H$($);this.memoryDir=o0.join(W,oJ)}this.config={...t2,...J}}async initialize(){if(this.initialized)return;await i.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=o0.join(this.memoryDir,e2);try{let J=await i.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -118,7 +118,7 @@ Full output saved to: ${X}`}catch{return`${J}
118
118
 
119
119
  ${Y}`}}import{Mutex as x8}from"async-mutex";import{nanoid as M8}from"nanoid";import*as j0 from"node:fs/promises";import*as V6 from"node:path";import{Mutex as q8}from"async-mutex";import O8 from"write-file-atomic";var K1=1,M$=8388608;function z6($,J){let Z={version:K1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
120
120
  `}function a1($,J){return $ instanceof Error&&"code"in $&&$.code===J}function G8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function y8($,J,Z){let W;try{W=JSON.parse($)}catch(K){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:K})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==K1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((K)=>{if(!K||typeof K!=="object"||!("id"in K)||typeof K.id!=="string"||!("content"in K)||!G8(K.content)||!("queuedAt"in K)||typeof K.queuedAt!=="number"||"persisted"in K&&typeof K.persisted!=="boolean"||"origin"in K&&K.origin!=="user"&&K.origin!=="background_subagent"||"metadata"in K&&(K.metadata===null||typeof K.metadata!=="object"||Array.isArray(K.metadata))||"outputSchema"in K&&K.outputSchema!==void 0&&(!K.outputSchema||typeof K.outputSchema!=="object"||Array.isArray(K.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let H="outputSchema"in K&&K.outputSchema!==void 0?X1(K.outputSchema).schema:void 0;return{id:K.id,content:K.content,queuedAt:K.queuedAt,..."persisted"in K&&K.persisted===!0?{persisted:!0}:{},..."origin"in K&&K.origin?{origin:K.origin}:{},..."metadata"in K&&K.metadata?{metadata:JSON.parse(JSON.stringify(K.metadata))}:{},...H?{outputSchema:H}:{}}});return{version:K1,sessionId:Z,messages:Y}}function U8($){return new Set($.flatMap((J)=>J.type==="inbox_acknowledged"?J.data.messageIds:[]))}class Q1{workspaceRoot;sessionId;filePath;mutex=new q8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new Q1($,J,H1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=z6(this.sessionId,Z);if(Buffer.byteLength(W)>M$)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:K1,sessionId:this.sessionId,messages:[]};try{if((await j0.stat(this.filePath)).size>M$)throw Error(`Steering inbox exceeds ${M$} bytes: ${this.filePath}`);await j0.chmod(this.filePath,384),$=y8(await j0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!a1(Y,"ENOENT"))throw Y}let J=z0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=U8(B6(await j0.readFile(J,"utf8"),J))}catch(Y){if(!a1(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await j0.mkdir(V6.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await j0.unlink(this.filePath).catch((W)=>{if(!a1(W,"ENOENT"))throw W});return}let Z=J??z6(this.sessionId,$);if(Buffer.byteLength(Z)>M$)throw Error(`Steering inbox exceeds ${M$} bytes: ${this.filePath}`);await O8(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as y0 from"node:fs/promises";import*as G6 from"node:path";import{nanoid as s}from"nanoid";class a0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new G0(z0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=a0.instances.get(Z);if(!W)W=new a0($,J),a0.instances.set(Z,W);return W}static release($,J){a0.instances.delete(`${J}\x00${$}`)}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);E$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($)}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z)await $.onCommitted(W)}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}E$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function z$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class A0 extends Error{}var _8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.",b8=20,N8=1e4,S8=1e5,A8=2592000000,D6=128,P8=1e6;function E8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>D6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>P8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>D6||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function y6($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,K=Y.turnId,H=Y.inputMessageIds,X=Y.turnsCount,Q=Y.toolCallsCount,z=Y.durationMs,D=Array.isArray(H)?H.filter((V)=>typeof V==="string"&&V.length>0&&V.length<=128):[];if(typeof K!=="string"||K.length===0||K.length>128||J!==void 0&&K!==J||!Array.isArray(H)||H.length>b8||D.length!==H.length||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>N8||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>S8||typeof z!=="number"||!Number.isSafeInteger(z)||z<0||z>A8)return;let q;if("goalFinalization"in Y){if(q=E8(Y.goalFinalization),!q)return}return{turnId:K,inputMessageIds:[...new Set(D)],turnsCount:X,toolCallsCount:Q,durationMs:z,...q?{goalFinalization:q}:{}}}function f8($,J){let Z=t($),W=Z.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(W<0)return;for(let Y=Z.length-1;Y>W;Y--){let K=Z[Y];if(K?.type!=="message_created")continue;let H=y6(K,J);if(H)return H}return}function T8($){let J=t($);for(let Z=J.length-1;Z>=0;Z--){let W=J[Z];if(W?.type!=="message_created")continue;let Y=y6(W);if(!Y?.goalFinalization)continue;if(!J.slice(0,Z).some((H)=>H.type==="turn_started"&&H.data.turnId===Y.turnId))continue;return{turnId:Y.turnId,finalization:Y}}return}function s1($,J){let Z=t($),W=J?Z.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J):-1;if(J&&W<0)return{all:[],orphaned:[]};let Y=new Map,K=new Set,H=new Set;for(let Q of Z.slice(W+1)){if(Q.type==="interaction_requested"){H.add(Q.data.toolCallId);continue}if(Q.type!=="part_created")continue;let z=Q.data.payload&&typeof Q.data.payload==="object"&&!Array.isArray(Q.data.payload)?Q.data.payload:{},D=typeof z.toolCallId==="string"?z.toolCallId:Q.data.partId;if(Q.data.partType==="tool_call")Y.set(D,{toolCallId:D,messageId:Q.data.messageId,toolName:typeof z.toolName==="string"?z.toolName:"unknown",input:z.input??null});else if(Q.data.partType==="tool_result")K.add(D),K.add(Q.data.partId),K.add(Q.data.messageId)}let X=[...Y.values()];return{all:X,orphaned:X.filter((Q)=>!K.has(Q.toolCallId)&&!H.has(Q.toolCallId))}}class I0{projectPath;maxSessions;version;constructor($=a(),J=100,Z=L6()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:s(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:w6(this.projectPath),version:this.version,data:Z}}log($){return a0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=z0(this.projectPath,$);if((await new G0(Z).readAll()).length>0)return;let K=new Date().toISOString(),H={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:K,updatedAt:K},X=this.createEvent("session_created",$,H);await this.log($).commit(X)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=q6;return J}async initialize(){try{let $=H$(this.projectPath);await y0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,K,H){try{await this.ensureSessionCreated($,K);let X=new Date().toISOString(),Q=s(),z={messageId:Q,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},D=this.createEvent("message_created",$,z),q=J==="assistant"&&H?.trim()?[this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:"reasoning",payload:{text:H},createdAt:X})]:[],V=typeof Z==="string"?[this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:"text",payload:{text:Z},createdAt:X})]:Z.map((w)=>this.createEvent("part_created",$,{partId:s(),messageId:Q,partType:w.type==="text"?"text":"image",payload:w.type==="text"?{text:w.text}:{mimeType:k8(w.image_url.url)??"image/png",dataUrl:w.image_url.url},createdAt:X}));return await this.log($).commitBatch([D,...q,...V]),Q}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=t(W),K=Y.some((V)=>V.type==="inbox_acknowledged"&&V.data.messageIds.includes(J.inboxMessageId)),H=Y.find((V)=>V.type==="message_created"&&V.data.inboxMessageId===J.inboxMessageId),X=Y.findLast((V)=>{if(V.type!=="part_created"||V.data.partType!=="tool_call"||!V.data.payload||typeof V.data.payload!=="object"||Array.isArray(V.data.payload))return!1;let w=V.data.payload;if(w.toolName!=="Task"||!w.input||typeof w.input!=="object"||Array.isArray(w.input))return!1;let b=w.input,T=b.resume_from??b.resume;return b.run_in_background===!0&&b.subagent_session_id===J.childSessionId&&b.description===J.subagentRef.subagentDescription&&(b.subagent_type===void 0||b.subagent_type===J.subagentRef.subagentType)&&(b.resume_from===void 0||b.resume===void 0||b.resume_from===b.resume)&&(T===void 0?J.subagentRef.subagentResumedFrom===void 0:T===J.subagentRef.subagentResumedFrom)});if(!X)return Z={eligible:!1,acknowledged:K,persisted:!1,...H?{messageId:H.data.messageId}:{}},[];if(K)return Z={eligible:!0,acknowledged:!0,persisted:!1,...H?{messageId:H.data.messageId}:{}},[];let Q=Y.find((V)=>V.type==="part_created"&&V.data.partType==="subtask_ref"&&V.data.payload!==null&&typeof V.data.payload==="object"&&!Array.isArray(V.data.payload)&&V.data.payload.childSessionId===J.childSessionId&&V.data.payload.status===J.subagentRef.subagentStatus);if(H&&Q)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:H.data.messageId},[];let z=new Date().toISOString(),D=H?.data.messageId??s(),q=[];if(!H){let V={messageId:D,role:"user",inboxMessageId:J.inboxMessageId,createdAt:z,metadata:JSON.parse(JSON.stringify(J.metadata))};q.push(this.createEvent("message_created",$,V)),q.push(this.createEvent("part_created",$,{partId:s(),messageId:D,partType:"text",payload:{text:J.content},createdAt:z}))}if(!Q){let V=Y.findLast((b)=>b.type==="part_created"&&b.data.partType==="subtask_ref"&&b.data.messageId===X.data.messageId&&b.data.payload!==null&&typeof b.data.payload==="object"&&!Array.isArray(b.data.payload)&&b.data.payload.childSessionId===J.childSessionId),w=V?.data.payload&&typeof V.data.payload==="object"&&!Array.isArray(V.data.payload)?V.data.payload:void 0;q.push(this.createEvent("part_created",$,{partId:s(),messageId:X.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof w?.startedAt==="string"?w.startedAt:z,finishedAt:z},createdAt:z}))}return Z={eligible:!0,acknowledged:!1,persisted:q.length>0,messageId:D},q}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=t(Z);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===J.turnId))throw new A0;let Y=z$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof A0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=t(W),K=new Set(Y.flatMap((z)=>z.type==="inbox_acknowledged"?z.data.messageIds:[])),H=[...new Set(Z)].filter((z)=>!K.has(z)),X=Y.findLast((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===J.turnId);if(X){if(X.type==="turn_aborted"||H.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:H,acknowledgedAt:J.completedAt})]}let Q=z$(Y).active;if(!Q||Q.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...H.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:H,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof A0))throw W}}async saveTurnAbort($,J){await this.saveTurnTerminal($,"turn_aborted",J)}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=t(J),W=z$(Z).active;return W?s1(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=t(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let K=Y.input;return K.run_in_background===!0&&typeof K.subagent_session_id==="string"?[K.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=t(W),K=z$(Y).active,H=s1(Y);if(!K&&H.orphaned.length===0)throw new A0;let X=K?f8(Y,K.turnId):void 0;if(K&&X&&H.orphaned.length===0){Z={turnId:K.turnId,outcome:"completed",finalization:X};let V=new Set(Y.flatMap((T)=>T.type==="inbox_acknowledged"?T.data.messageIds:[])),w=X.inputMessageIds.filter((T)=>!V.has(T)),b=new Date().toISOString();return[...w.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:w,acknowledgedAt:b})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:b,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs})]}Z=K?{turnId:K.turnId,outcome:"aborted"}:void 0;let Q=K?s1(Y,K.turnId).all.length:0,z=new Date().toISOString(),D=K?Date.parse(K.startedAt):Number.NaN,q=H.orphaned.flatMap((V)=>{let w=J.adoptedToolResults?.get(V.toolCallId),b=w?.toolCallId===V.toolCallId&&w.toolName===V.toolName?w:void 0,T=this.createEvent("part_created",$,{partId:V.toolCallId,messageId:b?V.messageId:V.toolCallId,partType:"tool_result",payload:b?{toolCallId:V.toolCallId,toolName:V.toolName,output:b.output,error:b.error??null,...b.metadata===void 0?{}:{metadata:b.metadata}}:{toolCallId:V.toolCallId,toolName:V.toolName,output:null,error:_8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:z});if(!b?.subagentRef)return[T];let P=b.subagentRef;return[T,this.createEvent("part_created",$,{partId:s(),messageId:V.messageId,partType:"subtask_ref",payload:{childSessionId:P.subagentSessionId,agentType:P.subagentType,description:P.subagentDescription??"",status:P.subagentStatus,summary:P.subagentSummary??"",resumedFrom:P.subagentResumedFrom??null,rootAgentId:P.subagentRootId??P.subagentSessionId,resumeDepth:P.subagentResumeDepth??0,verificationVerdict:P.verificationVerdict??null,startedAt:z,finishedAt:z},createdAt:z})]});return K?[...q,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:z,turnsCount:0,toolCallsCount:Q,durationMs:Number.isFinite(D)?Math.max(0,Date.now()-D):0})]:q})}catch(W){if(!(W instanceof A0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?T8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="interaction_requested"&&K.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((K)=>K.type==="interaction_responded"&&K.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="interaction_responded"&&K.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((K)=>K.type==="interaction_recovered"&&K.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((K)=>K.type==="review_started"&&K.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((K)=>K.type==="review_started"&&!Z.some((H)=>H.type==="review_completed"&&H.data.reviewId===K.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="review_started"&&K.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y){try{await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),H=W??s(),X=[];if(!W){let D={messageId:H,role:"assistant",parentMessageId:void 0,createdAt:K};X.push(this.createEvent("message_created",$,D))}let Q=s(),z={partId:Q,messageId:H,partType:"tool_call",payload:{toolCallId:Q,toolName:J,input:Z},createdAt:K};if(X.push(this.createEvent("part_created",$,z)),J==="Task"&&Z&&typeof Z==="object"){let D=Z,q=typeof D.subagent_session_id==="string"?D.subagent_session_id:void 0,V=typeof D.subagent_type==="string"?D.subagent_type:void 0;if(q&&V){let w={partId:s(),messageId:H,partType:"subtask_ref",payload:{childSessionId:q,agentType:V,status:"running",summary:typeof D.description==="string"?D.description:"",startedAt:K},createdAt:K};X.push(this.createEvent("part_created",$,w))}}return await this.log($).commitBatch(X),Q}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,J,Z,W,Y=null,K,H,X,Q){try{await this.ensureSessionCreated($,H);let z=new Date().toISOString(),D=Y??s();return await this.log($).commitValidatedBatch((q)=>{let V=X?.subagentStatus==="running"?t(q).findLast((k)=>k.type==="part_created"&&k.data.partType==="subtask_ref"&&k.data.payload!==null&&typeof k.data.payload==="object"&&!Array.isArray(k.data.payload)&&k.data.payload.childSessionId===X.subagentSessionId&&(k.data.payload.status==="completed"||k.data.payload.status==="failed"||k.data.payload.status==="cancelled")):void 0,w=V?.data.payload,b=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},T=w?{...b,subagentSessionId:w.childSessionId,subagentType:w.agentType,description:w.description,subagentStatus:w.status,subagentSummary:w.summary,subagentResumedFrom:w.resumedFrom,subagentRootId:w.rootAgentId,subagentResumeDepth:w.resumeDepth,verificationVerdict:w.verificationVerdict}:Q,P=[];if(!Y){let k={messageId:D,role:"assistant",parentMessageId:void 0,createdAt:z};P.push(this.createEvent("message_created",$,k))}let x={partId:J,messageId:D,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:K??null,...T===void 0?{}:{metadata:T}},createdAt:z};if(P.push(this.createEvent("part_created",$,x)),X&&!V){let k=X.subagentStatus==="running"?null:z,W0={partId:s(),messageId:D,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:z,finishedAt:k},createdAt:z};P.push(this.createEvent("part_created",$,W0))}return P}),J}catch(z){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,z),z}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=s(),H={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(Z),Q={partId:s(),messageId:K,partType:"summary",payload:{text:J,metadata:X,...Z.replacementMessages?{replacementMessages:O6(Z.replacementMessages)}:{}},createdAt:Y},z=[this.createEvent("message_created",$,H),this.createEvent("part_created",$,Q)];return await this.log($).commitBatch(z),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=z0(this.projectPath,$),W=await new G0(J).readAll();return W.length>0?t(W):null}catch{return null}}async loadSession($){try{let J=z0(this.projectPath,$),Z=new G0(J),W=t(await Z.readAll());if(W.length===0)return null;let Y=W.find((K)=>K.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=z0(this.projectPath,$),Z=new G0(J),W=t(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let Q of W){if(Q.type==="message_created")Y.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let z=Y.get(Q.data.messageId);if(z){let D=Q.data.payload;z.content=D.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let z=Y.get(Q.data.messageId);if(z)z.content=z.content?`${z.content}
121
- [Image]`:"[Image]"}}let K=Array.from(Y.values()),H=W[W.length-1],X=new Date(H.timestamp).getTime();return{messages:K,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=H$(this.projectPath);return(await y0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=z0(this.projectPath,$),Z=new G0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let K=t(Y),H=Y[Y.length-1],X=K.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=z0(this.projectPath,$);await new G0(J).delete(),await y0.unlink(H1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-rj1z55m8.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,J,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let Y=t(W);if(Y.some((X)=>(X.type==="turn_completed"||X.type==="turn_aborted")&&X.data.turnId===Z.turnId))throw new A0;let H=z$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return J==="turn_completed"?this.createEvent("turn_completed",$,Z):this.createEvent("turn_aborted",$,Z)})}catch(W){if(!(W instanceof A0))throw W}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=z0(this.projectPath,Z),K=await new G0(W).getStats();J+=K.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=H$(this.projectPath);await y0.mkdir($,{recursive:!0,mode:493});let J=G6.join($,".health-check");return await y0.writeFile(J,"test","utf-8"),await y0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return j6()}}function k8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var U6=131072,F6=new Map;function t1($,J){let Z=`${$}\x00${J}`,W=F6.get(Z);if(!W)W=new x8,F6.set(Z,W);return W}function J2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>U6)throw Error(`${J} exceeds ${U6} bytes`);return JSON.parse(Z)}function _6($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function h8($,J){return JSON.stringify($)===JSON.stringify(J)}function R8($,J){if($.request.interactionType!=="elicitation")return J2(J,"Interaction response");return J2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function b6($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function C8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function I8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
121
+ [Image]`:"[Image]"}}let K=Array.from(Y.values()),H=W[W.length-1],X=new Date(H.timestamp).getTime();return{messages:K,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=H$(this.projectPath);return(await y0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=z0(this.projectPath,$),Z=new G0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let K=t(Y),H=Y[Y.length-1],X=K.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=z0(this.projectPath,$);await new G0(J).delete(),await y0.unlink(H1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-22pmyhp9.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,J,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let Y=t(W);if(Y.some((X)=>(X.type==="turn_completed"||X.type==="turn_aborted")&&X.data.turnId===Z.turnId))throw new A0;let H=z$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return J==="turn_completed"?this.createEvent("turn_completed",$,Z):this.createEvent("turn_aborted",$,Z)})}catch(W){if(!(W instanceof A0))throw W}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=z0(this.projectPath,Z),K=await new G0(W).getStats();J+=K.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=H$(this.projectPath);await y0.mkdir($,{recursive:!0,mode:493});let J=G6.join($,".health-check");return await y0.writeFile(J,"test","utf-8"),await y0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return j6()}}function k8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var U6=131072,F6=new Map;function t1($,J){let Z=`${$}\x00${J}`,W=F6.get(Z);if(!W)W=new x8,F6.set(Z,W);return W}function J2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>U6)throw Error(`${J} exceeds ${U6} bytes`);return JSON.parse(Z)}function _6($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function h8($,J){return JSON.stringify($)===JSON.stringify(J)}function R8($,J){if($.request.interactionType!=="elicitation")return J2(J,"Interaction response");return J2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function b6($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function C8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function I8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
122
122
  `)}function v8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let H=I8(J);return{toolOutput:`User answers:
123
123
  ${H}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
124
124
  ${H}
@@ -140,7 +140,7 @@ When facing complex multi-step tasks:
140
140
  3. If a step fails, diagnose the root cause rather than repeating the same approach.
141
141
  4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
142
142
  5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function p0($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function t6($){let J=$.trim();if(J=J.replace(/,\s*([}\]])/g,"$1"),J.startsWith("{")&&!J.endsWith("}"))J+="}";J=J.replace(/,\s*([}\]])/g,"$1");try{let Z=JSON.parse(J);if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))return Z;return null}catch{return null}}function I$($){let J=t6($);if(J)return J;try{let Z=JSON.parse($);return typeof Z==="string"?t6(Z):null}catch{return null}}function A4($){let J=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(J?.contextualProjectRules!==!0)return[];if(!Array.isArray(J.ruleReferences))throw Error("Invalid contextual project rule provenance");return J.ruleReferences.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid contextual project rule reference");let W=Z;if(typeof W.id!=="string"||typeof W.relativePath!=="string"||!["project","local"].includes(String(W.source))||typeof W.contentSha256!=="string"||!/^[a-f0-9]{64}$/u.test(W.contentSha256))throw Error("Invalid contextual project rule reference");return{id:W.id,relativePath:W.relativePath,source:W.source,contentSha256:W.contentSha256}})}function V$($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function P4($){let J=new Set,Z=!1;for(let W of $){if(W.role==="assistant"){if(W.tool_calls&&W.tool_calls.length>0){for(let K of W.tool_calls)if("function"in K&&K.function.name==="Task")J.add(K.id)}else if(Z)Z=!1;continue}if(W.role!=="tool"||W.name!=="Task"||!W.tool_call_id||!J.has(W.tool_call_id)||typeof W.metadata!=="object"||W.metadata===null||Array.isArray(W.metadata))continue;let Y=W.metadata;if(Y.toolCallId===W.tool_call_id&&Y.toolName==="Task"&&Y.error===null)Z=!0}return Z}function E4($){if(!($ instanceof Error))return"未知错误";let W=$.lastError??$;if(W.responseBody)try{let X=JSON.parse(W.responseBody)?.error?.message;if(X){let Q=W.statusCode?` (HTTP ${W.statusCode})`:"";return`${X}${Q}`}}catch{}let Y=$.message,K=Y.match(/Last error:\s*(.+)$/);if(K)return K[1];return Y}function f4($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((Z)=>$.message.toLowerCase().includes(Z.toLowerCase()))}function T4($,J){if(!J)return"Tool execution failed (no details).";let Z=[`Error: ${J.message||"Unknown error"}`];if(J.type==="validation_error")Z.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(J.type==="permission_denied")Z.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(J.type==="timeout_error")Z.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(J.type==="execution_error"){let W=J.message??"";if(W.includes("ENOENT")||W.includes("no such file"))Z.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(W.includes("EACCES")||W.includes("permission"))Z.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(W.includes("not found in file")||W.includes("old_string"))Z.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${$} with the exact text.`);else if(W.includes("ENOTDIR"))Z.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return Z.join(`
143
- `)}function j2($){if(!($ instanceof Error))return!1;return JJ($)||$.status===413}function k4($,J){let Z=J,W=Z.index??0;if(!$.has(W))$.set(W,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let Y=$.get(W);if(Z.id&&!Y.id)Y.id=Z.id;if(Z.function?.name&&!Y.name)Y.name=Z.function.name;if(Z.function?.arguments)Y.arguments+=Z.function.arguments}function x4($){if($.size===0)return;return Array.from($.values()).filter((J)=>J.id&&J.name).map((J)=>({id:J.id,type:"function",function:{name:J.name,arguments:J.arguments}}))}async function*M4($,J,Z,W,Y,K){let H="",X="",Q,z,D=new Map;try{let q=$.chatService.streamChat(J,Z,W,Y),V=0;for await(let w of q){if(W?.aborted)break;if(w.providerRetry){yield{kind:"provider_retry",...w.providerRetry};continue}if(w.providerStall){yield{kind:"provider_stall",...w.providerStall};continue}if(V++,w.modelFallback){K?.discard(),H="",X="",Q=void 0,z=void 0,D.clear(),V=0,yield{kind:"model_fallback"};continue}if(w.content)H+=w.content,yield{kind:"content_delta",delta:w.content};if(w.reasoningContent)X+=w.reasoningContent,yield{kind:"thinking_delta",delta:w.reasoningContent};if(w.usage)Q=w.usage;if(w.toolCalls){for(let b of w.toolCalls)if(k4(D,b),K){let P=b.index??0,x=D.get(P);if(x&&x.id&&x.name)try{let k=I$(x.arguments);if(k===null)continue;let W0={id:x.id,type:"function",function:{name:x.name,arguments:x.arguments}},B0=$.toolExecutor.getRegistry().get(x.name)?.kind,O=K.addTool(W0,k);if(x.arguments=W0.function.arguments,O==="prelaunched")yield{kind:"tool_start",toolCall:W0,toolKind:B0}}catch{}}}if(w.finishReason){z=w.finishReason;break}}if(V===0&&!W?.aborted&&H.length===0&&D.size===0)return I.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),K?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};return{content:H,reasoningContent:X||void 0,toolCalls:x4(D),usage:Q,finishReason:z}}catch(q){if(f4(q))return I.warn("[Loop] 流式请求失败,降级到非流式模式"),K?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};throw q}}async function*YJ($,J,Z,W,Y,K,H,X){if(W===void 0)return I.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Q=Y6(J.messages,K);if(Q)J.messages=Q.messages,I.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${Q.snippedCount} 轮旧工具结果(缓存已过期)`);let z=k$(J.messages),D=!1;if(z.snippedCount>0)D=!0,I.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${z.snippedCount} 轮旧工具调用,释放约 ${z.estimatedTokensFreed} tokens`);let q=$.chatService.getConfig(),V=q.model,w=q.maxContextTokens??0,b=q.maxOutputTokens??$.config.maxOutputTokens??Math.min(Math.max(Math.floor(w*U4),F4),_4),T=w-b;if(w<=0||T<=0){if(D)J.messages=z.messages;return I.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(模型上下文窗口未知)`),D?"snipped":"none"}let P=Math.floor(T*0.8);if(I.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{promptTokens:W,maxContextTokens:w,maxOutputTokens:b,availableForInput:T,threshold:P,shouldCompact:W>=P}),W<P){if(D)J.messages=z.messages;return D?"snipped":"none"}let x=X?.lastCompactionTurn===void 0?void 0:Z-X.lastCompactionTurn,k=x!==void 0&&x<=b4,W0=Math.floor(T*N4);if(k&&W<W0){if(D)J.messages=z.messages;return I.debug(`[Loop] [轮次 ${Z}] 跳过连续 LLM 压缩,距离上次压缩 ${x} 轮`),D?"snipped":"none"}I.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`);let L0="failed",B0,O,g0;yield{kind:"compaction",phase:"start",reason:"threshold"};try{let p=D?z.messages:J.messages,R=await X$.compact(p,{trigger:"auto",modelName:V,modelProvider:q.provider,maxContextTokens:w,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:W,signal:Y,activeTask:H,workspaceRoot:J.workspaceRoot||a(),sessionId:J.sessionId});if(R.usage)yield{kind:"token_usage",usage:O1(R.usage,w)};if(B0=R.success?"llm":"fallback",O=R.preTokens,g0=R.postTokens,R.success)I.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${R.preTokens} -> ${R.postTokens} tokens`);else I.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${R.preTokens} -> ${R.postTokens} tokens`);if(await T$($,J,R.summary,{trigger:"auto",reason:"threshold",strategy:B0,preTokens:R.preTokens,postTokens:R.postTokens,filesIncluded:R.filesIncluded,replacementMessages:R.compactedMessages},{required:$.executionEngine!==void 0}),J.messages=R.compactedMessages,X)X.lastCompactionTurn=Z;return L0=R.success?"completed":"fallback","compacted"}catch(p){if(C0(p))return I.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),"none";if(D)J.messages=z.messages;return I.error(`[Loop] [轮次 ${Z}] 压缩失败,继续执行`,p),D?"snipped":"none"}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:L0,strategy:B0,preTokens:O,postTokens:g0}}}function h4($,J,Z,W){let Y=W?$J(W):"user-cancel";return{success:!1,error:{type:"aborted",message:(Y==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z,abortReason:Y}}}function e6($,J,Z){return{success:!1,error:{type:"tool_persistence_failed",message:o2},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}async function*R4($,J,Z,W,Y){let K=Date.now(),H=0,X=[],Q=null,z=!1,D=(q,V,w)=>{return z=!0,h4(q,V,K,w)};try{let q=$.toolExecutor.getRegistry(),V=Z.permissionMode,w=W?.outputSchema?X1(W.outputSchema):void 0,b=()=>{let G=$.applySkillToolRestrictions(q.getFunctionDeclarationsByMode(V));if(!w)return G;return[...G.filter((y)=>y.name!==U0),w.declaration]},T=f6(),P=R6(),x=A6(),k=Y;if(typeof q.getDeferredToolsListing==="function"){let G=q.getDeferredToolsListing();if(G&&k)k=`${k}
143
+ `)}function j2($){if(!($ instanceof Error))return!1;return JJ($)||$.status===413}function k4($,J){let Z=J,W=Z.index??0;if(!$.has(W))$.set(W,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let Y=$.get(W);if(Z.id&&!Y.id)Y.id=Z.id;if(Z.function?.name&&!Y.name)Y.name=Z.function.name;if(Z.function?.arguments)Y.arguments+=Z.function.arguments}function x4($){if($.size===0)return;return Array.from($.values()).filter((J)=>J.id&&J.name).map((J)=>({id:J.id,type:"function",function:{name:J.name,arguments:J.arguments}}))}async function*M4($,J,Z,W,Y,K){let H="",X="",Q,z,D=new Map;try{let q=$.chatService.streamChat(J,Z,W,Y),V=0;for await(let w of q){if(W?.aborted)break;if(w.providerCircuit){yield{kind:"provider_circuit",...w.providerCircuit};continue}if(w.providerRetry){yield{kind:"provider_retry",...w.providerRetry};continue}if(w.providerStall){yield{kind:"provider_stall",...w.providerStall};continue}if(V++,w.modelFallback){K?.discard(),H="",X="",Q=void 0,z=void 0,D.clear(),V=0,yield{kind:"model_fallback"};continue}if(w.content)H+=w.content,yield{kind:"content_delta",delta:w.content};if(w.reasoningContent)X+=w.reasoningContent,yield{kind:"thinking_delta",delta:w.reasoningContent};if(w.usage)Q=w.usage;if(w.toolCalls){for(let b of w.toolCalls)if(k4(D,b),K){let P=b.index??0,x=D.get(P);if(x&&x.id&&x.name)try{let k=I$(x.arguments);if(k===null)continue;let W0={id:x.id,type:"function",function:{name:x.name,arguments:x.arguments}},B0=$.toolExecutor.getRegistry().get(x.name)?.kind,O=K.addTool(W0,k);if(x.arguments=W0.function.arguments,O==="prelaunched")yield{kind:"tool_start",toolCall:W0,toolKind:B0}}catch{}}}if(w.finishReason){z=w.finishReason;break}}if(V===0&&!W?.aborted&&H.length===0&&D.size===0)return I.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),K?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};return{content:H,reasoningContent:X||void 0,toolCalls:x4(D),usage:Q,finishReason:z}}catch(q){if(f4(q))return I.warn("[Loop] 流式请求失败,降级到非流式模式"),K?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};throw q}}async function*YJ($,J,Z,W,Y,K,H,X){if(W===void 0)return I.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let Q=Y6(J.messages,K);if(Q)J.messages=Q.messages,I.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${Q.snippedCount} 轮旧工具结果(缓存已过期)`);let z=k$(J.messages),D=!1;if(z.snippedCount>0)D=!0,I.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${z.snippedCount} 轮旧工具调用,释放约 ${z.estimatedTokensFreed} tokens`);let q=$.chatService.getConfig(),V=q.model,w=q.maxContextTokens??0,b=q.maxOutputTokens??$.config.maxOutputTokens??Math.min(Math.max(Math.floor(w*U4),F4),_4),T=w-b;if(w<=0||T<=0){if(D)J.messages=z.messages;return I.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(模型上下文窗口未知)`),D?"snipped":"none"}let P=Math.floor(T*0.8);if(I.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{promptTokens:W,maxContextTokens:w,maxOutputTokens:b,availableForInput:T,threshold:P,shouldCompact:W>=P}),W<P){if(D)J.messages=z.messages;return D?"snipped":"none"}let x=X?.lastCompactionTurn===void 0?void 0:Z-X.lastCompactionTurn,k=x!==void 0&&x<=b4,W0=Math.floor(T*N4);if(k&&W<W0){if(D)J.messages=z.messages;return I.debug(`[Loop] [轮次 ${Z}] 跳过连续 LLM 压缩,距离上次压缩 ${x} 轮`),D?"snipped":"none"}I.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`);let L0="failed",B0,O,g0;yield{kind:"compaction",phase:"start",reason:"threshold"};try{let p=D?z.messages:J.messages,R=await X$.compact(p,{trigger:"auto",modelName:V,modelProvider:q.provider,maxContextTokens:w,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:W,signal:Y,activeTask:H,workspaceRoot:J.workspaceRoot||a(),sessionId:J.sessionId});if(R.usage)yield{kind:"token_usage",usage:O1(R.usage,w)};if(B0=R.success?"llm":"fallback",O=R.preTokens,g0=R.postTokens,R.success)I.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${R.preTokens} -> ${R.postTokens} tokens`);else I.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${R.preTokens} -> ${R.postTokens} tokens`);if(await T$($,J,R.summary,{trigger:"auto",reason:"threshold",strategy:B0,preTokens:R.preTokens,postTokens:R.postTokens,filesIncluded:R.filesIncluded,replacementMessages:R.compactedMessages},{required:$.executionEngine!==void 0}),J.messages=R.compactedMessages,X)X.lastCompactionTurn=Z;return L0=R.success?"completed":"fallback","compacted"}catch(p){if(C0(p))return I.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),"none";if(D)J.messages=z.messages;return I.error(`[Loop] [轮次 ${Z}] 压缩失败,继续执行`,p),D?"snipped":"none"}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:L0,strategy:B0,preTokens:O,postTokens:g0}}}function h4($,J,Z,W){let Y=W?$J(W):"user-cancel";return{success:!1,error:{type:"aborted",message:(Y==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z,abortReason:Y}}}function e6($,J,Z){return{success:!1,error:{type:"tool_persistence_failed",message:o2},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}async function*R4($,J,Z,W,Y){let K=Date.now(),H=0,X=[],Q=null,z=!1,D=(q,V,w)=>{return z=!0,h4(q,V,K,w)};try{let q=$.toolExecutor.getRegistry(),V=Z.permissionMode,w=W?.outputSchema?X1(W.outputSchema):void 0,b=()=>{let G=$.applySkillToolRestrictions(q.getFunctionDeclarationsByMode(V));if(!w)return G;return[...G.filter((y)=>y.name!==U0),w.declaration]},T=f6(),P=R6(),x=A6(),k=Y;if(typeof q.getDeferredToolsListing==="function"){let G=q.getDeferredToolsListing();if(G&&k)k=`${k}
144
144
 
145
145
  ${G}`}if(k)k+=S4;if(w)k=`${k??""}
146
146