blade-code 0.10.15 → 0.10.16

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-4hawehmd.js → chunk-0ndm72az.js} +2 -2
  3. package/dist/{chunk-gav4hxcv.js → chunk-1n60pgsq.js} +2 -2
  4. package/dist/{chunk-dpt56hah.js → chunk-2c3zavy2.js} +1 -1
  5. package/dist/{chunk-afxpp33r.js → chunk-2e03enfb.js} +1 -1
  6. package/dist/chunk-2g41y2tz.js +1 -0
  7. package/dist/{chunk-nfqsnkbt.js → chunk-334jhwxz.js} +39 -39
  8. package/dist/chunk-3qhqbj09.js +2 -0
  9. package/dist/{chunk-k47f7zqm.js → chunk-3wbheq1y.js} +1 -1
  10. package/dist/chunk-4k615fx6.js +1 -0
  11. package/dist/chunk-4svjvyyd.js +1 -0
  12. package/dist/chunk-4twtqram.js +22 -0
  13. package/dist/chunk-51hjqrt8.js +1 -0
  14. package/dist/{chunk-8j01ssaf.js → chunk-5chec8rs.js} +1 -1
  15. package/dist/{chunk-4dq9y7zn.js → chunk-6207mbmr.js} +2 -2
  16. package/dist/{chunk-g11hq0e5.js → chunk-6g5k5de1.js} +1 -1
  17. package/dist/{chunk-vmq248m7.js → chunk-6pa6c2n0.js} +1 -1
  18. package/dist/{chunk-heqs3xan.js → chunk-6sb7cg95.js} +1 -1
  19. package/dist/chunk-87vsgqvy.js +1 -0
  20. package/dist/chunk-88639hse.js +1 -0
  21. package/dist/chunk-8brheywa.js +1 -0
  22. package/dist/{chunk-kvx3sb3z.js → chunk-96h588rd.js} +1 -1
  23. package/dist/{chunk-ee7an1kq.js → chunk-9m1ayjve.js} +1 -1
  24. package/dist/chunk-ajy99edp.js +100 -0
  25. package/dist/{chunk-agdamn30.js → chunk-as56atkw.js} +2 -2
  26. package/dist/chunk-bcxbrbvd.js +1 -0
  27. package/dist/{chunk-732n8xj6.js → chunk-d9k98jy2.js} +1 -1
  28. package/dist/chunk-djktk1az.js +1 -0
  29. package/dist/{chunk-7x5cqfy7.js → chunk-dskgbv7c.js} +2 -2
  30. package/dist/{chunk-74shfpve.js → chunk-entmz5b1.js} +1 -1
  31. package/dist/chunk-f2qj464t.js +1 -0
  32. package/dist/{chunk-z8c5rhdh.js → chunk-fa6313dv.js} +1 -1
  33. package/dist/{chunk-xx1d9kfd.js → chunk-fvj1mzgs.js} +1 -1
  34. package/dist/{chunk-jjy8sg10.js → chunk-gc9wfvfd.js} +2 -2
  35. package/dist/{chunk-n72www7h.js → chunk-gwx7jz87.js} +3 -3
  36. package/dist/chunk-h1kgh7xz.js +10 -0
  37. package/dist/{chunk-7bq9p4ab.js → chunk-h37yw6g3.js} +2 -2
  38. package/dist/{chunk-s5666ta0.js → chunk-jpwfq49n.js} +2 -2
  39. package/dist/{chunk-ktf3bpmw.js → chunk-k3nkcaap.js} +2 -2
  40. package/dist/{chunk-2mzcxq6c.js → chunk-kbpc97n3.js} +2 -2
  41. package/dist/{chunk-m4f213hk.js → chunk-kn8xx8ng.js} +2 -2
  42. package/dist/{chunk-ng8a4btc.js → chunk-ky0v990x.js} +3 -3
  43. package/dist/{chunk-0z7rg4f3.js → chunk-mbrevmbp.js} +2 -2
  44. package/dist/{chunk-x1qw695m.js → chunk-mcr47s40.js} +4 -4
  45. package/dist/chunk-n2hwfw7v.js +200 -0
  46. package/dist/{chunk-a170cgzr.js → chunk-n6jjfyqn.js} +1 -1
  47. package/dist/{chunk-5s123nbs.js → chunk-prgh321y.js} +1 -1
  48. package/dist/{chunk-7wjy6kgt.js → chunk-q3c07kb4.js} +1 -1
  49. package/dist/{chunk-afkhzdfc.js → chunk-qkrssft1.js} +1 -1
  50. package/dist/{chunk-p4zt7ts9.js → chunk-qt114yth.js} +1 -1
  51. package/dist/chunk-qwpbwhmn.js +1 -0
  52. package/dist/{chunk-9tnaads5.js → chunk-r1jxbx1h.js} +1 -1
  53. package/dist/{chunk-5wecprcp.js → chunk-s31msata.js} +2 -2
  54. package/dist/{chunk-eav8jpk1.js → chunk-sxj3psy3.js} +2 -2
  55. package/dist/{chunk-mtk2tf9n.js → chunk-t3b689pm.js} +1 -1
  56. package/dist/chunk-vhxarqb0.js +6 -0
  57. package/dist/{chunk-632rgzcf.js → chunk-wt7gy9bm.js} +2 -2
  58. package/dist/{chunk-zmg66vp7.js → chunk-wxvkrxf4.js} +2 -2
  59. package/dist/chunk-xet98pc1.js +5 -0
  60. package/dist/chunk-xzhk0smg.js +4 -0
  61. package/dist/chunk-y26ngyc2.js +1 -0
  62. package/dist/{chunk-3aqdjrtm.js → chunk-y2g5a5bp.js} +1 -1
  63. package/dist/chunk-y61ne49f.js +1 -0
  64. package/dist/{chunk-zn7c21zj.js → chunk-y78smk7g.js} +2 -2
  65. package/dist/chunk-ynncadtz.js +1 -0
  66. package/dist/{chunk-dsj62dcg.js → chunk-yqfqj7mh.js} +1 -1
  67. package/dist/{chunk-363pgv1e.js → chunk-yvf4nmds.js} +2 -2
  68. package/dist/{chunk-ybvdac8k.js → chunk-yz2bsntj.js} +1 -1
  69. package/dist/{chunk-r76wc1cn.js → chunk-zdkc4kj1.js} +1 -1
  70. package/dist/{chunk-4zs5r4n4.js → chunk-zt5wq0qj.js} +1 -1
  71. package/dist/web/assets/{ChatView-rHWZ9qCy.js → ChatView-YFotW0KS.js} +3 -3
  72. package/dist/web/assets/{CodeBlockHighlighter-KpN8jpS4.js → CodeBlockHighlighter-DYuOTwXS.js} +1 -1
  73. package/dist/web/assets/{FilePreview-BbEcYewq.js → FilePreview-CWOBOnzz.js} +1 -1
  74. package/dist/web/assets/{MarkdownRenderer-Cpqkv5Ml.js → MarkdownRenderer-YiYvkN2w.js} +3 -3
  75. package/dist/web/assets/{SettingsModal-D6NZP8vM.js → SettingsModal-BT-oFKGN.js} +1 -1
  76. package/dist/web/assets/{TaskSwitcher-cT1qKR6s.js → TaskSwitcher-D5Gd6FN9.js} +1 -1
  77. package/dist/web/assets/{TerminalPanel-0MehdzKr.js → TerminalPanel-C1hLHq_K.js} +1 -1
  78. package/dist/web/assets/{index-BYd4kNGp.js → index-DuYx6fkN.js} +4 -4
  79. package/dist/web/assets/{session-events-BH7O5JJl.js → session-events-K_9Lexp8.js} +1 -1
  80. package/dist/web/index.html +2 -2
  81. package/package.json +1 -1
  82. package/dist/chunk-09k2b1tw.js +0 -10
  83. package/dist/chunk-1amhvwmj.js +0 -22
  84. package/dist/chunk-1c9rkm57.js +0 -1
  85. package/dist/chunk-25abj6rx.js +0 -1
  86. package/dist/chunk-2cqsqrxx.js +0 -4
  87. package/dist/chunk-3m8pschr.js +0 -1
  88. package/dist/chunk-5psydp1v.js +0 -1
  89. package/dist/chunk-5tpjb8yn.js +0 -1
  90. package/dist/chunk-67vf8r5v.js +0 -6
  91. package/dist/chunk-6y9w5296.js +0 -1
  92. package/dist/chunk-csn0epd2.js +0 -100
  93. package/dist/chunk-d7976m5f.js +0 -5
  94. package/dist/chunk-f4z3gkbs.js +0 -2
  95. package/dist/chunk-fvrmjhz5.js +0 -1
  96. package/dist/chunk-h6w3ggx9.js +0 -1
  97. package/dist/chunk-hxp5qs1x.js +0 -1
  98. package/dist/chunk-mc29y7tj.js +0 -200
  99. package/dist/chunk-qpd1jmm4.js +0 -1
  100. package/dist/chunk-t6cmqsdj.js +0 -1
  101. package/dist/chunk-wz3z8908.js +0 -1
  102. package/dist/chunk-z5zcwwfm.js +0 -1
  103. package/dist/chunk-zn2cec1d.js +0 -1
@@ -19,4 +19,4 @@ ${c}`:""].filter(Boolean).join(`
19
19
  `)}]}))},Ze=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=C(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
20
  `)}]}))},pe=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=C(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
21
  `)}]}))},et=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:o,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=C(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
- `)}]}))},tt=(e,t,n)=>{const{currentSessionId:a,setConfirmation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||"",s=b(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)}))},nt=(e,t,n)=>{var I,f;const{currentSessionId:a,currentSessionRef:o,messages:u,setConfirmation:s,setElicitation:i}=t();if(e.sessionId!==a)return;const r=e.requestId,d=u.find(g=>{var h,S;return((S=(h=g.agentContent)==null?void 0:h.confirmation)==null?void 0:S.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(g=>{var h,S;return((S=(h=g.agentContent)==null?void 0:h.elicitation)==null?void 0:S.toolCallId)===r}),m=(f=l==null?void 0:l.agentContent)==null?void 0:f.elicitation;l&&(m==null?void 0:m.status)==="pending"&&i(l.id,{...m,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...o?{sessionRef:o}:{}}})},Z=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0})},st=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"compacting"})},it=(e,t,n)=>{e.sessionId===t().currentSessionId&&(t().resetContextUsage(),n({agentPhase:"running"}))},ot=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerRetry:null,providerStall:null})},at=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},rt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerStall:e.phase==="detected"?e:null})},ut=(e,t,n)=>{const{currentSessionId:a,setQuestion:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=b(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)})))},dt=(e,t,n)=>{const{currentSessionId:a,setElicitation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=b(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)})))},lt=(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})}))},O=(e,t)=>{const{currentSessionId:n,endAgentResponse:a}=t();e.sessionId===n&&a()},ct=(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=he(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()},gt=(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,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,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 $(i.agentContent))r.status==="running"&&s(i.id,r.id,{status:"failed"});o()}},ft=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},It=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},St=(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})},ht=(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})},yt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},Ct=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},bt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},vt=(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:Ie(o),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},At=(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)},kt=(e,t,n)=>{ne({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},Tt=(e,t,n)=>{se(e,t)},$t=(e,t,n)=>{ie(e,t,n)},P={"message.created":be,"message.delta":ve,"message.complete":Ae,"structured.output":ke,"thinking.delta":Te,"thinking.completed":$e,"tool.start":ne,"tool.progress":se,"tool.result":ie,"mcp.catalog.changed":Ne,"mcp.content.changed":Me,"mcp.resource.updated":Re,"mcp.connection.changed":xe,"mcp.log":Pe,"mcp.instructions.changed":we,"mcp.task.changed":De,"project.rules.loaded":_e,"user.shell.started":je,"user.shell.output":qe,"user.shell.completed":Fe,"token.usage":Oe,"task.updated":Ve,"subagent.start":Ee,"subagent.update":Ke,"subagent.delta":Ue,"subagent.thinking.delta":Be,"subagent.tool.start":Le,"subagent.tool.progress":Ge,"subagent.tool.result":He,"subagent.mcp.catalog.changed":We,"subagent.mcp.content.changed":Qe,"subagent.mcp.resource.updated":ze,"subagent.mcp.connection.changed":Ye,"subagent.mcp.log":Xe,"subagent.mcp.instructions.changed":Ze,"subagent.mcp.task.changed":pe,"subagent.project.rules.loaded":et,"subagent.complete":Je,"permission.asked":tt,"permission.timeout":nt,"turn.started":Z,"committed.turn_started":Z,"committed.turn_completed":O,"committed.turn_aborted":O,"provider.retry":at,"provider.stall":rt,"compaction.started":st,"compaction.completed":it,"model.fallback":ot,"question.required":ut,"elicitation.required":dt,"interaction.resolved":lt,"session.completed":O,"session.error":ct,"session.status":gt,"run.cancelled":mt,"steering.queued":ft,"follow_up.queued":It,"follow_up.started":ht,"steering.applied":St,"goal.updated":yt,"goal.cleared":Ct,"goal.continuation.started":bt,"session.rewound":vt,"review.tool.started":kt,"review.tool.progress":Tt,"review.tool.completed":$t,"review.completed":At},Nt=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]),Pt=(e,t)=>n=>{const a=e().currentSessionRef,o=n.properties;if(!a||o.sessionId!==a.sessionId||o.projectPath!==a.projectPath)return;if(Nt.has(n.type)){T.drainAll();const s=P[n.type];s&&s(n.properties,e,t);return}if(n.type==="tool.start"&&T.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=P["message.delta"];I&&I(o,e,t);return}const l=r?"after":"before",m=`content:${d}:${l}`;T.drainAllExcept(m),T.append(m,c,I=>{const{appendDelta:f}=e();d&&f(d,I,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:s,currentAssistantMessageId:i}=e();if(o.sessionId!==s)return;if(!i){const l=P["thinking.delta"];l&&l(o,e,t);return}const r=o.delta,d=o.messageId||i,c=`thinking:${d}`;T.drainAllExcept(c),T.append(c,r,l=>{const{appendThinking:m}=e();d&&m(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(),m=C(l,r||void 0,c);T.append(d,i,I=>{const{currentAssistantMessageId:f,messages:g,updateSubagent:h}=e(),S=m||C(g,r||void 0,f);S&&h(S.messageId,S.subagent.id,A=>({sessionId:A.sessionId||r,output:(A.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(),m=C(l,r||void 0,c);T.append(d,i,I=>{const{currentAssistantMessageId:f,messages:g,updateSubagent:h}=e(),S=m||C(g,r||void 0,f);S&&h(S.messageId,S.subagent.id,A=>({sessionId:A.sessionId||r,thinking:(A.thinking||"")+I}))});return}const u=P[n.type];u&&u(n.properties,e,t)};export{de as a,X as b,M as c,ue as d,Ie as e,Pt as f,$ as g,T as h,he as i,xt as j,le as k,w as l,Rt as t,Y as u,V as w};
22
+ `)}]}))},tt=(e,t,n)=>{const{currentSessionId:a,setConfirmation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||"",s=b(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)}))},nt=(e,t,n)=>{var I,f;const{currentSessionId:a,currentSessionRef:o,messages:u,setConfirmation:s,setElicitation:i}=t();if(e.sessionId!==a)return;const r=e.requestId,d=u.find(g=>{var h,S;return((S=(h=g.agentContent)==null?void 0:h.confirmation)==null?void 0:S.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(g=>{var h,S;return((S=(h=g.agentContent)==null?void 0:h.elicitation)==null?void 0:S.toolCallId)===r}),m=(f=l==null?void 0:l.agentContent)==null?void 0:f.elicitation;l&&(m==null?void 0:m.status)==="pending"&&i(l.id,{...m,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...o?{sessionRef:o}:{}}})},Z=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0})},st=(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"}))},ot=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerRetry:null,providerStall:null})},at=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},rt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerStall:e.phase==="detected"?e:null})},ut=(e,t,n)=>{const{currentSessionId:a,setQuestion:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=b(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)})))},dt=(e,t,n)=>{const{currentSessionId:a,setElicitation:o}=t();if(e.sessionId!==a)return;const u=e.requestId||e.toolCallId||"",s=b(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)})))},lt=(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})}))},O=(e,t)=>{const{currentSessionId:n,endAgentResponse:a}=t();e.sessionId===n&&a()},ct=(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=he(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()},gt=(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,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,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 $(i.agentContent))r.status==="running"&&s(i.id,r.id,{status:"failed"});o()}},ft=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},It=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},St=(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})},ht=(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})},yt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},Ct=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},bt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},vt=(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:Ie(o),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},At=(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)},kt=(e,t,n)=>{ne({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},Tt=(e,t,n)=>{se(e,t)},$t=(e,t,n)=>{ie(e,t,n)},P={"message.created":be,"message.delta":ve,"message.complete":Ae,"structured.output":ke,"thinking.delta":Te,"thinking.completed":$e,"tool.start":ne,"tool.progress":se,"tool.result":ie,"mcp.catalog.changed":Ne,"mcp.content.changed":Me,"mcp.resource.updated":Re,"mcp.connection.changed":xe,"mcp.log":Pe,"mcp.instructions.changed":we,"mcp.task.changed":De,"project.rules.loaded":_e,"user.shell.started":je,"user.shell.output":qe,"user.shell.completed":Fe,"token.usage":Oe,"task.updated":Ve,"subagent.start":Ee,"subagent.update":Ke,"subagent.delta":Ue,"subagent.thinking.delta":Be,"subagent.tool.start":Le,"subagent.tool.progress":Ge,"subagent.tool.result":He,"subagent.mcp.catalog.changed":We,"subagent.mcp.content.changed":Qe,"subagent.mcp.resource.updated":ze,"subagent.mcp.connection.changed":Ye,"subagent.mcp.log":Xe,"subagent.mcp.instructions.changed":Ze,"subagent.mcp.task.changed":pe,"subagent.project.rules.loaded":et,"subagent.complete":Je,"permission.asked":tt,"permission.timeout":nt,"turn.started":Z,"committed.turn_started":Z,"committed.turn_completed":O,"committed.turn_aborted":O,"provider.retry":at,"provider.stall":rt,"compaction.started":st,"compaction.completed":it,"model.fallback":ot,"question.required":ut,"elicitation.required":dt,"interaction.resolved":lt,"session.completed":O,"session.error":ct,"session.status":gt,"run.cancelled":mt,"steering.queued":ft,"follow_up.queued":It,"follow_up.started":ht,"steering.applied":St,"goal.updated":yt,"goal.cleared":Ct,"goal.continuation.started":bt,"session.rewound":vt,"review.tool.started":kt,"review.tool.progress":Tt,"review.tool.completed":$t,"review.completed":At},Nt=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]),Pt=(e,t)=>n=>{const a=e().currentSessionRef,o=n.properties;if(!a||o.sessionId!==a.sessionId||o.projectPath!==a.projectPath)return;if(Nt.has(n.type)){T.drainAll();const s=P[n.type];s&&s(n.properties,e,t);return}if(n.type==="tool.start"&&T.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=P["message.delta"];I&&I(o,e,t);return}const l=r?"after":"before",m=`content:${d}:${l}`;T.drainAllExcept(m),T.append(m,c,I=>{const{appendDelta:f}=e();d&&f(d,I,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:s,currentAssistantMessageId:i}=e();if(o.sessionId!==s)return;if(!i){const l=P["thinking.delta"];l&&l(o,e,t);return}const r=o.delta,d=o.messageId||i,c=`thinking:${d}`;T.drainAllExcept(c),T.append(c,r,l=>{const{appendThinking:m}=e();d&&m(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(),m=C(l,r||void 0,c);T.append(d,i,I=>{const{currentAssistantMessageId:f,messages:g,updateSubagent:h}=e(),S=m||C(g,r||void 0,f);S&&h(S.messageId,S.subagent.id,A=>({sessionId:A.sessionId||r,output:(A.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(),m=C(l,r||void 0,c);T.append(d,i,I=>{const{currentAssistantMessageId:f,messages:g,updateSubagent:h}=e(),S=m||C(g,r||void 0,f);S&&h(S.messageId,S.subagent.id,A=>({sessionId:A.sessionId||r,thinking:(A.thinking||"")+I}))});return}const u=P[n.type];u&&u(n.properties,e,t)};export{de as a,X as b,M as c,ue as d,Ie as e,Pt as f,$ as g,T as h,he as i,xt as j,le as k,w as l,Rt as t,Y as u,V 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-BYd4kNGp.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-DuYx6fkN.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-BH7O5JJl.js">
12
+ <link rel="modulepreload" crossorigin href="/assets/session-events-K_9Lexp8.js">
13
13
  <link rel="stylesheet" crossorigin href="/assets/index-BC7ygRH_.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.15",
3
+ "version": "0.10.16",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1,10 +0,0 @@
1
- import{f as Q,g as R,h as T,i as W}from"./chunk-n72www7h.js";import"./chunk-r76wc1cn.js";import"./chunk-z8c5rhdh.js";import"./chunk-afxpp33r.js";import"./chunk-k47f7zqm.js";import"./chunk-x1qw695m.js";import"./chunk-ee7an1kq.js";import"./chunk-p4zt7ts9.js";import"./chunk-mc29y7tj.js";import"./chunk-095x2ykj.js";import"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import{Vc as M}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-m4f213hk.js";import"./chunk-agdamn30.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import{vf as J}from"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.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{r as R}from"./chunk-afxpp33r.js";import{s as WJ}from"./chunk-k47f7zqm.js";import{$ as a,F as p,I as m,J as d,L as l,Z as i,_ as r,aa as n,v as P}from"./chunk-x1qw695m.js";import{ka as zJ}from"./chunk-ee7an1kq.js";import"./chunk-p4zt7ts9.js";import{Va as g,Ya as c,hb as v}from"./chunk-mc29y7tj.js";import{sb as y}from"./chunk-095x2ykj.js";import{$b as B,Fb as C,Kb as O,Nb as f,Tb as T,Ub as u,Yb as q}from"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import{fd as QJ}from"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-2mzcxq6c.js";import{od as ZJ}from"./chunk-8j01ssaf.js";import"./chunk-m4f213hk.js";import"./chunk-agdamn30.js";import"./chunk-9tnaads5.js";import{Td as $J}from"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import{ee as E}from"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import{cf as h,df as S,ef as I}from"./chunk-f4z3gkbs.js";import{if as s}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import{of as e,rf as JJ}from"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import{Readable as BJ,Writable as VJ}from"node:stream";import*as b from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as LJ}from"@agentclientprotocol/sdk";import t from"node:path";import{RequestError as FJ}from"@agentclientprotocol/sdk";import{nanoid as x}from"nanoid";var j=E("Agent");function k(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function GJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:k(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:k("headers"in J?J.headers:void 0)};return null}function XJ(J){let Z={};for(let Q of J){let Y=GJ(Q);if(Y)Z[Q.name]=Y}return Z}function o(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 jJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:T(Z)}]:o(J.content)}function DJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}class A{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;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.mode=this.mapPermissionModeToMode(H.permissionMode)}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 l.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await B.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),P.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))this.messages=await B.loadSession(this.id,this.cwd);let Z=this.options.mcpServers?XJ(this.options.mcpServers):void 0,Q=P.getInstance().getTerminalService(this.id);if(this.runtime=await p.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 G=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(F)=>$.onOutput?.("stdout",F)});return{exitCode:G.exitCode,stdout:G.stdout,stderr:G.stderr,...G.error?{error:G.error}:{},timedOut:G.error==="Command timed out",aborted:G.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await R.recoverInterrupted(this.cwd,this.id,this.runtime))this.messages=await B.loadSession(this.id,this.cwd);this.agent=await this.createAgent(),await r(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=c.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)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")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of jJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);j.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{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],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 G=await this.runtime.rewindSession($);return this.messages=[...G.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),G}},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($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,X,L=(D)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:D.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D.result?.message||D.result?.error||`Subagent ${D.status}`}}]})},W=this.runtime.resumeSubagent({agentId:$,prompt:G,onCompleted:(D)=>{if(F)L(D);else X=D}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W.session.id,status:"in_progress",title:`Resuming ${W.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${W.source.id} at depth ${W.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,X)L(X);return W}},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($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,G,F)},complete:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,G,F)},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($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,G)},getLogs:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,G)},setLoggingLevel:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,G)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await R.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:G,onEvent:(W)=>{if(W.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W.toolCall.id,status:"in_progress",title:`Review: ${W.toolCall.function.name}`,content:[],kind:this.mapToolKind(W.toolKind)});else if(W.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.toolCall.id,status:W.result.success?"completed":"failed",content:[]})}}),X=await F.completion,L=(await R.list(this.cwd,this.id)).find((W)=>W.start.reviewId===F.reviewId);if(!L)throw Error(`Review not found: ${F.reviewId}`);return this.messages=await B.loadSession(this.id,this.cwd),{reviewId:F.reviewId,status:X.status,findings:X.findings.length,content:C(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,G,F)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(G,null,2)}}],kind:L})},sendToolResult:($,G)=>{if(G.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:G.summary}})}}},Y=await a(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];if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages)this.messages=[...Y.data.compactedMessages];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 j.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=n(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}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),j.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(P.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((F)=>F.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=f(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 F=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!F.accepted)throw Error(F.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${F.queued})`),F.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let G=new AbortController;this.pendingPrompt=G;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),i(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,G.signal)}let F={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.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)}}},X=await g(this.agent.chatStream(Y,F,{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 D=W.toolCall,U=D.function.name;if(U===O)break;let _=this.mapToolKind(W.toolKind),V=`Executing ${U}`;if(U==="Task"&&"function"in D)try{let N=JSON.parse(D.function.arguments),w=N.resume_from??N.resume;if(typeof w==="string")V=`Resuming ${String(N.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:V,content:[],kind:_});break}case"tool_progress":{let D=W.toolCall;if(D.function.name===O)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let D=W.toolCall;if(D.function.name===O)break;let U=W.result,_=[],V=U.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let w of V.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;_.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))_.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let w=D.function.name,YJ=d(m(w,U));_.push({type:"content",content:{type:"text",text:YJ}})}if(D.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))_.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let N=U.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:N,content:_});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"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let D of W.messages){if(!D.recovered||D.persisted)continue;for(let U of o(D.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:U})}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&&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;default:break}});if(this.messages=[...F.messages],!X.success){let W=X.error?.type??"unknown";throw FJ.internalError({failureType:W},`Agent turn failed (${W})`)}if(G.signal.aborted)return{stopReason:"cancelled"};let L={...X.metadata?.structuredOutput?{structuredOutput:X.metadata.structuredOutput,outputSchemaDigest:X.metadata.structuredOutputSchemaDigest}:{},...X.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:X.metadata.goalVerificationVerdict,...X.metadata.goalVerifierSessionId?{verifierSessionId:X.metadata.goalVerifierSessionId}:{},...X.metadata.goalVerificationEvidenceSha256?{evidenceSha256:X.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(L).length>0?{_meta:L}:{}}}catch(F){if(G.signal.aborted||F instanceof Error&&F.name==="AbortError")return{stopReason:"cancelled"};throw j.error(`[AcpSession ${this.id}] Prompt error:`,F),F}finally{if(this.pendingPrompt===G){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($)=>{if(Y=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){H+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let G=T($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?DJ($.record):G}}]})}});if(this.messages.push({role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}}),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,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){j.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)j.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 B.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=Q,j.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(j.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 B.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((Y)=>{j.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 B.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.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 B.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.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 B.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.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 B.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(Y){if(!(Y instanceof q)&&Y.code!=="ENOENT")throw Y;await B.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(()=>P.destroySession(this.id)),j.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,H=0,z=0,$=(F)=>{if(Q.length>0)Q.push({type:"text",text:`
13
- `}),z+=1;if(Q.push(F),F.type==="text")z+=F.text.length};for(let F of J)if(F.type==="text")Z.push(F.text),$({type:"text",text:F.text});else if(F.type==="image"){let X=`data:${F.mimeType};base64,${F.data}`;Y+=1,H+=X.length,Z.push(`[Image: ${F.mimeType}]`),$({type:"image_url",image_url:{url:X}})}else if(F.type==="resource"){let X=F.resource;if("text"in X){let L=`<file path="${X.uri}">
14
- ${X.text}
15
- </file>`;Z.push(L),$({type:"text",text:L})}}else if(F.type==="resource_link"){let X=`[Resource: ${F.uri}]`;Z.push(X),$({type:"text",text:X})}if(Y>h)throw Error(`ACP prompt contains more than ${h} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>I)throw Error(`ACP prompt text exceeds ${I} characters`);let G=Z.join(`
16
- `);return{content:Y>0?Q:G,displayText:G}}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()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{j.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}));j.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 j.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return j.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=x(),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}},G=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!G)return{approved:!1,reason:y};let F=G.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let X=F.optionId;if(X==="allow_always")return{approved:!0,scope:"project"};if(X==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=X==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(Y){return j.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((L,W)=>`answer:${H}:${W}`),G=`answer:${H}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((L,W)=>({optionId:$[W],name:L.label,kind:"allow_once"})),{optionId:G,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:x(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((L)=>`${L.label}: ${L.description}`)].join(`
19
- `)}}]}}),Z);if(!F)return{approved:!1,reason:y};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let X=$.indexOf(F.outcome.optionId);if(X<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[z.header]=z.options[X].label}return{approved:!0,answers:Y}}catch(H){return j.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 j.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:x(),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=(G)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),G()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((G)=>z(()=>Q(G)),(G)=>z(()=>Y(G)))})}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 K=E("Agent");class M{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return K.info("[BladeAgent] Initializing ACP connection"),K.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:LJ,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=QJ("acp"),Q=J.cwd||s(),Y=J._meta?.["blade/taskIsolation"],H=Y==="local"||Y==="worktree"?Y:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await WJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,G=$?.metadata.projectPath??Q;K.info(`[BladeAgent] Creating new session: ${Z}`),K.debug(`[BladeAgent] Session cwd: ${G}`);let F=new A(Z,G,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await F.initialize(),this.assertNotDestroyed()}catch(X){throw await F.destroy().catch(()=>{return}),X}return this.sessions.set(Z,F),K.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),F.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,F.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!t.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await B.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(),!t.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await B.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new A(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(),K.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 B.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([B.loadSession(J.sessionId,J.cwd),B.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let H=new A(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){K.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)K.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else K.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){K.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")K.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&ZJ(J.value))K.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&JJ(J.value))K.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&e(J.value))K.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&$J(J.value))K.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 zJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function sJ(){let J=VJ.toWeb(process.stdout),Z=BJ.toWeb(process.stdin),Q=b.ndJsonStream(J,Z);await new b.AgentSideConnection((H)=>new M(H),Q).closed}export{sJ as runAcpIntegration};
@@ -1 +0,0 @@
1
- import{sc as a,tc as b}from"./chunk-0z7rg4f3.js";import"./chunk-7x5cqfy7.js";import"./chunk-g11hq0e5.js";export{a as globalOptions,b as cliConfig};
@@ -1 +0,0 @@
1
- import{$b as f,Wb as a,Xb as b,Yb as c,Zb as d,_b as e}from"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import"./chunk-8j01ssaf.js";import"./chunk-heqs3xan.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
@@ -1,4 +0,0 @@
1
- import{$ as F,Z as y}from"./chunk-x1qw695m.js";import{$b as Q,Lb as Z,Nb as x}from"./chunk-csn0epd2.js";import{Ld as $}from"./chunk-agdamn30.js";import{if as K}from"./chunk-5s123nbs.js";async function O(){await $(K())}async function j(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let V of z)G.push(V);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:K(),surface:"headless",workspaceRoot:K()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:V}=z;return{mode:"agent",content:V?`Please use the "${G}" skill to help me with: ${V}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
-
3
- ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as B,stat as D}from"node:fs/promises";import H from"node:path";function L(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return x(z).schema}async function P(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return L(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=H.resolve(b.outputSchema),z=await D(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>Z)throw Error(`Output schema exceeds ${Z} bytes: ${q}`);return L(await B(q,"utf8"),q)}function J(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function N(b){try{return await Q.loadSession(b,K())}catch(q){if(J(q))return null;throw q}}async function T(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=K();return Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G})}let[q,z]=await Promise.all([Q.loadSession(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:K()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=K();return Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G})}return{sessionId:z,messages:await Q.loadSession(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await N(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,K())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
- export{O as m,j as n,I as o,P as p,T as q};
@@ -1 +0,0 @@
1
- import{qd as a,rd as b,sd as c}from"./chunk-m4f213hk.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1 +0,0 @@
1
- import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-mc29y7tj.js";import"./chunk-095x2ykj.js";import"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-8j01ssaf.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1 +0,0 @@
1
- import{$c as m,Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g,Wc as h,Xc as i,Yc as j,Zc as k,_c as l,ad as n,bd as o,cd as p,dd as q}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.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,6 +0,0 @@
1
- import{m as Gq,n as Vq,o as Xq,p as Bq,q as Kq}from"./chunk-2cqsqrxx.js";import{s as $q}from"./chunk-k47f7zqm.js";import{F as a,H as o,I as n,K as y,L as t}from"./chunk-x1qw695m.js";import"./chunk-ee7an1kq.js";import"./chunk-p4zt7ts9.js";import{Va as i,Ya as s,hb as r}from"./chunk-mc29y7tj.js";import"./chunk-095x2ykj.js";import{$b as h,Kb as S}from"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import{sc as qq}from"./chunk-0z7rg4f3.js";import{uc as Qq,vc as Yq,wc as Zq}from"./chunk-5wecprcp.js";import{xc as e}from"./chunk-632rgzcf.js";import"./chunk-ktf3bpmw.js";import{Xc as v}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-m4f213hk.js";import"./chunk-agdamn30.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import{Ue as m,Ve as l}from"./chunk-3aqdjrtm.js";import{$e as w,Ye as u,_e as Q,bf as b}from"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as I}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import nq from"yargs";import{hideBin as tq}from"yargs/helpers";var g=1;function K(Y){return Q.Object({event_version:Q.Literal(g),...Y})}var Uq=K({type:Q.Literal("content_delta"),delta:Q.String()}),Rq=K({type:Q.Literal("thinking_delta"),delta:Q.String()}),Mq=K({type:Q.Literal("thinking"),content:Q.String()}),Pq=K({type:Q.Literal("stream_end")}),fq=K({type:Q.Literal("content"),content:Q.String()}),Nq=K({type:Q.Literal("structured_output"),output:Q.Record(Q.String(),Q.Unknown()),schema_digest:Q.String({pattern:"^[a-f0-9]{64}$"})}),T=b(["readonly","write","execute"]),Eq=K({type:Q.Literal("tool_start"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T)}),xq=K({type:Q.Literal("tool_progress"),tool_name:Q.String(),message:Q.String(),progress:Q.Optional(Q.Number()),total:Q.Optional(Q.Number())}),Iq=K({type:Q.Literal("tool_result"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T),success:Q.Optional(Q.Boolean()),error_type:Q.Optional(Q.String()),error_message:Q.Optional(Q.String())}),Jq=K({type:Q.Literal("mcp_catalog_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Lq=K({type:Q.Literal("mcp_content_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),content_kind:b(["resources","resource_templates","prompts"]),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Wq=K({type:Q.Literal("mcp_resource_updated"),revision:Q.Integer({minimum:1}),server_name:Q.String(),uri:Q.String()}),Sq=K({type:Q.Literal("mcp_connection_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),phase:b(["reconnecting","recovered","failed"]),reason:Q.String(),attempt:Q.Integer({minimum:0}),max_attempts:Q.Integer({minimum:0}),next_retry_at:Q.Optional(Q.Integer({minimum:0})),error:Q.Optional(Q.String())}),Oq=K({type:Q.Literal("mcp_log"),revision:Q.Integer({minimum:1}),server_name:Q.String(),level:b(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:Q.Optional(Q.String()),message:Q.String(),projected_bytes:Q.Integer({minimum:0}),data_sha256:Q.String(),truncated:Q.Boolean(),details_omitted:Q.Boolean(),timestamp:Q.Integer({minimum:0}),synthetic:Q.Optional(Q.Boolean())}),hq=K({type:Q.Literal("mcp_instructions_changed"),revision:Q.Integer({minimum:0}),server_name:Q.String(),action:b(["added","removed"]),reason:b(["snapshot","connection","disconnection"]),text:Q.Optional(Q.String()),source_bytes:Q.Optional(Q.Integer({minimum:0})),projected_bytes:Q.Optional(Q.Integer({minimum:0})),sha256:Q.Optional(Q.String()),truncated:Q.Optional(Q.Boolean()),details_omitted:Q.Optional(Q.Boolean())}),Cq=K({type:Q.Literal("mcp_task_changed"),revision:Q.Integer({minimum:0}),task_id:Q.String(),server_name:Q.String(),tool_name:Q.String(),status:b(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:Q.Optional(Q.String()),created_at:Q.Integer({minimum:0}),updated_at:Q.Integer({minimum:0}),completed_at:Q.Optional(Q.Integer({minimum:0})),has_result:Q.Boolean(),error:Q.Optional(Q.String())}),kq=K({type:Q.Literal("project_rules_loaded"),files:Q.Array(Q.Object({id:Q.String(),relative_path:Q.String(),source:b(["project","local"]),conditional:Q.Boolean(),content_sha256:Q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:Q.Array(Q.String()),blocked_write:Q.Boolean()}),Fq=K({type:Q.Literal("user_shell_started"),execution_id:Q.String(),command:Q.String(),auxiliary:Q.Boolean()}),wq=K({type:Q.Literal("user_shell_output"),execution_id:Q.String(),stream:b(["stdout","stderr"]),chunk:Q.String(),stream_truncated:Q.Boolean()}),yq=K({type:Q.Literal("user_shell_completed"),execution_id:Q.String(),message_id:Q.String(),status:b(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:Q.Union([Q.Integer(),Q.Null()]),duration_ms:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),truncated:Q.Boolean(),auxiliary:Q.Boolean()}),gq=K({type:Q.Literal("phase"),phase:b(["turn","searching","inspecting","target_hit","executing","completed"]),status:b(["ongoing","hit","done"]),message:Q.String(),turn:Q.Optional(Q.Number()),tool_name:Q.Optional(Q.String()),target:Q.Optional(Q.String())}),Tq=K({type:Q.Literal("tool_detail"),tool_name:Q.String(),detail:Q.String()}),cq=K({type:Q.Literal("task_update"),tasks:Q.Array(y)}),dq=K({type:Q.Literal("goal"),state:b(["updated","cleared"]),goal_id:Q.Optional(Q.String()),status:Q.Optional(b(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:Q.Optional(Q.Integer({minimum:1})),verification_status:Q.Optional(b(["pending","pass","fail","partial"])),verifier_session_id:Q.Optional(Q.String()),verification_evidence_sha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))}),pq=K({type:Q.Literal("subagent"),state:b(["spawned","completed"]),session_id:Q.String(),subagent_type:Q.Optional(Q.String()),success:Q.Optional(Q.Boolean()),summary:Q.Optional(Q.String()),verification_verdict:Q.Optional(b(["pass","fail","partial"])),resumed_from:Q.Optional(Q.String()),root_agent_id:Q.Optional(Q.String()),resume_depth:Q.Optional(Q.Integer({minimum:0}))}),mq=K({type:Q.Literal("token_usage"),input_tokens:Q.Number(),output_tokens:Q.Number(),total_tokens:Q.Number(),max_context_tokens:Q.Number(),cache_read_tokens:Q.Optional(Q.Number()),cache_write_tokens:Q.Optional(Q.Number()),cost_usd:Q.Optional(Q.Number())}),uq=K({type:Q.Literal("compacting"),state:b(["started","completed"])}),lq=K({type:Q.Literal("provider_retry"),phase:b(["scheduled","attempt","recovered","exhausted"]),attempt:Q.Integer({minimum:0}),max_retries:Q.Integer({minimum:0}),reason:b(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:Q.Optional(Q.Integer({minimum:100,maximum:599})),delay_ms:Q.Optional(Q.Integer({minimum:0})),next_retry_at:Q.Optional(Q.Integer({minimum:0}))}),vq=K({type:Q.Literal("provider_stall"),phase:b(["detected","recovered"]),stall_count:Q.Integer({minimum:1}),duration_ms:Q.Integer({minimum:0}),warning_after_ms:Q.Integer({minimum:1}),timeout_ms:Q.Integer({minimum:1}),output_started:Q.Boolean()}),iq=K({type:Q.Literal("turn_limit"),turns_count:Q.Number(),action:Q.Literal("continue")}),sq=K({type:Q.Literal("task_session"),session_id:Q.String(),project_path:Q.String(),source_project_path:Q.String(),isolation:b(["local","worktree"]),worktree_branch:Q.Optional(Q.String()),base_commit:Q.Optional(Q.String())}),rq=K({type:Q.Literal("task_admission"),state:b(["queued","running"]),queue_position:Q.Optional(Q.Integer({minimum:1})),queue_depth:Q.Integer({minimum:0}),in_flight:Q.Integer({minimum:0}),max_concurrent_tasks:Q.Integer({minimum:1})}),aq=K({type:Q.Literal("output"),content:Q.String(),exit_code:Q.Number()}),oq=K({type:Q.Literal("error"),message:Q.String()}),zQ=w(Q.Union([Uq,Rq,Mq,Pq,fq,Nq,Eq,xq,Iq,Jq,Lq,Wq,Sq,Oq,hq,Cq,kq,Fq,wq,yq,gq,Tq,cq,dq,pq,mq,uq,lq,vq,iq,sq,rq,aq,oq]));function c(Y,Z){return{event_version:g,type:Y,...Z}}function eq(Y){if(Y?.signal)return{signal:Y.signal,dispose:()=>{return}};let Z=new AbortController,H=()=>Z.abort("interrupt");return process.once("SIGINT",H),process.once("SIGTERM",H),{signal:Z.signal,dispose:()=>{process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H)}}}var qQ=b(["text","jsonl"]),QQ=Q.Object({headless:Q.Optional(Q.Boolean()),message:Q.Optional(Q.String()),_:Q.Optional(Q.Array(Q.Union([Q.String(),Q.Number()]))),model:Q.Optional(Q.String()),systemPrompt:Q.Optional(Q.String()),appendSystemPrompt:Q.Optional(Q.String()),maxTurns:Q.Optional(Q.Refine(Q.Integer({maximum:l}),(Y)=>Y===-1||Y>0,()=>"must be -1 or a positive integer")),permissionMode:Q.Optional(Q.Enum(m)),mcpConfig:Q.Optional(Q.Array(Q.String())),strictMcpConfig:Q.Optional(Q.Boolean()),sessionId:Q.Optional(Q.String()),allowedTools:Q.Optional(Q.Array(Q.String())),disallowedTools:Q.Optional(Q.Array(Q.String())),agents:Q.Optional(Q.String()),continue:Q.Optional(Q.Boolean()),resume:Q.Optional(Q.Union([Q.String(),Q.Boolean()])),forkSession:Q.Optional(Q.Boolean()),taskIsolation:Q.Optional(b(["local","worktree"])),outputFormat:Q.Optional(qQ),jsonSchema:Q.Optional(Q.String()),outputSchema:Q.Optional(Q.String())});class Dq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Y){this.openedThinking=Y}hasOpenThinking(){return this.openedThinking}completeStream(){let Y={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Y}}function YQ(Y){return Y.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function ZQ(Y){let Z=u(QQ,Y);if(!Z.success)throw Error(`Invalid headless options: ${YQ(Z.error)}`);return Z.data}function $Q(Y){return Y.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let H=await DQ(Z);process.exit(H)})}function D(Y,Z=""){Y.write(`${Z}
2
- `)}function GQ(Y){return`[task] [${Y.status}] ${Y.subject}`}function VQ(){return{requestConfirmation:async(Y)=>Y.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:Y.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function XQ(Y){if(!(Y instanceof Error))return"Unknown error";let V=Y.lastError??Y;if(V.responseBody)try{let j=JSON.parse(V.responseBody)?.error?.message;if(j)return V.statusCode?`${j} (HTTP ${V.statusCode})`:j}catch{}let q=Y.message.match(/Last error:\s*(.+)$/);if(q)return q[1];return Y.message}function BQ(Y){return Y==="jsonl"?"jsonl":"text"}function d(Y,Z){let H=(...V)=>{for(let q of V){let $=Z[q];if(typeof $==="string"&&$.trim()!=="")return $}return};switch(Y){case"Read":case"Edit":case"Write":case"UndoEdit":return H("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return H("notebook_path");case"Grep":return H("path","pattern");case"Glob":return H("pattern");case"WebFetch":return H("url");case"WebSearch":return H("query");case"Bash":return H("command","description");case"Task":return H("description");case"LSP":return H("filePath","operation");case"EnterWorktree":return H("name");case"ExitWorktree":return H("action");default:return}}function KQ(Y,Z,H,V){let q=new Set(["Glob","Grep","WebSearch","LS"]),$=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Y)&&!V.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(V.targetLocked)return{phase:"executing",status:"hit",message:H?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(q.has(Y))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if($.has(Y))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:V.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function p(Y,Z,H=!1){let V=(q,$)=>{Y.stdout.write(`${JSON.stringify(c(q,$))}
3
- `)};return{contentDelta(q){if(Z==="jsonl"){V("content_delta",{delta:q});return}if(H)return;Y.stdout.write(q)},thinkingDelta(q,$){if(Z==="jsonl")return V("thinking_delta",{delta:q}),$;if(!$)Y.stderr.write("[thinking] ");return Y.stderr.write(q),!0},thinking(q){if(Z==="jsonl"){V("thinking",{content:q});return}D(Y.stderr,`[thinking] ${q}`)},streamEnd(q,$){if(Z==="jsonl"){V("stream_end",{});return}if($)Y.stderr.write(`
4
- `);if(q)Y.stdout.write(`
5
- `)},content(q){if(Z==="jsonl"){V("content",{content:q});return}D(Y.stdout,q)},structuredOutput(q){if(Z==="jsonl"){V("structured_output",{output:q.output,schema_digest:q.schemaDigest});return}D(Y.stdout,JSON.stringify(q.output))},toolStart(q,$,j,z){if(Z==="jsonl"){V("tool_start",{tool_name:q,summary:$,target:j,tool_kind:z});return}D(Y.stderr,`[tool:start] ${$}`)},toolProgress(q,$,j,z){if(Z==="jsonl"){V("tool_progress",{tool_name:q,message:$,progress:j,total:z});return}D(Y.stderr,`[tool:progress] ${q}: ${$}`)},toolResult(q,$,j,z,R){if(Z==="jsonl"){V("tool_result",{tool_name:q,summary:$,target:j,tool_kind:z,success:R?.success,error_type:R?.errorType,error_message:R?.errorMessage});return}D(Y.stderr,`[tool:result] ${$}`)},mcpCatalogChanged(q){if(Z==="jsonl"){V("mcp_catalog_changed",{revision:q.revision,server_name:q.serverName,added:q.added,removed:q.removed,updated:q.updated});return}D(Y.stderr,`[mcp:catalog] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpContentChanged(q){if(Z==="jsonl"){V("mcp_content_changed",{revision:q.revision,server_name:q.serverName,content_kind:q.contentKind==="resourceTemplates"?"resource_templates":q.contentKind,added:q.added,removed:q.removed,updated:q.updated});return}D(Y.stderr,`[mcp:${q.contentKind}] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpResourceUpdated(q){if(Z==="jsonl"){V("mcp_resource_updated",{revision:q.revision,server_name:q.serverName,uri:q.uri});return}D(Y.stderr,`[mcp:resource] r${q.revision} ${q.serverName} updated ${q.uri}`)},mcpConnectionChanged(q){if(Z==="jsonl"){V("mcp_connection_changed",{revision:q.revision,server_name:q.serverName,phase:q.phase,reason:q.reason,attempt:q.attempt,max_attempts:q.maxAttempts,...q.nextRetryAt!==void 0?{next_retry_at:q.nextRetryAt}:{},...q.error?{error:q.error}:{}});return}D(Y.stderr,`[mcp:connection] r${q.revision} ${q.serverName} ${q.phase} ${q.attempt}/${q.maxAttempts}`)},mcpLog(q){if(Z==="jsonl"){V("mcp_log",{revision:q.revision,server_name:q.serverName,level:q.level,logger:q.logger,message:q.message,projected_bytes:q.projectedBytes,data_sha256:q.dataSha256,truncated:q.truncated,details_omitted:q.detailsOmitted,timestamp:q.timestamp,synthetic:q.synthetic});return}D(Y.stderr,`[mcp:log] ${q.level} ${q.serverName}${q.logger?` logger=${q.logger}`:""}: ${q.message}`)},mcpInstructionsChanged(q){if(Z==="jsonl"){V("mcp_instructions_changed",{revision:q.revision,server_name:q.serverName,action:q.action,reason:q.reason,text:q.text,source_bytes:q.sourceBytes,projected_bytes:q.projectedBytes,sha256:q.sha256,truncated:q.truncated,details_omitted:q.detailsOmitted});return}D(Y.stderr,`[mcp:instructions] ${q.action} ${q.serverName}${q.truncated?" (truncated)":""}`)},mcpTaskChanged(q){if(Z==="jsonl"){V("mcp_task_changed",{revision:q.revision,task_id:q.taskId,server_name:q.serverName,tool_name:q.toolName,status:q.status,status_message:q.statusMessage,created_at:q.createdAt,updated_at:q.updatedAt,completed_at:q.completedAt,has_result:q.hasResult,error:q.error});return}D(Y.stderr,`[mcp:task] ${q.taskId} ${q.serverName}/${q.toolName} `+q.status)},projectRulesLoaded(q){if(Z==="jsonl"){V("project_rules_loaded",{files:q.files.map(($)=>({id:$.id,relative_path:$.relativePath,source:$.source,conditional:$.conditional,content_sha256:$.contentSha256})),trigger_paths:q.triggerPaths,blocked_write:q.blockedWrite});return}D(Y.stderr,`[project-rules] loaded ${q.files.length} file(s)${q.blockedWrite?" before write":""}`)},userShellStarted(q,$,j){if(Z==="jsonl"){V("user_shell_started",{execution_id:q,command:$,auxiliary:j});return}D(Y.stderr,`[user-shell:start] ${$}`)},userShellOutput(q,$,j,z){if(Z==="jsonl"){V("user_shell_output",{execution_id:q,stream:$,chunk:j,stream_truncated:z});return}($==="stderr"?Y.stderr:Y.stdout).write(j)},userShellCompleted(q){if(Z==="jsonl"){V("user_shell_completed",{execution_id:q.executionId,message_id:q.messageId,status:q.record.status,exit_code:q.record.exitCode,duration_ms:q.record.durationMs,stdout:q.record.stdout,stderr:q.record.stderr,truncated:q.record.truncated,auxiliary:q.auxiliary});return}D(Y.stderr,`[user-shell:${q.record.status}] exit=${q.record.exitCode??"null"} ${q.record.durationMs}ms`)},phase(q,$,j,z={}){if(Z==="jsonl"){V("phase",{phase:q,status:$,message:j,turn:z.turn,tool_name:z.toolName,target:z.target});return}D(Y.stderr,`[phase:${q}] ${j}`)},toolDetail(q,$){if(Z==="jsonl"){V("tool_detail",{tool_name:q,detail:$});return}D(Y.stderr,$)},taskUpdate(q){if(Z==="jsonl"){V("task_update",{tasks:q});return}for(let $ of q)D(Y.stderr,GQ($))},goal(q){if(Z==="jsonl"){V("goal",{state:q.goal?"updated":"cleared",goal_id:q.goal?.goalId,status:q.goal?.status,verification_attempt:q.goal?.completionVerification?.attempt,verification_status:q.goal?.completionVerification?.status,verifier_session_id:q.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:q.goal?.completionVerification?.evidenceSha256});return}if(q.goal)D(Y.stderr,`[goal:${q.goal.status}] ${q.goal.objective}`);else D(Y.stderr,"[goal:cleared]")},subagent(q){let $=q.kind==="subagent_spawned";if(Z==="jsonl"){V("subagent",{state:$?"spawned":"completed",session_id:q.sessionId,subagent_type:q.type,success:$?void 0:q.success,summary:$?void 0:q.summary,verification_verdict:$?void 0:q.verificationVerdict,resumed_from:q.resumedFrom,root_agent_id:q.rootAgentId,resume_depth:q.resumeDepth});return}D(Y.stderr,`[subagent:${$?"spawned":"completed"}] ${q.sessionId}${q.resumedFrom?` resumed from ${q.resumedFrom}`:""}`)},tokenUsage(q){if(Z==="jsonl"){V("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens,cache_read_tokens:q.cacheReadTokens,cache_write_tokens:q.cacheWriteTokens,cost_usd:q.costUsd});return}D(Y.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){if(Z==="jsonl"){V("compacting",{state:q?"started":"completed"});return}D(Y.stderr,q?"[context] compacting started":"[context] compacting completed")},providerRetry(q){if(Z==="jsonl"){V("provider_retry",{phase:q.phase,attempt:q.attempt,max_retries:q.maxRetries,reason:q.reason,status_code:q.statusCode,delay_ms:q.delayMs,next_retry_at:q.nextRetryAt});return}let $=q.delayMs!==void 0?` in ${Math.max(0,Math.ceil(q.delayMs/1000))}s`:"";D(Y.stderr,`[provider-retry:${q.phase}] ${q.attempt}/${q.maxRetries} ${q.reason}${$}`)},providerStall(q){if(Z==="jsonl"){V("provider_stall",{phase:q.phase,stall_count:q.stallCount,duration_ms:q.durationMs,warning_after_ms:q.warningAfterMs,timeout_ms:q.timeoutMs,output_started:q.outputStarted});return}D(Y.stderr,`[provider-stall:${q.phase}] ${q.durationMs}ms / ${q.timeoutMs}ms`)},turnLimit(q){if(Z==="jsonl"){V("turn_limit",{turns_count:q,action:"continue"});return}D(Y.stderr,`[turn-limit] continuing after ${q} turns`)},taskSession(q){if(Z==="jsonl"){V("task_session",{session_id:q.sessionId,project_path:q.projectPath,source_project_path:q.sourceProjectPath,isolation:q.isolation,worktree_branch:q.worktreeBranch,base_commit:q.baseCommit});return}D(Y.stderr,`[task:${q.isolation}] ${q.sessionId} ${q.sourceProjectPath} -> ${q.projectPath}${q.worktreeBranch?` (${q.worktreeBranch})`:""}`)},taskAdmission(q){if(Z==="jsonl"){V("task_admission",{state:q.state,queue_position:q.queuePosition,queue_depth:q.queueDepth,in_flight:q.inFlight,max_concurrent_tasks:q.maxConcurrentTasks});return}D(Y.stderr,q.state==="queued"?`[task:queued] position ${q.queuePosition??1}/${q.queueDepth} (running ${q.inFlight}/${q.maxConcurrentTasks})`:`[task:running] admitted (running ${q.inFlight}/${q.maxConcurrentTasks})`)},output(q,$=0){if(Z==="jsonl"){V("output",{content:q,exit_code:$});return}D($===0?Y.stdout:Y.stderr,q)},error(q){if(Z==="jsonl"){V("error",{message:q});return}D(Y.stderr,q)}}}async function DQ(Y,Z={stdout:process.stdout,stderr:process.stderr},H){let V="text",q=p(Z,V),$=new Dq,j={targetLocked:!1},z,R,J=eq(H);try{let B=ZQ(Y);V=BQ(B.outputFormat);let P=await Bq(B);q=p(Z,V,Boolean(P)),await Gq();let jq=await Vq(B),A=await Xq(jq);if(A.mode==="output"){if(A.content)q.output(A.content,A.exitCode??0);return A.exitCode??0}let L=A.content.trimStart().startsWith("!")?A.content.trimStart().slice(1).trim():void 0;if(L!==void 0&&B.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(L!==void 0&&P)throw Error("Output schemas cannot be combined with user shell commands");if(B.taskIsolation&&(B.continue||B.resume||B.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:U,messages:C,metadata:k}=await Kq({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),E=B.permissionMode??k?.permissionMode??"yolo",F=B.model&&B.model!=="inherit"?B.model:v()?.id,_=B.taskIsolation?await $q.createSessionTask({sessionId:U,prompt:A.content,sourceProjectPath:I(),isolation:B.taskIsolation,dispatch:{version:1,prompt:A.content,sourceProjectPath:I(),isolation:B.taskIsolation,permissionMode:E,...F?{modelId:F}:{},...P?{outputSchema:P}:{}}}):void 0,M=_?.metadata.projectPath??k?.projectPath??I();if(!_)await h.setSessionPermissionMode(U,M,E);let bq=_?!1:await r.cancelPendingNonInteractive(M,U);if(_)q.taskSession({sessionId:U,projectPath:M,sourceProjectPath:_.metadata.taskSourceProjectPath??I(),isolation:B.taskIsolation,worktreeBranch:_.metadata.taskWorktreeBranch,baseCommit:_.metadata.taskBaseCommit}),R=s.subscribe((G)=>{if(G.type!=="task.status"||G.sessionId!==U||G.projectPath!==M||!["queued","running"].includes(String(G.properties.taskStatus))||typeof G.properties.taskQueueDepth!=="number"||typeof G.properties.taskInFlight!=="number"||typeof G.properties.taskConcurrencyLimit!=="number")return;q.taskAdmission({state:G.properties.taskStatus,queuePosition:typeof G.properties.taskQueuePosition==="number"?G.properties.taskQueuePosition:void 0,queueDepth:G.properties.taskQueueDepth,inFlight:G.properties.taskInFlight,maxConcurrentTasks:G.properties.taskConcurrencyLimit})});let Hq={messages:bq?await h.loadSession(U,M):[...C],userId:"cli-user",sessionId:U,workspaceRoot:M,permissionMode:E,signal:J.signal,..._?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:VQ()};if(z=await a.create({sessionId:U,workspaceRoot:M,modelId:B.model,permissionMode:E,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?e(B.agents):void 0,..._?.taskWorktree?{taskWorktree:_.taskWorktree}:{},..._?.metadata.taskIsolation?{taskIsolation:_.metadata.taskIsolation}:{},...C.length>0?{sessionStart:{isResume:!0,resumeSessionId:U}}:{}}),L!==void 0){let G=await z.executeUserShellCommand(L,{signal:J.signal,onEvent:(X)=>{if(X.type==="started")q.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")q.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated)}});return q.userShellCompleted(G),G.record.status==="completed"?0:G.record.status==="aborted"?130:G.record.exitCode??1}let zq=B.maxTurns??z.getConfig().maxTurns,_q=_?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,Aq=await t.createWithRuntime(z,{sessionId:U,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:E,toolWhitelist:B.allowedTools,toolBlacklist:_q,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),O=await i(Aq.chatStream(A.content,Hq,{stream:!0,signal:J.signal,maxTurns:B.maxTurns,outputSchema:P,...zq===-1?{onTurnLimitReached:async(G)=>{return q.turnLimit(G.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(G)=>{switch(G.kind){case"content_delta":if(!P||V==="jsonl")$.markAssistantContent();q.contentDelta(G.delta);break;case"thinking_delta":$.setThinkingOpened(q.thinkingDelta(G.delta,$.hasOpenThinking()));break;case"stream_end":{let X=$.completeStream();q.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),N=o(X.function.name,f),x=d(X.function.name,f),W=KQ(X.function.name,N,x,j);if(W.shouldLockTarget)j.targetLocked=!0;q.phase(W.phase,W.status,W.message,{toolName:X.function.name,target:x}),q.toolStart(X.function.name,N,x,G.toolKind)}catch{q.phase(j.targetLocked?"executing":"searching",j.targetLocked?"hit":"ongoing",j.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),q.toolStart(X.function.name,X.function.name,void 0,G.toolKind)}break}case"tool_progress":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;q.toolProgress(X.function.name,G.update.message,G.update.progress,G.update.total);break}case"tool_result":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;let f;try{let x=JSON.parse(X.function.arguments);f=d(X.function.name,x)}catch{f=void 0}let N=n(X.function.name,G.result);if(q.toolResult(X.function.name,N.summary,f,void 0,{success:G.result.success,errorType:G.result.error?.type,errorMessage:G.result.error?.message}),N.detail)q.toolDetail(X.function.name,N.detail);break}case"token_usage":q.tokenUsage(G.usage);break;case"compaction":q.compacting(G.phase==="start");break;case"task_update":q.taskUpdate(G.tasks);break;case"structured_output":q.structuredOutput(G);break;case"mcp_catalog_changed":q.mcpCatalogChanged(G);break;case"mcp_content_changed":q.mcpContentChanged(G);break;case"mcp_resource_updated":q.mcpResourceUpdated(G);break;case"mcp_connection_changed":q.mcpConnectionChanged(G);break;case"mcp_log":q.mcpLog(G);break;case"mcp_instructions_changed":q.mcpInstructionsChanged(G);break;case"mcp_task_changed":q.mcpTaskChanged(G);break;case"project_rules_loaded":q.projectRulesLoaded(G);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":q.goal(G);break;case"subagent_spawned":case"subagent_completed":q.subagent(G);break;case"model_fallback":break;case"provider_retry":q.providerRetry(G);break;case"provider_stall":q.providerStall(G);break;case"turn_start":if(G.turn===1)j.targetLocked=!1;q.phase("turn",j.targetLocked?"hit":"ongoing",`Turn ${G.turn} started`,{turn:G.turn});break;default:{let X=G}}});if(O.metadata?.outputTruncated)q.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!O.success)return q.error(`Error: ${O.error?.message??"Agent execution failed"}`),1;return q.phase("completed","done","Headless run completed"),0}catch(B){if($.hasOpenThinking()&&V==="text")Z.stderr.write(`
6
- `);return q.error(`Error: ${XQ(B)}`),1}finally{R?.();try{await z?.dispose()}finally{J.dispose()}}}async function cQ(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:H,"output-format":V,"system-prompt":q,"append-system-prompt":$,"max-turns":j,...z}=qq,R=nq(tq(process.argv)).scriptName("blade").strict(!1).options(z).middleware([Yq,Qq,Zq]);return $Q(R),await R.parse(),!0}export{DQ as runHeadless,cQ as handleHeadlessMode,QQ as HeadlessOptionsSchema};
@@ -1 +0,0 @@
1
- import{uf as a,vf as b,wf as c,xf as d,yf as e,zf as f}from"./chunk-7x5cqfy7.js";import"./chunk-g11hq0e5.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};