blade-code 0.10.104 → 0.10.106

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 (63) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-x6m0h59v.js → chunk-1b4rh25n.js} +1 -1
  3. package/dist/{chunk-pkack2dw.js → chunk-2a03fwgm.js} +1 -1
  4. package/dist/chunk-31c266h5.js +1 -0
  5. package/dist/{chunk-t55d9bjv.js → chunk-4ywjs5fw.js} +1 -1
  6. package/dist/{chunk-0tbdbnyp.js → chunk-51ep7gct.js} +1 -1
  7. package/dist/{chunk-e40ntkjm.js → chunk-6hcp4y6z.js} +1 -1
  8. package/dist/{chunk-8886s1qa.js → chunk-6ywj6p3q.js} +1 -1
  9. package/dist/{chunk-r9p130v6.js → chunk-6yxr3rwf.js} +1 -1
  10. package/dist/{chunk-x2wsb8w2.js → chunk-95xnc5t8.js} +1 -1
  11. package/dist/chunk-amkhz6er.js +1 -0
  12. package/dist/{chunk-vtq52np4.js → chunk-b8q7vjd9.js} +1 -1
  13. package/dist/{chunk-mm762w5r.js → chunk-bxrnsq3n.js} +1 -1
  14. package/dist/chunk-cwjxrz7p.js +23 -0
  15. package/dist/{chunk-w7vhgbhr.js → chunk-dpadcz0y.js} +1 -1
  16. package/dist/{chunk-sg795gzk.js → chunk-dy058mrn.js} +1 -1
  17. package/dist/{chunk-stmmw8m8.js → chunk-gtznn0fk.js} +1 -1
  18. package/dist/{chunk-050537sc.js → chunk-h9yvynzr.js} +1 -1
  19. package/dist/{chunk-rnz5zxdw.js → chunk-mfd2nsfd.js} +1 -1
  20. package/dist/{chunk-zc7snr6f.js → chunk-ny2gnbq8.js} +1 -1
  21. package/dist/{chunk-6nc7mcxx.js → chunk-qb7weaz0.js} +1 -1
  22. package/dist/chunk-rtnyzakh.js +118 -0
  23. package/dist/{chunk-496d1ag5.js → chunk-sh94x2js.js} +1 -1
  24. package/dist/{chunk-jntgg3zj.js → chunk-szkxjpr1.js} +1 -1
  25. package/dist/{chunk-32yfgw9s.js → chunk-tyd3bz74.js} +1 -1
  26. package/dist/{chunk-cj0c0ffd.js → chunk-tze04t3t.js} +1 -1
  27. package/dist/{chunk-b69xvpah.js → chunk-v60x3dy1.js} +1 -1
  28. package/dist/{chunk-terw7qdx.js → chunk-v6zjf4jx.js} +4 -4
  29. package/dist/{chunk-jk209m4h.js → chunk-vqke0a40.js} +1 -1
  30. package/dist/{chunk-mxjsttbc.js → chunk-w2a5dqg5.js} +1 -1
  31. package/dist/{chunk-epdzdv4e.js → chunk-wcm4hm35.js} +1 -1
  32. package/dist/{chunk-3rpmd93p.js → chunk-wvnw6wfz.js} +1 -1
  33. package/dist/{chunk-knmvaxsb.js → chunk-x6frzhkf.js} +1 -1
  34. package/dist/{chunk-sv9apfmy.js → chunk-xxzdnt4g.js} +2 -2
  35. package/dist/{chunk-m5zx8enh.js → chunk-xzy7vtdf.js} +1 -1
  36. package/dist/{chunk-4m38k0rp.js → chunk-ykzg875x.js} +1 -1
  37. package/dist/{chunk-scq56220.js → chunk-z0manfyv.js} +1 -1
  38. package/dist/{chunk-kfcbaj44.js → chunk-zvawerhj.js} +1 -1
  39. package/dist/web/assets/{ChatView-_4ut_-Jh.js → ChatView-p9tMKcFw.js} +4 -4
  40. package/dist/web/assets/{CodeBlockHighlighter-DkDr6wE9.js → CodeBlockHighlighter-DD7FIfcr.js} +1 -1
  41. package/dist/web/assets/{FilePreview-DCI-oqhJ.js → FilePreview-DDpZFwlq.js} +1 -1
  42. package/dist/web/assets/{KanbanBoard-CB5C4tJC.js → KanbanBoard-1Bkr6fIi.js} +1 -1
  43. package/dist/web/assets/{MarkdownRenderer-ychfmIQK.js → MarkdownRenderer-hkB9aVVA.js} +3 -3
  44. package/dist/web/assets/{SettingsModal-SSdk0Bjr.js → SettingsModal-KpvOJhBi.js} +1 -1
  45. package/dist/web/assets/{TaskSwitcher-EnaUhn3o.js → TaskSwitcher-2FU_n9lh.js} +1 -1
  46. package/dist/web/assets/{TerminalPanel-BcWxLSV3.js → TerminalPanel-C-LpIqOw.js} +1 -1
  47. package/dist/web/assets/{arrow-left-Ob5r20g7.js → arrow-left-Bf8UJl0b.js} +1 -1
  48. package/dist/web/assets/{calendar-clock-eOALT8DB.js → calendar-clock-BTAxrL8A.js} +1 -1
  49. package/dist/web/assets/{chevrons-up-down-BkZBwmbt.js → chevrons-up-down-CTzVylwH.js} +1 -1
  50. package/dist/web/assets/{clock-3-DQp9SzYc.js → clock-3-Cm6_vdYx.js} +1 -1
  51. package/dist/web/assets/{external-link-BuGUowPD.js → external-link-DJln2WFN.js} +1 -1
  52. package/dist/web/assets/{folder-c92kw1oI.js → folder-BXj3pohP.js} +1 -1
  53. package/dist/web/assets/{index-CS8jtO_A.js → index-DQL9otjm.js} +4 -4
  54. package/dist/web/assets/{pause-DP_CXoH7.js → pause-W092j5bW.js} +1 -1
  55. package/dist/web/assets/{play-DcRwtohz.js → play-OpsbZ_PE.js} +1 -1
  56. package/dist/web/assets/{session-events-CrAgnaj2.js → session-events-BuugneNw.js} +1 -1
  57. package/dist/web/assets/{teamService-JyVbGQhi.js → teamService-Aj-8ajEO.js} +1 -1
  58. package/dist/web/index.html +1 -2
  59. package/package.json +1 -1
  60. package/dist/chunk-31aeh672.js +0 -23
  61. package/dist/chunk-kfgw21tq.js +0 -1
  62. package/dist/chunk-rx2eax1g.js +0 -118
  63. package/dist/chunk-z8ddwve9.js +0 -1
@@ -1,4 +1,4 @@
1
- import{c as e}from"./index-CS8jtO_A.js";/**
1
+ import{c as e}from"./index-DQL9otjm.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- import{c as o}from"./index-CS8jtO_A.js";/**
1
+ import{c as o}from"./index-DQL9otjm.js";/**
2
2
  * @license lucide-react v0.300.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -19,4 +19,4 @@ ${c}`:""].filter(Boolean).join(`
19
19
  `)}]}))},pt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:s,updateSubagent:r}=t();if(e.sessionId!==n)return;const i=C(s,e.subagentSessionId,a);if(!i)return;const o=String(e.serverName),u=String(e.action),d=`mcp-instructions:${String(e.revision)}:${o}:${u}`;r(i.messageId,i.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:o,action:u,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP instructions ${u}: ${o}`+(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
  `)}]}))},Ft=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:s,updateSubagent:r}=t();if(e.sessionId!==n)return;const i=C(s,e.subagentSessionId,a);if(!i)return;const o=String(e.taskId),u=String(e.status),d=`mcp-task:${o}`;r(i.messageId,i.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Task",arguments:JSON.stringify({taskId:o,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:u==="failed"||u==="cancelled"?"error":u==="completed"?"success":"running",startTime:Number(e.createdAt)||Date.now(),summary:`MCP task ${u}: ${o} · ${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
  `)}]}))},qt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:a,messages:s,updateSubagent:r}=t();if(e.sessionId!==n)return;const i=C(s,e.subagentSessionId,a);if(!i)return;const o=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],u=`project-rules:${o.map(d=>String(d.id)).join(",")}`;r(i.messageId,i.subagent.id,d=>({toolCalls:[...(d.toolCalls||[]).filter(c=>c.toolCallId!==u),{toolCallId:u,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:e.blockedWrite}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`Project rules loaded: ${o.length}`,output:o.map(c=>`${String(c.relativePath)} ${String(c.source)} SHA-256: ${String(c.contentSha256)}`).join(`
22
- `)}]}))},Et=(e,t,n)=>{const{currentSessionId:a,setConfirmation:s}=t();if(e.sessionId!==a)return;const r=e.requestId||"",i=v(t,n,r?`assistant-permission-${r}`:void 0);if(!i)return;const o=e.details,u=e.toolName||(o==null?void 0:o.toolName)||"Tool";s(i,{toolCallId:r,toolName:u,description:e.description,diff:(o==null?void 0:o.details)||(o==null?void 0:o.diff)||"",allowRemember:(o==null?void 0:o.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:r}}:c)}))},Bt=(e,t,n)=>{var f,m;const{currentSessionId:a,currentSessionRef:s,messages:r,setConfirmation:i,setElicitation:o}=t();if(e.sessionId!==a)return;const u=e.requestId,d=r.find(S=>{var y,h;return((h=(y=S.agentContent)==null?void 0:y.confirmation)==null?void 0:h.toolCallId)===u}),c=(f=d==null?void 0:d.agentContent)==null?void 0:f.confirmation;d&&(c==null?void 0:c.status)==="pending"&&i(d.id,{...c,status:"denied"});const l=r.find(S=>{var y,h;return((h=(y=S.agentContent)==null?void 0:y.elicitation)==null?void 0:h.toolCallId)===u}),g=(m=l==null?void 0:l.agentContent)==null?void 0:m.elicitation;l&&(g==null?void 0:g.status)==="pending"&&o(l.id,{...g,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...s?{sessionRef:s}:{}}})},ge=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0,turnRecovery:null})};function Vt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;if(typeof t.turnId!="string"||!t.turnId||!Number.isSafeInteger(t.inputMessageCount)||t.inputMessageCount<0)return null;const n={turnId:t.turnId,inputMessageCount:t.inputMessageCount};return t.state==="completed"||t.state==="resumable"?{state:t.state,...n}:t.state==="requires_attention"&&(t.reason==="successful_tool_result"||t.reason==="interrupted_tool_call")?{state:t.state,...n,reason:t.reason}:null}const Kt=(e,t,n)=>{const a=t(),s=a.currentSessionRef;if(e.sessionId!==a.currentSessionId||!s||e.projectPath!==s.projectPath)return;const r=Vt(e.assessment);r&&(n({turnRecovery:r}),a.resyncSessionMessages(s))},Ut=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:e.reason==="context_limit"?"recovering_context":"compacting"})},Jt=(e,t,n)=>{e.sessionId===t().currentSessionId&&(t().resetContextUsage(),n({agentPhase:"running"}))},Wt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null})},Lt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerAdmission:e.phase==="queued"?e:null})},Ht=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerCircuit:e.phase==="closed"?null:e})},Gt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},Qt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerStall:e.phase==="detected"?e:null})},Yt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",actionStationarity:e.phase==="recovered"?null:e})},zt=(e,t,n)=>{const{currentSessionId:a,setQuestion:s}=t();if(e.sessionId!==a)return;const r=e.requestId||e.toolCallId||"",i=v(t,n,r?`assistant-question-${r}`:void 0);i&&(s(i,{toolCallId:r,questions:e.questions,status:"pending"}),n(o=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:o.sessions.map(u=>u.sessionId===e.sessionId&&u.projectPath===e.projectPath?{...u,pendingInteraction:{type:"question",requestId:r}}:u)})))},Xt=(e,t,n)=>{const{currentSessionId:a,setElicitation:s}=t();if(e.sessionId!==a)return;const r=e.requestId||e.toolCallId||"",i=v(t,n,r?`assistant-elicitation-${r}`:void 0),o=e.elicitation;!i||!o||(s(i,{toolCallId:r,details:o,status:"pending"}),n(u=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:u.sessions.map(d=>d.sessionId===e.sessionId&&d.projectPath===e.projectPath?{...d,pendingInteraction:{type:"elicitation",requestId:r}}:d)})))},Zt=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId!==a)return;const s=e.requestId;n(r=>({agentPhase:"running",sessions:r.sessions.map(i=>{var o;return i.sessionId===e.sessionId&&i.projectPath===e.projectPath&&((o=i.pendingInteraction)==null?void 0:o.requestId)===s?{...i,pendingInteraction:void 0}:i})}))},Z=(e,t)=>{const n=t().currentSessionRef;n&&e.sessionId===n.sessionId&&e.projectPath===n.projectPath&&t().resyncSessionMessages(n)},en=(e,t)=>{const{currentSessionId:n,currentSessionRef:a,endAgentResponse:s}=t();e.sessionId!==n||!a||e.projectPath!==a.projectPath||(s(),Z(e,t))},me=(e,t)=>{const n=t().currentSessionRef;!n||e.sessionId!==n.sessionId||e.projectPath!==n.projectPath||t().endAgentResponse()},tn=(e,t,n)=>{const{currentSessionId:a,currentSessionRef:s,endAgentResponse:r}=t();if(e.sessionId!==a)return;const i=e.taskFailure&&typeof e.taskFailure=="object"&&!Array.isArray(e.taskFailure)?e.taskFailure:void 0,o=Ue(i==null?void 0:i.code);n({agentPhase:"error",error:e.error||"An error occurred",errorContext:{kind:"execution",...s?{sessionRef:s}:{},...o?{failureCode:o}:{}}}),r(),Z(e,t)},nn=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId===a)if(e.status==="idle")n({isStreaming:!1,isStopping:!1,agentPhase:"idle",providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0}),Z(e,t);else if(e.status==="queued"||e.status==="running"||e.status==="waiting_permission"){const s=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:s,pendingInputDelivery:s>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",providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null})},sn=(e,t,n)=>{const{currentSessionId:a,endAgentResponse:s,messages:r,updateSubagent:i}=t();if(e.sessionId===a){n(o=>({isStreaming:!1,agentPhase:"idle",messages:o.messages.map(u=>{var c;const d=(c=u.agentContent)==null?void 0:c.elicitation;return(d==null?void 0:d.status)!=="pending"||!u.agentContent?u:{...u,agentContent:{...u.agentContent,elicitation:{...d,status:"cancelled"}}}})}));for(const o of r)for(const u of P(o.agentContent))u.status==="running"&&i(o.id,u.id,{status:"failed"});s()}},Ne=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},$e=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},on=(e,t,n)=>{if(typeof e.childSessionId=="string"){const a={...e,subagentSessionId:e.childSessionId,success:e.status==="completed"};C(t().messages,e.childSessionId,t().currentAssistantMessageId)?X(a,t):it(e.childSessionId,a,n)}e.delivery==="current_turn"?Ne(e,t,n):$e(e,t,n)},an=(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})},rn=(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})},un=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},dn=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=t().goal;!a||a.goalId!==e.goalId||n({goal:{...a,executionFrontier:e.frontier,...e.stall?{frontierStall:e.stall}:{frontierStall:void 0}}})},ln=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},cn=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},gn=(e,t,n)=>{if(e.sessionId!==t().currentSessionId||!Array.isArray(e.messages))return;const a=Date.now(),s=e.messages.flatMap((r,i)=>{if(typeof r!="object"||r===null)return[];const o=r;return!["user","assistant","system","tool"].includes(String(o.role))||!Array.isArray(o.content)&&typeof o.content!="string"?[]:[{id:`rewind-${i}-${a}`,role:o.role,content:o.content,timestamp:a+i,metadata:typeof o.metadata=="object"&&o.metadata!==null?o.metadata:void 0,thinkingContent:typeof o.thinkingContent=="string"?o.thinkingContent:typeof o.reasoningContent=="string"?o.reasoningContent:void 0,tool_call_id:typeof o.tool_call_id=="string"?o.tool_call_id:void 0,name:typeof o.name=="string"?o.name:void 0,tool_calls:o.tool_calls}]});n({messages:Ve(s),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},mn=(e,t,n)=>{const a=t().currentSessionRef;if(!a||e.sessionId!==a.sessionId||e.projectPath!==a.projectPath)return;const s=e.status,r=s==="completed"||s==="stale"?"completed":s==="aborted"?"cancelled":s==="interrupted"?"interrupted":"failed";n(i=>({sessions:i.sessions.map(o=>o.sessionId===a.sessionId&&o.projectPath===a.projectPath?{...o,taskStatus:r,taskStatusReason:void 0,taskFailure:void 0,taskCompletedAt:new Date().toISOString()}:o)})),t().selectSession(a)},fn=(e,t,n)=>{ke({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},In=(e,t,n)=>{we(e,t)},Sn=(e,t,n)=>{Pe(e,t,n)},hn=(e,t)=>{const n=t().currentSessionRef;n&&queueMicrotask(()=>void t().loadTeams(n))},O={"message.created":ot,"message.delta":at,"message.complete":rt,"structured.output":ut,"thinking.delta":dt,"thinking.completed":lt,"tool.start":ke,"tool.progress":we,"tool.result":Pe,"mcp.catalog.changed":ct,"mcp.content.changed":gt,"mcp.resource.updated":mt,"mcp.connection.changed":ft,"mcp.log":It,"mcp.instructions.changed":St,"mcp.task.changed":ht,"project.rules.loaded":yt,"user.shell.started":bt,"user.shell.output":Ct,"user.shell.completed":vt,"token.usage":At,"task.updated":kt,"subagent.start":Tt,"subagent.update":wt,"subagent.delta":Pt,"subagent.thinking.delta":Nt,"subagent.tool.start":$t,"subagent.tool.progress":Mt,"subagent.tool.result":Rt,"subagent.mcp.catalog.changed":_t,"subagent.mcp.content.changed":xt,"subagent.mcp.resource.updated":jt,"subagent.mcp.connection.changed":Dt,"subagent.mcp.log":Ot,"subagent.mcp.instructions.changed":pt,"subagent.mcp.task.changed":Ft,"subagent.project.rules.loaded":qt,"subagent.complete":X,"subagent.completion.queued":on,"permission.asked":Et,"permission.timeout":Bt,"turn.started":ge,"turn.recovery":Kt,"committed.turn_started":ge,"committed.turn_completed":me,"committed.turn_aborted":me,"provider.admission":Lt,"provider.circuit":Ht,"provider.retry":Gt,"provider.stall":Qt,"action.stationarity":Yt,"compaction.started":Ut,"compaction.completed":Jt,"model.fallback":Wt,"question.required":zt,"elicitation.required":Xt,"interaction.resolved":Zt,"session.completed":en,"session.error":tn,"session.status":nn,"run.cancelled":sn,"steering.queued":Ne,"follow_up.queued":$e,"follow_up.started":rn,"steering.applied":an,"goal.updated":un,"goal.frontier.updated":dn,"goal.cleared":ln,"goal.continuation.started":cn,"session.rewound":gn,"review.tool.started":fn,"review.tool.progress":In,"review.tool.completed":Sn,"review.completed":mn},yn=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]);function bn(e,t){if(e.seq!==void 0||e.type!=="tool.start"&&e.type!=="tool.result")return;const n=t().currentSessionRef,a=e.properties.toolName,s=e.properties.toolCallId;if(!n||!Ze(a)||typeof s!="string")return;const r=et.getState();e.type==="tool.start"?r.beginAgentActivity(n,{toolCallId:s,toolName:a,argumentsValue:e.properties.arguments}):r.completeAgentActivity(n,{toolCallId:s,toolName:a,success:e.properties.success===!0||e.properties.status==="completed",metadata:e.properties.metadata}),Ge.getState().openFilePreview({tab:"browser"})}const Tn=(e,t)=>n=>{const a=e().currentSessionRef,s=n.properties;if(!a||s.sessionId!==a.sessionId||s.projectPath!==a.projectPath)return;if(bn(n,e),n.type.startsWith("team.")){hn(s,e);return}if(yn.has(n.type)){w.drainAll();const i=O[n.type];i&&i(n.properties,e,t);return}if(n.type==="tool.start"&&w.drainAll(),n.type==="message.delta"){const{currentSessionId:i,currentAssistantMessageId:o,hasToolCalls:u}=e();if(s.sessionId!==i)return;const d=s.messageId||o,c=s.delta;if(!o){const f=O["message.delta"];f&&f(s,e,t);return}const l=u?"after":"before",g=`content:${d}:${l}`;w.drainAllExcept(g),w.append(g,c,f=>{const{appendDelta:m}=e();d&&m(d,f,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:i,currentAssistantMessageId:o}=e();if(s.sessionId!==i)return;if(!o){const l=O["thinking.delta"];l&&l(s,e,t);return}const u=s.delta,d=s.messageId||o,c=`thinking:${d}`;w.drainAllExcept(c),w.append(c,u,l=>{const{appendThinking:g}=e();d&&g(d,l)});return}if(n.type==="subagent.delta"){const{currentSessionId:i}=e();if(s.sessionId!==i)return;const o=s.delta;if(!o)return;const u=s.subagentSessionId||"",d=`subagent:${u}`,{currentAssistantMessageId:c,messages:l}=e(),g=C(l,u||void 0,c);w.append(d,o,f=>{const{currentAssistantMessageId:m,messages:S,updateSubagent:y}=e(),h=g||C(S,u||void 0,m);h&&y(h.messageId,h.subagent.id,I=>({sessionId:I.sessionId||u,output:(I.output||"")+f}))});return}if(n.type==="subagent.thinking.delta"){const{currentSessionId:i}=e();if(s.sessionId!==i)return;const o=s.delta;if(!o)return;const u=s.subagentSessionId||"",d=`subagent-thinking:${u}`,{currentAssistantMessageId:c,messages:l}=e(),g=C(l,u||void 0,c);w.append(d,o,f=>{const{currentAssistantMessageId:m,messages:S,updateSubagent:y}=e(),h=g||C(S,u||void 0,m);h&&y(h.messageId,h.subagent.id,I=>({sessionId:I.sessionId||u,thinking:(I.thinking||"")+f}))});return}const r=O[n.type];r&&r(n.properties,e,t)};export{Oe as a,le as b,$ as c,De as d,fe as e,Ve as f,P as g,Tn as h,w as i,Ue as j,kn as k,Ge as l,pe as m,p as n,et as o,An as t,Ie as u,W as w};
22
+ `)}]}))},Et=(e,t,n)=>{const{currentSessionId:a,setConfirmation:s}=t();if(e.sessionId!==a)return;const r=e.requestId||"",i=v(t,n,r?`assistant-permission-${r}`:void 0);if(!i)return;const o=e.details,u=e.toolName||(o==null?void 0:o.toolName)||"Tool";s(i,{toolCallId:r,toolName:u,description:e.description,diff:(o==null?void 0:o.details)||(o==null?void 0:o.diff)||"",allowRemember:(o==null?void 0:o.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:r}}:c)}))},Bt=(e,t,n)=>{var f,m;const{currentSessionId:a,currentSessionRef:s,messages:r,setConfirmation:i,setElicitation:o}=t();if(e.sessionId!==a)return;const u=e.requestId,d=r.find(S=>{var y,h;return((h=(y=S.agentContent)==null?void 0:y.confirmation)==null?void 0:h.toolCallId)===u}),c=(f=d==null?void 0:d.agentContent)==null?void 0:f.confirmation;d&&(c==null?void 0:c.status)==="pending"&&i(d.id,{...c,status:"denied"});const l=r.find(S=>{var y,h;return((h=(y=S.agentContent)==null?void 0:y.elicitation)==null?void 0:h.toolCallId)===u}),g=(m=l==null?void 0:l.agentContent)==null?void 0:m.elicitation;l&&(g==null?void 0:g.status)==="pending"&&o(l.id,{...g,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...s?{sessionRef:s}:{}}})},ge=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0,turnRecovery:null})};function Vt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;if(typeof t.turnId!="string"||!t.turnId||!Number.isSafeInteger(t.inputMessageCount)||t.inputMessageCount<0)return null;const n={turnId:t.turnId,inputMessageCount:t.inputMessageCount};return t.state==="completed"||t.state==="resumable"?{state:t.state,...n}:t.state==="requires_attention"&&(t.reason==="successful_tool_result"||t.reason==="interrupted_tool_call")?{state:t.state,...n,reason:t.reason}:null}const Kt=(e,t,n)=>{const a=t(),s=a.currentSessionRef;if(e.sessionId!==a.currentSessionId||!s||e.projectPath!==s.projectPath)return;const r=Vt(e.assessment);r&&(n({turnRecovery:r}),a.resyncSessionMessages(s))},Ut=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:e.reason==="context_limit"?"recovering_context":"compacting"})},Jt=(e,t,n)=>{e.sessionId===t().currentSessionId&&(t().resetContextUsage(),n({agentPhase:"running"}))},Wt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null})},Lt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerAdmission:e.phase==="queued"?e:null})},Ht=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerCircuit:e.phase==="closed"?null:e})},Gt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},Qt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerStall:e.phase==="detected"?e:null})},Yt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",actionStationarity:e.phase==="recovered"?null:e})},zt=(e,t,n)=>{const{currentSessionId:a,setQuestion:s}=t();if(e.sessionId!==a)return;const r=e.requestId||e.toolCallId||"",i=v(t,n,r?`assistant-question-${r}`:void 0);i&&(s(i,{toolCallId:r,questions:e.questions,status:"pending"}),n(o=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:o.sessions.map(u=>u.sessionId===e.sessionId&&u.projectPath===e.projectPath?{...u,pendingInteraction:{type:"question",requestId:r}}:u)})))},Xt=(e,t,n)=>{const{currentSessionId:a,setElicitation:s}=t();if(e.sessionId!==a)return;const r=e.requestId||e.toolCallId||"",i=v(t,n,r?`assistant-elicitation-${r}`:void 0),o=e.elicitation;!i||!o||(s(i,{toolCallId:r,details:o,status:"pending"}),n(u=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:u.sessions.map(d=>d.sessionId===e.sessionId&&d.projectPath===e.projectPath?{...d,pendingInteraction:{type:"elicitation",requestId:r}}:d)})))},Zt=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId!==a)return;const s=e.requestId;n(r=>({agentPhase:"running",sessions:r.sessions.map(i=>{var o;return i.sessionId===e.sessionId&&i.projectPath===e.projectPath&&((o=i.pendingInteraction)==null?void 0:o.requestId)===s?{...i,pendingInteraction:void 0}:i})}))},Z=(e,t)=>{const n=t().currentSessionRef;n&&e.sessionId===n.sessionId&&e.projectPath===n.projectPath&&t().resyncSessionMessages(n)},en=(e,t)=>{const{currentSessionId:n,currentSessionRef:a,endAgentResponse:s}=t();e.sessionId!==n||!a||e.projectPath!==a.projectPath||(s(),Z(e,t))},me=(e,t)=>{const n=t().currentSessionRef;!n||e.sessionId!==n.sessionId||e.projectPath!==n.projectPath||t().endAgentResponse()},tn=(e,t,n)=>{const{currentSessionId:a,currentSessionRef:s,endAgentResponse:r}=t();if(e.sessionId!==a)return;const i=e.taskFailure&&typeof e.taskFailure=="object"&&!Array.isArray(e.taskFailure)?e.taskFailure:void 0,o=Ue(i==null?void 0:i.code);n({agentPhase:"error",error:e.error||"An error occurred",errorContext:{kind:"execution",...s?{sessionRef:s}:{},...o?{failureCode:o}:{}}}),r(),Z(e,t)},nn=(e,t,n)=>{const{currentSessionId:a}=t();if(e.sessionId===a)if(e.status==="idle")n({isStreaming:!1,isStopping:!1,agentPhase:"idle",providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0}),Z(e,t);else if(e.status==="queued"||e.status==="running"||e.status==="waiting_permission"){const s=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:s,pendingInputDelivery:s>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",providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null})},sn=(e,t,n)=>{const{currentSessionId:a,endAgentResponse:s,messages:r,updateSubagent:i}=t();if(e.sessionId===a){n(o=>({isStreaming:!1,agentPhase:"idle",messages:o.messages.map(u=>{var c;const d=(c=u.agentContent)==null?void 0:c.elicitation;return(d==null?void 0:d.status)!=="pending"||!u.agentContent?u:{...u,agentContent:{...u.agentContent,elicitation:{...d,status:"cancelled"}}}})}));for(const o of r)for(const u of P(o.agentContent))u.status==="running"&&i(o.id,u.id,{status:"failed"});s()}},Ne=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},$e=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},on=(e,t,n)=>{if(typeof e.childSessionId=="string"){const a={...e,subagentSessionId:e.childSessionId,success:e.status==="completed"};C(t().messages,e.childSessionId,t().currentAssistantMessageId)?X(a,t):it(e.childSessionId,a,n)}e.delivery==="current_turn"?Ne(e,t,n):$e(e,t,n)},an=(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})},rn=(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})},un=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},dn=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const a=t().goal;!a||a.goalId!==e.goalId||n({goal:{...a,executionFrontier:e.frontier,frontierStall:e.stall}})},ln=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},cn=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},gn=(e,t,n)=>{if(e.sessionId!==t().currentSessionId||!Array.isArray(e.messages))return;const a=Date.now(),s=e.messages.flatMap((r,i)=>{if(typeof r!="object"||r===null)return[];const o=r;return!["user","assistant","system","tool"].includes(String(o.role))||!Array.isArray(o.content)&&typeof o.content!="string"?[]:[{id:`rewind-${i}-${a}`,role:o.role,content:o.content,timestamp:a+i,metadata:typeof o.metadata=="object"&&o.metadata!==null?o.metadata:void 0,thinkingContent:typeof o.thinkingContent=="string"?o.thinkingContent:typeof o.reasoningContent=="string"?o.reasoningContent:void 0,tool_call_id:typeof o.tool_call_id=="string"?o.tool_call_id:void 0,name:typeof o.name=="string"?o.name:void 0,tool_calls:o.tool_calls}]});n({messages:Ve(s),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},mn=(e,t,n)=>{const a=t().currentSessionRef;if(!a||e.sessionId!==a.sessionId||e.projectPath!==a.projectPath)return;const s=e.status,r=s==="completed"||s==="stale"?"completed":s==="aborted"?"cancelled":s==="interrupted"?"interrupted":"failed";n(i=>({sessions:i.sessions.map(o=>o.sessionId===a.sessionId&&o.projectPath===a.projectPath?{...o,taskStatus:r,taskStatusReason:void 0,taskFailure:void 0,taskCompletedAt:new Date().toISOString()}:o)})),t().selectSession(a)},fn=(e,t,n)=>{ke({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},In=(e,t,n)=>{we(e,t)},Sn=(e,t,n)=>{Pe(e,t,n)},hn=(e,t)=>{const n=t().currentSessionRef;n&&queueMicrotask(()=>void t().loadTeams(n))},O={"message.created":ot,"message.delta":at,"message.complete":rt,"structured.output":ut,"thinking.delta":dt,"thinking.completed":lt,"tool.start":ke,"tool.progress":we,"tool.result":Pe,"mcp.catalog.changed":ct,"mcp.content.changed":gt,"mcp.resource.updated":mt,"mcp.connection.changed":ft,"mcp.log":It,"mcp.instructions.changed":St,"mcp.task.changed":ht,"project.rules.loaded":yt,"user.shell.started":bt,"user.shell.output":Ct,"user.shell.completed":vt,"token.usage":At,"task.updated":kt,"subagent.start":Tt,"subagent.update":wt,"subagent.delta":Pt,"subagent.thinking.delta":Nt,"subagent.tool.start":$t,"subagent.tool.progress":Mt,"subagent.tool.result":Rt,"subagent.mcp.catalog.changed":_t,"subagent.mcp.content.changed":xt,"subagent.mcp.resource.updated":jt,"subagent.mcp.connection.changed":Dt,"subagent.mcp.log":Ot,"subagent.mcp.instructions.changed":pt,"subagent.mcp.task.changed":Ft,"subagent.project.rules.loaded":qt,"subagent.complete":X,"subagent.completion.queued":on,"permission.asked":Et,"permission.timeout":Bt,"turn.started":ge,"turn.recovery":Kt,"committed.turn_started":ge,"committed.turn_completed":me,"committed.turn_aborted":me,"provider.admission":Lt,"provider.circuit":Ht,"provider.retry":Gt,"provider.stall":Qt,"action.stationarity":Yt,"compaction.started":Ut,"compaction.completed":Jt,"model.fallback":Wt,"question.required":zt,"elicitation.required":Xt,"interaction.resolved":Zt,"session.completed":en,"session.error":tn,"session.status":nn,"run.cancelled":sn,"steering.queued":Ne,"follow_up.queued":$e,"follow_up.started":rn,"steering.applied":an,"goal.updated":un,"goal.frontier.updated":dn,"goal.cleared":ln,"goal.continuation.started":cn,"session.rewound":gn,"review.tool.started":fn,"review.tool.progress":In,"review.tool.completed":Sn,"review.completed":mn},yn=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]);function bn(e,t){if(e.seq!==void 0||e.type!=="tool.start"&&e.type!=="tool.result")return;const n=t().currentSessionRef,a=e.properties.toolName,s=e.properties.toolCallId;if(!n||!Ze(a)||typeof s!="string")return;const r=et.getState();e.type==="tool.start"?r.beginAgentActivity(n,{toolCallId:s,toolName:a,argumentsValue:e.properties.arguments}):r.completeAgentActivity(n,{toolCallId:s,toolName:a,success:e.properties.success===!0||e.properties.status==="completed",metadata:e.properties.metadata}),Ge.getState().openFilePreview({tab:"browser"})}const Tn=(e,t)=>n=>{const a=e().currentSessionRef,s=n.properties;if(!a||s.sessionId!==a.sessionId||s.projectPath!==a.projectPath)return;if(bn(n,e),n.type.startsWith("team.")){hn(s,e);return}if(yn.has(n.type)){w.drainAll();const i=O[n.type];i&&i(n.properties,e,t);return}if(n.type==="tool.start"&&w.drainAll(),n.type==="message.delta"){const{currentSessionId:i,currentAssistantMessageId:o,hasToolCalls:u}=e();if(s.sessionId!==i)return;const d=s.messageId||o,c=s.delta;if(!o){const f=O["message.delta"];f&&f(s,e,t);return}const l=u?"after":"before",g=`content:${d}:${l}`;w.drainAllExcept(g),w.append(g,c,f=>{const{appendDelta:m}=e();d&&m(d,f,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:i,currentAssistantMessageId:o}=e();if(s.sessionId!==i)return;if(!o){const l=O["thinking.delta"];l&&l(s,e,t);return}const u=s.delta,d=s.messageId||o,c=`thinking:${d}`;w.drainAllExcept(c),w.append(c,u,l=>{const{appendThinking:g}=e();d&&g(d,l)});return}if(n.type==="subagent.delta"){const{currentSessionId:i}=e();if(s.sessionId!==i)return;const o=s.delta;if(!o)return;const u=s.subagentSessionId||"",d=`subagent:${u}`,{currentAssistantMessageId:c,messages:l}=e(),g=C(l,u||void 0,c);w.append(d,o,f=>{const{currentAssistantMessageId:m,messages:S,updateSubagent:y}=e(),h=g||C(S,u||void 0,m);h&&y(h.messageId,h.subagent.id,I=>({sessionId:I.sessionId||u,output:(I.output||"")+f}))});return}if(n.type==="subagent.thinking.delta"){const{currentSessionId:i}=e();if(s.sessionId!==i)return;const o=s.delta;if(!o)return;const u=s.subagentSessionId||"",d=`subagent-thinking:${u}`,{currentAssistantMessageId:c,messages:l}=e(),g=C(l,u||void 0,c);w.append(d,o,f=>{const{currentAssistantMessageId:m,messages:S,updateSubagent:y}=e(),h=g||C(S,u||void 0,m);h&&y(h.messageId,h.subagent.id,I=>({sessionId:I.sessionId||u,thinking:(I.thinking||"")+f}))});return}const r=O[n.type];r&&r(n.properties,e,t)};export{Oe as a,le as b,$ as c,De as d,fe as e,Ve as f,P as g,Tn as h,w as i,Ue as j,kn as k,Ge as l,pe as m,p as n,et as o,An as t,Ie as u,W as w};
@@ -1 +1 @@
1
- import{at as e,au as t,av as a,a3 as s,aw as m}from"./index-CS8jtO_A.js";import"./vendor-react-DofNRwfy.js";import"./vendor-radix-Bc1_Q9tz.js";import"./session-events-CrAgnaj2.js";const p=e(t.Object({id:t.String(),name:t.String(),subagentType:t.String(),description:t.String(),agentId:t.Optional(t.String()),status:a(["leader","running","completed","failed","cancelled","unknown"]),result:t.Optional(t.Unknown()),stats:t.Optional(t.Unknown()),worktreePath:t.Optional(t.String())})),d=e(t.Object({id:t.String(),subject:t.String(),description:t.String(),status:a(["pending","blocked","running","completed"]),owner:t.Optional(t.String()),priority:a(["high","medium","low"]),dependsOn:t.Array(t.String()),blocks:t.Array(t.String()),result:t.Optional(t.String()),createdAt:t.String(),startedAt:t.Optional(t.String()),completedAt:t.Optional(t.String())})),o=e(t.Object({name:t.String(),description:t.Optional(t.String()),status:a(["idle","running","completed","failed","deleted"]),leadAgentId:t.String(),leadSessionId:t.Optional(t.String()),workspaceRoot:t.Optional(t.String()),peerMessagingEnabled:t.Boolean(),createdAt:t.Number(),updatedAt:t.Number(),deletedAt:t.Optional(t.Number()),members:t.Array(p),tasks:t.Array(d)}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),name:t.String({minLength:1}),description:t.Optional(t.String()),leadAgentType:t.Optional(t.String()),peerMessagingEnabled:t.Optional(t.Boolean()),members:t.Array(t.Object({name:t.String({minLength:1}),subagentType:t.String({minLength:1}),description:t.Optional(t.String()),prompt:t.String({minLength:10,maxLength:32*1024})}),{maxItems:32}),tasks:t.Optional(t.Array(t.Object({subject:t.String({minLength:1}),description:t.String({minLength:1}),dependsOn:t.Optional(t.Array(t.String())),assignedTo:t.Optional(t.String()),priority:t.Optional(a(["high","medium","low"]))}),{maxItems:256}))}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),to:t.String({minLength:1}),message:t.String({minLength:1,maxLength:32*1024})}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),memberId:t.String({minLength:1})}));const S=t.Array(o),u={list:async n=>{const i=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return m(S,await s(`/teams?${i.toString()}`))},sendMessage:async(n,i,r,g)=>{await s(`/teams/${encodeURIComponent(i)}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n.sessionId,projectPath:n.projectPath,to:r,message:g})})},delete:async(n,i)=>{const r=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return o.parse(await s(`/teams/${encodeURIComponent(i)}?${r.toString()}`,{method:"DELETE"}))}};export{u as teamService};
1
+ import{at as e,au as t,av as a,a3 as s,aw as m}from"./index-DQL9otjm.js";import"./vendor-react-DofNRwfy.js";import"./vendor-radix-Bc1_Q9tz.js";import"./session-events-BuugneNw.js";const p=e(t.Object({id:t.String(),name:t.String(),subagentType:t.String(),description:t.String(),agentId:t.Optional(t.String()),status:a(["leader","running","completed","failed","cancelled","unknown"]),result:t.Optional(t.Unknown()),stats:t.Optional(t.Unknown()),worktreePath:t.Optional(t.String())})),d=e(t.Object({id:t.String(),subject:t.String(),description:t.String(),status:a(["pending","blocked","running","completed"]),owner:t.Optional(t.String()),priority:a(["high","medium","low"]),dependsOn:t.Array(t.String()),blocks:t.Array(t.String()),result:t.Optional(t.String()),createdAt:t.String(),startedAt:t.Optional(t.String()),completedAt:t.Optional(t.String())})),o=e(t.Object({name:t.String(),description:t.Optional(t.String()),status:a(["idle","running","completed","failed","deleted"]),leadAgentId:t.String(),leadSessionId:t.Optional(t.String()),workspaceRoot:t.Optional(t.String()),peerMessagingEnabled:t.Boolean(),createdAt:t.Number(),updatedAt:t.Number(),deletedAt:t.Optional(t.Number()),members:t.Array(p),tasks:t.Array(d)}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),name:t.String({minLength:1}),description:t.Optional(t.String()),leadAgentType:t.Optional(t.String()),peerMessagingEnabled:t.Optional(t.Boolean()),members:t.Array(t.Object({name:t.String({minLength:1}),subagentType:t.String({minLength:1}),description:t.Optional(t.String()),prompt:t.String({minLength:10,maxLength:32*1024})}),{maxItems:32}),tasks:t.Optional(t.Array(t.Object({subject:t.String({minLength:1}),description:t.String({minLength:1}),dependsOn:t.Optional(t.Array(t.String())),assignedTo:t.Optional(t.String()),priority:t.Optional(a(["high","medium","low"]))}),{maxItems:256}))}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),to:t.String({minLength:1}),message:t.String({minLength:1,maxLength:32*1024})}));e(t.Object({sessionId:t.String({minLength:1}),projectPath:t.String({minLength:1}),memberId:t.String({minLength:1})}));const S=t.Array(o),u={list:async n=>{const i=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return m(S,await s(`/teams?${i.toString()}`))},sendMessage:async(n,i,r,g)=>{await s(`/teams/${encodeURIComponent(i)}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n.sessionId,projectPath:n.projectPath,to:r,message:g})})},delete:async(n,i)=>{const r=new URLSearchParams({sessionId:n.sessionId,projectPath:n.projectPath});return o.parse(await s(`/teams/${encodeURIComponent(i)}?${r.toString()}`,{method:"DELETE"}))}};export{u as teamService};
@@ -5,10 +5,9 @@
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-CS8jtO_A.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-DQL9otjm.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-DofNRwfy.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/vendor-radix-Bc1_Q9tz.js">
11
- <link rel="modulepreload" crossorigin href="/assets/session-events-CrAgnaj2.js">
12
11
  <link rel="stylesheet" crossorigin href="/assets/index-DGf6Z2kM.css">
13
12
  </head>
14
13
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.104",
3
+ "version": "0.10.106",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1,23 +0,0 @@
1
- import{s as cz,t as pz}from"./chunk-t55d9bjv.js";import{u as S}from"./chunk-epdzdv4e.js";import{A as Oz,v as gz,w as wz,x as Dz,y as _z,z as Nz}from"./chunk-x6m0h59v.js";import{H as E,Q as Bz,R as Gz,V as Uz,Y as jz,Z as Vz,aa as Kz,qa as Az,ra as qz,sa as Pz,ta as Rz}from"./chunk-terw7qdx.js";import"./chunk-abd57h72.js";import{Ha as uz}from"./chunk-kfcbaj44.js";import{Ja as Fz}from"./chunk-xm8nyj5z.js";import{Db as Yz,Mb as Lz,rb as Xz}from"./chunk-0tbdbnyp.js";import{Xb as g}from"./chunk-8hprmrd5.js";import{Cd as p,Dd as $z,Fd as h,Id as Wz,Nd as P,Qd as j,ad as zz,kd as y,ld as c,md as Hz,rd as Jz,ud as Qz,wd as Zz}from"./chunk-rx2eax1g.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{ve as mz}from"./chunk-vtq52np4.js";import"./chunk-z9gd9spf.js";import{Qe as kz,Re as Iz}from"./chunk-mxjsttbc.js";import"./chunk-v508x7cg.js";import{af as m}from"./chunk-dg0d3303.js";import{ff as e}from"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import{qf as Cz}from"./chunk-2hb222re.js";import"./chunk-pkack2dw.js";import"./chunk-mm762w5r.js";import"./chunk-kf7whgr7.js";import{ig as fz}from"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-jntgg3zj.js";import"./chunk-41cg66y0.js";import{ah as yz,dh as Mz}from"./chunk-3rpmd93p.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import{Hh as C,Ih as t,Kh as f,Lh as u}from"./chunk-c475tfqf.js";import{Ph as bz}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import{pi as M}from"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import{wi as hz,zi as Sz}from"./chunk-9p20hhs0.js";import"./chunk-m5zx8enh.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import{Vi as s}from"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import{Readable as JH,Writable as QH}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as zH,RequestError as HH}from"@agentclientprotocol/sdk";import{createHash as lz}from"node:crypto";import{RequestError as Tz}from"@agentclientprotocol/sdk";import{nanoid as I}from"nanoid";var U=M("Agent"),i=4,iz=1000,a=4000,r=120000,o=0.2;function n(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function az(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:n(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:n("headers"in z?z.headers:void 0)};return null}function rz(z){let J={};for(let H of z){let W=az(H);if(W)J[H.name]=W}return J}function xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function oz(z){let J=$z(z.metadata);return J?[{type:"text",text:p(J)}]:xz(z.content)}function nz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}function sz(z){if(!e(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...y("capacity"),resource:z.resource}}function tz(z,J){let H=Math.max(0,J-1),W=Math.min(iz*2**H,a),Y=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,Z=1-o+2*o*Y;return Math.min(a,Math.max(0,Math.round(W*Z)))}function ez(z){if(!(z instanceof Tz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Hz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class b{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,W,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Oz({maxPendingItems:wz,maxPendingBytes:Dz,writeTimeoutMs:_z,signal:H.signal,sizeOf:(Y)=>Buffer.byteLength(JSON.stringify(Y)),write:async(Y)=>{await H.sessionUpdate(Y)},onFailure:(Y)=>this.handleUpdateEgressFailure(Y)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([j.loadSession(this.id,this.cwd),j.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await j.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...z]}mapPermissionModeToMode(z){switch(z){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 Kz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await j.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),E.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Lz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?rz(this.options.mcpServers):void 0,H=E.getInstance().getTerminalService(this.id);if(this.runtime=await Uz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,F)=>{let L=await H.execute($,{cwd:F.cwd,env:F.env,timeout:F.timeoutMs,signal:F.signal,allowLocalFallback:!1,onOutput:(B)=>F.onOutput?.("stdout",B)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await S.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:F,messageId:L,content:B}=$.properties,G=$.properties.metadata;if($.type==="team.message.received"&&typeof F==="string"&&typeof L==="string"&&typeof B==="string"&&Gz(G,{messageId:L,teamName:F}))(async()=>{let V=await this.runtime?.enqueueSteering(B,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:G});if(!V?.accepted)return;if(await new Bz(F,s()).markDelivered([L]),V.delivery==="next_turn")this.requestPendingResume()})().catch((V)=>{U.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,V)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let X=await this.runtime.getGoal(),Y=this.runtime.getPendingSteeringCount()>0,Z=X?.status==="active"||X?.status==="verifying";if(Y||Z)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Zz(J))continue;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of oz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);U.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(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],this.contextMessages=await this.loadModelContextOr($.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),$}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!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(Z)=>{if(await this.setServiceTier(Z),!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(Z)=>{if(await this.setResponseVerbosity(Z),!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(Z)=>{if(await this.setCommunicationStyle(Z),!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(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,L,B=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},G=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(V)=>{if(F)B(V);else L=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,L)B(L);return G}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,$,F)},complete:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,$,F)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,$)},getLogs:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,$)},setLoggingLevel:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,$)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Z,{signal:$})}},codeReview:{run:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await S.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:$,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),L=await F.completion,B=(await S.list(this.cwd,this.id)).find((G)=>G.start.reviewId===F.reviewId);if(!B)throw Error(`Review not found: ${F.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:F.reviewId,status:L.status,findings:L.findings.length,content:zz(B.start,L)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,F)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:B})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},W=await Pz(z,H),X=W.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await j.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let Y=W.content||W.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){if(J.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,H,W=new Promise((X)=>{H=X});this.pendingSideConversation=J,this.pendingSideConversationCompletion=W;try{return await this.handleSlashCommand(z,J.signal)}catch(X){if(J.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(H(),this.pendingSideConversationCompletion===W)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Rz(this.cwd,this.runtime?.getAgentResources()),J=["model","permissions","theme","config","exit","ide"],W=z.filter((X)=>!J.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),U.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(E.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,X=H.displayText,Y=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((w)=>w.outputSchema)?.outputSchema:void 0),Z;if(Y!==void 0)Z=Wz(Y).schema;if(X.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let $=Fz(X);if($){if(Z)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(W)&&W.some((w)=>w.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand($.question?`/btw ${$.question}`:"/btw")}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let w=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!w.accepted)throw Error(w.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${w.queued})`),w.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let F=new AbortController,L=()=>{F.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let B=!1,G=!1,V=!1,R,T=new Promise((w)=>{R=w});this.pendingPrompt=F,this.pendingPromptCompletion=T;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),Az(X)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,F.signal)}let w={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},N=await Yz(this.agent.chatStream(W,w,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{V=!0;let K=Q.toolCall,O=K.function.name;if(O===h)break;let q=this.mapToolKind(Q.toolKind),D=`Executing ${O}`;if(O==="Task"&&"function"in K)try{let x=JSON.parse(K.function.arguments),_=x.resume_from??x.resume;if(typeof _==="string")D=`Resuming ${String(x.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:K.id,status:"in_progress",title:D,content:[],kind:q});break}case"tool_progress":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;let O=Q.result,q=[],D=O.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;q.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))q.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=K.function.name,dz=Vz(Qz(jz(_,O),Jz));q.push({type:"content",content:{type:"text",text:dz}})}if(K.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let x=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:x,content:q});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
3
- `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Q.contentKind} r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
4
- `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Q.revision} (${Q.serverName}): ${Q.uri}
5
- `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Q.revision} (${Q.serverName}): ${Q.phase} ${Q.attempt}/${Q.maxAttempts}
6
- `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${Q.revision} (${Q.serverName}) ${Q.level}${Q.logger?` logger=${Q.logger}`:""}: ${Q.message}
7
- `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Q.revision} (${Q.serverName}): ${Q.action}${Q.detailsOmitted?" details-omitted":""}
8
- `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Q.revision} ${Q.taskId} (${Q.serverName}/${Q.toolName}): ${Q.status}${Q.hasResult?" result-available":""}
9
- `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Q.files.length}${Q.blockedWrite?" (write retry required)":""}
10
- `}});break;case"provider_admission":B=Q.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":Q.phase!=="admitted"?{phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,...Q.reason!==void 0?{reason:Q.reason}:{},queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:Q.phase,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{},...Q.nextProbeAt!==void 0?{nextProbeAt:Q.nextProbeAt}:{},openDurationMs:Q.openDurationMs,...Q.sampleCount!==void 0?{sampleCount:Q.sampleCount}:{},...Q.failureCount!==void 0?{failureCount:Q.failureCount}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.delayMs!==void 0?{delayMs:Q.delayMs}:{},...Q.nextRetryAt!==void 0?{nextRetryAt:Q.nextRetryAt}:{},...Q.mode!==void 0?{mode:Q.mode}:{},...Q.recoveryBudgetMs!==void 0?{recoveryBudgetMs:Q.recoveryBudgetMs}:{},...Q.recoveryElapsedMs!==void 0?{recoveryElapsedMs:Q.recoveryElapsedMs}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{},...Q.exhaustedBy!==void 0?{exhaustedBy:Q.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Q.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware}}});break;case"task_update":this.sendPlanUpdate(Q.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:Q.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:Q.goal.goalId,status:Q.goal.status,taskListId:Q.frontier.taskListId,total:Q.frontier.total,completed:Q.frontier.completed,inProgress:Q.frontier.inProgress,pending:Q.frontier.pending,blocked:Q.frontier.blocked,nextTask:Q.frontier.nextTask,digestSha256:Q.frontier.digestSha256,...Q.goal.frontierStall?{stall:{category:Q.goal.frontierStall.category,consecutiveCount:Q.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(Q.tasks);break;case"steering_applied":break;case"follow_up_started":{let K=0;for(let O of Q.messages){if(!O.recovered||O.persisted)continue;if(J.projectedRecoveredInputIds?.has(O.id))continue;for(let q of xz(O.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(O.id),K++}if(K>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${K} queued instruction${K===1?"":"s"} recovered after restart]
11
- `}});break}case"goal_updated":if(Q.goal)this.sendUpdate(this.goalSessionUpdate(Q.goal));if(Q.goal&&Q.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Q.goal.status}: ${Q.goal.objective}]
12
- `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Q.goal.goalId,continuation:Q.continuation,...Q.prematureStopPattern?{prematureStopPattern:Q.prematureStopPattern}:{},...Q.prematureStopCount!==void 0?{prematureStopCount:Q.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Q.phase,...Q.reason?{reason:Q.reason}:{},...Q.strategy?{strategy:Q.strategy}:{},...Q.outcome?{outcome:Q.outcome}:{},...Q.preTokens!==void 0?{preTokens:Q.preTokens}:{},...Q.preTokenSource?{preTokenSource:Q.preTokenSource}:{},...Q.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Q.estimatedPendingTokens}:{},...Q.postTokens!==void 0?{postTokens:Q.postTokens}:{},...Q.sampleAttempts!==void 0?{sampleAttempts:Q.sampleAttempts}:{},...Q.inputReductions!==void 0?{inputReductions:Q.inputReductions}:{},...Q.messagesOmitted!==void 0?{messagesOmitted:Q.messagesOmitted}:{},...Q.filesOmitted!==void 0?{filesOmitted:Q.filesOmitted}:{},...Q.imagesOmitted!==void 0?{imagesOmitted:Q.imagesOmitted}:{},...Q.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Q.fallbackTargetTokens}:{},...Q.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Q.fallbackMessagesOmitted}:{},...Q.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Q.fallbackMessagesTruncated}:{},...Q.failureReason?{failureReason:Q.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())F.abort("acp-egress-failed")});if(!await this.flushUpdates())F.abort("acp-egress-failed");this.contextMessages=[...w.messages];let v=await j.loadSession(this.id,this.cwd);if(this.messages=v.length>0?v:[...w.messages],!N.success){let Q=N.error?.type??"unknown",K=N.error?.details??N.error?.message??"Agent execution failed",O=sz(K)??c(K);throw Tz.internalError({failureType:Q,modelId:this.runtime.getCurrentModelId(),taskFailure:O,outputStarted:G,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${Q})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let l={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(l).length>0?{_meta:l}:{}}}catch(w){if(F.signal.aborted||w instanceof Error&&w.name==="AbortError")return{stopReason:"cancelled"};throw U.error(`[AcpSession ${this.id}] Prompt error:`,w),w}finally{if(J.abortSignal?.removeEventListener("abort",L),B&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(R(),this.pendingPromptCompletion===T)this.pendingPromptCompletion=null;if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let H=new AbortController,W,X=new Promise(($)=>{W=$});this.pendingUserShell=H,this.pendingUserShellCompletion=X;let Y,Z="";try{let $=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(L)=>{if(Y=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Z+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let B=p(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Z?nz(L.record):B}}]})}}),F={role:"user",content:$.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify($.record))}};if(this.messages.push(F),this.contextMessages.push(F),$.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:$.record.status==="aborted"?"cancelled":"end_turn"}}catch($){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:$ instanceof Error?$.message:String($)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw $}finally{if(W(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===H){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight)return;this.pendingResumeScheduled=!0;let J=this.pendingResumeGeneration,H=()=>{if(J!==this.pendingResumeGeneration)return;this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,this.resumePendingIfIdle()};if(z>0)this.pendingResumeTimer=setTimeout(H,z),this.pendingResumeTimer.unref?.();else queueMicrotask(H)}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:i,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let H="preflight",W=!1,X,Y=null;try{let Z=this.runtime.getPendingSteeringCount()>0,$=Z?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let F=$?.status==="active"||$?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Z&&!F))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Z&&!F){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}H=Z?"pending_input":"goal",W=!0;let B=r-(Date.now()-this.pendingResumeRecoveryStartedAt);if(B<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}let G=new AbortController;Y=setTimeout(()=>{G.abort("acp-pending-resume-budget-exhausted")},B),Y.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Z,goalContinuationOnly:F,projectedRecoveredInputIds:H==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:G.signal});if(z!==this.pendingResumeGeneration)return;if(G.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1)this.sendUpdate(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:H}));this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Z){if(z!==this.pendingResumeGeneration)return;let $=W?ez(Z):{taskFailure:c(Z),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},L=(H==="preflight"||H==="pending_input"&&this.runtime.getPendingSteeringCount()>0)&&$?.taskFailure.retryable===!0&&!$.toolExecutionStarted&&$.toolCallsCount===0&&!$.outputStarted,B=tz(this.id,J),G=Date.now()-this.pendingResumeRecoveryStartedAt,V=J<i,R=G+B<=r;if(L&&V&&R)this.pendingResumeRequested=!0,X=B,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:H,taskFailure:$.taskFailure,delayMs:B})),U.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${B}ms`);else{let T=L&&(!V||!R)?"exhausted":"failed";if(this.sendUpdate(this.pendingResumeSessionUpdate(T,{attempt:J,kind:H,taskFailure:$?.taskFailure})),U.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L}, phase=${T})`,Z),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest()}}finally{if(Y!==null)clearTimeout(Y);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.ensurePendingResumeScheduled(X)}}cancel(){U.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)U.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"].includes(z)?z:"default",W=this.mapModeIdToPermissionMode(H);await j.setSessionPermissionMode(this.id,this.cwd,W),this.mode=H,U.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(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(U.info(`[AcpSession ${this.id}] Model set to: ${z}`),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 J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await j.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(H){if(J&&J!==z)await this.agent.switchModel(J).catch((W)=>{U.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw H}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(H){throw await this.runtime.refresh({reasoningEffort:J.selection}),H}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(H){throw await this.runtime.refresh({serviceTier:J.selection}),H}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(H){throw await this.runtime.refresh({responseVerbosity:J.selection}),H}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),H=this.runtime.resolveCommunicationStyleConfiguration(z);if(H.source!=="built-in"&&!H.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:H.source==="built-in"?null:H.contentSha256})}catch(W){if(!(W instanceof P)&&W.code!=="ENOENT")throw W;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...H.source!=="built-in"&&H.contentSha256?{communicationStyleDigest:H.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:J.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Nz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,H=this.runtime,W=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,Y=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Z,$=async(F)=>{try{await F()}catch(L){Z??=L}};if(await $(()=>this.cancel()),W)await $(()=>W);if(X)await $(()=>X);if(Y)await $(()=>Y);if(z&&W&&H)await $(()=>H.discardPendingInput());if(J)await $(()=>J.destroy());if(H)await $(()=>H.dispose());if(await $(()=>E.destroySession(this.id)),U.debug(`[AcpSession ${this.id}] Destroyed`),Z!==void 0)throw Z}resolvePrompt(z){let J=[],H=[],W=0,X=0,Y=0,Z=(L)=>{if(H.length>0)H.push({type:"text",text:`
13
- `}),Y+=1;if(H.push(L),L.type==="text")Y+=L.text.length};for(let L of z)if(L.type==="text")J.push(L.text),Z({type:"text",text:L.text});else if(L.type==="image"){let B=`data:${L.mimeType};base64,${L.data}`;W+=1,X+=B.length,J.push(`[Image: ${L.mimeType}]`),Z({type:"image_url",image_url:{url:B}})}else if(L.type==="resource"){let B=L.resource;if("text"in B){let G=`<file path="${B.uri}">
14
- ${B.text}
15
- </file>`;J.push(G),Z({type:"text",text:G})}}else if(L.type==="resource_link"){let B=`[Resource: ${L.uri}]`;J.push(B),Z({type:"text",text:B})}if(W>C)throw Error(`ACP prompt contains more than ${C} images`);if(X>t)throw Error("ACP prompt images exceed the 5 MiB limit");if(Y>f)throw Error(`ACP prompt text exceeds ${f} characters`);if(Buffer.byteLength(J.join(`
16
- `),"utf8")>u)throw Error(`ACP prompt text exceeds ${u} bytes`);let F=J.join(`
17
- `);return{content:W>0?H:F,displayText:F}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;U.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));U.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let H=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(H))return U.debug(`[AcpSession ${this.id}] Auto-approving ${H} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(H==="write"||H==="execute"))return U.debug(`[AcpSession ${this.id}] Rejecting ${H} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let W=I(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.details)X.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
18
- - ${z.risks.join(`
19
- - `)}`}});let Y=this.mapToolKind(H),Z={sessionId:this.id,options:z.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:W,status:"pending",title:z.title||"Permission Required",content:X,kind:Y}},$=await this.waitForClientInteraction(this.connection.requestPermission(Z),J);if(!$)return{approved:!1,reason:g};let F=$.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let L=F.optionId;if(L==="allow_always")return{approved:!0,scope:"project"};if(L==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let B=L==="allow_once";return{approved:B,scope:"once",reason:B?void 0:"User denied the operation"}}catch(W){return U.warn(`[AcpSession ${this.id}] Permission request failed:`,W),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let H=z.questions??[];if(H.length===0)return{approved:!1,reason:"No structured questions were provided"};if(H.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let W={};try{for(let[X,Y]of H.entries()){let Z=Y.options.map((B,G)=>`answer:${X}:${G}`),$=`answer:${X}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Y.options.map((B,G)=>({optionId:Z[G],name:B.label,kind:"allow_once"})),{optionId:$,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:Y.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Y.question,...Y.options.map((B)=>`${B.label}: ${B.description}`)].join(`
20
- `)}}]}}),J);if(!F)return{approved:!1,reason:g};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Z.indexOf(F.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};W[Y.header]=Y.options[L].label}return{approved:!0,answers:W}}catch(X){return U.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let H=z.mcpElicitation;if(!H)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(H.mode==="url"){let X=await this.requestElicitationChoice("MCP external authorization",[H.message,`Server: ${H.serverName}`,`Domain: ${H.domain??"unknown"}`,`URL: ${H.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
21
- `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(X==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:X==="decline"?"User declined URL":"User cancelled",elicitation:{action:X==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let X of H.fields??[]){let Y=await this.collectAcpElicitationField(X,J);if(Y.cancelled)return{approved:!1,reason:Y.reason,elicitation:{action:"cancel"}};if(Y.value!==void 0)W[X.name]=Y.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return U.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let H=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((Y,Z)=>({id:`option:${Z}`,label:Y.label,value:Y.value})),W=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
22
- `),[...H.map((Y)=>({id:Y.id,label:Y.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(W==="skip")return{cancelled:!1};let X=H.find((Y)=>Y.id===W);if(!X)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:X.value}}if(z.defaultValue!==void 0){let H=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
23
- `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(H==="default")return{cancelled:!1,value:z.defaultValue};if(H==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,H,W){let X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.map((Y)=>({optionId:Y.id,name:Y.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),W);return X?.outcome.outcome==="selected"?X.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,W)=>{let X=!1,Y=($)=>{if(X)return;X=!0,J.removeEventListener("abort",Z),$()},Z=()=>Y(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then(($)=>Y(()=>H($)),($)=>Y(()=>W($)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var A=M("Agent");class d{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=kz();this.runtimeResidencyValue=new pz({maxResident:z?.maxResidentSessionRuntimes??yz,idleMs:z?.sessionRuntimeIdleMs??Mz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof cz)throw HH.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Iz(),{protocolVersion:zH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=m("acp"),H=await this.reserveSessionRuntime(J),W=z.cwd||bz(),X=z._meta?.["blade/taskIsolation"],Y=X==="local"||X==="worktree"?X:void 0,Z=z._meta?.["blade/taskPrompt"],$;try{let F=Y?await gz.createSessionTask({sessionId:J,prompt:typeof Z==="string"&&Z.trim()?Z:"ACP task session",sourceProjectPath:W,isolation:Y}):void 0,L=F?.metadata.projectPath??W;return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session cwd: ${L}`),$=new b(J,L,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...F?.taskWorktree?{taskWorktree:F.taskWorktree}:{},...F?.metadata.taskIsolation?{taskIsolation:F.metadata.taskIsolation}:{}}),await $.initialize(),this.assertNotDestroyed(),this.commitSession(J,$,H),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),$.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,F?.metadata,$.getModelConfiguration())}catch(F){throw H.cancel(),await $?.destroy().catch(()=>{return}),F}}async listSessions(z){if(z.cwd!=null&&!Ez.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await j.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskFailure?{"blade/taskFailure":H.taskFailure}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{},...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskIsolation?{"blade/taskIsolation":H.taskIsolation}:{},...H.taskSourceProjectPath?{"blade/taskSourceProjectPath":H.taskSourceProjectPath}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{},...H.taskDiffStat?{"blade/taskDiffStat":H.taskDiffStat}:{},...H.taskQueuePosition?{"blade/taskQueuePosition":H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{"blade/taskQueueDepth":H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":H.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Ez.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=m("fork"),H=await this.reserveSessionRuntime(J),W;try{let X=await j.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:J});return this.assertNotDestroyed(),W=new b(X.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:X.messages,permissionMode:X.metadata.permissionMode,mcpServers:z.mcpServers}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(X.sessionId,W,H),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(X.sessionId,X.metadata,W.getModelConfiguration())}catch(X){throw H.cancel(),await W?.destroy().catch(()=>{return}),X}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await j.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let J=await this.reserveSessionRuntime(z.sessionId),H;try{let[W,X]=await Promise.all([j.loadSession(z.sessionId,z.cwd),j.findSessionMetadata(z.sessionId,z.cwd)]);if(!X)throw Error(`Session not found: ${z.sessionId}`);return H=new b(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:X.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),await H.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,H,J),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}catch(W){throw J.cancel(),await H?.destroy().catch(()=>{return}),W}}commitSession(z,J,H){let W=H.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),W.release()}async closeResidentSession(z,J={}){let H=this.sessions.get(z);if(!H)return;let W=this.runtimeResidency.owns(z,H),X;try{await H.destroy(J)}catch(Z){X=Z}let Y=await this.runtimeResidency.forget(z,H);if(this.sessions.get(z)===H)this.sessions.delete(z);if(W&&!Y&&X===void 0)throw Error(`ACP Session is still active: ${z}`);if(X!==void 0)throw X}buildChildSessionResponse(z,J,H){return{sessionId:z,...this.buildSessionSetup(H,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let H=z?.models??[],W=(z?.currentModelId&&H.some((Z)=>Z.id===z.currentModelId)?z.currentModelId:void 0)??H[0]?.id,X=[{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"}],Y=[];if(H.length>0)Y.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:H.map((Z)=>({value:Z.id,name:Z.displayName??Z.model,description:`${z?.modelProviders[Z.provider]?.name??Z.provider} · ${Z.model}`}))});if(z?.reasoning)Y.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="off"?"Disable model reasoning":`Use ${Z} reasoning effort`}))]});if(z?.serviceTier)Y.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="fast"?"Use the provider priority tier":Z==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)Y.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:`Use ${Z} response verbosity`}))]});if(z?.communicationStyle)Y.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Z)=>({value:Z.id,name:Z.name,description:`${Z.description} · ${Z.source}`}))});return{modes:{availableModes:X,currentModeId:J},configOptions:Y.length>0?Y:void 0}}async closeSession(z){this.assertNotDestroyed();let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let H=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await H.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&Cz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await H.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Sz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await H.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&hz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await H.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&fz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await H.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(H.getModelConfiguration(),H.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(H){z??=H}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await uz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function eH(){let z=QH.toWeb(process.stdout),J=JH.toWeb(process.stdin),H=k.ndJsonStream(z,J),W,X=new k.AgentSideConnection((Z)=>{return W=new d(Z),W},H),Y=mz(async()=>{await W?.destroy()});try{await X.closed}finally{Y(),await W?.destroy()}}export{eH as runAcpIntegration};
@@ -1 +0,0 @@
1
- import{h as a,i as b,j as c,k as d,l as e}from"./chunk-32yfgw9s.js";import"./chunk-m5zx8enh.js";import"./chunk-fhfzdyba.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};