blade-code 0.10.32 → 0.10.34

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 (103) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-6r89cn2n.js → chunk-00gwp388.js} +2 -2
  3. package/dist/{chunk-7xytd1h7.js → chunk-0kqp5z4v.js} +2 -2
  4. package/dist/{chunk-b0mha3tr.js → chunk-1142vwqa.js} +2 -2
  5. package/dist/{chunk-ntmfefxh.js → chunk-16449n3m.js} +2 -2
  6. package/dist/{chunk-mwae107k.js → chunk-1ep6bcpc.js} +1 -1
  7. package/dist/{chunk-3bhh4v42.js → chunk-1qj0qms6.js} +1 -1
  8. package/dist/chunk-2c8d4q3y.js +1 -0
  9. package/dist/{chunk-tx77qaz8.js → chunk-2gca6fvf.js} +2 -2
  10. package/dist/{chunk-s61wcay9.js → chunk-2sdbj0zz.js} +2 -2
  11. package/dist/{chunk-xh1y705a.js → chunk-3ctcv013.js} +2 -2
  12. package/dist/{chunk-80r40y6k.js → chunk-3j6bsp1q.js} +2 -2
  13. package/dist/{chunk-774excyf.js → chunk-58gk92k3.js} +1 -1
  14. package/dist/chunk-5f956qbf.js +1 -0
  15. package/dist/{chunk-r68y2q62.js → chunk-5knt529c.js} +2 -2
  16. package/dist/{chunk-rakyf5b7.js → chunk-5v642sh3.js} +2 -2
  17. package/dist/{chunk-w49crtzx.js → chunk-64f79ce5.js} +2 -2
  18. package/dist/{chunk-cdkrdsbw.js → chunk-7a8k7ck4.js} +1 -1
  19. package/dist/{chunk-g2gvcp09.js → chunk-7afbvxqt.js} +1 -1
  20. package/dist/{chunk-75y3mb0z.js → chunk-7ryqs453.js} +2 -2
  21. package/dist/chunk-87ge6dkk.js +2 -0
  22. package/dist/chunk-958rac3y.js +1 -0
  23. package/dist/{chunk-q4q0r97b.js → chunk-95jjpdh9.js} +2 -2
  24. package/dist/{chunk-7bpwnpfx.js → chunk-ag0z1q2q.js} +2 -2
  25. package/dist/chunk-ap5qpeh4.js +1 -0
  26. package/dist/{chunk-e66zyvph.js → chunk-b9y9mc7f.js} +1 -1
  27. package/dist/{chunk-2tb3qm3v.js → chunk-ba2dky3s.js} +1 -1
  28. package/dist/{chunk-799zdv81.js → chunk-bx99mx3k.js} +1 -1
  29. package/dist/{chunk-3ck3fxff.js → chunk-c23bewtt.js} +1 -1
  30. package/dist/chunk-c6fq52m9.js +1 -0
  31. package/dist/{chunk-bcs58pet.js → chunk-crwa61tq.js} +1 -1
  32. package/dist/{chunk-yekzckgm.js → chunk-d3gx05ph.js} +3 -3
  33. package/dist/{chunk-xhdm1b4g.js → chunk-d90tnjst.js} +1 -1
  34. package/dist/{chunk-c7b5wmpm.js → chunk-dsxjgty6.js} +2 -2
  35. package/dist/{chunk-7fgx7ztz.js → chunk-dvf4cfye.js} +1 -1
  36. package/dist/chunk-dvyv53nz.js +1 -0
  37. package/dist/chunk-ecsj4njh.js +1 -0
  38. package/dist/chunk-epyys9aw.js +6 -0
  39. package/dist/{chunk-azcjz03h.js → chunk-fb80q06q.js} +2 -2
  40. package/dist/{chunk-bmsv08sa.js → chunk-fjbptkh2.js} +2 -2
  41. package/dist/chunk-fw1fm9cn.js +2 -0
  42. package/dist/{chunk-fp1892aa.js → chunk-g0gqxn3c.js} +1 -1
  43. package/dist/{chunk-x0x5e65d.js → chunk-h34g9v9z.js} +1 -1
  44. package/dist/chunk-h3cvnbah.js +1 -0
  45. package/dist/{chunk-cjgnf6qy.js → chunk-jdms602t.js} +1 -1
  46. package/dist/chunk-jh6b81rb.js +10 -0
  47. package/dist/chunk-mr0xs5t4.js +22 -0
  48. package/dist/{chunk-wmsak7d3.js → chunk-mxffhqe5.js} +239 -239
  49. package/dist/{chunk-nah8b1gv.js → chunk-nq1wqpsx.js} +1 -1
  50. package/dist/chunk-p01t6c78.js +4 -0
  51. package/dist/{chunk-8y2nh9sm.js → chunk-pgy1mtgw.js} +1 -1
  52. package/dist/{chunk-y5rsamex.js → chunk-pnjftj8t.js} +2 -2
  53. package/dist/{chunk-fb514tmd.js → chunk-prqgpq92.js} +1 -1
  54. package/dist/{chunk-b0en9trj.js → chunk-qd7r2w39.js} +1 -1
  55. package/dist/chunk-qr8j2mr6.js +1 -0
  56. package/dist/{chunk-6gngfvwt.js → chunk-rjg5rq90.js} +1 -1
  57. package/dist/{chunk-jtk2t4wy.js → chunk-s1j86hhh.js} +19 -19
  58. package/dist/chunk-s3sv04hf.js +1 -0
  59. package/dist/{chunk-aspqajv2.js → chunk-sexhm0r5.js} +1 -1
  60. package/dist/{chunk-qgvgd1kq.js → chunk-sgyk3gq1.js} +2 -2
  61. package/dist/chunk-sjc7bm23.js +1 -0
  62. package/dist/{chunk-t23t9yff.js → chunk-t1z46fqz.js} +1 -1
  63. package/dist/chunk-tvrxzsna.js +1 -0
  64. package/dist/{chunk-b4xcn24b.js → chunk-v6x80gdg.js} +1 -1
  65. package/dist/{chunk-z1qa6vm5.js → chunk-vfecv6cv.js} +1 -1
  66. package/dist/chunk-vhpvt5v8.js +1 -0
  67. package/dist/{chunk-14zhd8qs.js → chunk-vqqxjgf2.js} +1 -1
  68. package/dist/chunk-wz6atg87.js +8 -0
  69. package/dist/{chunk-5mszemkz.js → chunk-y9a1jwnv.js} +2 -2
  70. package/dist/{chunk-7m4qc5vv.js → chunk-ysr3frmw.js} +1 -1
  71. package/dist/chunk-zp9p9tk6.js +1 -0
  72. package/dist/web/assets/{ChatView-D2g5ADlO.js → ChatView-B7_Um8KR.js} +2 -2
  73. package/dist/web/assets/{CodeBlockHighlighter-CheLBzlr.js → CodeBlockHighlighter-JzE91vkT.js} +1 -1
  74. package/dist/web/assets/{FilePreview-DWiuoQOM.js → FilePreview-BTbtoUBJ.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-C8h_WRI9.js → MarkdownRenderer-IaPtOh2w.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-CKIKFL6a.js → SettingsModal-CPgWPfZ2.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-DMaOLa_m.js → TaskSwitcher-D4RZxQKp.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-BXLKU2zU.js → TerminalPanel-yWbQfbYa.js} +1 -1
  79. package/dist/web/assets/{index-CxwsVMYL.js → index-BnCT8SxR.js} +8 -8
  80. package/dist/web/assets/{session-events-BZdQ71sF.js → session-events-BZao_jMQ.js} +20 -20
  81. package/dist/web/index.html +2 -2
  82. package/package.json +1 -1
  83. package/dist/chunk-191xtaca.js +0 -1
  84. package/dist/chunk-273ak5v8.js +0 -10
  85. package/dist/chunk-2969c7yb.js +0 -22
  86. package/dist/chunk-2jr254j7.js +0 -4
  87. package/dist/chunk-42ns4a92.js +0 -1
  88. package/dist/chunk-758hxypj.js +0 -2
  89. package/dist/chunk-9r0fxre0.js +0 -1
  90. package/dist/chunk-fd5dzcht.js +0 -1
  91. package/dist/chunk-gs18nx4h.js +0 -1
  92. package/dist/chunk-gy51z423.js +0 -1
  93. package/dist/chunk-hdje6ywy.js +0 -1
  94. package/dist/chunk-jdq05trf.js +0 -3
  95. package/dist/chunk-mspp2qpn.js +0 -1
  96. package/dist/chunk-qe49h8e0.js +0 -6
  97. package/dist/chunk-rzxk60wq.js +0 -1
  98. package/dist/chunk-sfhevsq1.js +0 -1
  99. package/dist/chunk-t23a5yvk.js +0 -1
  100. package/dist/chunk-txqctnca.js +0 -1
  101. package/dist/chunk-w0wzx47n.js +0 -1
  102. package/dist/chunk-x1r4b7pt.js +0 -2
  103. package/dist/chunk-yvwmfddz.js +0 -1
@@ -1,22 +1,22 @@
1
- var Se=Object.defineProperty;var ye=(e,t,n)=>t in e?Se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var K=(e,t,n)=>ye(e,typeof t!="symbol"?t+"":t,n);function M(){return{timeline:[],textBefore:"",toolCalls:[],textAfter:"",thinkingContent:"",tasks:[],subagent:null,subagents:[],confirmation:null,question:null,elicitation:null}}function N(e){return e?e.subagents&&e.subagents.length>0?e.subagents:e.subagent?[e.subagent]:[]:[]}function J(e,t,n){const a=(n?t.find(o=>o.id===n||o.sessionId===n):void 0)??t[t.length-1]??null;return{...e,subagents:t,subagent:a}}function re(e,t){const n=[...N(e)];let a=n.findIndex(s=>s.id===t.id||!!(s.sessionId&&t.sessionId&&s.sessionId===t.sessionId));if(a===-1&&t.sessionId&&(a=n.findIndex(s=>!s.sessionId&&s.status==="running"&&s.type===t.type&&s.description===t.description)),a===-1)return n.push(t),J(e,n,t.id);const o=n[a],u={...o,...t,id:o.id};return n[a]=u,J(e,n,u.id)}function G(e,t){return`${t}-${e.length}`}function he(e,t){if(!t)return e;const n=[...j(e)],a=n[n.length-1];return(a==null?void 0:a.type)==="text"?n[n.length-1]={...a,content:a.content+t}:n.push({id:G(n,"text"),type:"text",content:t}),{...e,timeline:n}}function Ce(e,t){if(!t)return e;const n=[...j(e)],a=n[n.length-1];return(a==null?void 0:a.type)==="thinking"?n[n.length-1]={...a,content:a.content+t}:n.push({id:G(n,"thinking"),type:"thinking",content:t}),{...e,timeline:n}}function oe(e,t){const n=e.toolCalls.some(s=>s.toolCallId===t.toolCallId),a=n?e.toolCalls:[...e.toolCalls,t];if(n)return{...e,toolCalls:a};const o=[...j(e)],u=o[o.length-1];return(u==null?void 0:u.type)==="tool_group"?o[o.length-1]={...u,toolCallIds:[...u.toolCallIds,t.toolCallId]}:o.push({id:G(o,"tool_group"),type:"tool_group",toolCallIds:[t.toolCallId]}),{...e,timeline:o,toolCalls:a}}function j(e){if(e.timeline&&e.timeline.length>0)return e.timeline;const t=[];return e.thinkingContent&&t.push({id:"legacy-thinking",type:"thinking",content:e.thinkingContent}),e.textBefore&&t.push({id:"legacy-text-before",type:"text",content:e.textBefore}),e.toolCalls.length>0&&t.push({id:"legacy-tool-group",type:"tool_group",toolCallIds:e.toolCalls.map(n=>n.toolCallId)}),e.textAfter&&t.push({id:"legacy-text-after",type:"text",content:e.textAfter}),t}function be(e){return j(e).filter(t=>t.type==="text").map(t=>t.content).filter(Boolean).join(`
1
+ var he=Object.defineProperty;var ye=(e,t,n)=>t in e?he(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var K=(e,t,n)=>ye(e,typeof t!="symbol"?t+"":t,n);function M(){return{timeline:[],textBefore:"",toolCalls:[],textAfter:"",thinkingContent:"",tasks:[],subagent:null,subagents:[],confirmation:null,question:null,elicitation:null}}function N(e){return e?e.subagents&&e.subagents.length>0?e.subagents:e.subagent?[e.subagent]:[]:[]}function B(e,t,n){const a=(n?t.find(o=>o.id===n||o.sessionId===n):void 0)??t[t.length-1]??null;return{...e,subagents:t,subagent:a}}function ue(e,t){const n=[...N(e)];let a=n.findIndex(s=>s.id===t.id||!!(s.sessionId&&t.sessionId&&s.sessionId===t.sessionId));if(a===-1&&t.sessionId&&(a=n.findIndex(s=>!s.sessionId&&s.status==="running"&&s.type===t.type&&s.description===t.description)),a===-1)return n.push(t),B(e,n,t.id);const o=n[a],u={...o,...t,id:o.id};return n[a]=u,B(e,n,u.id)}function H(e,t){return`${t}-${e.length}`}function Ce(e,t){if(!t)return e;const n=[...j(e)],a=n[n.length-1];return(a==null?void 0:a.type)==="text"?n[n.length-1]={...a,content:a.content+t}:n.push({id:H(n,"text"),type:"text",content:t}),{...e,timeline:n}}function be(e,t){if(!t)return e;const n=[...j(e)],a=n[n.length-1];return(a==null?void 0:a.type)==="thinking"?n[n.length-1]={...a,content:a.content+t}:n.push({id:H(n,"thinking"),type:"thinking",content:t}),{...e,timeline:n}}function oe(e,t){const n=e.toolCalls.some(s=>s.toolCallId===t.toolCallId),a=n?e.toolCalls:[...e.toolCalls,t];if(n)return{...e,toolCalls:a};const o=[...j(e)],u=o[o.length-1];return(u==null?void 0:u.type)==="tool_group"?o[o.length-1]={...u,toolCallIds:[...u.toolCallIds,t.toolCallId]}:o.push({id:H(o,"tool_group"),type:"tool_group",toolCallIds:[t.toolCallId]}),{...e,timeline:o,toolCalls:a}}function j(e){if(e.timeline&&e.timeline.length>0)return e.timeline;const t=[];return e.thinkingContent&&t.push({id:"legacy-thinking",type:"thinking",content:e.thinkingContent}),e.textBefore&&t.push({id:"legacy-text-before",type:"text",content:e.textBefore}),e.toolCalls.length>0&&t.push({id:"legacy-tool-group",type:"tool_group",toolCallIds:e.toolCalls.map(n=>n.toolCallId)}),e.textAfter&&t.push({id:"legacy-text-after",type:"text",content:e.textAfter}),t}function ve(e){return j(e).filter(t=>t.type==="text").map(t=>t.content).filter(Boolean).join(`
2
2
 
3
- `)}const ve=2166136261,Ae=16777619;function L(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.map(t=>L(t)).join(",")}]`:typeof e=="object"?`{${Object.entries(e).sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>`${JSON.stringify(n)}:${L(a)}`).join(",")}}`:JSON.stringify(e)}function ue(e){let t=ve>>>0;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,Ae);return(t>>>0).toString(16)}function de(e){return typeof e=="string"?e:L(e??{})}function Q(e){return e==="completed"?"completed":e==="failed"||e==="cancelled"?"failed":"running"}function H({explicitId:e,messageId:t,toolName:n,argumentsValue:a,toolKind:o,output:u}){if(e)return e;const s=[t||"unknown-message",n||"Unknown",de(a),o||"",u||""].join("|");return`tool-${ue(s)}`}function F({explicitId:e,sessionId:t,messageId:n,agentType:a,description:o,summary:u}){if(e)return e;if(t)return t;const s=[n||"unknown-message",a||"subagent",o||"",u||""].join("|");return`subagent-${ue(s)}`}const ke=(e,t)=>{if(!t||typeof t!="object")return null;const n=Q(t.status),a=typeof t.summary=="string"?t.summary:void 0;return{id:F({explicitId:typeof t.subagentId=="string"?t.subagentId:void 0,sessionId:t.childSessionId,messageId:e,agentType:t.agentType,description:t.description,summary:t.summary}),type:t.agentType||"subagent",description:t.description||t.summary||"",status:n,startTime:Date.now(),sessionId:t.childSessionId,resumedFrom:t.resumedFrom,rootAgentId:t.rootAgentId,resumeDepth:typeof t.resumeDepth=="number"?t.resumeDepth:void 0,verificationVerdict:t.verificationVerdict==="pass"||t.verificationVerdict==="fail"||t.verificationVerdict==="partial"?t.verificationVerdict:void 0,output:n==="running"?void 0:a}},Te=(e,t)=>!t||typeof t!="object"?[]:(Array.isArray(t.subtaskRefs)?t.subtaskRefs:t.subtaskRef&&typeof t.subtaskRef=="object"?[t.subtaskRef]:[]).map(a=>ke(e,a)).filter(a=>a!==null);function x(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
4
- `)}function U(e){if(!e.agentContent)return e;let t=e.agentContent;for(const n of Te(e.id,e.metadata))t=re(t,n);return{...e,agentContent:t}}function $e(e){var a,o,u;const t=[];let n=null;for(const s of e)if(s.role!=="system"){if(s.role==="user")n&&(t.push(U(n)),n=null),t.push({id:s.id,role:s.role,content:s.content,timestamp:s.timestamp||Date.now(),metadata:s.metadata});else if(s.role==="assistant"){n&&t.push(U(n));const i=s.metadata;let r=M();s.thinkingContent&&(r=Ce(r,s.thinkingContent),r.thinkingContent=s.thinkingContent);const d=x(s.content);if(d&&(r=he(r,d),r.textBefore=d),s.tool_calls&&Array.isArray(s.tool_calls))for(const c of s.tool_calls){const l=((a=c.function)==null?void 0:a.name)||"Unknown",g=de((o=c.function)==null?void 0:o.arguments);if(l==="Task"){let m={};try{m=JSON.parse(g)}catch{}const S=typeof m.subagent_type=="string"?m.subagent_type:"subagent",h=typeof m.description=="string"?m.description:S;r=re(r,{id:F({explicitId:c.id,sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,messageId:s.id,agentType:S,description:h}),type:S,description:h,status:"running",startTime:Date.now(),sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,resumedFrom:typeof m.resume_from=="string"?m.resume_from:typeof m.resume=="string"?m.resume:void 0});continue}const I={toolCallId:H({explicitId:c.id,messageId:s.id,toolName:l,argumentsValue:(u=c.function)==null?void 0:u.arguments}),toolName:l,arguments:g,status:"running",startTime:Date.now()};r=oe(r,I)}n={id:s.id,role:"assistant",content:x(s.content),timestamp:s.timestamp||Date.now(),metadata:i,agentContent:r}}else if(s.role==="tool"&&n&&n.agentContent){const i=s,r=s.metadata,d=i.tool_call_id||(r==null?void 0:r.toolCallId),c=i.name||(r==null?void 0:r.toolName)||"Tool",l=r!=null&&r.metadata&&typeof r.metadata=="object"&&!Array.isArray(r.metadata)?r.metadata:r,g=r!=null&&r.independentVerification&&typeof r.independentVerification=="object"&&!Array.isArray(r.independentVerification)?r.independentVerification:void 0,I=(r==null?void 0:r.status)==="failed"||(r==null?void 0:r.status)==="error"||typeof(r==null?void 0:r.error)=="string"&&r.error.length>0,m=N(n.agentContent),S=m.findIndex(y=>y.id===d);if(S>=0){const y=m[S],f=typeof(l==null?void 0:l.subagentStatus)=="string"?Q(l.subagentStatus):I?"failed":"completed";m[S]={...y,sessionId:typeof(l==null?void 0:l.subagentSessionId)=="string"?l.subagentSessionId:y.sessionId,type:typeof(l==null?void 0:l.subagentType)=="string"?l.subagentType:y.type,status:f,resumedFrom:typeof(l==null?void 0:l.subagentResumedFrom)=="string"?l.subagentResumedFrom:y.resumedFrom,rootAgentId:typeof(l==null?void 0:l.subagentRootId)=="string"?l.subagentRootId:y.rootAgentId,resumeDepth:typeof(l==null?void 0:l.subagentResumeDepth)=="number"?l.subagentResumeDepth:y.resumeDepth,verificationVerdict:(l==null?void 0:l.verificationVerdict)==="pass"||(l==null?void 0:l.verificationVerdict)==="fail"||(l==null?void 0:l.verificationVerdict)==="partial"?l.verificationVerdict:(g==null?void 0:g.verificationVerdict)==="pass"||(g==null?void 0:g.verificationVerdict)==="fail"||(g==null?void 0:g.verificationVerdict)==="partial"?g.verificationVerdict:y.verificationVerdict,output:typeof(l==null?void 0:l.subagentSummary)=="string"?l.subagentSummary:x(s.content)||y.output},n.agentContent=J(n.agentContent,m,y.id);continue}const h=n.agentContent.toolCalls.find(y=>y.toolCallId===d);h?(h.output=x(s.content),h.status=I?"error":"success",h.metadata=l,h.summary=typeof(l==null?void 0:l.summary)=="string"?l.summary:h.summary,(!h.toolName||h.toolName==="Unknown")&&(h.toolName=c)):n.agentContent=oe(n.agentContent,{toolCallId:H({explicitId:d,messageId:n.id,toolName:c,output:x(s.content)}),toolName:c,output:x(s.content),status:I?"error":"success",startTime:Date.now(),metadata:l,summary:typeof(l==null?void 0:l.summary)=="string"?l.summary:void 0})}}return n&&t.push(U(n)),t}const le={authentication:"task.failure.authentication",permission:"task.failure.permission",rate_limit:"task.failure.rateLimit",timeout:"task.failure.timeout",network:"task.failure.network",model_unavailable:"task.failure.modelUnavailable",context_limit:"task.failure.contextLimit",unsupported_input:"task.failure.unsupportedInput",runtime:"task.failure.runtime"},Ne={authentication:!1,permission:!1,rate_limit:!0,timeout:!0,network:!0,model_unavailable:!0,context_limit:!1,unsupported_input:!1,runtime:!0};function Me(e){if(typeof e=="string"&&Object.keys(le).includes(e))return e}function Vt(e){return le[e]}function Kt(e){return Ne[e]}const Pe={flushTimeout:80};class Re{constructor(t){K(this,"config");K(this,"channels",new Map);this.config={...Pe,...t}}append(t,n,a){let o=this.channels.get(t);o||(o={buffer:"",timer:null,flushFn:null},this.channels.set(t,o)),o.buffer+=n,o.flushFn=a,o.timer||(o.timer=setTimeout(()=>{this.flushChannel(t)},this.config.flushTimeout))}flushChannel(t){const n=this.channels.get(t);if(!n||!n.buffer)return;const a=n.buffer,o=n.flushFn;n.buffer="",n.timer&&(clearTimeout(n.timer),n.timer=null),o==null||o(a)}drainAll(){for(const[t]of this.channels)this.flushChannel(t);this.channels.clear()}drainAllExcept(t){for(const[n]of this.channels)n!==t&&this.flushChannel(n);for(const[n,a]of this.channels)n!==t&&!a.buffer&&this.channels.delete(n)}reset(){for(const[,t]of this.channels)t.timer&&clearTimeout(t.timer);this.channels.clear()}}const $=new Re,xe=100,b=(e,t,n)=>{if(t)for(const a of e){const o=N(a.agentContent).find(u=>u.id===t||u.sessionId===t);if(o)return{messageId:a.id,subagent:o}}if(n){const a=e.find(s=>s.id===n),o=N(a==null?void 0:a.agentContent),u=o.find(s=>s.status==="running")??o[o.length-1];if(u)return{messageId:n,subagent:u}}for(const a of[...e].reverse()){const o=N(a.agentContent),u=o.find(s=>s.status==="running")??o[o.length-1];if(u)return{messageId:a.id,subagent:u}}};function De(e,t,n){n(a=>{const o={...a.pendingSubagentCompletions??{}};if(o[e]===void 0&&Object.keys(o).length>=xe){const u=Object.keys(o)[0];u&&delete o[u]}return o[e]={...t},{pendingSubagentCompletions:o}})}function z(e,t,n){var u;if(!e)return;const a=(u=t().pendingSubagentCompletions)==null?void 0:u[e];!a||!b(t().messages,e,t().currentAssistantMessageId)||(Y({...a,subagentSessionId:e,success:a.status==="completed"},t),n(s=>{const i={...s.pendingSubagentCompletions??{}};return delete i[e],{pendingSubagentCompletions:i}}))}const v=(e,t,n,a=!1)=>{const{currentAssistantMessageId:o,messages:u,addMessage:s,startAgentResponse:i}=e();if(n&&a){const l=u.find(I=>I.id===n&&I.role==="assistant");if(l)return i(l.id),l.id;const g={id:n,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};return s(g),i(n),n}if(o&&!o.startsWith("call_")&&u.some(l=>l.id===o&&l.role==="assistant"))return o;if(n){const l=u.find(g=>g.id===n&&g.role==="assistant");if(l)return i(l.id),l.id}const r=u[u.length-1];if((r==null?void 0:r.role)==="assistant")return r.id;const d=n||`assistant-${Date.now()}`,c={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};return s(c),i(d),t(l=>({messages:l.messages.map(g=>g.id===d?{...g,agentContent:{...g.agentContent||M()}}:g)})),d},we=(e,t,n)=>{const{currentSessionId:a,addMessage:o,startAgentResponse:u,messages:s,updateMessage:i}=t();if(e.sessionId!==a)return;const r=e.messageId,d=e.role||"assistant",c=s.find(g=>g.id===r),l={id:r,role:d,content:e.content||"",timestamp:Date.now(),agentContent:d==="assistant"?M():void 0};c?i(r,{role:d,content:l.content,agentContent:d==="assistant"?{...c.agentContent||M()}:void 0}):o(l),d==="assistant"&&u(r)},_e=(e,t,n)=>{const{currentSessionId:a,appendDelta:o,currentAssistantMessageId:u,hasToolCalls:s,addMessage:i,startAgentResponse:r}=t();if(e.sessionId!==a)return;const d=e.messageId,c=e.delta;if(!u){const g={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};i(g),r(d),t().appendDelta(d,c,"before");return}o(u,c,s?"after":"before")},je=(e,t)=>{const{currentSessionId:n,updateMessage:a,messages:o}=t();if(e.sessionId!==n)return;const u=e.messageId,s=o.find(i=>i.id===u);s!=null&&s.agentContent&&a(u,{content:be(s.agentContent)})},Fe=(e,t,n)=>{var r;const{currentSessionId:a}=t();if(e.sessionId!==a)return;const o=e.output;if(!o||typeof o!="object"||Array.isArray(o))return;const u=v(t,n,e.messageId);if(!u)return;const s=t().messages.find(d=>d.id===u);if(!s)return;const i=JSON.stringify(o,null,2);t().updateMessage(u,{content:i,metadata:{...s.metadata,structuredOutput:{output:o,schemaDigest:e.schemaDigest}},agentContent:s.agentContent?{...s.agentContent,textBefore:"",textAfter:"",timeline:(r=s.agentContent.timeline)==null?void 0:r.filter(d=>d.type!=="text")}:void 0})},qe=(e,t,n)=>{const{currentSessionId:a,appendThinking:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId);u&&o(u,e.delta)},Oe=()=>{},ce=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o,setHasToolCalls:u,setSubagent:s}=t();if(e.sessionId!==a)return;const i=v(t,n,e.messageId||e.toolCallId,typeof e.messageId=="string");if(!i)return;u(!0);const r=e.toolName||"Unknown",d=e.arguments;let c,l="",g,I;if(r==="Task")try{const S=JSON.parse(d);c=S.subagent_type,l=S.description||S.query||c||"",g=S.subagent_session_id,I=S.resume_from||S.resume}catch{}if(c){s(i,{id:F({explicitId:e.toolCallId,sessionId:g,messageId:i,agentType:c,description:l}),type:c,description:l,status:"running",startTime:Date.now(),sessionId:g,resumedFrom:I,output:"",thinking:""}),z(g,t,n);return}const m={toolCallId:H({explicitId:e.toolCallId,messageId:i,toolName:r,argumentsValue:d,toolKind:e.toolKind}),toolName:r,arguments:d,toolKind:e.toolKind,status:"running",startTime:Date.now()};o(i,m)},ge=(e,t)=>{const{currentSessionId:n,updateToolCall:a,messages:o}=t();if(e.sessionId!==n)return;const u=e.toolCallId;if(!u)return;const s=o.find(i=>{var r;return(r=i.agentContent)==null?void 0:r.toolCalls.some(d=>d.toolCallId===u)});s&&a(s.id,u,{summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message})},me=(e,t,n)=>{var se;const{currentSessionId:a,appendToolCall:o,setHasToolCalls:u,updateToolCall:s,updateSubagent:i,messages:r}=t();if(e.sessionId!==a)return;const d=e.toolCallId;if(!d)return;const c=r.find(A=>{var T;return(T=A.agentContent)==null?void 0:T.toolCalls.some(R=>R.toolCallId===d)}),l=r.find(A=>N(A.agentContent).some(T=>T.id===d)),g=(c==null?void 0:c.id)||(l==null?void 0:l.id)||v(t,n,e.messageId,!0);if(!g)return;const I=typeof e.output=="string"?e.output:"",m=e.success===!0||e.status==="completed",S=e.summary||(I&&I.trim()?I.trim().split(`
5
- `)[0].slice(0,120):m?"执行成功":"执行失败"),h=(se=c==null?void 0:c.agentContent)==null?void 0:se.toolCalls.find(A=>A.toolCallId===d),y=typeof e.toolName=="string"?e.toolName:(h==null?void 0:h.toolName)??"Unknown",f=e.metadata;c?s(g,d,{status:m?"success":"error",summary:S,output:I,metadata:f}):l||(u(!0),o(g,{toolCallId:d,toolName:y,status:m?"success":"error",summary:S,output:I,startTime:Date.now(),metadata:f}));const q=t().messages.find(A=>A.id===g),k=N(q==null?void 0:q.agentContent).find(A=>A.id===d),P=f&&typeof f.subagentSessionId=="string"?f.subagentSessionId:void 0,D=f&&typeof f.subagentStatus=="string"?f.subagentStatus:void 0,X=f&&typeof f.subagentType=="string"?f.subagentType:void 0,Z=f&&typeof f.subagentSummary=="string"?f.subagentSummary:void 0,p=f&&typeof f.subagentResumedFrom=="string"?f.subagentResumedFrom:void 0,ee=f&&typeof f.subagentRootId=="string"?f.subagentRootId:void 0,te=f&&typeof f.subagentResumeDepth=="number"?f.subagentResumeDepth:void 0,ne=(f==null?void 0:f.verificationVerdict)==="pass"||(f==null?void 0:f.verificationVerdict)==="fail"||(f==null?void 0:f.verificationVerdict)==="partial"?f.verificationVerdict:void 0;if(k){const A=D?Q(D):e.success?"completed":"failed",T=k.status!=="running"&&A==="running";i(g,k.id,{sessionId:k.sessionId||P,type:X||k.type,status:T?k.status:A,resumedFrom:p||k.resumedFrom,rootAgentId:ee||k.rootAgentId,resumeDepth:te??k.resumeDepth,verificationVerdict:ne??k.verificationVerdict,output:T?k.output:Z||k.output})}P&&D&&n(A=>({messages:A.messages.map(T=>{if(T.id!==g)return T;const R=T.metadata??{},O=Array.isArray(R.subtaskRefs)?R.subtaskRefs:[],w=O.findIndex(ie=>ie.childSessionId===P||ie.subagentId===d),C=w>=0?O[w]:R.subtaskRef??{},E={...C,subagentId:d,childSessionId:P,agentType:X||(typeof(C==null?void 0:C.agentType)=="string"?C.agentType:"subagent"),status:D,summary:Z||(typeof(C==null?void 0:C.summary)=="string"?C.summary:""),resumedFrom:p||(typeof(C==null?void 0:C.resumedFrom)=="string"?C.resumedFrom:void 0),rootAgentId:ee||(typeof(C==null?void 0:C.rootAgentId)=="string"?C.rootAgentId:P),resumeDepth:te??(typeof(C==null?void 0:C.resumeDepth)=="number"?C.resumeDepth:0),verificationVerdict:ne||(typeof(C==null?void 0:C.verificationVerdict)=="string"?C.verificationVerdict:void 0)},V=[...O];return w>=0?V[w]=E:V.push(E),{...T,metadata:{...R,subtaskRef:E,subtaskRefs:V}}})})),z(P,t,n)},Ee=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-catalog-${String(e.revision)}`);if(!u)return;const s=Array.isArray(e.added)?e.added.map(String):[],i=Array.isArray(e.removed)?e.removed.map(String):[],r=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP catalog r${String(e.revision)}: +${s.length} -${i.length} ~${r.length}`;o(u,{toolCallId:`mcp-catalog:${String(e.revision)}`,toolName:"MCP Catalog",arguments:JSON.stringify({serverName:e.serverName,added:s,removed:i,updated:r}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[s.length>0?`Added: ${s.join(", ")}`:"",i.length>0?`Removed: ${i.join(", ")}`:"",r.length>0?`Updated: ${r.join(", ")}`:""].filter(Boolean).join(`
6
- `)})},Ve=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-content-${String(e.revision)}`);if(!u)return;const s=Array.isArray(e.added)?e.added.map(String):[],i=Array.isArray(e.removed)?e.removed.map(String):[],r=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP ${String(e.contentKind)} r${String(e.revision)}: +${s.length} -${i.length} ~${r.length}`;o(u,{toolCallId:`mcp-content:${String(e.revision)}`,toolName:"MCP Content",arguments:JSON.stringify({serverName:e.serverName,contentKind:e.contentKind,added:s,removed:i,updated:r}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[s.length>0?`Added: ${s.join(", ")}`:"",i.length>0?`Removed: ${i.join(", ")}`:"",r.length>0?`Updated: ${r.join(", ")}`:""].filter(Boolean).join(`
7
- `)})},Ke=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-resource-${String(e.revision)}`);u&&o(u,{toolCallId:`mcp-resource:${String(e.revision)}`,toolName:"MCP Resource",arguments:JSON.stringify({serverName:e.serverName,uri:e.uri}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP resource updated: ${String(e.uri)}`,output:`${String(e.serverName)} · revision ${String(e.revision)}`})},Ue=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-connection-${String(e.revision)}`);if(!u)return;const s=String(e.phase),i=`MCP ${String(e.serverName)} ${s}`+(s==="reconnecting"?` (${String(e.attempt)}/${String(e.maxAttempts)})`:"");o(u,{toolCallId:`mcp-connection:${String(e.revision)}`,toolName:"MCP Connection",arguments:JSON.stringify({serverName:e.serverName,phase:s,reason:e.reason,attempt:e.attempt,maxAttempts:e.maxAttempts}),toolKind:"readonly",status:s==="failed"?"error":"success",startTime:Date.now(),summary:i,output:[`Reason: ${String(e.reason)}`,e.error?`Error: ${String(e.error)}`:""].filter(Boolean).join(`
8
- `)})},Be=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-log-${String(e.revision)}`);if(!u)return;const s=String(e.level),i=typeof e.logger=="string"?e.logger:void 0,r=`MCP ${s} · ${String(e.serverName)}`+(i?` · ${i}`:"");o(u,{toolCallId:`mcp-log:${String(e.revision)}`,toolName:"MCP Log",arguments:JSON.stringify({serverName:e.serverName,level:s,logger:i}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:[String(e.message),`SHA-256: ${String(e.dataSha256)}`,e.truncated===!0?"Truncated":"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
9
- `)})},Je=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=String(e.serverName),s=String(e.action),i=v(t,n,e.messageId||`mcp-instructions-${String(e.revision)}-${u}`);if(!i)return;const r=`MCP instructions ${s}: ${u}`+(e.truncated===!0?" (truncated)":"");o(i,{toolCallId:`mcp-instructions:${String(e.revision)}:${u}:${s}`,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:u,action:s,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:[typeof e.text=="string"?e.text:"",e.sha256?`SHA-256: ${String(e.sha256)}`:"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
10
- `)})},Le=(e,t,n)=>{var I,m;const{currentSessionId:a,appendToolCall:o,updateToolCall:u}=t();if(e.sessionId!==a)return;const s=String(e.taskId),i=String(e.status),r=`mcp-task:${s}`,d=v(t,n,e.messageId||`mcp-task-${s}`);if(!d)return;const c=`MCP task ${i}: ${s} · ${String(e.serverName)}/${String(e.toolName)}`,l={status:i==="failed"||i==="cancelled"?"error":i==="completed"?"success":"running",summary:c,output:[typeof e.statusMessage=="string"?e.statusMessage:"",e.hasResult===!0?"Result available via TaskOutput":"",typeof e.error=="string"?`Error: ${e.error}`:""].filter(Boolean).join(`
11
- `)};if((m=(I=t().messages.find(S=>S.id===d))==null?void 0:I.agentContent)==null?void 0:m.toolCalls.some(S=>S.toolCallId===r)){u(d,r,l);return}o(d,{toolCallId:r,toolName:"MCP Task",arguments:JSON.stringify({taskId:s,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:l.status,startTime:Number(e.createdAt)||Date.now(),summary:l.summary,output:l.output})},He=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],s=v(t,n,e.messageId||`project-rules-${Date.now()}`);if(!s)return;const i=e.blockedWrite===!0,r=`Project rules loaded: ${u.length}`+(i?" (write retry required)":"");o(s,{toolCallId:`project-rules:${u.map(d=>String(d.id)).join(",")}`,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:i}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:u.map(d=>`${String(d.relativePath)} ${String(d.source)} SHA-256: ${String(d.contentSha256)}`).join(`
12
- `)})},W=e=>`user-shell-${e}`,Ge=(e,t,n)=>{const{currentSessionId:a,addMessage:o,messages:u,updateMessage:s}=t();if(e.sessionId!==a||typeof e.executionId!="string"||typeof e.command!="string")return;const i=W(e.executionId),r={id:i,role:"user",content:`! ${e.command}`,timestamp:Date.now(),metadata:{userShellExecution:{executionId:e.executionId,command:e.command,status:"running",output:""}}};u.some(d=>d.id===i)?s(i,r):o(r),e.auxiliary!==!0&&n({isStreaming:!0,agentPhase:"running",error:null,errorContext:null})},Qe=(e,t)=>{var d;const{currentSessionId:n,messages:a,updateMessage:o}=t();if(e.sessionId!==n||typeof e.executionId!="string"||typeof e.chunk!="string")return;const u=W(e.executionId),s=a.find(c=>c.id===u);if(!s)return;const i=(d=s.metadata)!=null&&d.userShellExecution&&typeof s.metadata.userShellExecution=="object"?s.metadata.userShellExecution:{},r=`${typeof i.output=="string"?i.output:""}${e.chunk}`;o(u,{content:`! ${String(i.command??"")}
13
- ${r}`,metadata:{...s.metadata,userShellExecution:{...i,output:r,streamTruncated:e.streamTruncated===!0}}})},ze=(e,t,n)=>{const{currentSessionId:a,messages:o,addMessage:u,updateMessage:s}=t();if(e.sessionId!==a||typeof e.executionId!="string"||!e.record||typeof e.record!="object"||Array.isArray(e.record))return;const i=e.record,r=typeof i.command=="string"?i.command:"",d=typeof i.stdout=="string"?i.stdout:"",c=typeof i.stderr=="string"?i.stderr:"",l=[d,c?`stderr:
3
+ `)}const Ae=2166136261,Te=16777619;function J(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.map(t=>J(t)).join(",")}]`:typeof e=="object"?`{${Object.entries(e).sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>`${JSON.stringify(n)}:${J(a)}`).join(",")}}`:JSON.stringify(e)}function de(e){let t=Ae>>>0;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,Te);return(t>>>0).toString(16)}function le(e){return typeof e=="string"?e:J(e??{})}function G(e){return e==="completed"?"completed":e==="failed"||e==="cancelled"?"failed":"running"}function L({explicitId:e,messageId:t,toolName:n,argumentsValue:a,toolKind:o,output:u}){if(e)return e;const s=[t||"unknown-message",n||"Unknown",le(a),o||"",u||""].join("|");return`tool-${de(s)}`}function F({explicitId:e,sessionId:t,messageId:n,agentType:a,description:o,summary:u}){if(e)return e;if(t)return t;const s=[n||"unknown-message",a||"subagent",o||"",u||""].join("|");return`subagent-${de(s)}`}const ke=(e,t)=>{if(!t||typeof t!="object")return null;const n=G(t.status),a=typeof t.summary=="string"?t.summary:void 0;return{id:F({explicitId:typeof t.subagentId=="string"?t.subagentId:void 0,sessionId:t.childSessionId,messageId:e,agentType:t.agentType,description:t.description,summary:t.summary}),type:t.agentType||"subagent",description:t.description||t.summary||"",status:n,startTime:Date.now(),sessionId:t.childSessionId,resumedFrom:t.resumedFrom,rootAgentId:t.rootAgentId,resumeDepth:typeof t.resumeDepth=="number"?t.resumeDepth:void 0,verificationVerdict:t.verificationVerdict==="pass"||t.verificationVerdict==="fail"||t.verificationVerdict==="partial"?t.verificationVerdict:void 0,output:n==="running"?void 0:a}},$e=(e,t)=>!t||typeof t!="object"?[]:(Array.isArray(t.subtaskRefs)?t.subtaskRefs:t.subtaskRef&&typeof t.subtaskRef=="object"?[t.subtaskRef]:[]).map(a=>ke(e,a)).filter(a=>a!==null);function x(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
4
+ `)}function U(e){if(!e.agentContent)return e;let t=e.agentContent;for(const n of $e(e.id,e.metadata))t=ue(t,n);return{...e,agentContent:t}}function Ne(e){var a,o,u;const t=[];let n=null;for(const s of e)if(s.role!=="system"){if(s.role==="user")n&&(t.push(U(n)),n=null),t.push({id:s.id,role:s.role,content:s.content,timestamp:s.timestamp||Date.now(),metadata:s.metadata});else if(s.role==="assistant"){n&&t.push(U(n));const i=s.metadata;let r=M();s.thinkingContent&&(r=be(r,s.thinkingContent),r.thinkingContent=s.thinkingContent);const d=x(s.content);if(d&&(r=Ce(r,d),r.textBefore=d),s.tool_calls&&Array.isArray(s.tool_calls))for(const c of s.tool_calls){const l=((a=c.function)==null?void 0:a.name)||"Unknown",g=le((o=c.function)==null?void 0:o.arguments);if(l==="Task"){let m={};try{m=JSON.parse(g)}catch{}const S=typeof m.subagent_type=="string"?m.subagent_type:"subagent",y=typeof m.description=="string"?m.description:S;r=ue(r,{id:F({explicitId:c.id,sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,messageId:s.id,agentType:S,description:y}),type:S,description:y,status:"running",startTime:Date.now(),sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,resumedFrom:typeof m.resume_from=="string"?m.resume_from:typeof m.resume=="string"?m.resume:void 0});continue}const I={toolCallId:L({explicitId:c.id,messageId:s.id,toolName:l,argumentsValue:(u=c.function)==null?void 0:u.arguments}),toolName:l,arguments:g,status:"running",startTime:Date.now()};r=oe(r,I)}n={id:s.id,role:"assistant",content:x(s.content),timestamp:s.timestamp||Date.now(),metadata:i,agentContent:r}}else if(s.role==="tool"&&n&&n.agentContent){const i=s,r=s.metadata,d=i.tool_call_id||(r==null?void 0:r.toolCallId),c=i.name||(r==null?void 0:r.toolName)||"Tool",l=r!=null&&r.metadata&&typeof r.metadata=="object"&&!Array.isArray(r.metadata)?r.metadata:r,g=r!=null&&r.independentVerification&&typeof r.independentVerification=="object"&&!Array.isArray(r.independentVerification)?r.independentVerification:void 0,I=(r==null?void 0:r.status)==="failed"||(r==null?void 0:r.status)==="error"||typeof(r==null?void 0:r.error)=="string"&&r.error.length>0,m=N(n.agentContent),S=m.findIndex(h=>h.id===d);if(S>=0){const h=m[S],f=typeof(l==null?void 0:l.subagentStatus)=="string"?G(l.subagentStatus):I?"failed":"completed";m[S]={...h,sessionId:typeof(l==null?void 0:l.subagentSessionId)=="string"?l.subagentSessionId:h.sessionId,type:typeof(l==null?void 0:l.subagentType)=="string"?l.subagentType:h.type,status:f,resumedFrom:typeof(l==null?void 0:l.subagentResumedFrom)=="string"?l.subagentResumedFrom:h.resumedFrom,rootAgentId:typeof(l==null?void 0:l.subagentRootId)=="string"?l.subagentRootId:h.rootAgentId,resumeDepth:typeof(l==null?void 0:l.subagentResumeDepth)=="number"?l.subagentResumeDepth:h.resumeDepth,verificationVerdict:(l==null?void 0:l.verificationVerdict)==="pass"||(l==null?void 0:l.verificationVerdict)==="fail"||(l==null?void 0:l.verificationVerdict)==="partial"?l.verificationVerdict:(g==null?void 0:g.verificationVerdict)==="pass"||(g==null?void 0:g.verificationVerdict)==="fail"||(g==null?void 0:g.verificationVerdict)==="partial"?g.verificationVerdict:h.verificationVerdict,output:typeof(l==null?void 0:l.subagentSummary)=="string"?l.subagentSummary:x(s.content)||h.output},n.agentContent=B(n.agentContent,m,h.id);continue}const y=n.agentContent.toolCalls.find(h=>h.toolCallId===d);y?(y.output=x(s.content),y.status=I?"error":"success",y.metadata=l,y.summary=typeof(l==null?void 0:l.summary)=="string"?l.summary:y.summary,(!y.toolName||y.toolName==="Unknown")&&(y.toolName=c)):n.agentContent=oe(n.agentContent,{toolCallId:L({explicitId:d,messageId:n.id,toolName:c,output:x(s.content)}),toolName:c,output:x(s.content),status:I?"error":"success",startTime:Date.now(),metadata:l,summary:typeof(l==null?void 0:l.summary)=="string"?l.summary:void 0})}}return n&&t.push(U(n)),t}const ce={authentication:"task.failure.authentication",permission:"task.failure.permission",rate_limit:"task.failure.rateLimit",timeout:"task.failure.timeout",network:"task.failure.network",model_unavailable:"task.failure.modelUnavailable",context_limit:"task.failure.contextLimit",unsupported_input:"task.failure.unsupportedInput",runtime:"task.failure.runtime"},Me={authentication:!1,permission:!1,rate_limit:!0,timeout:!0,network:!0,model_unavailable:!0,context_limit:!1,unsupported_input:!1,runtime:!0};function Pe(e){if(typeof e=="string"&&Object.keys(ce).includes(e))return e}function Ut(e){return ce[e]}function Bt(e){return Me[e]}const Re={flushTimeout:80};class xe{constructor(t){K(this,"config");K(this,"channels",new Map);this.config={...Re,...t}}append(t,n,a){let o=this.channels.get(t);o||(o={buffer:"",timer:null,flushFn:null},this.channels.set(t,o)),o.buffer+=n,o.flushFn=a,o.timer||(o.timer=setTimeout(()=>{this.flushChannel(t)},this.config.flushTimeout))}flushChannel(t){const n=this.channels.get(t);if(!n||!n.buffer)return;const a=n.buffer,o=n.flushFn;n.buffer="",n.timer&&(clearTimeout(n.timer),n.timer=null),o==null||o(a)}drainAll(){for(const[t]of this.channels)this.flushChannel(t);this.channels.clear()}drainAllExcept(t){for(const[n]of this.channels)n!==t&&this.flushChannel(n);for(const[n,a]of this.channels)n!==t&&!a.buffer&&this.channels.delete(n)}reset(){for(const[,t]of this.channels)t.timer&&clearTimeout(t.timer);this.channels.clear()}}const $=new xe,De=100,b=(e,t,n)=>{if(t)for(const a of e){const o=N(a.agentContent).find(u=>u.id===t||u.sessionId===t);if(o)return{messageId:a.id,subagent:o}}if(n){const a=e.find(s=>s.id===n),o=N(a==null?void 0:a.agentContent),u=o.find(s=>s.status==="running")??o[o.length-1];if(u)return{messageId:n,subagent:u}}for(const a of[...e].reverse()){const o=N(a.agentContent),u=o.find(s=>s.status==="running")??o[o.length-1];if(u)return{messageId:a.id,subagent:u}}};function we(e,t,n){n(a=>{const o={...a.pendingSubagentCompletions??{}};if(o[e]===void 0&&Object.keys(o).length>=De){const u=Object.keys(o)[0];u&&delete o[u]}return o[e]={...t},{pendingSubagentCompletions:o}})}function Q(e,t,n){var u;if(!e)return;const a=(u=t().pendingSubagentCompletions)==null?void 0:u[e];!a||!b(t().messages,e,t().currentAssistantMessageId)||(W({...a,subagentSessionId:e,success:a.status==="completed"},t),n(s=>{const i={...s.pendingSubagentCompletions??{}};return delete i[e],{pendingSubagentCompletions:i}}))}const v=(e,t,n,a=!1)=>{const{currentAssistantMessageId:o,messages:u,addMessage:s,startAgentResponse:i}=e();if(n&&a){const l=u.find(I=>I.id===n&&I.role==="assistant");if(l)return i(l.id),l.id;const g={id:n,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};return s(g),i(n),n}if(o&&!o.startsWith("call_")&&u.some(l=>l.id===o&&l.role==="assistant"))return o;if(n){const l=u.find(g=>g.id===n&&g.role==="assistant");if(l)return i(l.id),l.id}const r=u[u.length-1];if((r==null?void 0:r.role)==="assistant")return r.id;const d=n||`assistant-${Date.now()}`,c={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};return s(c),i(d),t(l=>({messages:l.messages.map(g=>g.id===d?{...g,agentContent:{...g.agentContent||M()}}:g)})),d},_e=(e,t,n)=>{const{currentSessionId:a,addMessage:o,startAgentResponse:u,messages:s,updateMessage:i}=t();if(e.sessionId!==a)return;const r=e.messageId,d=e.role||"assistant",c=s.find(g=>g.id===r),l={id:r,role:d,content:e.content||"",timestamp:Date.now(),agentContent:d==="assistant"?M():void 0};c?i(r,{role:d,content:l.content,agentContent:d==="assistant"?{...c.agentContent||M()}:void 0}):o(l),d==="assistant"&&u(r)},je=(e,t,n)=>{const{currentSessionId:a,appendDelta:o,currentAssistantMessageId:u,hasToolCalls:s,addMessage:i,startAgentResponse:r}=t();if(e.sessionId!==a)return;const d=e.messageId,c=e.delta;if(!u){const g={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};i(g),r(d),t().appendDelta(d,c,"before");return}o(u,c,s?"after":"before")},Fe=(e,t)=>{const{currentSessionId:n,updateMessage:a,messages:o}=t();if(e.sessionId!==n)return;const u=e.messageId,s=o.find(i=>i.id===u);s!=null&&s.agentContent&&a(u,{content:ve(s.agentContent)})},qe=(e,t,n)=>{var r;const{currentSessionId:a}=t();if(e.sessionId!==a)return;const o=e.output;if(!o||typeof o!="object"||Array.isArray(o))return;const u=v(t,n,e.messageId);if(!u)return;const s=t().messages.find(d=>d.id===u);if(!s)return;const i=JSON.stringify(o,null,2);t().updateMessage(u,{content:i,metadata:{...s.metadata,structuredOutput:{output:o,schemaDigest:e.schemaDigest}},agentContent:s.agentContent?{...s.agentContent,textBefore:"",textAfter:"",timeline:(r=s.agentContent.timeline)==null?void 0:r.filter(d=>d.type!=="text")}:void 0})},Oe=(e,t,n)=>{const{currentSessionId:a,appendThinking:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId);u&&o(u,e.delta)},Ee=()=>{},ge=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o,setHasToolCalls:u,setSubagent:s}=t();if(e.sessionId!==a)return;const i=v(t,n,e.messageId||e.toolCallId,typeof e.messageId=="string");if(!i)return;u(!0);const r=e.toolName||"Unknown",d=e.arguments;let c,l="",g,I;if(r==="Task")try{const S=JSON.parse(d);c=S.subagent_type,l=S.description||S.query||c||"",g=S.subagent_session_id,I=S.resume_from||S.resume}catch{}if(c){s(i,{id:F({explicitId:e.toolCallId,sessionId:g,messageId:i,agentType:c,description:l}),type:c,description:l,status:"running",startTime:Date.now(),sessionId:g,resumedFrom:I,output:"",thinking:""}),Q(g,t,n);return}const m={toolCallId:L({explicitId:e.toolCallId,messageId:i,toolName:r,argumentsValue:d,toolKind:e.toolKind}),toolName:r,arguments:d,toolKind:e.toolKind,status:"running",startTime:Date.now()};o(i,m)},me=(e,t)=>{const{currentSessionId:n,updateToolCall:a,messages:o}=t();if(e.sessionId!==n)return;const u=e.toolCallId;if(!u)return;const s=o.find(i=>{var r;return(r=i.agentContent)==null?void 0:r.toolCalls.some(d=>d.toolCallId===u)});s&&a(s.id,u,{summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message})},fe=(e,t,n)=>{var se;const{currentSessionId:a,appendToolCall:o,setHasToolCalls:u,updateToolCall:s,updateSubagent:i,messages:r}=t();if(e.sessionId!==a)return;const d=e.toolCallId;if(!d)return;const c=r.find(A=>{var k;return(k=A.agentContent)==null?void 0:k.toolCalls.some(R=>R.toolCallId===d)}),l=r.find(A=>N(A.agentContent).some(k=>k.id===d)),g=(c==null?void 0:c.id)||(l==null?void 0:l.id)||v(t,n,e.messageId,!0);if(!g)return;const I=typeof e.output=="string"?e.output:"",m=e.success===!0||e.status==="completed",S=e.summary||(I&&I.trim()?I.trim().split(`
5
+ `)[0].slice(0,120):m?"执行成功":"执行失败"),y=(se=c==null?void 0:c.agentContent)==null?void 0:se.toolCalls.find(A=>A.toolCallId===d),h=typeof e.toolName=="string"?e.toolName:(y==null?void 0:y.toolName)??"Unknown",f=e.metadata;c?s(g,d,{status:m?"success":"error",summary:S,output:I,metadata:f}):l||(u(!0),o(g,{toolCallId:d,toolName:h,status:m?"success":"error",summary:S,output:I,startTime:Date.now(),metadata:f}));const q=t().messages.find(A=>A.id===g),T=N(q==null?void 0:q.agentContent).find(A=>A.id===d),P=f&&typeof f.subagentSessionId=="string"?f.subagentSessionId:void 0,D=f&&typeof f.subagentStatus=="string"?f.subagentStatus:void 0,X=f&&typeof f.subagentType=="string"?f.subagentType:void 0,Z=f&&typeof f.subagentSummary=="string"?f.subagentSummary:void 0,p=f&&typeof f.subagentResumedFrom=="string"?f.subagentResumedFrom:void 0,ee=f&&typeof f.subagentRootId=="string"?f.subagentRootId:void 0,te=f&&typeof f.subagentResumeDepth=="number"?f.subagentResumeDepth:void 0,ne=(f==null?void 0:f.verificationVerdict)==="pass"||(f==null?void 0:f.verificationVerdict)==="fail"||(f==null?void 0:f.verificationVerdict)==="partial"?f.verificationVerdict:void 0;if(T){const A=D?G(D):e.success?"completed":"failed",k=T.status!=="running"&&A==="running";i(g,T.id,{sessionId:T.sessionId||P,type:X||T.type,status:k?T.status:A,resumedFrom:p||T.resumedFrom,rootAgentId:ee||T.rootAgentId,resumeDepth:te??T.resumeDepth,verificationVerdict:ne??T.verificationVerdict,output:k?T.output:Z||T.output})}P&&D&&n(A=>({messages:A.messages.map(k=>{if(k.id!==g)return k;const R=k.metadata??{},O=Array.isArray(R.subtaskRefs)?R.subtaskRefs:[],w=O.findIndex(ie=>ie.childSessionId===P||ie.subagentId===d),C=w>=0?O[w]:R.subtaskRef??{},E={...C,subagentId:d,childSessionId:P,agentType:X||(typeof(C==null?void 0:C.agentType)=="string"?C.agentType:"subagent"),status:D,summary:Z||(typeof(C==null?void 0:C.summary)=="string"?C.summary:""),resumedFrom:p||(typeof(C==null?void 0:C.resumedFrom)=="string"?C.resumedFrom:void 0),rootAgentId:ee||(typeof(C==null?void 0:C.rootAgentId)=="string"?C.rootAgentId:P),resumeDepth:te??(typeof(C==null?void 0:C.resumeDepth)=="number"?C.resumeDepth:0),verificationVerdict:ne||(typeof(C==null?void 0:C.verificationVerdict)=="string"?C.verificationVerdict:void 0)},V=[...O];return w>=0?V[w]=E:V.push(E),{...k,metadata:{...R,subtaskRef:E,subtaskRefs:V}}})})),Q(P,t,n)},Ve=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-catalog-${String(e.revision)}`);if(!u)return;const s=Array.isArray(e.added)?e.added.map(String):[],i=Array.isArray(e.removed)?e.removed.map(String):[],r=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP catalog r${String(e.revision)}: +${s.length} -${i.length} ~${r.length}`;o(u,{toolCallId:`mcp-catalog:${String(e.revision)}`,toolName:"MCP Catalog",arguments:JSON.stringify({serverName:e.serverName,added:s,removed:i,updated:r}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[s.length>0?`Added: ${s.join(", ")}`:"",i.length>0?`Removed: ${i.join(", ")}`:"",r.length>0?`Updated: ${r.join(", ")}`:""].filter(Boolean).join(`
6
+ `)})},Ke=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-content-${String(e.revision)}`);if(!u)return;const s=Array.isArray(e.added)?e.added.map(String):[],i=Array.isArray(e.removed)?e.removed.map(String):[],r=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP ${String(e.contentKind)} r${String(e.revision)}: +${s.length} -${i.length} ~${r.length}`;o(u,{toolCallId:`mcp-content:${String(e.revision)}`,toolName:"MCP Content",arguments:JSON.stringify({serverName:e.serverName,contentKind:e.contentKind,added:s,removed:i,updated:r}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[s.length>0?`Added: ${s.join(", ")}`:"",i.length>0?`Removed: ${i.join(", ")}`:"",r.length>0?`Updated: ${r.join(", ")}`:""].filter(Boolean).join(`
7
+ `)})},Ue=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-resource-${String(e.revision)}`);u&&o(u,{toolCallId:`mcp-resource:${String(e.revision)}`,toolName:"MCP Resource",arguments:JSON.stringify({serverName:e.serverName,uri:e.uri}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP resource updated: ${String(e.uri)}`,output:`${String(e.serverName)} · revision ${String(e.revision)}`})},Be=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-connection-${String(e.revision)}`);if(!u)return;const s=String(e.phase),i=`MCP ${String(e.serverName)} ${s}`+(s==="reconnecting"?` (${String(e.attempt)}/${String(e.maxAttempts)})`:"");o(u,{toolCallId:`mcp-connection:${String(e.revision)}`,toolName:"MCP Connection",arguments:JSON.stringify({serverName:e.serverName,phase:s,reason:e.reason,attempt:e.attempt,maxAttempts:e.maxAttempts}),toolKind:"readonly",status:s==="failed"?"error":"success",startTime:Date.now(),summary:i,output:[`Reason: ${String(e.reason)}`,e.error?`Error: ${String(e.error)}`:""].filter(Boolean).join(`
8
+ `)})},Je=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=v(t,n,e.messageId||`mcp-log-${String(e.revision)}`);if(!u)return;const s=String(e.level),i=typeof e.logger=="string"?e.logger:void 0,r=`MCP ${s} · ${String(e.serverName)}`+(i?` · ${i}`:"");o(u,{toolCallId:`mcp-log:${String(e.revision)}`,toolName:"MCP Log",arguments:JSON.stringify({serverName:e.serverName,level:s,logger:i}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:[String(e.message),`SHA-256: ${String(e.dataSha256)}`,e.truncated===!0?"Truncated":"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
9
+ `)})},Le=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=String(e.serverName),s=String(e.action),i=v(t,n,e.messageId||`mcp-instructions-${String(e.revision)}-${u}`);if(!i)return;const r=`MCP instructions ${s}: ${u}`+(e.truncated===!0?" (truncated)":"");o(i,{toolCallId:`mcp-instructions:${String(e.revision)}:${u}:${s}`,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:u,action:s,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:[typeof e.text=="string"?e.text:"",e.sha256?`SHA-256: ${String(e.sha256)}`:"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
10
+ `)})},He=(e,t,n)=>{var I,m;const{currentSessionId:a,appendToolCall:o,updateToolCall:u}=t();if(e.sessionId!==a)return;const s=String(e.taskId),i=String(e.status),r=`mcp-task:${s}`,d=v(t,n,e.messageId||`mcp-task-${s}`);if(!d)return;const c=`MCP task ${i}: ${s} · ${String(e.serverName)}/${String(e.toolName)}`,l={status:i==="failed"||i==="cancelled"?"error":i==="completed"?"success":"running",summary:c,output:[typeof e.statusMessage=="string"?e.statusMessage:"",e.hasResult===!0?"Result available via TaskOutput":"",typeof e.error=="string"?`Error: ${e.error}`:""].filter(Boolean).join(`
11
+ `)};if((m=(I=t().messages.find(S=>S.id===d))==null?void 0:I.agentContent)==null?void 0:m.toolCalls.some(S=>S.toolCallId===r)){u(d,r,l);return}o(d,{toolCallId:r,toolName:"MCP Task",arguments:JSON.stringify({taskId:s,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:l.status,startTime:Number(e.createdAt)||Date.now(),summary:l.summary,output:l.output})},Ge=(e,t,n)=>{const{currentSessionId:a,appendToolCall:o}=t();if(e.sessionId!==a)return;const u=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],s=v(t,n,e.messageId||`project-rules-${Date.now()}`);if(!s)return;const i=e.blockedWrite===!0,r=`Project rules loaded: ${u.length}`+(i?" (write retry required)":"");o(s,{toolCallId:`project-rules:${u.map(d=>String(d.id)).join(",")}`,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:i}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:r,output:u.map(d=>`${String(d.relativePath)} ${String(d.source)} SHA-256: ${String(d.contentSha256)}`).join(`
12
+ `)})},z=e=>`user-shell-${e}`,Qe=(e,t,n)=>{const{currentSessionId:a,addMessage:o,messages:u,updateMessage:s}=t();if(e.sessionId!==a||typeof e.executionId!="string"||typeof e.command!="string")return;const i=z(e.executionId),r={id:i,role:"user",content:`! ${e.command}`,timestamp:Date.now(),metadata:{userShellExecution:{executionId:e.executionId,command:e.command,status:"running",output:""}}};u.some(d=>d.id===i)?s(i,r):o(r),e.auxiliary!==!0&&n({isStreaming:!0,agentPhase:"running",error:null,errorContext:null})},ze=(e,t)=>{var d;const{currentSessionId:n,messages:a,updateMessage:o}=t();if(e.sessionId!==n||typeof e.executionId!="string"||typeof e.chunk!="string")return;const u=z(e.executionId),s=a.find(c=>c.id===u);if(!s)return;const i=(d=s.metadata)!=null&&d.userShellExecution&&typeof s.metadata.userShellExecution=="object"?s.metadata.userShellExecution:{},r=`${typeof i.output=="string"?i.output:""}${e.chunk}`;o(u,{content:`! ${String(i.command??"")}
13
+ ${r}`,metadata:{...s.metadata,userShellExecution:{...i,output:r,streamTruncated:e.streamTruncated===!0}}})},We=(e,t,n)=>{const{currentSessionId:a,messages:o,addMessage:u,updateMessage:s}=t();if(e.sessionId!==a||typeof e.executionId!="string"||!e.record||typeof e.record!="object"||Array.isArray(e.record))return;const i=e.record,r=typeof i.command=="string"?i.command:"",d=typeof i.stdout=="string"?i.stdout:"",c=typeof i.stderr=="string"?i.stderr:"",l=[d,c?`stderr:
14
14
  ${c}`:""].filter(Boolean).join(`
15
- `),g=W(e.executionId),I={role:"user",content:[`! ${r}`,l||"(no output)"].join(`
16
- `),metadata:{userShellCommand:i}};o.some(m=>m.id===g)?s(g,I):u({id:g,...I,timestamp:Date.now()}),e.auxiliary!==!0&&n({isStreaming:!1,isStopping:!1,agentPhase:"idle"}),(e.delivery==="current_turn"||e.delivery==="next_turn")&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):0,pendingInputDelivery:e.delivery==="current_turn"?"current_turn":"next_turn"})},We=(e,t)=>{const{currentSessionId:n,updateTokenUsage:a,setMaxContextTokens:o}=t();e.sessionId===n&&(a({inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,cacheReadTokens:e.cacheReadTokens??0,cacheWriteTokens:e.cacheWriteTokens??0,costUsd:e.costUsd}),e.maxContextTokens&&o(e.maxContextTokens,!1))},Ye=(e,t)=>{const{currentSessionId:n,setTasks:a,currentAssistantMessageId:o}=t();if(e.sessionId!==n||!o)return;const u=e.tasks||[];a(o,u)},Xe=(e,t,n)=>{const{currentSessionId:a,setSubagent:o,currentAssistantMessageId:u}=t();if(e.sessionId!==a||!u)return;const s={id:F({explicitId:e.subagentId,sessionId:e.subagentSessionId,messageId:u,agentType:e.type,description:e.description}),type:e.type||"unknown",description:e.description||"",status:"running",startTime:Date.now(),sessionId:e.subagentSessionId,resumedFrom:e.resumedFrom,rootAgentId:e.rootAgentId,resumeDepth:typeof e.resumeDepth=="number"?e.resumeDepth:void 0};o(u,s),z(s.sessionId,t,n)},Ze=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.subagentSessionId,i=b(o,s,a);i&&u(i.messageId,i.subagent.id,{sessionId:i.subagent.sessionId||s,currentTool:e.toolName})},pe=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.delta;if(!s)return;const i=e.subagentSessionId,r=b(o,i,a);r&&u(r.messageId,r.subagent.id,d=>({sessionId:d.sessionId||i,output:(d.output||"")+s}))},et=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.delta;if(!s)return;const i=e.subagentSessionId,r=b(o,i,a);r&&u(r.messageId,r.subagent.id,d=>({sessionId:d.sessionId||i,thinking:(d.thinking||"")+s}))},Y=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.subagentSessionId,i=b(o,s,a);if(!i)return;const r=e.status==="completed"?"completed":e.status==="failed"||e.status==="cancelled"?"failed":e.success?"completed":"failed";u(i.messageId,i.subagent.id,{sessionId:i.subagent.sessionId||s,type:typeof e.type=="string"?e.type:i.subagent.type,description:typeof e.description=="string"?e.description:i.subagent.description,status:r,currentTool:void 0,output:typeof e.summary=="string"?e.summary:i.subagent.output,resumedFrom:typeof e.resumedFrom=="string"?e.resumedFrom:i.subagent.resumedFrom,rootAgentId:typeof e.rootAgentId=="string"?e.rootAgentId:i.subagent.rootAgentId,resumeDepth:typeof e.resumeDepth=="number"?e.resumeDepth:i.subagent.resumeDepth,verificationVerdict:e.verificationVerdict==="pass"||e.verificationVerdict==="fail"||e.verificationVerdict==="partial"?e.verificationVerdict:i.subagent.verificationVerdict})},tt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId,i=e.toolName;if(!s||!i)return;const r=e.subagentSessionId,d=b(o,r,a);if(!d)return;const c={toolCallId:s,toolName:i,arguments:e.arguments,toolKind:e.toolKind,status:"running",startTime:Date.now()};u(d.messageId,d.subagent.id,l=>{const g=l.toolCalls||[];return{sessionId:l.sessionId||r,currentTool:i,toolCalls:g.some(I=>I.toolCallId===s)?g:[...g,c]}})},nt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId;if(!s)return;const i=e.toolName,r=e.subagentSessionId,d=b(o,r,a);if(!d)return;const c=e.output,l=e.success===!0,g=l?"success":"error",I=e.summary||(c&&c.trim()?c.trim().split(`
17
- `)[0].slice(0,120):l?"执行成功":"执行失败");u(d.messageId,d.subagent.id,m=>({sessionId:m.sessionId||r,currentTool:m.currentTool===i?void 0:m.currentTool,toolCalls:(m.toolCalls||[]).map(S=>S.toolCallId===s?{...S,status:g,summary:I,output:c,metadata:e.metadata}:S)}))},st=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId;if(!s)return;const i=b(o,e.subagentSessionId,a);i&&u(i.messageId,i.subagent.id,r=>({toolCalls:(r.toolCalls||[]).map(d=>d.toolCallId===s?{...d,summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message}:d)}))},it=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=Array.isArray(e.added)?e.added.map(String):[],r=Array.isArray(e.removed)?e.removed.map(String):[],d=Array.isArray(e.updated)?e.updated.map(String):[],c=`mcp-catalog:${String(e.revision)}`;u(s.messageId,s.subagent.id,l=>({toolCalls:[...(l.toolCalls||[]).filter(g=>g.toolCallId!==c),{toolCallId:c,toolName:"MCP Catalog",arguments:JSON.stringify({serverName:e.serverName,added:i,removed:r,updated:d}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP catalog r${String(e.revision)}: +${i.length} -${r.length} ~${d.length}`,output:[i.length>0?`Added: ${i.join(", ")}`:"",r.length>0?`Removed: ${r.join(", ")}`:"",d.length>0?`Updated: ${d.join(", ")}`:""].filter(Boolean).join(`
18
- `)}]}))},ot=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=Array.isArray(e.added)?e.added.map(String):[],r=Array.isArray(e.removed)?e.removed.map(String):[],d=Array.isArray(e.updated)?e.updated.map(String):[],c=`mcp-content:${String(e.revision)}`;u(s.messageId,s.subagent.id,l=>({toolCalls:[...(l.toolCalls||[]).filter(g=>g.toolCallId!==c),{toolCallId:c,toolName:"MCP Content",arguments:JSON.stringify({serverName:e.serverName,contentKind:e.contentKind,added:i,removed:r,updated:d}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP ${String(e.contentKind)} r${String(e.revision)}: +${i.length} -${r.length} ~${d.length}`}]}))},at=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=`mcp-resource:${String(e.revision)}`;u(s.messageId,s.subagent.id,r=>({toolCalls:[...(r.toolCalls||[]).filter(d=>d.toolCallId!==i),{toolCallId:i,toolName:"MCP Resource",arguments:JSON.stringify({serverName:e.serverName,uri:e.uri}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP resource updated: ${String(e.uri)}`}]}))},rt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=String(e.phase),r=`mcp-connection:${String(e.revision)}`;u(s.messageId,s.subagent.id,d=>({toolCalls:[...(d.toolCalls||[]).filter(c=>c.toolCallId!==r),{toolCallId:r,toolName:"MCP Connection",arguments:JSON.stringify({serverName:e.serverName,phase:i,reason:e.reason,attempt:e.attempt,maxAttempts:e.maxAttempts}),toolKind:"readonly",status:i==="failed"?"error":"success",startTime:Date.now(),summary:`MCP ${String(e.serverName)} ${i}`+(i==="reconnecting"?` (${String(e.attempt)}/${String(e.maxAttempts)})`:""),output:e.error?`Error: ${String(e.error)}`:void 0}]}))},ut=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=String(e.level),r=typeof e.logger=="string"?e.logger:void 0,d=`mcp-log:${String(e.revision)}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Log",arguments:JSON.stringify({serverName:e.serverName,level:i,logger:r}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP ${i} · ${String(e.serverName)}`+(r?` · ${r}`:""),output:[String(e.message),`SHA-256: ${String(e.dataSha256)}`,e.truncated===!0?"Truncated":"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
19
- `)}]}))},dt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=String(e.serverName),r=String(e.action),d=`mcp-instructions:${String(e.revision)}:${i}:${r}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:i,action:r,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP instructions ${r}: ${i}`+(e.truncated===!0?" (truncated)":""),output:[typeof e.text=="string"?e.text:"",e.sha256?`SHA-256: ${String(e.sha256)}`:"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
20
- `)}]}))},lt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=String(e.taskId),r=String(e.status),d=`mcp-task:${i}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Task",arguments:JSON.stringify({taskId:i,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:r==="failed"||r==="cancelled"?"error":r==="completed"?"success":"running",startTime:Number(e.createdAt)||Date.now(),summary:`MCP task ${r}: ${i} · ${String(e.serverName)}/${String(e.toolName)}`,output:[typeof e.statusMessage=="string"?e.statusMessage:"",e.hasResult===!0?"Result available via TaskOutput":"",typeof e.error=="string"?`Error: ${e.error}`:""].filter(Boolean).join(`
21
- `)}]}))},ct=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],r=`project-rules:${i.map(d=>String(d.id)).join(",")}`;u(s.messageId,s.subagent.id,d=>({toolCalls:[...(d.toolCalls||[]).filter(c=>c.toolCallId!==r),{toolCallId:r,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:e.blockedWrite}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`Project rules loaded: ${i.length}`,output:i.map(c=>`${String(c.relativePath)} ${String(c.source)} SHA-256: ${String(c.contentSha256)}`).join(`
22
- `)}]}))},gt=(e,t,n)=>{const{currentSessionId:a,setConfirmation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||"",s=v(t,n,u?`assistant-permission-${u}`:void 0);if(!s)return;const i=e.details,r=e.toolName||(i==null?void 0:i.toolName)||"Tool";o(s,{toolCallId:u,toolName:r,description:e.description,diff:(i==null?void 0:i.details)||(i==null?void 0:i.diff)||"",allowRemember:(i==null?void 0:i.type)!=="mcpSampling",status:"pending"}),n(d=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:d.sessions.map(c=>c.sessionId===e.sessionId&&c.projectPath===e.projectPath?{...c,pendingInteraction:{type:"permission",requestId:u}}:c)}))},mt=(e,t,n)=>{var I,m;const{currentSessionId:a,currentSessionRef:o,messages:u,setConfirmation:s,setElicitation:i}=t();if(e.sessionId!==a)return;const r=e.requestId,d=u.find(S=>{var h,y;return((y=(h=S.agentContent)==null?void 0:h.confirmation)==null?void 0:y.toolCallId)===r}),c=(I=d==null?void 0:d.agentContent)==null?void 0:I.confirmation;d&&(c==null?void 0:c.status)==="pending"&&s(d.id,{...c,status:"denied"});const l=u.find(S=>{var h,y;return((y=(h=S.agentContent)==null?void 0:h.elicitation)==null?void 0:y.toolCallId)===r}),g=(m=l==null?void 0:l.agentContent)==null?void 0:m.elicitation;l&&(g==null?void 0:g.status)==="pending"&&i(l.id,{...g,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...o?{sessionRef:o}:{}}})},ae=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0})},ft=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:e.reason==="context_limit"?"recovering_context":"compacting"})},It=(e,t,n)=>{e.sessionId===t().currentSessionId&&(t().resetContextUsage(),n({agentPhase:"running"}))},St=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerRetry:null,providerStall:null,actionStationarity:null})},yt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},ht=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerStall:e.phase==="detected"?e:null})},Ct=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",actionStationarity:e.phase==="recovered"?null:e})},bt=(e,t,n)=>{const{currentSessionId:a,setQuestion:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=v(t,n,u?`assistant-question-${u}`:void 0);s&&(o(s,{toolCallId:u,questions:e.questions,status:"pending"}),n(i=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:i.sessions.map(r=>r.sessionId===e.sessionId&&r.projectPath===e.projectPath?{...r,pendingInteraction:{type:"question",requestId:u}}:r)})))},vt=(e,t,n)=>{const{currentSessionId:a,setElicitation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=v(t,n,u?`assistant-elicitation-${u}`:void 0),i=e.elicitation;!s||!i||(o(s,{toolCallId:u,details:i,status:"pending"}),n(r=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:r.sessions.map(d=>d.sessionId===e.sessionId&&d.projectPath===e.projectPath?{...d,pendingInteraction:{type:"elicitation",requestId:u}}:d)})))},At=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId!==a)return;const o=e.requestId;n(u=>({agentPhase:"running",sessions:u.sessions.map(s=>{var i;return s.sessionId===e.sessionId&&s.projectPath===e.projectPath&&((i=s.pendingInteraction)==null?void 0:i.requestId)===o?{...s,pendingInteraction:void 0}:s})}))},B=(e,t)=>{const{currentSessionId:n,endAgentResponse:a}=t();e.sessionId===n&&a()},kt=(e,t,n)=>{const{currentSessionId:a,currentSessionRef:o,endAgentResponse:u}=t();if(e.sessionId!==a)return;const s=e.taskFailure&&typeof e.taskFailure=="object"&&!Array.isArray(e.taskFailure)?e.taskFailure:void 0,i=Me(s==null?void 0:s.code);n({agentPhase:"error",error:e.error||"An error occurred",errorContext:{kind:"execution",...o?{sessionRef:o}:{},...i?{failureCode:i}:{}}}),u()},Tt=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId===a)if(e.status==="idle")n({isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0});else if(e.status==="queued"||e.status==="running"||e.status==="waiting_permission"){const o=typeof e.queued=="number"?Math.max(0,e.queued):0;n({isStreaming:!0,agentPhase:e.status==="waiting_permission"?"waiting_permission":"running",currentRunId:typeof e.runId=="string"?e.runId:t().currentRunId,pendingSteeringCount:o,pendingInputDelivery:o>0&&(e.pendingInputDelivery==="current_turn"||e.pendingInputDelivery==="next_turn")?e.pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})}else e.status==="error"&&n({isStreaming:!1,isStopping:!1,agentPhase:"error",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null})},$t=(e,t,n)=>{const{currentSessionId:a,endAgentResponse:o,messages:u,updateSubagent:s}=t();if(e.sessionId===a){n(i=>({isStreaming:!1,agentPhase:"idle",messages:i.messages.map(r=>{var c;const d=(c=r.agentContent)==null?void 0:c.elicitation;return(d==null?void 0:d.status)!=="pending"||!r.agentContent?r:{...r,agentContent:{...r.agentContent,elicitation:{...d,status:"cancelled"}}}})}));for(const i of u)for(const r of N(i.agentContent))r.status==="running"&&s(i.id,r.id,{status:"failed"});o()}},fe=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},Ie=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},Nt=(e,t,n)=>{if(typeof e.childSessionId=="string"){const a={...e,subagentSessionId:e.childSessionId,success:e.status==="completed"};b(t().messages,e.childSessionId,t().currentAssistantMessageId)?Y(a,t):De(e.childSessionId,a,n)}e.delivery==="current_turn"?fe(e,t,n):Ie(e,t,n)},Mt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({pendingSteeringCount:a,pendingInputDelivery:a>0?t().pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},Pt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({agentPhase:"running",pendingSteeringCount:a,pendingInputDelivery:a>0?"current_turn":null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},Rt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},xt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},Dt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},wt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId||!Array.isArray(e.messages))return;const a=Date.now(),o=e.messages.flatMap((u,s)=>{if(typeof u!="object"||u===null)return[];const i=u;return!["user","assistant","system","tool"].includes(String(i.role))||!Array.isArray(i.content)&&typeof i.content!="string"?[]:[{id:`rewind-${s}-${a}`,role:i.role,content:i.content,timestamp:a+s,metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:void 0,thinkingContent:typeof i.thinkingContent=="string"?i.thinkingContent:typeof i.reasoningContent=="string"?i.reasoningContent:void 0,tool_call_id:typeof i.tool_call_id=="string"?i.tool_call_id:void 0,name:typeof i.name=="string"?i.name:void 0,tool_calls:i.tool_calls}]});n({messages:$e(o),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},_t=(e,t,n)=>{const a=t().currentSessionRef;if(!a||e.sessionId!==a.sessionId||e.projectPath!==a.projectPath)return;const o=e.status,u=o==="completed"||o==="stale"?"completed":o==="aborted"?"cancelled":o==="interrupted"?"interrupted":"failed";n(s=>({sessions:s.sessions.map(i=>i.sessionId===a.sessionId&&i.projectPath===a.projectPath?{...i,taskStatus:u,taskStatusReason:void 0,taskFailure:void 0,taskCompletedAt:new Date().toISOString()}:i)})),t().selectSession(a)},jt=(e,t,n)=>{ce({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},Ft=(e,t,n)=>{ge(e,t)},qt=(e,t,n)=>{me(e,t,n)},_={"message.created":we,"message.delta":_e,"message.complete":je,"structured.output":Fe,"thinking.delta":qe,"thinking.completed":Oe,"tool.start":ce,"tool.progress":ge,"tool.result":me,"mcp.catalog.changed":Ee,"mcp.content.changed":Ve,"mcp.resource.updated":Ke,"mcp.connection.changed":Ue,"mcp.log":Be,"mcp.instructions.changed":Je,"mcp.task.changed":Le,"project.rules.loaded":He,"user.shell.started":Ge,"user.shell.output":Qe,"user.shell.completed":ze,"token.usage":We,"task.updated":Ye,"subagent.start":Xe,"subagent.update":Ze,"subagent.delta":pe,"subagent.thinking.delta":et,"subagent.tool.start":tt,"subagent.tool.progress":st,"subagent.tool.result":nt,"subagent.mcp.catalog.changed":it,"subagent.mcp.content.changed":ot,"subagent.mcp.resource.updated":at,"subagent.mcp.connection.changed":rt,"subagent.mcp.log":ut,"subagent.mcp.instructions.changed":dt,"subagent.mcp.task.changed":lt,"subagent.project.rules.loaded":ct,"subagent.complete":Y,"subagent.completion.queued":Nt,"permission.asked":gt,"permission.timeout":mt,"turn.started":ae,"committed.turn_started":ae,"committed.turn_completed":B,"committed.turn_aborted":B,"provider.retry":yt,"provider.stall":ht,"action.stationarity":Ct,"compaction.started":ft,"compaction.completed":It,"model.fallback":St,"question.required":bt,"elicitation.required":vt,"interaction.resolved":At,"session.completed":B,"session.error":kt,"session.status":Tt,"run.cancelled":$t,"steering.queued":fe,"follow_up.queued":Ie,"follow_up.started":Pt,"steering.applied":Mt,"goal.updated":Rt,"goal.cleared":xt,"goal.continuation.started":Dt,"session.rewound":wt,"review.tool.started":jt,"review.tool.progress":Ft,"review.tool.completed":qt,"review.completed":_t},Ot=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]),Ut=(e,t)=>n=>{const a=e().currentSessionRef,o=n.properties;if(!a||o.sessionId!==a.sessionId||o.projectPath!==a.projectPath)return;if(Ot.has(n.type)){$.drainAll();const s=_[n.type];s&&s(n.properties,e,t);return}if(n.type==="tool.start"&&$.drainAll(),n.type==="message.delta"){const{currentSessionId:s,currentAssistantMessageId:i,hasToolCalls:r}=e();if(o.sessionId!==s)return;const d=o.messageId||i,c=o.delta;if(!i){const I=_["message.delta"];I&&I(o,e,t);return}const l=r?"after":"before",g=`content:${d}:${l}`;$.drainAllExcept(g),$.append(g,c,I=>{const{appendDelta:m}=e();d&&m(d,I,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:s,currentAssistantMessageId:i}=e();if(o.sessionId!==s)return;if(!i){const l=_["thinking.delta"];l&&l(o,e,t);return}const r=o.delta,d=o.messageId||i,c=`thinking:${d}`;$.drainAllExcept(c),$.append(c,r,l=>{const{appendThinking:g}=e();d&&g(d,l)});return}if(n.type==="subagent.delta"){const{currentSessionId:s}=e();if(o.sessionId!==s)return;const i=o.delta;if(!i)return;const r=o.subagentSessionId||"",d=`subagent:${r}`,{currentAssistantMessageId:c,messages:l}=e(),g=b(l,r||void 0,c);$.append(d,i,I=>{const{currentAssistantMessageId:m,messages:S,updateSubagent:h}=e(),y=g||b(S,r||void 0,m);y&&h(y.messageId,y.subagent.id,f=>({sessionId:f.sessionId||r,output:(f.output||"")+I}))});return}if(n.type==="subagent.thinking.delta"){const{currentSessionId:s}=e();if(o.sessionId!==s)return;const i=o.delta;if(!i)return;const r=o.subagentSessionId||"",d=`subagent-thinking:${r}`,{currentAssistantMessageId:c,messages:l}=e(),g=b(l,r||void 0,c);$.append(d,i,I=>{const{currentAssistantMessageId:m,messages:S,updateSubagent:h}=e(),y=g||b(S,r||void 0,m);y&&h(y.messageId,y.subagent.id,f=>({sessionId:f.sessionId||r,thinking:(f.thinking||"")+I}))});return}const u=_[n.type];u&&u(n.properties,e,t)};export{Ce as a,oe as b,M as c,he as d,$e as e,Ut as f,N as g,$ as h,Me as i,Kt as j,be as k,j as l,Vt as t,re as u,J as w};
15
+ `),g=z(e.executionId),I={role:"user",content:[`! ${r}`,l||"(no output)"].join(`
16
+ `),metadata:{userShellCommand:i}};o.some(m=>m.id===g)?s(g,I):u({id:g,...I,timestamp:Date.now()}),e.auxiliary!==!0&&n({isStreaming:!1,isStopping:!1,agentPhase:"idle"}),(e.delivery==="current_turn"||e.delivery==="next_turn")&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):0,pendingInputDelivery:e.delivery==="current_turn"?"current_turn":"next_turn"})},Ye=(e,t)=>{const{currentSessionId:n,updateTokenUsage:a,setMaxContextTokens:o}=t();e.sessionId===n&&(a({inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,cacheReadTokens:e.cacheReadTokens??0,cacheWriteTokens:e.cacheWriteTokens??0,costUsd:e.costUsd}),e.maxContextTokens&&o(e.maxContextTokens,!1))},Xe=(e,t)=>{const{currentSessionId:n,setTasks:a,currentAssistantMessageId:o}=t();if(e.sessionId!==n||!o)return;const u=e.tasks||[];a(o,u)},Ze=(e,t,n)=>{const{currentSessionId:a,setSubagent:o,currentAssistantMessageId:u}=t();if(e.sessionId!==a||!u)return;const s={id:F({explicitId:e.subagentId,sessionId:e.subagentSessionId,messageId:u,agentType:e.type,description:e.description}),type:e.type||"unknown",description:e.description||"",status:"running",startTime:Date.now(),sessionId:e.subagentSessionId,resumedFrom:e.resumedFrom,rootAgentId:e.rootAgentId,resumeDepth:typeof e.resumeDepth=="number"?e.resumeDepth:void 0};o(u,s),Q(s.sessionId,t,n)},pe=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.subagentSessionId,i=b(o,s,a);i&&u(i.messageId,i.subagent.id,{sessionId:i.subagent.sessionId||s,currentTool:e.toolName})},et=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.delta;if(!s)return;const i=e.subagentSessionId,r=b(o,i,a);r&&u(r.messageId,r.subagent.id,d=>({sessionId:d.sessionId||i,output:(d.output||"")+s}))},tt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.delta;if(!s)return;const i=e.subagentSessionId,r=b(o,i,a);r&&u(r.messageId,r.subagent.id,d=>({sessionId:d.sessionId||i,thinking:(d.thinking||"")+s}))},W=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.subagentSessionId,i=b(o,s,a);if(!i)return;const r=e.status==="completed"?"completed":e.status==="failed"||e.status==="cancelled"?"failed":e.success?"completed":"failed";u(i.messageId,i.subagent.id,{sessionId:i.subagent.sessionId||s,type:typeof e.type=="string"?e.type:i.subagent.type,description:typeof e.description=="string"?e.description:i.subagent.description,status:r,currentTool:void 0,output:typeof e.summary=="string"?e.summary:i.subagent.output,resumedFrom:typeof e.resumedFrom=="string"?e.resumedFrom:i.subagent.resumedFrom,rootAgentId:typeof e.rootAgentId=="string"?e.rootAgentId:i.subagent.rootAgentId,resumeDepth:typeof e.resumeDepth=="number"?e.resumeDepth:i.subagent.resumeDepth,verificationVerdict:e.verificationVerdict==="pass"||e.verificationVerdict==="fail"||e.verificationVerdict==="partial"?e.verificationVerdict:i.subagent.verificationVerdict})},nt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId,i=e.toolName;if(!s||!i)return;const r=e.subagentSessionId,d=b(o,r,a);if(!d)return;const c={toolCallId:s,toolName:i,arguments:e.arguments,toolKind:e.toolKind,status:"running",startTime:Date.now()};u(d.messageId,d.subagent.id,l=>{const g=l.toolCalls||[];return{sessionId:l.sessionId||r,currentTool:i,toolCalls:g.some(I=>I.toolCallId===s)?g:[...g,c]}})},st=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId;if(!s)return;const i=e.toolName,r=e.subagentSessionId,d=b(o,r,a);if(!d)return;const c=e.output,l=e.success===!0,g=l?"success":"error",I=e.summary||(c&&c.trim()?c.trim().split(`
17
+ `)[0].slice(0,120):l?"执行成功":"执行失败");u(d.messageId,d.subagent.id,m=>({sessionId:m.sessionId||r,currentTool:m.currentTool===i?void 0:m.currentTool,toolCalls:(m.toolCalls||[]).map(S=>S.toolCallId===s?{...S,status:g,summary:I,output:c,metadata:e.metadata}:S)}))},it=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId;if(!s)return;const i=b(o,e.subagentSessionId,a);i&&u(i.messageId,i.subagent.id,r=>({toolCalls:(r.toolCalls||[]).map(d=>d.toolCallId===s?{...d,summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message}:d)}))},ot=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=Array.isArray(e.added)?e.added.map(String):[],r=Array.isArray(e.removed)?e.removed.map(String):[],d=Array.isArray(e.updated)?e.updated.map(String):[],c=`mcp-catalog:${String(e.revision)}`;u(s.messageId,s.subagent.id,l=>({toolCalls:[...(l.toolCalls||[]).filter(g=>g.toolCallId!==c),{toolCallId:c,toolName:"MCP Catalog",arguments:JSON.stringify({serverName:e.serverName,added:i,removed:r,updated:d}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP catalog r${String(e.revision)}: +${i.length} -${r.length} ~${d.length}`,output:[i.length>0?`Added: ${i.join(", ")}`:"",r.length>0?`Removed: ${r.join(", ")}`:"",d.length>0?`Updated: ${d.join(", ")}`:""].filter(Boolean).join(`
18
+ `)}]}))},at=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=Array.isArray(e.added)?e.added.map(String):[],r=Array.isArray(e.removed)?e.removed.map(String):[],d=Array.isArray(e.updated)?e.updated.map(String):[],c=`mcp-content:${String(e.revision)}`;u(s.messageId,s.subagent.id,l=>({toolCalls:[...(l.toolCalls||[]).filter(g=>g.toolCallId!==c),{toolCallId:c,toolName:"MCP Content",arguments:JSON.stringify({serverName:e.serverName,contentKind:e.contentKind,added:i,removed:r,updated:d}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP ${String(e.contentKind)} r${String(e.revision)}: +${i.length} -${r.length} ~${d.length}`}]}))},rt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=`mcp-resource:${String(e.revision)}`;u(s.messageId,s.subagent.id,r=>({toolCalls:[...(r.toolCalls||[]).filter(d=>d.toolCallId!==i),{toolCallId:i,toolName:"MCP Resource",arguments:JSON.stringify({serverName:e.serverName,uri:e.uri}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP resource updated: ${String(e.uri)}`}]}))},ut=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=String(e.phase),r=`mcp-connection:${String(e.revision)}`;u(s.messageId,s.subagent.id,d=>({toolCalls:[...(d.toolCalls||[]).filter(c=>c.toolCallId!==r),{toolCallId:r,toolName:"MCP Connection",arguments:JSON.stringify({serverName:e.serverName,phase:i,reason:e.reason,attempt:e.attempt,maxAttempts:e.maxAttempts}),toolKind:"readonly",status:i==="failed"?"error":"success",startTime:Date.now(),summary:`MCP ${String(e.serverName)} ${i}`+(i==="reconnecting"?` (${String(e.attempt)}/${String(e.maxAttempts)})`:""),output:e.error?`Error: ${String(e.error)}`:void 0}]}))},dt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=String(e.level),r=typeof e.logger=="string"?e.logger:void 0,d=`mcp-log:${String(e.revision)}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Log",arguments:JSON.stringify({serverName:e.serverName,level:i,logger:r}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP ${i} · ${String(e.serverName)}`+(r?` · ${r}`:""),output:[String(e.message),`SHA-256: ${String(e.dataSha256)}`,e.truncated===!0?"Truncated":"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
19
+ `)}]}))},lt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=String(e.serverName),r=String(e.action),d=`mcp-instructions:${String(e.revision)}:${i}:${r}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:i,action:r,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP instructions ${r}: ${i}`+(e.truncated===!0?" (truncated)":""),output:[typeof e.text=="string"?e.text:"",e.sha256?`SHA-256: ${String(e.sha256)}`:"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
20
+ `)}]}))},ct=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=String(e.taskId),r=String(e.status),d=`mcp-task:${i}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Task",arguments:JSON.stringify({taskId:i,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:r==="failed"||r==="cancelled"?"error":r==="completed"?"success":"running",startTime:Number(e.createdAt)||Date.now(),summary:`MCP task ${r}: ${i} · ${String(e.serverName)}/${String(e.toolName)}`,output:[typeof e.statusMessage=="string"?e.statusMessage:"",e.hasResult===!0?"Result available via TaskOutput":"",typeof e.error=="string"?`Error: ${e.error}`:""].filter(Boolean).join(`
21
+ `)}]}))},gt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(o,e.subagentSessionId,a);if(!s)return;const i=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],r=`project-rules:${i.map(d=>String(d.id)).join(",")}`;u(s.messageId,s.subagent.id,d=>({toolCalls:[...(d.toolCalls||[]).filter(c=>c.toolCallId!==r),{toolCallId:r,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:e.blockedWrite}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`Project rules loaded: ${i.length}`,output:i.map(c=>`${String(c.relativePath)} ${String(c.source)} SHA-256: ${String(c.contentSha256)}`).join(`
22
+ `)}]}))},mt=(e,t,n)=>{const{currentSessionId:a,setConfirmation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||"",s=v(t,n,u?`assistant-permission-${u}`:void 0);if(!s)return;const i=e.details,r=e.toolName||(i==null?void 0:i.toolName)||"Tool";o(s,{toolCallId:u,toolName:r,description:e.description,diff:(i==null?void 0:i.details)||(i==null?void 0:i.diff)||"",allowRemember:(i==null?void 0:i.type)!=="mcpSampling",status:"pending"}),n(d=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:d.sessions.map(c=>c.sessionId===e.sessionId&&c.projectPath===e.projectPath?{...c,pendingInteraction:{type:"permission",requestId:u}}:c)}))},ft=(e,t,n)=>{var I,m;const{currentSessionId:a,currentSessionRef:o,messages:u,setConfirmation:s,setElicitation:i}=t();if(e.sessionId!==a)return;const r=e.requestId,d=u.find(S=>{var y,h;return((h=(y=S.agentContent)==null?void 0:y.confirmation)==null?void 0:h.toolCallId)===r}),c=(I=d==null?void 0:d.agentContent)==null?void 0:I.confirmation;d&&(c==null?void 0:c.status)==="pending"&&s(d.id,{...c,status:"denied"});const l=u.find(S=>{var y,h;return((h=(y=S.agentContent)==null?void 0:y.elicitation)==null?void 0:h.toolCallId)===r}),g=(m=l==null?void 0:l.agentContent)==null?void 0:m.elicitation;l&&(g==null?void 0:g.status)==="pending"&&i(l.id,{...g,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...o?{sessionRef:o}:{}}})},ae=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0})},It=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:e.reason==="context_limit"?"recovering_context":"compacting"})},St=(e,t,n)=>{e.sessionId===t().currentSessionId&&(t().resetContextUsage(),n({agentPhase:"running"}))},ht=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerRetry:null,providerStall:null,actionStationarity:null})},yt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},Ct=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerStall:e.phase==="detected"?e:null})},bt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",actionStationarity:e.phase==="recovered"?null:e})},vt=(e,t,n)=>{const{currentSessionId:a,setQuestion:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=v(t,n,u?`assistant-question-${u}`:void 0);s&&(o(s,{toolCallId:u,questions:e.questions,status:"pending"}),n(i=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:i.sessions.map(r=>r.sessionId===e.sessionId&&r.projectPath===e.projectPath?{...r,pendingInteraction:{type:"question",requestId:u}}:r)})))},At=(e,t,n)=>{const{currentSessionId:a,setElicitation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=v(t,n,u?`assistant-elicitation-${u}`:void 0),i=e.elicitation;!s||!i||(o(s,{toolCallId:u,details:i,status:"pending"}),n(r=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:r.sessions.map(d=>d.sessionId===e.sessionId&&d.projectPath===e.projectPath?{...d,pendingInteraction:{type:"elicitation",requestId:u}}:d)})))},Tt=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId!==a)return;const o=e.requestId;n(u=>({agentPhase:"running",sessions:u.sessions.map(s=>{var i;return s.sessionId===e.sessionId&&s.projectPath===e.projectPath&&((i=s.pendingInteraction)==null?void 0:i.requestId)===o?{...s,pendingInteraction:void 0}:s})}))},Y=(e,t)=>{const n=t().currentSessionRef;n&&e.sessionId===n.sessionId&&e.projectPath===n.projectPath&&t().resyncSessionMessages(n)},kt=(e,t)=>{const{currentSessionId:n,currentSessionRef:a,endAgentResponse:o}=t();e.sessionId!==n||!a||e.projectPath!==a.projectPath||(o(),Y(e,t))},re=(e,t)=>{const n=t().currentSessionRef;!n||e.sessionId!==n.sessionId||e.projectPath!==n.projectPath||t().endAgentResponse()},$t=(e,t,n)=>{const{currentSessionId:a,currentSessionRef:o,endAgentResponse:u}=t();if(e.sessionId!==a)return;const s=e.taskFailure&&typeof e.taskFailure=="object"&&!Array.isArray(e.taskFailure)?e.taskFailure:void 0,i=Pe(s==null?void 0:s.code);n({agentPhase:"error",error:e.error||"An error occurred",errorContext:{kind:"execution",...o?{sessionRef:o}:{},...i?{failureCode:i}:{}}}),u(),Y(e,t)},Nt=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId===a)if(e.status==="idle")n({isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0});else if(e.status==="queued"||e.status==="running"||e.status==="waiting_permission"){const o=typeof e.queued=="number"?Math.max(0,e.queued):0;n({isStreaming:!0,agentPhase:e.status==="waiting_permission"?"waiting_permission":"running",currentRunId:typeof e.runId=="string"?e.runId:t().currentRunId,pendingSteeringCount:o,pendingInputDelivery:o>0&&(e.pendingInputDelivery==="current_turn"||e.pendingInputDelivery==="next_turn")?e.pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})}else e.status==="error"&&n({isStreaming:!1,isStopping:!1,agentPhase:"error",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null})},Mt=(e,t,n)=>{const{currentSessionId:a,endAgentResponse:o,messages:u,updateSubagent:s}=t();if(e.sessionId===a){n(i=>({isStreaming:!1,agentPhase:"idle",messages:i.messages.map(r=>{var c;const d=(c=r.agentContent)==null?void 0:c.elicitation;return(d==null?void 0:d.status)!=="pending"||!r.agentContent?r:{...r,agentContent:{...r.agentContent,elicitation:{...d,status:"cancelled"}}}})}));for(const i of u)for(const r of N(i.agentContent))r.status==="running"&&s(i.id,r.id,{status:"failed"});o(),Y(e,t)}},Ie=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},Se=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},Pt=(e,t,n)=>{if(typeof e.childSessionId=="string"){const a={...e,subagentSessionId:e.childSessionId,success:e.status==="completed"};b(t().messages,e.childSessionId,t().currentAssistantMessageId)?W(a,t):we(e.childSessionId,a,n)}e.delivery==="current_turn"?Ie(e,t,n):Se(e,t,n)},Rt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({pendingSteeringCount:a,pendingInputDelivery:a>0?t().pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},xt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({agentPhase:"running",pendingSteeringCount:a,pendingInputDelivery:a>0?"current_turn":null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},Dt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},wt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},_t=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},jt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId||!Array.isArray(e.messages))return;const a=Date.now(),o=e.messages.flatMap((u,s)=>{if(typeof u!="object"||u===null)return[];const i=u;return!["user","assistant","system","tool"].includes(String(i.role))||!Array.isArray(i.content)&&typeof i.content!="string"?[]:[{id:`rewind-${s}-${a}`,role:i.role,content:i.content,timestamp:a+s,metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:void 0,thinkingContent:typeof i.thinkingContent=="string"?i.thinkingContent:typeof i.reasoningContent=="string"?i.reasoningContent:void 0,tool_call_id:typeof i.tool_call_id=="string"?i.tool_call_id:void 0,name:typeof i.name=="string"?i.name:void 0,tool_calls:i.tool_calls}]});n({messages:Ne(o),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},Ft=(e,t,n)=>{const a=t().currentSessionRef;if(!a||e.sessionId!==a.sessionId||e.projectPath!==a.projectPath)return;const o=e.status,u=o==="completed"||o==="stale"?"completed":o==="aborted"?"cancelled":o==="interrupted"?"interrupted":"failed";n(s=>({sessions:s.sessions.map(i=>i.sessionId===a.sessionId&&i.projectPath===a.projectPath?{...i,taskStatus:u,taskStatusReason:void 0,taskFailure:void 0,taskCompletedAt:new Date().toISOString()}:i)})),t().selectSession(a)},qt=(e,t,n)=>{ge({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},Ot=(e,t,n)=>{me(e,t)},Et=(e,t,n)=>{fe(e,t,n)},_={"message.created":_e,"message.delta":je,"message.complete":Fe,"structured.output":qe,"thinking.delta":Oe,"thinking.completed":Ee,"tool.start":ge,"tool.progress":me,"tool.result":fe,"mcp.catalog.changed":Ve,"mcp.content.changed":Ke,"mcp.resource.updated":Ue,"mcp.connection.changed":Be,"mcp.log":Je,"mcp.instructions.changed":Le,"mcp.task.changed":He,"project.rules.loaded":Ge,"user.shell.started":Qe,"user.shell.output":ze,"user.shell.completed":We,"token.usage":Ye,"task.updated":Xe,"subagent.start":Ze,"subagent.update":pe,"subagent.delta":et,"subagent.thinking.delta":tt,"subagent.tool.start":nt,"subagent.tool.progress":it,"subagent.tool.result":st,"subagent.mcp.catalog.changed":ot,"subagent.mcp.content.changed":at,"subagent.mcp.resource.updated":rt,"subagent.mcp.connection.changed":ut,"subagent.mcp.log":dt,"subagent.mcp.instructions.changed":lt,"subagent.mcp.task.changed":ct,"subagent.project.rules.loaded":gt,"subagent.complete":W,"subagent.completion.queued":Pt,"permission.asked":mt,"permission.timeout":ft,"turn.started":ae,"committed.turn_started":ae,"committed.turn_completed":re,"committed.turn_aborted":re,"provider.retry":yt,"provider.stall":Ct,"action.stationarity":bt,"compaction.started":It,"compaction.completed":St,"model.fallback":ht,"question.required":vt,"elicitation.required":At,"interaction.resolved":Tt,"session.completed":kt,"session.error":$t,"session.status":Nt,"run.cancelled":Mt,"steering.queued":Ie,"follow_up.queued":Se,"follow_up.started":xt,"steering.applied":Rt,"goal.updated":Dt,"goal.cleared":wt,"goal.continuation.started":_t,"session.rewound":jt,"review.tool.started":qt,"review.tool.progress":Ot,"review.tool.completed":Et,"review.completed":Ft},Vt=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]),Jt=(e,t)=>n=>{const a=e().currentSessionRef,o=n.properties;if(!a||o.sessionId!==a.sessionId||o.projectPath!==a.projectPath)return;if(Vt.has(n.type)){$.drainAll();const s=_[n.type];s&&s(n.properties,e,t);return}if(n.type==="tool.start"&&$.drainAll(),n.type==="message.delta"){const{currentSessionId:s,currentAssistantMessageId:i,hasToolCalls:r}=e();if(o.sessionId!==s)return;const d=o.messageId||i,c=o.delta;if(!i){const I=_["message.delta"];I&&I(o,e,t);return}const l=r?"after":"before",g=`content:${d}:${l}`;$.drainAllExcept(g),$.append(g,c,I=>{const{appendDelta:m}=e();d&&m(d,I,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:s,currentAssistantMessageId:i}=e();if(o.sessionId!==s)return;if(!i){const l=_["thinking.delta"];l&&l(o,e,t);return}const r=o.delta,d=o.messageId||i,c=`thinking:${d}`;$.drainAllExcept(c),$.append(c,r,l=>{const{appendThinking:g}=e();d&&g(d,l)});return}if(n.type==="subagent.delta"){const{currentSessionId:s}=e();if(o.sessionId!==s)return;const i=o.delta;if(!i)return;const r=o.subagentSessionId||"",d=`subagent:${r}`,{currentAssistantMessageId:c,messages:l}=e(),g=b(l,r||void 0,c);$.append(d,i,I=>{const{currentAssistantMessageId:m,messages:S,updateSubagent:y}=e(),h=g||b(S,r||void 0,m);h&&y(h.messageId,h.subagent.id,f=>({sessionId:f.sessionId||r,output:(f.output||"")+I}))});return}if(n.type==="subagent.thinking.delta"){const{currentSessionId:s}=e();if(o.sessionId!==s)return;const i=o.delta;if(!i)return;const r=o.subagentSessionId||"",d=`subagent-thinking:${r}`,{currentAssistantMessageId:c,messages:l}=e(),g=b(l,r||void 0,c);$.append(d,i,I=>{const{currentAssistantMessageId:m,messages:S,updateSubagent:y}=e(),h=g||b(S,r||void 0,m);h&&y(h.messageId,h.subagent.id,f=>({sessionId:f.sessionId||r,thinking:(f.thinking||"")+I}))});return}const u=_[n.type];u&&u(n.properties,e,t)};export{be as a,oe as b,M as c,Ce as d,Ne as e,Jt as f,N as g,$ as h,Pe as i,Bt as j,ve as k,j as l,Ut as t,ue as u,B as w};
@@ -5,11 +5,11 @@
5
5
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>BladeCode</title>
8
- <script type="module" crossorigin src="/assets/index-CxwsVMYL.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-BnCT8SxR.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-DG5dkZ_t.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/vendor-radix-DXRuAJHH.js">
11
11
  <link rel="modulepreload" crossorigin href="/assets/vendor-icons-ICv1v-tf.js">
12
- <link rel="modulepreload" crossorigin href="/assets/session-events-BZdQ71sF.js">
12
+ <link rel="modulepreload" crossorigin href="/assets/session-events-BZao_jMQ.js">
13
13
  <link rel="stylesheet" crossorigin href="/assets/index-7zaeanZL.css">
14
14
  </head>
15
15
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.32",
3
+ "version": "0.10.34",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{ee as a,fe as b,ge as c,he as d,ie as e}from"./chunk-80r40y6k.js";import"./chunk-t23t9yff.js";import"./chunk-fb514tmd.js";import"./chunk-7m4qc5vv.js";import"./chunk-yekzckgm.js";import"./chunk-799zdv81.js";import"./chunk-xh1y705a.js";import"./chunk-mwae107k.js";import"./chunk-3ck3fxff.js";import"./chunk-x1r4b7pt.js";import"./chunk-7fgx7ztz.js";import"./chunk-75y3mb0z.js";import"./chunk-y5rsamex.js";import"./chunk-nah8b1gv.js";import"./chunk-azcjz03h.js";import"./chunk-7xytd1h7.js";import"./chunk-cjgnf6qy.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
@@ -1,10 +0,0 @@
1
- import{f as Q,g as R,h as T,i as W}from"./chunk-jdq05trf.js";import"./chunk-x0x5e65d.js";import"./chunk-3bhh4v42.js";import"./chunk-cdkrdsbw.js";import"./chunk-758hxypj.js";import"./chunk-wmsak7d3.js";import"./chunk-7bpwnpfx.js";import"./chunk-6r89cn2n.js";import"./chunk-jtk2t4wy.js";import"./chunk-8y2nh9sm.js";import"./chunk-ntmfefxh.js";import"./chunk-fp1892aa.js";import"./chunk-s61wcay9.js";import"./chunk-r68y2q62.js";import{nd as M}from"./chunk-tx77qaz8.js";import"./chunk-v508x7cg.js";import"./chunk-xhdm1b4g.js";import"./chunk-5mszemkz.js";import"./chunk-c7b5wmpm.js";import"./chunk-e66zyvph.js";import"./chunk-bmsv08sa.js";import"./chunk-80r40y6k.js";import"./chunk-t23t9yff.js";import"./chunk-fb514tmd.js";import"./chunk-7m4qc5vv.js";import"./chunk-yekzckgm.js";import"./chunk-799zdv81.js";import"./chunk-xh1y705a.js";import"./chunk-mwae107k.js";import"./chunk-3ck3fxff.js";import"./chunk-x1r4b7pt.js";import"./chunk-7fgx7ztz.js";import"./chunk-75y3mb0z.js";import"./chunk-y5rsamex.js";import"./chunk-nah8b1gv.js";import{Uf as J}from"./chunk-azcjz03h.js";import"./chunk-7xytd1h7.js";import"./chunk-cjgnf6qy.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";import b from"chalk";import H from"open";var $=`
2
- ____ _ _
3
- | __ )| | __ _ __| | ___
4
- | _ \\| |/ _\` |/ _\` |/ _ \\
5
- | |_) | | (_| | (_| | __/
6
- |____/|_|\\__,_|\\__,_|\\___|
7
- `,E={command:"web",describe:"Start Blade server and open web interface",builder:Q,handler:async(X)=>{let F=R(X);if(await M(),!process.env.BLADE_SERVER_PASSWORD)console.log(b.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(b.gray(` Set this environment variable to enable Basic Auth.
8
- `));let C=await W.listenAsync(F);if(console.log(b.cyan($)),console.log(b.gray(` v${J()}
9
- `)),F.hostname==="0.0.0.0"){let q=`http://localhost:${C.port}`;console.log(b.blue.bold(" Local access: "),b.white(q));let Y=T();for(let Z of Y)console.log(b.blue.bold(" Network access: "),b.white(`http://${Z}:${C.port}`));H(q).catch(()=>{})}else{let q=C.url.toString();console.log(b.blue.bold(" Web interface: "),b.white(q)),H(q).catch(()=>{})}console.log(""),console.log(b.gray(` Press Ctrl+C to stop the server.
10
- `)),await new Promise(()=>{}),await C.stop()}};export{E as webCommand};
@@ -1,22 +0,0 @@
1
- import{s as E}from"./chunk-cdkrdsbw.js";import{t as FJ}from"./chunk-758hxypj.js";import{$ as o,G as l,J as i,K as r,M as a,_ as n,aa as t,ba as s,w as A}from"./chunk-wmsak7d3.js";import{la as HJ}from"./chunk-7bpwnpfx.js";import"./chunk-6r89cn2n.js";import{Oa as v,bb as m,kb as d}from"./chunk-jtk2t4wy.js";import{tb as T}from"./chunk-8y2nh9sm.js";import{Mb as f,Tb as u,Wb as g,cc as M,dc as c,fc as R,ic as p,nc as _,qc as D}from"./chunk-ntmfefxh.js";import"./chunk-fp1892aa.js";import"./chunk-s61wcay9.js";import"./chunk-r68y2q62.js";import"./chunk-tx77qaz8.js";import"./chunk-v508x7cg.js";import{yd as zJ}from"./chunk-xhdm1b4g.js";import"./chunk-5mszemkz.js";import"./chunk-c7b5wmpm.js";import{Jd as WJ}from"./chunk-e66zyvph.js";import"./chunk-bmsv08sa.js";import"./chunk-80r40y6k.js";import"./chunk-t23t9yff.js";import{oe as YJ}from"./chunk-fb514tmd.js";import"./chunk-7m4qc5vv.js";import"./chunk-yekzckgm.js";import"./chunk-799zdv81.js";import"./chunk-xh1y705a.js";import"./chunk-mwae107k.js";import"./chunk-3ck3fxff.js";import{wf as I,xf as S,yf as y}from"./chunk-x1r4b7pt.js";import{Cf as QJ}from"./chunk-7fgx7ztz.js";import{Gf as b}from"./chunk-75y3mb0z.js";import"./chunk-y5rsamex.js";import{Nf as ZJ,Qf as $J}from"./chunk-nah8b1gv.js";import"./chunk-azcjz03h.js";import"./chunk-7xytd1h7.js";import"./chunk-cjgnf6qy.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";import{Readable as KJ,Writable as UJ}from"node:stream";import*as x from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as wJ}from"@agentclientprotocol/sdk";import JJ from"node:path";import{RequestError as GJ}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=b("Agent");function C(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function DJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:C(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:C("headers"in J?J.headers:void 0)};return null}function BJ(J){let Z={};for(let Q of J){let Y=DJ(Q);if(Y)Z[Q.name]=Y}return Z}function e(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function LJ(J){let Z=c(J.metadata);return Z?[{type:"text",text:M(Z)}]:e(J.content)}function VJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}mapPermissionModeToMode(J){switch(J){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return a.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await d.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?BJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await l.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(X)=>$.onOutput?.("stdout",X)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.failureKind==="timeout",aborted:F.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await o(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=v.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":z.properties}}),this.schedulePendingResume();return}if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;let Q=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!Q)continue;for(let Y of LJ(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Q,content:Y}))return}}let J=await this.runtime?.getGoal();if(J&&!await this.sendUpdateAndWait(this.goalSessionUpdate(J)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async($)=>{if(await this.setServiceTier($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async($)=>{if(await this.setResponseVerbosity($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async($)=>{if(await this.setCommunicationStyle($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=!1,j,B=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},L=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(X)B(W);else j=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,j)B(j);return L}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,F,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,X)},complete:async($,F,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,X)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),j=await X.completion,B=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===X.reviewId);if(!B)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:j.status,findings:j.findings.length,content:f(B.start,j)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,X)=>{let j=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:B})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await t(J,Q),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(Q){return G.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=s(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((X)=>X.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=p(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let X=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!X.accepted)throw Error(X.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${X.queued})`),X.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),n(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let X={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}},j=await m(this.agent.chatStream(Y,X,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let w=W.toolCall,q=w.function.name;if(q===R)break;let N=this.mapToolKind(W.toolKind),V=`Executing ${q}`;if(q==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:N});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let q=W.result,N=[],V=q.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;N.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))N.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,XJ=r(g(i(K,q),u));N.push({type:"content",content:{type:"text",text:XJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))N.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:N});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
3
- `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
4
- `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
5
- `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
6
- `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
7
- `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
8
- `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
9
- `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
10
- `}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:W.phase,attempt:W.attempt,maxRetries:W.maxRetries,reason:W.reason,...W.statusCode!==void 0?{statusCode:W.statusCode}:{},...W.delayMs!==void 0?{delayMs:W.delayMs}:{},...W.nextRetryAt!==void 0?{nextRetryAt:W.nextRetryAt}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:W.phase,stallCount:W.stallCount,durationMs:W.durationMs,warningAfterMs:W.warningAfterMs,timeoutMs:W.timeoutMs,outputStarted:W.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:W.phase,toolName:W.toolName,runLength:W.runLength,nudgeThreshold:W.nudgeThreshold,haltThreshold:W.haltThreshold,progressAware:W.progressAware}}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let w of W.messages){if(!w.recovered||w.persisted)continue;for(let q of e(w.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
11
- `}});break;case"goal_updated":if(W.goal)this.sendUpdate(this.goalSessionUpdate(W.goal));if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
12
- `}});break;case"goal_continuation_started":break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:W.phase,...W.reason?{reason:W.reason}:{},...W.strategy?{strategy:W.strategy}:{},...W.outcome?{outcome:W.outcome}:{},...W.preTokens!==void 0?{preTokens:W.preTokens}:{},...W.postTokens!==void 0?{postTokens:W.postTokens}:{}}}});break;default:break}});this.contextMessages=[...X.messages];let B=await D.loadSession(this.id,this.cwd);if(this.messages=B.length>0?B:[...X.messages],!j.success){let W=j.error?.type??"unknown";throw GJ.internalError({failureType:W},`Agent turn failed (${W})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let L={...j.metadata?.structuredOutput?{structuredOutput:j.metadata.structuredOutput,outputSchemaDigest:j.metadata.structuredOutputSchemaDigest}:{},...j.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:j.metadata.goalVerificationVerdict,...j.metadata.goalVerifierSessionId?{verifierSessionId:j.metadata.goalVerifierSessionId}:{},...j.metadata.goalVerificationEvidenceSha256?{evidenceSha256:j.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(L).length>0?{_meta:L}:{}}}catch(X){if(F.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,X),X}finally{if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let Y,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async(F)=>{if(Y=F.executionId,F.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.executionId,status:"in_progress",title:`! ${F.command}`,content:[],kind:"execute"});return}if(F.type==="output"){H+=F.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:F.chunk}}]});return}let X=M(F.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:F.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?VJ(F.record):X}}]})}}),$={role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}};if(this.messages.push($),this.contextMessages.push($),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Z=J?null:await this.runtime.getGoal(),Q=Z?.status==="active"||Z?.status==="verifying";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",Y=this.mapModeIdToPermissionMode(Q);await D.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=Q,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(G.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await D.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(Y){if(!(Y instanceof _)&&Y.code!=="ENOENT")throw Y;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,Y=async(H)=>{try{await H()}catch(z){Q??=z}};if(await Y(()=>this.cancel()),J)await Y(()=>J.destroy());if(Z)await Y(()=>Z.dispose());if(await Y(()=>A.destroySession(this.id)),G.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,H=0,z=0,$=(X)=>{if(Q.length>0)Q.push({type:"text",text:`
13
- `}),z+=1;if(Q.push(X),X.type==="text")z+=X.text.length};for(let X of J)if(X.type==="text")Z.push(X.text),$({type:"text",text:X.text});else if(X.type==="image"){let j=`data:${X.mimeType};base64,${X.data}`;Y+=1,H+=j.length,Z.push(`[Image: ${X.mimeType}]`),$({type:"image_url",image_url:{url:j}})}else if(X.type==="resource"){let j=X.resource;if("text"in j){let B=`<file path="${j.uri}">
14
- ${j.text}
15
- </file>`;Z.push(B),$({type:"text",text:B})}}else if(X.type==="resource_link"){let j=`[Resource: ${X.uri}]`;Z.push(j),$({type:"text",text:j})}if(Y>I)throw Error(`ACP prompt contains more than ${I} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>y)throw Error(`ACP prompt text exceeds ${y} characters`);let F=Z.join(`
16
- `);return{content:Y>0?Q:F,displayText:F}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}goalSessionUpdate(J){return{sessionUpdate:"session_info_update",updatedAt:J.updatedAt,_meta:{"blade/goal":{goalId:J.goalId,status:J.status,verificationAttempt:J.completionVerification?.attempt,verificationStatus:J.completionVerification?.status,verifierSessionId:J.completionVerification?.verifierSessionId,verificationEvidenceSha256:J.completionVerification?.evidenceSha256}}}}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{G.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return G.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=h(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
17
- - ${J.risks.join(`
18
- - `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},F=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!F)return{approved:!1,reason:T};let X=F.outcome;if(X.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let j=X.optionId;if(j==="allow_always")return{approved:!0,scope:"project"};if(j==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let B=j==="allow_once";return{approved:B,scope:"once",reason:B?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[H,z]of Q.entries()){let $=z.options.map((B,L)=>`answer:${H}:${L}`),F=`answer:${H}:cancel`,X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((B,L)=>({optionId:$[L],name:B.label,kind:"allow_once"})),{optionId:F,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((B)=>`${B.label}: ${B.description}`)].join(`
19
- `)}}]}}),Z);if(!X)return{approved:!1,reason:T};if(X.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let j=$.indexOf(X.outcome.optionId);if(j<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[z.header]=z.options[j].label}return{approved:!0,answers:Y}}catch(H){return G.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
- `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)Y[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),Y=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
21
- `),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Y==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===Y);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
22
- `),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,Y){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,Y)=>{let H=!1,z=(F)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),F()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((F)=>z(()=>Q(F)),(F)=>z(()=>Y(F)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var U=b("Agent");class k{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return U.info("[BladeAgent] Initializing ACP connection"),U.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:wJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=zJ("acp"),Q=J.cwd||QJ(),Y=J._meta?.["blade/taskIsolation"],H=Y==="local"||Y==="worktree"?Y:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await FJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,F=$?.metadata.projectPath??Q;U.info(`[BladeAgent] Creating new session: ${Z}`),U.debug(`[BladeAgent] Session cwd: ${F}`);let X=new O(Z,F,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await X.initialize(),this.assertNotDestroyed()}catch(j){throw await X.destroy().catch(()=>{return}),j}return this.sessions.set(Z,X),U.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),X.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,X.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!JJ.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await D.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!JJ.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await D.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new O(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),U.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),Y=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,Y);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===Y)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await D.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,Y]=await Promise.all([D.loadSession(J.sessionId,J.cwd),D.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let H=new O(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:Y.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],Y=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){U.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)U.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else U.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){U.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")U.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&WJ(J.value))U.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&$J(J.value))U.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&ZJ(J.value))U.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&YJ(J.value))U.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await HJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function ZQ(){let J=UJ.toWeb(process.stdout),Z=KJ.toWeb(process.stdin),Q=x.ndJsonStream(J,Z);await new x.AgentSideConnection((H)=>new k(H),Q).closed}export{ZQ as runAcpIntegration};
@@ -1,4 +0,0 @@
1
- import{id as W}from"./chunk-tx77qaz8.js";import{we as X}from"./chunk-yekzckgm.js";import{Cf as V}from"./chunk-7fgx7ztz.js";import{Ef as Q,Gf as U}from"./chunk-75y3mb0z.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
- 再按一次 Ctrl+C 退出
3
- `)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await Q()}catch(z){}try{let z=X.getInstance(),J=W(),N=J.session?.sessionId||"unknown",O=J.session?.workspaceRoot||V();if(z.isEnabled(O,N)){let Z=J.config?.config?.permissionMode||"default";await z.executeSessionEndHooks($(b),{projectDir:O,sessionId:N,permissionMode:Z})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,Y=new Promise((z,J)=>{setTimeout(()=>{J(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,Y])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{_(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var K=()=>{return F.getInstance()},P=(b)=>{return K().registerCleanup(b)},L=()=>{K().initialize()},k=(b=0)=>{K().shutdown("normal",b)};
4
- export{K as Sc,P as Tc,L as Uc,k as Vc};
@@ -1 +0,0 @@
1
- import{Ld as a,Md as b,Nd as c}from"./chunk-bmsv08sa.js";import"./chunk-xh1y705a.js";import"./chunk-mwae107k.js";import"./chunk-3ck3fxff.js";import"./chunk-x1r4b7pt.js";import"./chunk-7fgx7ztz.js";import"./chunk-75y3mb0z.js";import"./chunk-y5rsamex.js";import"./chunk-nah8b1gv.js";import"./chunk-azcjz03h.js";import"./chunk-7xytd1h7.js";import"./chunk-cjgnf6qy.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1,2 +0,0 @@
1
- import{D as o}from"./chunk-wmsak7d3.js";import{qc as i}from"./chunk-ntmfefxh.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
2
- export{m as t};
@@ -1 +0,0 @@
1
- import{hd as a,id as b,jd as c,kd as d,ld as e,md as f,nd as g,od as h,pd as i,qd as j,rd as k,sd as l,td as m,ud as n,vd as o,wd as p,xd as q}from"./chunk-tx77qaz8.js";import"./chunk-v508x7cg.js";import"./chunk-xhdm1b4g.js";import"./chunk-xh1y705a.js";import"./chunk-mwae107k.js";import"./chunk-3ck3fxff.js";import"./chunk-x1r4b7pt.js";import"./chunk-7fgx7ztz.js";import"./chunk-75y3mb0z.js";import"./chunk-y5rsamex.js";import"./chunk-nah8b1gv.js";import"./chunk-azcjz03h.js";import"./chunk-7xytd1h7.js";import"./chunk-cjgnf6qy.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1 +0,0 @@
1
- import{f as y,g as A,h as C,i as D}from"./chunk-jdq05trf.js";import"./chunk-x0x5e65d.js";import"./chunk-3bhh4v42.js";import"./chunk-cdkrdsbw.js";import"./chunk-758hxypj.js";import"./chunk-wmsak7d3.js";import"./chunk-7bpwnpfx.js";import"./chunk-6r89cn2n.js";import"./chunk-jtk2t4wy.js";import"./chunk-8y2nh9sm.js";import"./chunk-ntmfefxh.js";import"./chunk-fp1892aa.js";import"./chunk-s61wcay9.js";import"./chunk-r68y2q62.js";import{nd as q}from"./chunk-tx77qaz8.js";import"./chunk-v508x7cg.js";import"./chunk-xhdm1b4g.js";import"./chunk-5mszemkz.js";import"./chunk-c7b5wmpm.js";import"./chunk-e66zyvph.js";import"./chunk-bmsv08sa.js";import"./chunk-80r40y6k.js";import"./chunk-t23t9yff.js";import"./chunk-fb514tmd.js";import"./chunk-7m4qc5vv.js";import"./chunk-yekzckgm.js";import"./chunk-799zdv81.js";import"./chunk-xh1y705a.js";import"./chunk-mwae107k.js";import"./chunk-3ck3fxff.js";import"./chunk-x1r4b7pt.js";import"./chunk-7fgx7ztz.js";import"./chunk-75y3mb0z.js";import"./chunk-y5rsamex.js";import"./chunk-nah8b1gv.js";import"./chunk-azcjz03h.js";import"./chunk-7xytd1h7.js";import"./chunk-cjgnf6qy.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1 +0,0 @@
1
- import{Tf as a,Uf as b,Vf as c,Wf as d,Xf as e,Yf as f}from"./chunk-azcjz03h.js";import"./chunk-aspqajv2.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +0,0 @@
1
- import{Gd as a,Hd as b,Id as c}from"./chunk-c7b5wmpm.js";import"./chunk-e66zyvph.js";import"./chunk-y5rsamex.js";import"./chunk-nah8b1gv.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1 +0,0 @@
1
- import{Zf as a}from"./chunk-7xytd1h7.js";import"./chunk-cjgnf6qy.js";import"./chunk-q4q0r97b.js";import"./chunk-aspqajv2.js";export{a as WorkspaceTrustService};