blade-code 0.10.27 → 0.10.28

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 (107) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-03633tsz.js +10 -0
  3. package/dist/{chunk-0vsaphkr.js → chunk-0pbvrw1c.js} +1 -1
  4. package/dist/{chunk-z3kc23wz.js → chunk-0pcwv1h8.js} +1 -1
  5. package/dist/{chunk-1c4j6q7j.js → chunk-0xhd2mzm.js} +2 -2
  6. package/dist/{chunk-kahzw9qn.js → chunk-1e9cpchh.js} +39 -39
  7. package/dist/chunk-1kxz32m6.js +1 -0
  8. package/dist/chunk-1sregjyz.js +1 -0
  9. package/dist/{chunk-eeg6jn2c.js → chunk-1ycv8b9t.js} +1 -1
  10. package/dist/{chunk-99h83wjf.js → chunk-287fabvz.js} +2 -2
  11. package/dist/chunk-2byq2qja.js +1 -0
  12. package/dist/{chunk-z4d3t2bb.js → chunk-2gre3vrn.js} +2 -2
  13. package/dist/{chunk-sp1j3ng5.js → chunk-2ycs4wce.js} +1 -1
  14. package/dist/chunk-3t5gqr9e.js +1 -0
  15. package/dist/{chunk-gwxwpwqk.js → chunk-4y6pjd2n.js} +1 -1
  16. package/dist/{chunk-76fnqb4r.js → chunk-5wkv5g4v.js} +1 -1
  17. package/dist/{chunk-cx5daedg.js → chunk-69r9j0ms.js} +1 -1
  18. package/dist/{chunk-czs2rxyr.js → chunk-6qdwp1t3.js} +1 -1
  19. package/dist/{chunk-bmxzx4xg.js → chunk-6vfctcqp.js} +1 -1
  20. package/dist/chunk-6znn1a5v.js +1 -0
  21. package/dist/{chunk-k6gsac91.js → chunk-70kccy7a.js} +1 -1
  22. package/dist/{chunk-jvg2vnc3.js → chunk-78bknnzt.js} +2 -2
  23. package/dist/chunk-7hjz5jjn.js +9 -0
  24. package/dist/{chunk-7v0w3625.js → chunk-8djaj8m7.js} +2 -2
  25. package/dist/chunk-8k9ark1n.js +1 -0
  26. package/dist/chunk-98rbxm1y.js +22 -0
  27. package/dist/{chunk-9reqa9g1.js → chunk-9ev9k5bd.js} +2 -2
  28. package/dist/{chunk-y0c3knp9.js → chunk-a1a4351m.js} +2 -2
  29. package/dist/{chunk-ezarz0ye.js → chunk-a1ftc84p.js} +1 -1
  30. package/dist/{chunk-erwmqhkw.js → chunk-ae7f5mh9.js} +1 -1
  31. package/dist/{chunk-a09g8k55.js → chunk-apq6qqjg.js} +2 -2
  32. package/dist/{chunk-1thq2kns.js → chunk-axcaxcgk.js} +2 -2
  33. package/dist/chunk-br9230a2.js +2 -0
  34. package/dist/chunk-cbyewxx4.js +3 -0
  35. package/dist/{chunk-hxb7wg07.js → chunk-d6a4qw1m.js} +1 -1
  36. package/dist/{chunk-e1r2zqv3.js → chunk-djzy4zgc.js} +2 -2
  37. package/dist/chunk-dny4h2gz.js +4 -0
  38. package/dist/{chunk-yh81njxg.js → chunk-dx5996qr.js} +1 -1
  39. package/dist/{chunk-y4fj9way.js → chunk-ecvk8npm.js} +1 -1
  40. package/dist/{chunk-5wemkcp3.js → chunk-gbmnbckj.js} +2 -2
  41. package/dist/{chunk-y2ra5akr.js → chunk-gpa4y0xk.js} +1 -1
  42. package/dist/chunk-hb9yjfja.js +1 -0
  43. package/dist/{chunk-17k72zar.js → chunk-hbhcj665.js} +2 -2
  44. package/dist/{chunk-18ck4nnw.js → chunk-j9djsqqy.js} +2 -2
  45. package/dist/chunk-jk66yar2.js +1 -0
  46. package/dist/chunk-jvtzyba4.js +2 -0
  47. package/dist/{chunk-j4gvwm9w.js → chunk-k3wmp1xm.js} +1 -1
  48. package/dist/chunk-k52a3bq6.js +1 -0
  49. package/dist/chunk-n1qmwjmc.js +1 -0
  50. package/dist/chunk-p2j0wcca.js +111 -0
  51. package/dist/{chunk-kvgrg5p2.js → chunk-p2yb40zk.js} +1 -1
  52. package/dist/{chunk-d893y03w.js → chunk-p4hf7agx.js} +2 -2
  53. package/dist/chunk-q4fy74fz.js +2 -0
  54. package/dist/chunk-qewf02br.js +1 -0
  55. package/dist/chunk-qsj712zc.js +1 -0
  56. package/dist/{chunk-14hspehn.js → chunk-rf3jf275.js} +3 -3
  57. package/dist/{chunk-00ta2sme.js → chunk-rqvejn8x.js} +2 -2
  58. package/dist/chunk-ry7226b5.js +6 -0
  59. package/dist/{chunk-ymgnh4an.js → chunk-sh2kjand.js} +1 -1
  60. package/dist/{chunk-1zsz19bn.js → chunk-sjbqm4be.js} +1 -1
  61. package/dist/{chunk-39yvdt2g.js → chunk-stmsk0kz.js} +2 -2
  62. package/dist/{chunk-emwawshv.js → chunk-t0n90d7w.js} +1 -1
  63. package/dist/{chunk-v1kac601.js → chunk-taj3qfn3.js} +1 -1
  64. package/dist/{chunk-q24xmkqy.js → chunk-tct2ybbh.js} +2 -2
  65. package/dist/{chunk-h79p49hc.js → chunk-tdevyej4.js} +1 -1
  66. package/dist/{chunk-z2kfx8g0.js → chunk-wn60hv0w.js} +358 -350
  67. package/dist/chunk-x1a5wv45.js +1 -0
  68. package/dist/{chunk-600hfjag.js → chunk-x3dche8v.js} +2 -2
  69. package/dist/{chunk-b9akah7k.js → chunk-xqapcfw3.js} +1 -1
  70. package/dist/{chunk-77y8cb2q.js → chunk-yv2sdpxk.js} +1 -1
  71. package/dist/chunk-z516a7nx.js +1 -0
  72. package/dist/web/assets/ChatView-BtSSERlQ.js +18 -0
  73. package/dist/web/assets/{CodeBlockHighlighter-B8-o1K2L.js → CodeBlockHighlighter-CAuanOO0.js} +1 -1
  74. package/dist/web/assets/{FilePreview-BvUxzULZ.js → FilePreview-BKQ-EBj3.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-C-X3g9Ky.js → MarkdownRenderer-BdYjJ_NM.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-Dhjw1__j.js → SettingsModal-CB6hM8fT.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-BAHVGLmL.js → TaskSwitcher-sSD4B7C_.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-D3cC-lXf.js → TerminalPanel-ZnEoQU6o.js} +1 -1
  79. package/dist/web/assets/{index-D88fYWls.js → index-DtOztVFd.js} +7 -7
  80. package/dist/web/assets/session-events-C2PMff2v.js +22 -0
  81. package/dist/web/index.html +2 -2
  82. package/package.json +4 -1
  83. package/dist/chunk-1pjvzcrj.js +0 -2
  84. package/dist/chunk-2rdk9rzv.js +0 -1
  85. package/dist/chunk-4dnvydyv.js +0 -4
  86. package/dist/chunk-4qk4v6aw.js +0 -1
  87. package/dist/chunk-7kfnsts1.js +0 -1
  88. package/dist/chunk-awz9bn56.js +0 -1
  89. package/dist/chunk-cpk6vwyh.js +0 -1
  90. package/dist/chunk-dyf9jrds.js +0 -9
  91. package/dist/chunk-fgczbyhy.js +0 -1
  92. package/dist/chunk-g11e47n1.js +0 -1
  93. package/dist/chunk-hszqdsn3.js +0 -1
  94. package/dist/chunk-kbpg9amg.js +0 -100
  95. package/dist/chunk-m6crkryd.js +0 -6
  96. package/dist/chunk-pvf84eht.js +0 -1
  97. package/dist/chunk-rtct70pm.js +0 -3
  98. package/dist/chunk-rvz8yka7.js +0 -1
  99. package/dist/chunk-t3hahveb.js +0 -1
  100. package/dist/chunk-v874kevz.js +0 -22
  101. package/dist/chunk-wa33kkb2.js +0 -1
  102. package/dist/chunk-wawmjv8r.js +0 -10
  103. package/dist/chunk-wzxkfpec.js +0 -2
  104. package/dist/chunk-xg9fzft1.js +0 -1
  105. package/dist/chunk-yc8rrjsr.js +0 -1
  106. package/dist/web/assets/ChatView-B4Le8nGL.js +0 -7
  107. package/dist/web/assets/session-events-BoJrjSZ2.js +0 -22
@@ -1,6 +0,0 @@
1
- import{m as Yq,n as Zq,o as $q,p as Vq,q as Bq}from"./chunk-kvgrg5p2.js";import{s as Xq}from"./chunk-1zsz19bn.js";import{F as r,H as a,I as o,K as y,L as n}from"./chunk-z2kfx8g0.js";import"./chunk-gwxwpwqk.js";import"./chunk-emwawshv.js";import{$a as i,Ma as v,ib as s}from"./chunk-a09g8k55.js";import"./chunk-4dnvydyv.js";import{_b as S,jc as h}from"./chunk-kbpg9amg.js";import"./chunk-600hfjag.js";import{Cc as e}from"./chunk-y0c3knp9.js";import{Ec as qq,Fc as Gq,Gc as Qq}from"./chunk-1thq2kns.js";import{Hc as t}from"./chunk-99h83wjf.js";import"./chunk-e1r2zqv3.js";import{fd as l}from"./chunk-7v0w3625.js";import"./chunk-v508x7cg.js";import"./chunk-ymgnh4an.js";import"./chunk-17k72zar.js";import"./chunk-18ck4nnw.js";import"./chunk-h79p49hc.js";import"./chunk-jvg2vnc3.js";import"./chunk-q24xmkqy.js";import"./chunk-0vsaphkr.js";import"./chunk-eeg6jn2c.js";import"./chunk-bmxzx4xg.js";import"./chunk-14hspehn.js";import"./chunk-k6gsac91.js";import"./chunk-z4d3t2bb.js";import{ff as m}from"./chunk-b9akah7k.js";import{gf as u,if as G,jf as w,lf as j}from"./chunk-j4gvwm9w.js";import"./chunk-wzxkfpec.js";import{sf as I}from"./chunk-sp1j3ng5.js";import"./chunk-d893y03w.js";import"./chunk-1c4j6q7j.js";import"./chunk-cx5daedg.js";import"./chunk-1pjvzcrj.js";import"./chunk-39yvdt2g.js";import"./chunk-76fnqb4r.js";import"./chunk-00ta2sme.js";import"./chunk-z3kc23wz.js";import nq from"yargs";import{hideBin as tq}from"yargs/helpers";var g=1;function K(Q){return G.Object({event_version:G.Literal(g),...Q})}var zq=K({type:G.Literal("content_delta"),delta:G.String()}),Uq=K({type:G.Literal("thinking_delta"),delta:G.String()}),Rq=K({type:G.Literal("thinking"),content:G.String()}),Mq=K({type:G.Literal("stream_end")}),Pq=K({type:G.Literal("content"),content:G.String()}),Nq=K({type:G.Literal("structured_output"),output:G.Record(G.String(),G.Unknown()),schema_digest:G.String({pattern:"^[a-f0-9]{64}$"})}),T=j(["readonly","write","execute"]),fq=K({type:G.Literal("tool_start"),tool_name:G.String(),summary:G.String(),target:G.Optional(G.String()),tool_kind:G.Optional(T)}),Eq=K({type:G.Literal("tool_progress"),tool_name:G.String(),message:G.String(),progress:G.Optional(G.Number()),total:G.Optional(G.Number())}),xq=K({type:G.Literal("tool_result"),tool_name:G.String(),summary:G.String(),target:G.Optional(G.String()),tool_kind:G.Optional(T),success:G.Optional(G.Boolean()),error_type:G.Optional(G.String()),error_message:G.Optional(G.String())}),Iq=K({type:G.Literal("mcp_catalog_changed"),revision:G.Integer({minimum:1}),server_name:G.String(),added:G.Array(G.String()),removed:G.Array(G.String()),updated:G.Array(G.String())}),Jq=K({type:G.Literal("mcp_content_changed"),revision:G.Integer({minimum:1}),server_name:G.String(),content_kind:j(["resources","resource_templates","prompts"]),added:G.Array(G.String()),removed:G.Array(G.String()),updated:G.Array(G.String())}),Lq=K({type:G.Literal("mcp_resource_updated"),revision:G.Integer({minimum:1}),server_name:G.String(),uri:G.String()}),Wq=K({type:G.Literal("mcp_connection_changed"),revision:G.Integer({minimum:1}),server_name:G.String(),phase:j(["reconnecting","recovered","failed"]),reason:G.String(),attempt:G.Integer({minimum:0}),max_attempts:G.Integer({minimum:0}),next_retry_at:G.Optional(G.Integer({minimum:0})),error:G.Optional(G.String())}),Sq=K({type:G.Literal("mcp_log"),revision:G.Integer({minimum:1}),server_name:G.String(),level:j(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:G.Optional(G.String()),message:G.String(),projected_bytes:G.Integer({minimum:0}),data_sha256:G.String(),truncated:G.Boolean(),details_omitted:G.Boolean(),timestamp:G.Integer({minimum:0}),synthetic:G.Optional(G.Boolean())}),Oq=K({type:G.Literal("mcp_instructions_changed"),revision:G.Integer({minimum:0}),server_name:G.String(),action:j(["added","removed"]),reason:j(["snapshot","connection","disconnection"]),text:G.Optional(G.String()),source_bytes:G.Optional(G.Integer({minimum:0})),projected_bytes:G.Optional(G.Integer({minimum:0})),sha256:G.Optional(G.String()),truncated:G.Optional(G.Boolean()),details_omitted:G.Optional(G.Boolean())}),hq=K({type:G.Literal("mcp_task_changed"),revision:G.Integer({minimum:0}),task_id:G.String(),server_name:G.String(),tool_name:G.String(),status:j(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:G.Optional(G.String()),created_at:G.Integer({minimum:0}),updated_at:G.Integer({minimum:0}),completed_at:G.Optional(G.Integer({minimum:0})),has_result:G.Boolean(),error:G.Optional(G.String())}),Cq=K({type:G.Literal("project_rules_loaded"),files:G.Array(G.Object({id:G.String(),relative_path:G.String(),source:j(["project","local"]),conditional:G.Boolean(),content_sha256:G.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:G.Array(G.String()),blocked_write:G.Boolean()}),kq=K({type:G.Literal("user_shell_started"),execution_id:G.String(),command:G.String(),auxiliary:G.Boolean()}),Fq=K({type:G.Literal("user_shell_output"),execution_id:G.String(),stream:j(["stdout","stderr"]),chunk:G.String(),stream_truncated:G.Boolean()}),wq=K({type:G.Literal("user_shell_completed"),execution_id:G.String(),message_id:G.String(),status:j(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:G.Union([G.Integer(),G.Null()]),duration_ms:G.Number({minimum:0}),stdout:G.String(),stderr:G.String(),truncated:G.Boolean(),auxiliary:G.Boolean()}),yq=K({type:G.Literal("phase"),phase:j(["turn","searching","inspecting","target_hit","executing","completed"]),status:j(["ongoing","hit","done"]),message:G.String(),turn:G.Optional(G.Number()),tool_name:G.Optional(G.String()),target:G.Optional(G.String())}),gq=K({type:G.Literal("tool_detail"),tool_name:G.String(),detail:G.String()}),Tq=K({type:G.Literal("task_update"),tasks:G.Array(y)}),cq=K({type:G.Literal("goal"),state:j(["updated","cleared"]),goal_id:G.Optional(G.String()),status:G.Optional(j(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:G.Optional(G.Integer({minimum:1})),verification_status:G.Optional(j(["pending","pass","fail","partial"])),verifier_session_id:G.Optional(G.String()),verification_evidence_sha256:G.Optional(G.String({pattern:"^[a-f0-9]{64}$"}))}),dq=K({type:G.Literal("subagent"),state:j(["spawned","completed"]),session_id:G.String(),subagent_type:G.Optional(G.String()),success:G.Optional(G.Boolean()),summary:G.Optional(G.String()),verification_verdict:G.Optional(j(["pass","fail","partial"])),resumed_from:G.Optional(G.String()),root_agent_id:G.Optional(G.String()),resume_depth:G.Optional(G.Integer({minimum:0}))}),pq=K({type:G.Literal("token_usage"),input_tokens:G.Number(),output_tokens:G.Number(),total_tokens:G.Number(),max_context_tokens:G.Number(),cache_read_tokens:G.Optional(G.Number()),cache_write_tokens:G.Optional(G.Number()),cost_usd:G.Optional(G.Number())}),mq=K({type:G.Literal("compacting"),state:j(["started","completed"]),reason:G.Optional(j(["threshold","context_limit","turn_limit","manual"])),strategy:G.Optional(j(["llm","fallback","snip"])),outcome:G.Optional(j(["completed","fallback","failed"])),pre_tokens:G.Optional(G.Number({minimum:0})),post_tokens:G.Optional(G.Number({minimum:0}))}),uq=K({type:G.Literal("provider_retry"),phase:j(["scheduled","attempt","recovered","exhausted"]),attempt:G.Integer({minimum:0}),max_retries:G.Integer({minimum:0}),reason:j(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:G.Optional(G.Integer({minimum:100,maximum:599})),delay_ms:G.Optional(G.Integer({minimum:0})),next_retry_at:G.Optional(G.Integer({minimum:0}))}),lq=K({type:G.Literal("provider_stall"),phase:j(["detected","recovered"]),stall_count:G.Integer({minimum:1}),duration_ms:G.Integer({minimum:0}),warning_after_ms:G.Integer({minimum:1}),timeout_ms:G.Integer({minimum:1}),output_started:G.Boolean()}),vq=K({type:G.Literal("action_stationarity"),phase:j(["detected","recovered","halted"]),tool_name:G.String(),run_length:G.Integer({minimum:1}),nudge_threshold:G.Integer({minimum:1}),halt_threshold:G.Integer({minimum:1}),progress_aware:G.Boolean()}),iq=K({type:G.Literal("turn_limit"),turns_count:G.Number(),action:G.Literal("continue")}),sq=K({type:G.Literal("task_session"),session_id:G.String(),project_path:G.String(),source_project_path:G.String(),isolation:j(["local","worktree"]),worktree_branch:G.Optional(G.String()),base_commit:G.Optional(G.String())}),rq=K({type:G.Literal("task_admission"),state:j(["queued","running"]),queue_position:G.Optional(G.Integer({minimum:1})),queue_depth:G.Integer({minimum:0}),in_flight:G.Integer({minimum:0}),max_concurrent_tasks:G.Integer({minimum:1})}),aq=K({type:G.Literal("output"),content:G.String(),exit_code:G.Number()}),oq=K({type:G.Literal("error"),message:G.String()}),_G=w(G.Union([zq,Uq,Rq,Mq,Pq,Nq,fq,Eq,xq,Iq,Jq,Lq,Wq,Sq,Oq,hq,Cq,kq,Fq,wq,yq,gq,Tq,cq,dq,pq,mq,uq,lq,vq,iq,sq,rq,aq,oq]));function c(Q,X){return{event_version:g,type:Q,...X}}function eq(Q){if(Q?.signal)return{signal:Q.signal,dispose:()=>{return}};let X=new AbortController,H=()=>X.abort("interrupt");return process.once("SIGINT",H),process.once("SIGTERM",H),{signal:X.signal,dispose:()=>{process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H)}}}var qG=j(["text","jsonl"]),GG=G.Object({headless:G.Optional(G.Boolean()),message:G.Optional(G.String()),_:G.Optional(G.Array(G.Union([G.String(),G.Number()]))),model:G.Optional(G.String()),systemPrompt:G.Optional(G.String()),appendSystemPrompt:G.Optional(G.String()),verificationAgent:G.Optional(G.Boolean()),maxTurns:G.Optional(G.Refine(G.Integer(),(Q)=>Q===-1||Q>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:G.Optional(G.Enum(m)),mcpConfig:G.Optional(G.Array(G.String())),strictMcpConfig:G.Optional(G.Boolean()),sessionId:G.Optional(G.String()),allowedTools:G.Optional(G.Array(G.String())),disallowedTools:G.Optional(G.Array(G.String())),agents:G.Optional(G.String()),continue:G.Optional(G.Boolean()),resume:G.Optional(G.Union([G.String(),G.Boolean()])),forkSession:G.Optional(G.Boolean()),taskIsolation:G.Optional(j(["local","worktree"])),outputFormat:G.Optional(qG),jsonSchema:G.Optional(G.String()),outputSchema:G.Optional(G.String())});class Kq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Q){this.openedThinking=Q}hasOpenThinking(){return this.openedThinking}completeStream(){let Q={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Q}}function QG(Q){return Q.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function XG(Q){let X=u(GG,Q);if(!X.success)throw Error(`Invalid headless options: ${QG(X.error)}`);return X.data}function YG(Q){return Q.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(X)=>{if(!X.headless)return;let H=await DG(X);process.exit(H)})}function D(Q,X=""){Q.write(`${X}
2
- `)}function ZG(Q){return`[task] [${Q.status}] ${Q.subject}`}function $G(){return{requestConfirmation:async(Q)=>Q.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:Q.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function VG(Q){if(!(Q instanceof Error))return"Unknown error";let $=Q.lastError??Q;if($.responseBody)try{let b=JSON.parse($.responseBody)?.error?.message;if(b)return $.statusCode?`${b} (HTTP ${$.statusCode})`:b}catch{}let q=Q.message.match(/Last error:\s*(.+)$/);if(q)return q[1];return Q.message}function BG(Q){return Q==="jsonl"?"jsonl":"text"}function d(Q,X){let H=(...$)=>{for(let q of $){let Y=X[q];if(typeof Y==="string"&&Y.trim()!=="")return Y}return};switch(Q){case"Read":case"Edit":case"Write":case"UndoEdit":return H("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return H("notebook_path");case"Grep":return H("path","pattern");case"Glob":return H("pattern");case"WebFetch":return H("url");case"WebSearch":return H("query");case"Bash":return H("command","description");case"Task":return H("description");case"LSP":return H("filePath","operation");case"EnterWorktree":return H("name");case"ExitWorktree":return H("action");default:return}}function KG(Q,X,H,$){let q=new Set(["Glob","Grep","WebSearch","LS"]),Y=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Q)&&!$.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${X}`,shouldLockTarget:!0};if($.targetLocked)return{phase:"executing",status:"hit",message:H?`Working within target: ${X}`:`Executing: ${X}`,shouldLockTarget:!1};if(q.has(Q))return{phase:"searching",status:"ongoing",message:`Still searching: ${X}`,shouldLockTarget:!1};if(Y.has(Q))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${X}`,shouldLockTarget:!1};return{phase:"executing",status:$.targetLocked?"hit":"ongoing",message:`Executing: ${X}`,shouldLockTarget:!1}}function p(Q,X,H=!1){let $=(q,Y)=>{Q.stdout.write(`${JSON.stringify(c(q,Y))}
3
- `)};return{contentDelta(q){if(X==="jsonl"){$("content_delta",{delta:q});return}if(H)return;Q.stdout.write(q)},thinkingDelta(q,Y){if(X==="jsonl")return $("thinking_delta",{delta:q}),Y;if(!Y)Q.stderr.write("[thinking] ");return Q.stderr.write(q),!0},thinking(q){if(X==="jsonl"){$("thinking",{content:q});return}D(Q.stderr,`[thinking] ${q}`)},streamEnd(q,Y){if(X==="jsonl"){$("stream_end",{});return}if(Y)Q.stderr.write(`
4
- `);if(q)Q.stdout.write(`
5
- `)},content(q){if(X==="jsonl"){$("content",{content:q});return}D(Q.stdout,q)},structuredOutput(q){if(X==="jsonl"){$("structured_output",{output:q.output,schema_digest:q.schemaDigest});return}D(Q.stdout,JSON.stringify(q.output))},toolStart(q,Y,b,_){if(X==="jsonl"){$("tool_start",{tool_name:q,summary:Y,target:b,tool_kind:_});return}D(Q.stderr,`[tool:start] ${Y}`)},toolProgress(q,Y,b,_){if(X==="jsonl"){$("tool_progress",{tool_name:q,message:Y,progress:b,total:_});return}D(Q.stderr,`[tool:progress] ${q}: ${Y}`)},toolResult(q,Y,b,_,R){if(X==="jsonl"){$("tool_result",{tool_name:q,summary:Y,target:b,tool_kind:_,success:R?.success,error_type:R?.errorType,error_message:R?.errorMessage});return}D(Q.stderr,`[tool:result] ${Y}`)},mcpCatalogChanged(q){if(X==="jsonl"){$("mcp_catalog_changed",{revision:q.revision,server_name:q.serverName,added:q.added,removed:q.removed,updated:q.updated});return}D(Q.stderr,`[mcp:catalog] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpContentChanged(q){if(X==="jsonl"){$("mcp_content_changed",{revision:q.revision,server_name:q.serverName,content_kind:q.contentKind==="resourceTemplates"?"resource_templates":q.contentKind,added:q.added,removed:q.removed,updated:q.updated});return}D(Q.stderr,`[mcp:${q.contentKind}] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpResourceUpdated(q){if(X==="jsonl"){$("mcp_resource_updated",{revision:q.revision,server_name:q.serverName,uri:q.uri});return}D(Q.stderr,`[mcp:resource] r${q.revision} ${q.serverName} updated ${q.uri}`)},mcpConnectionChanged(q){if(X==="jsonl"){$("mcp_connection_changed",{revision:q.revision,server_name:q.serverName,phase:q.phase,reason:q.reason,attempt:q.attempt,max_attempts:q.maxAttempts,...q.nextRetryAt!==void 0?{next_retry_at:q.nextRetryAt}:{},...q.error?{error:q.error}:{}});return}D(Q.stderr,`[mcp:connection] r${q.revision} ${q.serverName} ${q.phase} ${q.attempt}/${q.maxAttempts}`)},mcpLog(q){if(X==="jsonl"){$("mcp_log",{revision:q.revision,server_name:q.serverName,level:q.level,logger:q.logger,message:q.message,projected_bytes:q.projectedBytes,data_sha256:q.dataSha256,truncated:q.truncated,details_omitted:q.detailsOmitted,timestamp:q.timestamp,synthetic:q.synthetic});return}D(Q.stderr,`[mcp:log] ${q.level} ${q.serverName}${q.logger?` logger=${q.logger}`:""}: ${q.message}`)},mcpInstructionsChanged(q){if(X==="jsonl"){$("mcp_instructions_changed",{revision:q.revision,server_name:q.serverName,action:q.action,reason:q.reason,text:q.text,source_bytes:q.sourceBytes,projected_bytes:q.projectedBytes,sha256:q.sha256,truncated:q.truncated,details_omitted:q.detailsOmitted});return}D(Q.stderr,`[mcp:instructions] ${q.action} ${q.serverName}${q.truncated?" (truncated)":""}`)},mcpTaskChanged(q){if(X==="jsonl"){$("mcp_task_changed",{revision:q.revision,task_id:q.taskId,server_name:q.serverName,tool_name:q.toolName,status:q.status,status_message:q.statusMessage,created_at:q.createdAt,updated_at:q.updatedAt,completed_at:q.completedAt,has_result:q.hasResult,error:q.error});return}D(Q.stderr,`[mcp:task] ${q.taskId} ${q.serverName}/${q.toolName} `+q.status)},projectRulesLoaded(q){if(X==="jsonl"){$("project_rules_loaded",{files:q.files.map((Y)=>({id:Y.id,relative_path:Y.relativePath,source:Y.source,conditional:Y.conditional,content_sha256:Y.contentSha256})),trigger_paths:q.triggerPaths,blocked_write:q.blockedWrite});return}D(Q.stderr,`[project-rules] loaded ${q.files.length} file(s)${q.blockedWrite?" before write":""}`)},userShellStarted(q,Y,b){if(X==="jsonl"){$("user_shell_started",{execution_id:q,command:Y,auxiliary:b});return}D(Q.stderr,`[user-shell:start] ${Y}`)},userShellOutput(q,Y,b,_){if(X==="jsonl"){$("user_shell_output",{execution_id:q,stream:Y,chunk:b,stream_truncated:_});return}(Y==="stderr"?Q.stderr:Q.stdout).write(b)},userShellCompleted(q){if(X==="jsonl"){$("user_shell_completed",{execution_id:q.executionId,message_id:q.messageId,status:q.record.status,exit_code:q.record.exitCode,duration_ms:q.record.durationMs,stdout:q.record.stdout,stderr:q.record.stderr,truncated:q.record.truncated,auxiliary:q.auxiliary});return}D(Q.stderr,`[user-shell:${q.record.status}] exit=${q.record.exitCode??"null"} ${q.record.durationMs}ms`)},phase(q,Y,b,_={}){if(X==="jsonl"){$("phase",{phase:q,status:Y,message:b,turn:_.turn,tool_name:_.toolName,target:_.target});return}D(Q.stderr,`[phase:${q}] ${b}`)},toolDetail(q,Y){if(X==="jsonl"){$("tool_detail",{tool_name:q,detail:Y});return}D(Q.stderr,Y)},taskUpdate(q){if(X==="jsonl"){$("task_update",{tasks:q});return}for(let Y of q)D(Q.stderr,ZG(Y))},goal(q){if(X==="jsonl"){$("goal",{state:q.goal?"updated":"cleared",goal_id:q.goal?.goalId,status:q.goal?.status,verification_attempt:q.goal?.completionVerification?.attempt,verification_status:q.goal?.completionVerification?.status,verifier_session_id:q.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:q.goal?.completionVerification?.evidenceSha256});return}if(q.goal)D(Q.stderr,`[goal:${q.goal.status}] ${q.goal.objective}`);else D(Q.stderr,"[goal:cleared]")},subagent(q){let Y=q.kind==="subagent_spawned";if(X==="jsonl"){$("subagent",{state:Y?"spawned":"completed",session_id:q.sessionId,subagent_type:q.type,success:Y?void 0:q.success,summary:Y?void 0:q.summary,verification_verdict:Y?void 0:q.verificationVerdict,resumed_from:q.resumedFrom,root_agent_id:q.rootAgentId,resume_depth:q.resumeDepth});return}D(Q.stderr,`[subagent:${Y?"spawned":"completed"}] ${q.sessionId}${q.resumedFrom?` resumed from ${q.resumedFrom}`:""}`)},tokenUsage(q){if(X==="jsonl"){$("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens,cache_read_tokens:q.cacheReadTokens,cache_write_tokens:q.cacheWriteTokens,cost_usd:q.costUsd});return}D(Q.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){let Y=q.phase==="start";if(X==="jsonl"){$("compacting",{state:Y?"started":"completed",reason:q.reason,strategy:q.strategy,outcome:q.outcome,pre_tokens:q.preTokens,post_tokens:q.postTokens});return}D(Q.stderr,Y?`[context] compacting started${q.reason?` (${q.reason})`:""}`:`[context] compacting ${q.outcome??"completed"}`)},providerRetry(q){if(X==="jsonl"){$("provider_retry",{phase:q.phase,attempt:q.attempt,max_retries:q.maxRetries,reason:q.reason,status_code:q.statusCode,delay_ms:q.delayMs,next_retry_at:q.nextRetryAt});return}let Y=q.delayMs!==void 0?` in ${Math.max(0,Math.ceil(q.delayMs/1000))}s`:"";D(Q.stderr,`[provider-retry:${q.phase}] ${q.attempt}/${q.maxRetries} ${q.reason}${Y}`)},providerStall(q){if(X==="jsonl"){$("provider_stall",{phase:q.phase,stall_count:q.stallCount,duration_ms:q.durationMs,warning_after_ms:q.warningAfterMs,timeout_ms:q.timeoutMs,output_started:q.outputStarted});return}D(Q.stderr,`[provider-stall:${q.phase}] ${q.durationMs}ms / ${q.timeoutMs}ms`)},actionStationarity(q){if(X==="jsonl"){$("action_stationarity",{phase:q.phase,tool_name:q.toolName,run_length:q.runLength,nudge_threshold:q.nudgeThreshold,halt_threshold:q.haltThreshold,progress_aware:q.progressAware});return}D(Q.stderr,`[action-stationarity:${q.phase}] ${q.toolName} ${q.runLength}/${q.haltThreshold}`)},turnLimit(q){if(X==="jsonl"){$("turn_limit",{turns_count:q,action:"continue"});return}D(Q.stderr,`[turn-limit] continuing after ${q} turns`)},taskSession(q){if(X==="jsonl"){$("task_session",{session_id:q.sessionId,project_path:q.projectPath,source_project_path:q.sourceProjectPath,isolation:q.isolation,worktree_branch:q.worktreeBranch,base_commit:q.baseCommit});return}D(Q.stderr,`[task:${q.isolation}] ${q.sessionId} ${q.sourceProjectPath} -> ${q.projectPath}${q.worktreeBranch?` (${q.worktreeBranch})`:""}`)},taskAdmission(q){if(X==="jsonl"){$("task_admission",{state:q.state,queue_position:q.queuePosition,queue_depth:q.queueDepth,in_flight:q.inFlight,max_concurrent_tasks:q.maxConcurrentTasks});return}D(Q.stderr,q.state==="queued"?`[task:queued] position ${q.queuePosition??1}/${q.queueDepth} (running ${q.inFlight}/${q.maxConcurrentTasks})`:`[task:running] admitted (running ${q.inFlight}/${q.maxConcurrentTasks})`)},output(q,Y=0){if(X==="jsonl"){$("output",{content:q,exit_code:Y});return}D(Y===0?Q.stdout:Q.stderr,q)},error(q){if(X==="jsonl"){$("error",{message:q});return}D(Q.stderr,q)}}}async function DG(Q,X={stdout:process.stdout,stderr:process.stderr},H){let $="text",q=p(X,$),Y=new Kq,b={targetLocked:!1},_,R,J=eq(H);try{let B=XG(Q);$=BG(B.outputFormat);let P=await Vq(B);q=p(X,$,Boolean(P)),await Yq();let Dq=await Zq(B),z=await $q(Dq);if(z.mode==="output"){if(z.content)q.output(z.content,z.exitCode??0);return z.exitCode??0}let L=z.content.trimStart().startsWith("!")?z.content.trimStart().slice(1).trim():void 0;if(L!==void 0&&B.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(L!==void 0&&P)throw Error("Output schemas cannot be combined with user shell commands");if(B.taskIsolation&&(B.continue||B.resume||B.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:U,messages:C,metadata:k}=await Bq({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),E=B.permissionMode??k?.permissionMode??"yolo",F=B.model&&B.model!=="inherit"?B.model:l()?.id,A=B.taskIsolation?await Xq.createSessionTask({sessionId:U,prompt:z.content,sourceProjectPath:I(),isolation:B.taskIsolation,dispatch:{version:1,prompt:z.content,sourceProjectPath:I(),isolation:B.taskIsolation,permissionMode:E,...F?{modelId:F}:{},...P?{outputSchema:P}:{}}}):void 0,M=A?.metadata.projectPath??k?.projectPath??I();if(!A)await h.setSessionPermissionMode(U,M,E);let jq=A?!1:await s.cancelPendingNonInteractive(M,U);if(A)q.taskSession({sessionId:U,projectPath:M,sourceProjectPath:A.metadata.taskSourceProjectPath??I(),isolation:B.taskIsolation,worktreeBranch:A.metadata.taskWorktreeBranch,baseCommit:A.metadata.taskBaseCommit}),R=v.subscribe((Z)=>{if(Z.type!=="task.status"||Z.sessionId!==U||Z.projectPath!==M||!["queued","running"].includes(String(Z.properties.taskStatus))||typeof Z.properties.taskQueueDepth!=="number"||typeof Z.properties.taskInFlight!=="number"||typeof Z.properties.taskConcurrencyLimit!=="number")return;q.taskAdmission({state:Z.properties.taskStatus,queuePosition:typeof Z.properties.taskQueuePosition==="number"?Z.properties.taskQueuePosition:void 0,queueDepth:Z.properties.taskQueueDepth,inFlight:Z.properties.taskInFlight,maxConcurrentTasks:Z.properties.taskConcurrencyLimit})});let bq={messages:jq?await h.loadSessionModelContext(U,M):[...C],userId:"cli-user",sessionId:U,workspaceRoot:M,permissionMode:E,signal:J.signal,...A?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:$G()};if(_=await r.create({sessionId:U,workspaceRoot:M,modelId:B.model,permissionMode:E,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?t(B.agents):void 0,...A?.taskWorktree?{taskWorktree:A.taskWorktree}:{},...A?.metadata.taskIsolation?{taskIsolation:A.metadata.taskIsolation}:{},...C.length>0?{sessionStart:{isResume:!0,resumeSessionId:U}}:{}}),L!==void 0){let Z=await _.executeUserShellCommand(L,{signal:J.signal,onEvent:(V)=>{if(V.type==="started")q.userShellStarted(V.executionId,V.command,V.auxiliary);else if(V.type==="output")q.userShellOutput(V.executionId,V.stream,V.chunk,V.streamTruncated)}});return q.userShellCompleted(Z),Z.record.status==="completed"?0:Z.record.status==="aborted"?130:Z.record.exitCode??1}let Hq=B.maxTurns??_.getConfig().maxTurns,_q=A?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,Aq=await n.createWithRuntime(_,{sessionId:U,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:E,toolWhitelist:B.allowedTools,toolBlacklist:_q,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),O=await i(Aq.chatStream(z.content,bq,{stream:!0,signal:J.signal,maxTurns:B.maxTurns,builtinVerification:B.verificationAgent!==!1,outputSchema:P,...Hq===-1?{onTurnLimitReached:async(Z)=>{return q.turnLimit(Z.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(Z)=>{switch(Z.kind){case"content_delta":if(!P||$==="jsonl")Y.markAssistantContent();q.contentDelta(Z.delta);break;case"thinking_delta":Y.setThinkingOpened(q.thinkingDelta(Z.delta,Y.hasOpenThinking()));break;case"stream_end":{let V=Y.completeStream();q.streamEnd(V.wroteAssistantContent,V.openedThinking);break}case"tool_start":{let V=Z.toolCall;if(!("function"in V))break;if(V.function.name===S)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(V.function.name))break;try{let N=JSON.parse(V.function.arguments),f=a(V.function.name,N),x=d(V.function.name,N),W=KG(V.function.name,f,x,b);if(W.shouldLockTarget)b.targetLocked=!0;q.phase(W.phase,W.status,W.message,{toolName:V.function.name,target:x}),q.toolStart(V.function.name,f,x,Z.toolKind)}catch{q.phase(b.targetLocked?"executing":"searching",b.targetLocked?"hit":"ongoing",b.targetLocked?`Working within target: ${V.function.name}`:`Still searching: ${V.function.name}`,{toolName:V.function.name}),q.toolStart(V.function.name,V.function.name,void 0,Z.toolKind)}break}case"tool_progress":{let V=Z.toolCall;if(!("function"in V))break;if(V.function.name===S)break;q.toolProgress(V.function.name,Z.update.message,Z.update.progress,Z.update.total);break}case"tool_result":{let V=Z.toolCall;if(!("function"in V))break;if(V.function.name===S)break;let N;try{let x=JSON.parse(V.function.arguments);N=d(V.function.name,x)}catch{N=void 0}let f=o(V.function.name,Z.result);if(q.toolResult(V.function.name,f.summary,N,void 0,{success:Z.result.success,errorType:Z.result.error?.type,errorMessage:Z.result.error?.message}),f.detail)q.toolDetail(V.function.name,f.detail);break}case"token_usage":q.tokenUsage(Z.usage);break;case"compaction":q.compacting(Z);break;case"task_update":q.taskUpdate(Z.tasks);break;case"structured_output":q.structuredOutput(Z);break;case"mcp_catalog_changed":q.mcpCatalogChanged(Z);break;case"mcp_content_changed":q.mcpContentChanged(Z);break;case"mcp_resource_updated":q.mcpResourceUpdated(Z);break;case"mcp_connection_changed":q.mcpConnectionChanged(Z);break;case"mcp_log":q.mcpLog(Z);break;case"mcp_instructions_changed":q.mcpInstructionsChanged(Z);break;case"mcp_task_changed":q.mcpTaskChanged(Z);break;case"project_rules_loaded":q.projectRulesLoaded(Z);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":q.goal(Z);break;case"subagent_spawned":case"subagent_completed":q.subagent(Z);break;case"model_fallback":break;case"provider_retry":q.providerRetry(Z);break;case"provider_stall":q.providerStall(Z);break;case"action_stationarity":q.actionStationarity(Z);break;case"turn_start":if(Z.turn===1)b.targetLocked=!1;q.phase("turn",b.targetLocked?"hit":"ongoing",`Turn ${Z.turn} started`,{turn:Z.turn});break;default:{let V=Z}}});if(O.metadata?.outputTruncated)q.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!O.success)return q.error(`Error: ${O.error?.message??"Agent execution failed"}`),1;return q.phase("completed","done","Headless run completed"),0}catch(B){if(Y.hasOpenThinking()&&$==="text")X.stderr.write(`
6
- `);return q.error(`Error: ${VG(B)}`),1}finally{R?.();try{await _?.dispose()}finally{J.dispose()}}}async function TG(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:H,"output-format":$,"system-prompt":q,"append-system-prompt":Y,"max-turns":b,..._}=e,R=nq(tq(process.argv)).scriptName("blade").strict(!1).options(_).middleware([Gq,qq,Qq]);return YG(R),await R.parse(),!0}export{DG as runHeadless,TG as handleHeadlessMode,GG as HeadlessOptionsSchema};
@@ -1 +0,0 @@
1
- import{Jf as a,Kf as b,Lf as c,Mf as d,Nf as e,Of as f}from"./chunk-1pjvzcrj.js";import"./chunk-z3kc23wz.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,3 +0,0 @@
1
- import{j as T1,k as R1}from"./chunk-77y8cb2q.js";import{l as E$}from"./chunk-v1kac601.js";import{r as C0}from"./chunk-ezarz0ye.js";import{s as rO}from"./chunk-1zsz19bn.js";import{A as B$,B as g$,C as A0,D as v$,E as u0,F as z$,I as d$,J as l$,L as sO,M as W1,N as F1,O as U1,P as D1,Q as _1,R as H1,S as B1,T as L1,U as w1,V as C1,Y as J4,ba as u1,u as p1,w as nO,x as n0,y as t$}from"./chunk-z2kfx8g0.js";import{ea as CO,ka as X0}from"./chunk-gwxwpwqk.js";import{Aa as O1,Ba as J1,Ca as Z1,Da as UO,Ea as JO,ma as R$,pa as l1,qa as c1,ra as eO,sa as $1,ta as i1,ua as s$,va as a1,wa as y0,xa as k1,ya as I1,za as f1}from"./chunk-emwawshv.js";import{$a as h$,Ka as T0,La as P,Ma as b,Na as tO,ib as P0}from"./chunk-a09g8k55.js";import{tb as dO}from"./chunk-4dnvydyv.js";import{Mb as lO,Ob as L$,Sb as cO,Xb as iO,Yb as aO,_b as a0,bc as S$,gc as oO,hc as y$,ic as m$,jc as R}from"./chunk-kbpg9amg.js";import{cd as o,gd as kO,nd as G0}from"./chunk-7v0w3625.js";import{od as P$}from"./chunk-ymgnh4an.js";import{Ad as pO}from"./chunk-h79p49hc.js";import{Cd as H$}from"./chunk-jvg2vnc3.js";import{Ld as y1,Md as m1,Pd as G1,Td as Z$,Ud as Y$,Yd as x0}from"./chunk-q24xmkqy.js";import{ge as IO,he as uO}from"./chunk-eeg6jn2c.js";import{le as MO,me as d0}from"./chunk-14hspehn.js";import{Ee as bO,Ue as qO,df as J$}from"./chunk-z4d3t2bb.js";import{gf as f,if as U,lf as Y0}from"./chunk-j4gvwm9w.js";import{nf as M$}from"./chunk-wzxkfpec.js";import{sf as g}from"./chunk-sp1j3ng5.js";import{wf as u}from"./chunk-d893y03w.js";import{Cf as f0}from"./chunk-1c4j6q7j.js";import{Ef as RO,Ff as gO,Hf as jO,If as vO}from"./chunk-cx5daedg.js";import{Kf as p0}from"./chunk-1pjvzcrj.js";import{Pf as OO}from"./chunk-39yvdt2g.js";import{Uf as U$,Yf as HO}from"./chunk-00ta2sme.js";import{$f as r$}from"./chunk-z3kc23wz.js";var z5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function Q5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as ZO,readFileSync as G$}from"node:fs";import{createServer as m2}from"node:http";import{networkInterfaces as h2}from"node:os";import{dirname as g2,extname as v2,join as I0}from"node:path";import{fileURLToPath as p2}from"node:url";import{brotliCompressSync as u2,gzipSync as d2,constants as l2}from"node:zlib";import{Hono as c2}from"hono";import{cors as i2}from"hono/cors";import{WebSocketServer as a2}from"ws";var g0=u("Service"),W4=30000,F4=new Set(["completed","failed","cancelled","interrupted"]);class j${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??UO.getInstance(),this.tickMs=$.tickMs??W4}start(){if(this.timer)return;g0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=b.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!F4.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,g0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){g0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),g0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let Y=await this.dispatch({prompt:$.prompt,title:$.title??U4($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:R$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:Y.session.sessionId,lastStatus:Y.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),b.publish({sessionId:Y.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:Y.session.sessionId,runId:Y.runId,status:Y.status}),g0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${Y.session.sessionId} (${Y.status})`)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);g0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,Y);let K=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:R$($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:K?K.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let Y=(await this.store.list()).find((X)=>X.lastRunSessionId===$);if(!Y)return;await this.store.update(Y.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function U4($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class s extends Error{code;statusCode;constructor($,O,J=500){super(O);this.code=$;this.statusCode=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class I extends s{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class _ extends s{constructor($){super("BAD_REQUEST",$,400)}}class j extends s{constructor($){super("CONFLICT",$,409)}}class v0 extends s{constructor($){super("TOO_MANY_REQUESTS",$,429)}}class N0 extends s{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class d extends s{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var F5=U.Object({error:U.Object({code:U.String(),message:U.String()})});import{Hono as D4}from"hono";var k$=u("Service"),_4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(Y0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function H4($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,codeTheme:$.codeTheme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks}}var DO=()=>{let $=new D4;return $.get("/",async(O)=>{try{let J=o();return O.json(J?H4(J):{})}catch(J){return k$.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=f(_4,J);if(!Z.success)throw new _("Invalid config update format");let{updates:Y,options:X}=Z.data;return await G0().updateConfig(Y,X),O.json({success:!0,updates:Y})}catch(J){throw k$.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=o();return O.json(J?.permissions||{})}catch(J){return k$.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as B4}from"hono";import{streamSSE as L4}from"hono/streaming";var w4=15000,A4=new Set(["task.status","task.delivery","session.created","session.updated","session.deleted","schedule.fired","permission.asked","question.required","elicitation.required","interaction.resolved"]),M4=new Set(["queued","running","completed","failed","cancelled","interrupted"]);function q4($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$,J=["changedFiles","additions","deletions","commits"];if(J.some((Z)=>typeof O[Z]!=="number"||!Number.isInteger(O[Z])||O[Z]<0))return;return Object.fromEntries(J.map((Z)=>[Z,O[Z]]))}function O$($,O){return typeof $==="number"&&Number.isInteger($)&&$>=O?$:void 0}function E4($){if(!$||typeof $!=="object"||Array.isArray($))return;let O=$;if(!["applied","discarded","conflicted"].includes(String(O.status))||typeof O.updatedAt!=="string")return;return{status:O.status,updatedAt:O.updatedAt,...typeof O.sourceCommit==="string"?{sourceCommit:O.sourceCommit}:{},...O$(O.changedFiles,0)!==void 0?{changedFiles:O.changedFiles}:{},...typeof O.message==="string"?{message:O.message}:{}}}var _O=()=>{let $=new B4;return $.get("/",(O)=>L4(O,async(J)=>{let Z,Y,X=!1,K=()=>{if(Y!==void 0)clearInterval(Y),Y=void 0;Z?.(),Z=void 0},N=()=>{if(X)return;X=!0,K()};J.onAbort(N),Z=b.subscribe((W)=>{if(!A4.has(W.type))return;if(W.type==="permission.asked"||W.type==="question.required"||W.type==="elicitation.required"){let L=W.properties.requestId;if(typeof L!=="string"||!L)return;J.writeSSE({data:JSON.stringify({type:"interaction.pending",properties:{sessionId:W.sessionId,projectPath:W.projectPath,interactionType:W.type==="question.required"?"question":W.type==="elicitation.required"?"elicitation":"permission",requestId:L}})}).catch(N);return}if(W.type==="interaction.resolved"){let L=W.properties.requestId;if(typeof L!=="string"||!L)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,requestId:L}})}).catch(N);return}if(W.type==="session.created"||W.type==="session.deleted"){J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath}})}).catch(N);return}if(W.type==="session.updated"){let L=W.properties.title;if(typeof L!=="string"||!L.trim())return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,title:L}})}).catch(N);return}if(W.type==="task.delivery"){let L=E4(W.properties.taskDelivery);if(!L)return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskDelivery:L,...W.properties.taskWorktreeRemoved===!0?{taskWorktreeRemoved:!0}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{}}})}).catch(N);return}if(W.type==="schedule.fired"){let L=W.properties.scheduleId,a=W.properties.firedAt;if(typeof L!=="string"||typeof a!=="string")return;J.writeSSE({data:JSON.stringify({type:W.type,properties:{scheduleId:L,firedAt:a,sessionId:W.sessionId,projectPath:W.projectPath,...typeof W.properties.runId==="string"?{runId:W.properties.runId}:{},...typeof W.properties.status==="string"?{status:W.properties.status}:{}}})}).catch(N);return}let H=W.properties.taskStatus;if(typeof H!=="string"||!M4.has(H))return;let E=q4(W.properties.taskDiffStat),C=O$(W.properties.taskQueuePosition,1),T=O$(W.properties.taskQueueDepth,0),c=O$(W.properties.taskConcurrencyLimit,1),r=O$(W.properties.taskInFlight,0);J.writeSSE({data:JSON.stringify({type:W.type,properties:{sessionId:W.sessionId,projectPath:W.projectPath,taskStatus:H,...typeof W.properties.taskStatusReason==="string"?{taskStatusReason:W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{taskFailure:W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{taskStartedAt:W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{taskCompletedAt:W.properties.taskCompletedAt}:{},...typeof W.properties.updatedAt==="string"?{updatedAt:W.properties.updatedAt}:{},...E?{taskDiffStat:E}:{},...C!==void 0?{taskQueuePosition:C}:{},...T!==void 0?{taskQueueDepth:T}:{},...c!==void 0?{taskConcurrencyLimit:c}:{},...r!==void 0?{taskInFlight:r}:{}}})}).catch(N)});try{if(J.aborted||X)return;if(await J.writeSSE({data:JSON.stringify({type:"connected",properties:{timestamp:Date.now()}})}),J.aborted||X)return;Y=setInterval(()=>{if(J.aborted||X)return;J.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(N)},w4);while(!J.aborted&&!X)await new Promise((W)=>setTimeout(W,1000))}finally{N()}})),$};import{Hono as b4}from"hono";var BO=()=>{let $=new b4;return $.get("/health",(O)=>{return O.json({healthy:!0,version:p0()})}),$.get("/info",(O)=>{let J=g(),Z=o();if(Z)u0.configure(Z.maxConcurrentTasks,Z.maxQueuedTasks);return O.json({version:p0(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:J,gitBranch:HO(J),taskAdmission:u0.getStats()})}),$};import LO from"node:path";import{Hono as C4}from"hono";var T4=U.Object({projectPath:U.String({minLength:1}),action:Y0(["trust","revoke"]),expectedDigest:U.Optional(U.String())}),R4=U.Object({projectPath:U.String({minLength:1}),sessionId:U.String({minLength:1}),enabled:U.Boolean()});function I$($){if(!$||!LO.isAbsolute($))throw new _("projectPath must be absolute");return LO.resolve($)}function wO($){if(!$)throw new _("sessionId is required");try{U$($)}catch(O){throw new _(O instanceof Error?O.message:"sessionId is invalid")}return $}async function F$($){let O=I$($),J=o()?.hooks??qO.hooks,Z=await J$.getInstance().loadWorkspaceHooks(O,J,{includeBaseForCurrentWorkspace:!1});await x0(O),Y$(O);let Y=d0.getInstance();return Y.loadConfig(Z,O),await Z$(O),Y.getConfig(O)}function AO($,O){let J=d0.getInstance(),Z=J.getConfig(O).enabled,Y=J.isSessionPaused($,O);return{sessionId:$,projectPath:O,enabled:J.isSessionEnabled($,O),paused:Y,configEnabled:Z}}var EO=()=>{let $=new C4;return $.get("/trust",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return await F$(J),O.json(await d0.getInstance().getTrustStatus(J))}),$.post("/trust",async(O)=>{let J=f(T4,await O.req.json());if(!J.success)throw new _("Invalid hook trust request");let{projectPath:Z,action:Y,expectedDigest:X}=J.data;await F$(Z);let K=d0.getInstance(),N;try{N=Y==="trust"?await K.trustProject(Z,X):await K.revokeProjectTrust(Z)}catch(W){if(W instanceof MO)throw new j(W.message);throw W}return O.json(N)}),$.get("/session",async(O)=>{let J=I$(O.req.query("projectPath")),Z=wO(O.req.query("sessionId"));return await F$(J),O.json(AO(Z,J))}),$.post("/session",async(O)=>{let J=f(R4,await O.req.json());if(!J.success)throw new _("Invalid hook session request");let Z=I$(J.data.projectPath),Y=wO(J.data.sessionId);await F$(Z);let X=d0.getInstance();if(J.data.enabled)X.enableSession(Y,Z);else X.disableSession(Y,Z);return O.json(AO(Y,Z))}),$};import{Hono as j4}from"hono";var w0=u("Service");function k4($){try{return CO($)}catch{return[]}}function I4($){if(!D$($)||!D$($.reference)||!D$($.argument))throw Error("Invalid MCP completion request");let O=$.reference.type,J=O==="prompt"&&typeof $.reference.name==="string"?{type:"prompt",name:$.reference.name}:O==="resource"&&typeof $.reference.uri==="string"?{type:"resource",uri:$.reference.uri}:void 0;if(!J||typeof $.argument.name!=="string"||typeof $.argument.value!=="string")throw Error("Invalid MCP completion request");let Z;if($.context!==void 0){if(!D$($.context))throw Error("Invalid MCP completion context");Z=Object.create(null);for(let[Y,X]of Object.entries($.context)){if(typeof X!=="string")throw Error("Invalid MCP completion context");Z[Y]=X}}return{reference:J,argument:{name:$.argument.name,value:$.argument.value},...Z?{context:Z}:{}}}function D$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}async function E0($,O){let J=o()?.mcpServers??{};for(let[Z,Y]of Object.entries(J)){if(O&&Z!==O)continue;if(!$.getServerStatus(Z))await $.registerServer(Z,Y,{connect:!1})}}var TO=()=>{let $=new j4;return $.get("/",async(O)=>{try{let J=X0.getInstance();await E0(J);let Z=J.getAllServers(),Y=await Promise.all(Array.from(Z.entries()).map(async([X,K])=>({id:X,name:X,status:K.status==="connected"?"connected":K.status==="reconnecting"?"reconnecting":K.status==="connecting"?"connecting":K.lastError?"error":"offline",endpoint:K.config.command?`${K.config.command} ${(K.config.args||[]).join(" ")}`.trim():K.config.url||"Unknown",description:`MCP server: ${X}`,tools:K.tools.map((N)=>N.name),completionSupported:K.client.completionSupported,tasks:K.client.tasks,resources:K.contentCatalog.resources,resourceTemplates:K.contentCatalog.resourceTemplates.map((N)=>({...N,variables:k4(N.uriTemplate)})),prompts:K.contentCatalog.prompts,connectedAt:K.connectedAt?.toISOString(),error:K.lastError?.message,recovery:K.recovery,logging:K.logging,instructions:K.instructions,oauthEnabled:K.client.oauthEnabled,oauthStatus:await K.client.getOAuthStatus()})));return O.json(Y)}catch(J){return w0.error("[McpRoutes] Failed to get MCP servers:",J),O.json({error:J instanceof Error?J.message:"Failed to get MCP servers"},500)}}),$.post("/:name/connect",async(O)=>{try{let J=O.req.param("name"),Z=X0.getInstance();return await E0(Z,J),await Z.connectServer(J),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to connect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/:name/disconnect",async(O)=>{try{let J=O.req.param("name"),Z=X0.getInstance();return await E0(Z,J),await Z.disconnectServer(J),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to disconnect MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.get("/:name/logs",async(O)=>{try{let J=O.req.param("name"),Z=Number(O.req.query("limit")??20),Y=Number(O.req.query("afterRevision")??0);if(!Number.isSafeInteger(Z)||Z<1||Z>100||!Number.isSafeInteger(Y)||Y<0)return O.json({error:"Invalid MCP log pagination"},400);let X=X0.getInstance();return await E0(X,J),O.json(X.getLogSnapshot(J,{limit:Z,afterRevision:Y}))}catch(J){return w0.error("[McpRoutes] Failed to get MCP logs:",J),O.json({error:J.message},500)}}),$.post("/:name/logging-level",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();if(!bO(Z.level))return O.json({success:!1,error:"Invalid MCP logging level"},400);let Y=X0.getInstance();return await E0(Y,J),await Y.setServerLoggingLevel(J,Z.level),O.json({success:!0,level:Z.level})}catch(J){return w0.error("[McpRoutes] Failed to set MCP logging level:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/complete",async(O)=>{try{let J=O.req.param("name"),Z=I4(await O.req.json()),Y=X0.getInstance();await E0(Y,J);let X=await Y.complete(J,Z);return O.json(X)}catch(J){return w0.error("[McpRoutes] Failed to complete MCP argument:",J),O.json({error:J.message},400)}}),$.post("/:name/oauth/login",async(O)=>{try{let J=O.req.param("name"),Z=X0.getInstance();await E0(Z,J);let Y=await Z.beginOAuthLogin(J);return O.json({success:!0,flowId:Y.flowId,authorizationUrl:Y.authorizationUrl},202)}catch(J){return w0.error("[McpRoutes] Failed to start MCP OAuth login:",J),O.json({success:!1,error:J.message},400)}}),$.post("/:name/oauth/logout",async(O)=>{try{let J=O.req.param("name"),Z=X0.getInstance();return await E0(Z,J),await Z.logoutOAuth(J),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to log out MCP OAuth:",J),O.json({success:!1,error:J.message},400)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name");await X0.getInstance().unregisterServer(J);let Y=o();if(Y?.mcpServers){let{[J]:X,...K}=Y.mcpServers;await G0().updateConfig({mcpServers:K})}return O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to delete MCP server:",J),O.json({success:!1,error:J.message},500)}}),$.post("/",async(O)=>{try{let J=await O.req.json(),{name:Z,config:Y}=J;if(!Z||!Y)return O.json({success:!1,error:"Missing name or config"},400);await X0.getInstance().registerServer(Z,Y);let K=o();return await G0().updateConfig({mcpServers:{...K?.mcpServers,[Z]:Y}}),O.json({success:!0})}catch(J){return w0.error("[McpRoutes] Failed to add MCP server:",J),O.json({success:!1,error:J.message},500)}}),$};import{getSupportedThinkingLevels as f4}from"@earendil-works/pi-ai";import{Hono as P4}from"hono";var _$=u("Service");function S4($,O,J=IO.list()){return{id:$.id,displayName:$.displayName,provider:$.provider,model:$.model,overrides:$.overrides,fallbackModels:$.fallbackModels,contextWindow:O.contextWindow,maxTokens:O.maxTokens,reasoning:O.reasoning,supportedReasoningEfforts:f4(O),supportedServiceTiers:jO(O),supportedResponseVerbosities:RO(O),communicationStyles:J,input:O.input}}function y4($){fO($.overrides);let O={displayName:$.displayName||void 0,overrides:$.overrides||void 0};if($.model)O.model=$.model;return O}function fO($){let O=$?.streamIdleTimeout;if(O!==void 0&&(!Number.isFinite(O)||O<1000))throw new _("streamIdleTimeout must be at least 1000ms")}var PO=()=>{let $=new P4;return $.get("/",async(O)=>{try{let J=o();if(!J)throw Error("Config not initialized");let Z=O.get("directory")||g(),[Y,X]=await Promise.all([H$(Z,J),x0(Z)]),K=Y.config.models,N=K.find((C)=>C.id===Y.config.currentModelId)??K[0],W=Y.catalog,H=X.communicationStyles.list(),E=(C)=>S4(C,W.resolveConfig(C),H);return O.json({configured:K.map(E),current:N?E(N):null})}catch(J){_$.error("[ModelsRoutes] Failed to get models:",J);let Z=new d("Failed to get models");return O.json(Z.toObject(),500)}}),$.post("/",async(O)=>{let J=f0(),Z,Y;try{let X=await O.req.json(),{provider:K,displayName:N,model:W,overrides:H,apiKey:E,modelProvider:C}=X;if(!K||!W)throw new _("provider and model are required");fO(H);let T;if(C){if(C.id!==K)throw new _("modelProvider.id must match the model provider");if(o()?.modelProviders[K])throw new _(`model provider already exists: ${K}`);T={name:C.name,baseUrl:C.baseUrl,wireApi:C.wireApi,...C.apiKeyEnv?{apiKeyEnv:C.apiKeyEnv}:{}};try{J.registerModelProvider(K,T,[W]),Y=K}catch(L){throw new _(L instanceof Error?L.message:"Invalid model provider")}}else J.getModel(K,W);if(E?.trim()){if(await J.setApiKey(K,E.trim()),T)Z=K}let c={provider:K,displayName:N||void 0,model:W,overrides:H||void 0},r=T?await G0().addModelWithProvider(c,T):await G0().addModel(c);return O.json({success:!0,model:r})}catch(X){if(Z)await J.credentials.delete(Z);if(Y){let K=o();J.configureModelProviders(K?.modelProviders??{},K?.models??[])}throw _$.error("[ModelsRoutes] Failed to add model:",X),X}}),$.put("/:modelId",async(O)=>{try{let J=O.req.param("modelId"),Z=await O.req.json(),{displayName:Y,overrides:X,model:K}=Z,N=kO(J);if(!N)throw new _("model config not found");if(K)f0().getModel(N.provider,K);return await G0().updateModel(J,y4({displayName:Y,overrides:X,model:K})),O.json({success:!0})}catch(J){throw _$.error("[ModelsRoutes] Failed to update model:",J),J}}),$.delete("/:modelId",async(O)=>{try{let J=O.req.param("modelId");return await G0().removeModel(J),O.json({success:!0})}catch(J){throw _$.error("[ModelsRoutes] Failed to delete model:",J),J}}),$};import{Hono as s4}from"hono";import SO from"node:path";import{Mutex as yO}from"async-mutex";import{Hono as m4}from"hono";import{streamSSE as h4}from"hono/streaming";import{LRUCache as g4}from"lru-cache";import{nanoid as c0}from"nanoid";var S=u("Service"),v4=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),p4=O1,u4=U.Object({title:U.Optional(U.String()),projectPath:U.Optional(U.String())}),d4=U.Object({projectPath:U.String()}),l4=U.Object({objective:U.String({minLength:1}),tokenBudget:U.Optional(U.Integer({minimum:1})),permissionMode:U.Optional(Y0(["default","autoEdit","plan","yolo"]))}),c4=U.Union([U.Object({action:U.Literal("pause")}),U.Object({action:U.Literal("resume")}),U.Object({action:U.Literal("edit"),objective:U.String({minLength:1})})]),l=new Map,w$,M0=new Map,i0=new Map,b0=new Map,q$=new g4({max:100,ttl:1800000});function mO($){return{sessionId:$.sessionId,projectPath:$.projectPath}}function z0($){if(!$)return;return M0.get($)??q$.get($)}function i4($){if(M0.get($.id)!==$)return;M0.delete($.id),q$.set($.id,$)}function a4($){M0.delete($),q$.delete($)}function W0($){return $?.status==="queued"||$?.status==="running"||$?.status==="waiting_permission"}function A$($,O="user-cancel"){if($.status==="cancelled"||$.status==="completed"||$.status==="failed")return!1;let J=$.pendingPermission;if($.pendingPermission=void 0,J?.resolve({approved:!1,reason:dO}),J)b.publish(mO($),"interaction.resolved",{requestId:J.permissionId});return $.abortController.abort(O),$.status="cancelled",b.publish(mO($),"run.cancelled",{runId:$.id}),!0}function Y1($,O=!1){let{permissionId:J,details:Z}=$;if(Z.type==="askUserQuestion"&&Z.questions)return{type:"question.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,questions:Z.questions,details:Z,...O?{replayed:!0}:{}}};if(Z.type==="mcpElicitation"&&Z.mcpElicitation)return{type:"elicitation.required",properties:{requestId:J,toolCallId:Z.toolCallId??J,elicitation:Z.mcpElicitation,...O?{replayed:!0}:{}}};return{type:"permission.asked",properties:{requestId:J,toolName:Z.toolName,description:Z.message,args:Z.args,details:Z,...O?{replayed:!0}:{}}}}function o4(){for(let $ of M0.values())A$($,"route-reset");M0.clear();for(let $ of i0.values())$.controller.abort("route-reset");i0.clear(),q$.clear(),w$=void 0,l.clear()}var z1=($)=>{if(!$||typeof $!=="object")return $;let O={...$},J=200000,Z=(Y,X)=>typeof Y==="number"&&Number.isSafeInteger(Y)&&Y>=0&&Y<=X?Y:0;if(typeof O.oldContent==="string"&&O.oldContent.length>J)delete O.oldContent;if(typeof O.newContent==="string"&&O.newContent.length>J)delete O.newContent;if(O.mcpResult&&typeof O.mcpResult==="object"&&!Array.isArray(O.mcpResult)){let Y=O.mcpResult,X=Array.isArray(Y.artifacts)?Y.artifacts.slice(0,64).flatMap((K)=>{if(!K||typeof K!=="object"||Array.isArray(K))return[];let N=K,W=new Set(["text","image","audio","resource"]);if(typeof N.id!=="string"||!/^[a-f0-9]{64}$/.test(N.id)||typeof N.sha256!=="string"||N.sha256!==N.id||typeof N.kind!=="string"||!W.has(N.kind)||Z(N.size,67108864)!==N.size||typeof N.persisted!=="boolean")return[];return[{id:N.id.slice(0,128),sha256:N.sha256.slice(0,128),kind:N.kind,size:N.size,persisted:N.persisted,...typeof N.mimeType==="string"?{mimeType:N.mimeType.slice(0,256)}:{},...typeof N.sourceUri==="string"?{sourceUri:N.sourceUri.slice(0,8192)}:{},...typeof N.path==="string"?{path:N.path.slice(0,8192)}:{}}]}):[];O.mcpResult={isError:Y.isError===!0,contentCount:Z(Y.contentCount,64),textBytes:Z(Y.textBytes,4194304),structuredBytes:Z(Y.structuredBytes,4194304),artifactCount:Z(Y.artifactCount,64),truncated:Y.truncated===!0,binaryOmitted:Y.binaryOmitted===!0,artifacts:X}}else delete O.mcpResult;return O};function n4($,O,J){switch(J.kind){case"tool_start":if("function"in J.toolCall)b.publish($,"subagent.update",{subagentSessionId:O,toolName:J.toolCall.function.name}),b.publish($,"subagent.tool.start",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,arguments:J.toolCall.function.arguments,toolKind:J.toolKind});break;case"tool_result":if("function"in J.toolCall)b.publish($,"subagent.tool.result",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,success:!J.result.error,summary:J.result.metadata?.summary,output:l$(d$(J.toolCall.function.name,J.result)),metadata:z1(J.result.metadata)});break;case"tool_progress":if("function"in J.toolCall)b.publish($,"subagent.tool.progress",{subagentSessionId:O,toolCallId:J.toolCall.id,toolName:J.toolCall.function.name,...J.update});break;case"content_delta":b.publish($,"subagent.delta",{subagentSessionId:O,delta:J.delta});break;case"thinking_delta":b.publish($,"subagent.thinking.delta",{subagentSessionId:O,delta:J.delta});break;case"stream_end":b.publish($,"subagent.stream.end",{subagentSessionId:O});break;case"provider_retry":b.publish($,"subagent.provider.retry",{subagentSessionId:O,phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,statusCode:J.statusCode,delayMs:J.delayMs,nextRetryAt:J.nextRetryAt});break;case"provider_stall":b.publish($,"subagent.provider.stall",{subagentSessionId:O,phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted});break;case"action_stationarity":b.publish($,"subagent.action.stationarity",{subagentSessionId:O,phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware});break;case"mcp_catalog_changed":b.publish($,"subagent.mcp.catalog.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_content_changed":b.publish($,"subagent.mcp.content.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,contentKind:J.contentKind,added:J.added,removed:J.removed,updated:J.updated});break;case"mcp_resource_updated":b.publish($,"subagent.mcp.resource.updated",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,uri:J.uri});break;case"mcp_connection_changed":b.publish($,"subagent.mcp.connection.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,maxAttempts:J.maxAttempts,nextRetryAt:J.nextRetryAt,error:J.error});break;case"mcp_log":b.publish($,"subagent.mcp.log",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,level:J.level,logger:J.logger,message:J.message,projectedBytes:J.projectedBytes,dataSha256:J.dataSha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});break;case"mcp_instructions_changed":b.publish($,"subagent.mcp.instructions.changed",{subagentSessionId:O,revision:J.revision,serverName:J.serverName,action:J.action,reason:J.reason,text:J.text,sourceBytes:J.sourceBytes,projectedBytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,detailsOmitted:J.detailsOmitted});break;case"mcp_task_changed":b.publish($,"subagent.mcp.task.changed",{subagentSessionId:O,revision:J.revision,taskId:J.taskId,serverName:J.serverName,toolName:J.toolName,status:J.status,statusMessage:J.statusMessage,createdAt:J.createdAt,updatedAt:J.updatedAt,completedAt:J.completedAt,hasResult:J.hasResult,error:J.error});break;case"project_rules_loaded":b.publish($,"subagent.project.rules.loaded",{subagentSessionId:O,files:J.files,triggerPaths:J.triggerPaths,blockedWrite:J.blockedWrite});break;default:break}}function Q$($,O="projectPath"){if(!SO.isAbsolute($))throw new _(`${O} must be absolute`);return SO.resolve($)}function p$($){try{U$($)}catch(O){throw new _(O instanceof Error?O.message:`Invalid session ID: ${$}`)}}function e($){return{sessionId:$.id,projectPath:$.projectPath}}function x$($,O,J){return{id:$.sessionId,projectPath:$.projectPath,title:$.title??`Session ${$.sessionId.slice(0,6)}`,createdAt:new Date($.firstMessageTime),updatedAt:new Date($.lastMessageTime),rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,taskStatus:$.taskStatus,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,pendingInteraction:$.pendingInteraction,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:$.taskQueuePosition,taskQueueDepth:$.taskQueueDepth,taskConcurrencyLimit:$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,taskWorktree:J,messages:O}}function f$($){return $.flatMap((O)=>{if(!cO(O)||O.role==="system"||O.role==="tool"&&O.name===a0)return[];let J=O.tool_calls?.filter((K)=>!("function"in K)||K.function.name!==a0),Z=typeof O.content==="string"?O.content.trim():"";if(O.role==="assistant"&&O.tool_calls?.length&&!J?.length&&!Z&&!O.reasoningContent&&!O.metadata)return[];let Y={...O,...O.tool_calls?{tool_calls:J&&J.length>0?J:void 0}:{}},X=aO(O.metadata);return[X?{...Y,content:iO(X)}:Y]})}function X$($,O){$.taskStatus=O.taskStatus,$.taskStatusReason=O.taskStatusReason,$.taskFailure=O.taskFailure,$.taskStartedAt=O.taskStartedAt,$.taskCompletedAt=O.taskCompletedAt,$.taskPromptSummary=O.taskPromptSummary,$.taskModelId=O.taskModelId,$.selectedModelId=O.selectedModelId,$.permissionMode=O.permissionMode,$.reasoningEffort=O.reasoningEffort,$.serviceTier=O.serviceTier,$.responseVerbosity=O.responseVerbosity,$.communicationStyle=O.communicationStyle,$.communicationStyleDigest=O.communicationStyleDigest,$.projectInstructionsDigest=O.projectInstructionsDigest,$.pendingInteraction=O.pendingInteraction,$.taskRetryAvailable=O.taskRetryAvailable,$.taskRetriedFrom=O.taskRetriedFrom,$.taskDelivery=O.taskDelivery,$.taskIsolation=O.taskIsolation,$.taskSourceProjectPath=O.taskSourceProjectPath,$.taskWorktreePath=O.taskWorktreePath,$.taskWorktreeBranch=O.taskWorktreeBranch,$.taskBaseCommit=O.taskBaseCommit,$.taskDiffStat=O.taskDiffStat,$.taskQueuePosition=O.taskQueuePosition,$.taskQueueDepth=O.taskQueueDepth,$.taskConcurrencyLimit=O.taskConcurrencyLimit,$.archivedAt=O.archivedAt,$.archivedBySessionId=O.archivedBySessionId,$.updatedAt=new Date(O.lastMessageTime)}async function S0($){let O=await R.findSessionMetadata($.id,$.projectPath);if(O)X$($,O)}function l0($){let O=z0($.currentRunId),J=O?.status==="waiting_permission"?"running":O?.status??$.taskStatus;return{sessionId:$.id,projectPath:$.projectPath,title:$.title,rootId:$.rootId,parentId:$.parentId,relationType:$.relationType,status:void 0,taskStatus:J,taskStatusReason:$.taskStatusReason,taskFailure:$.taskFailure,taskStartedAt:$.taskStartedAt,taskCompletedAt:$.taskCompletedAt,taskPromptSummary:$.taskPromptSummary,taskModelId:$.taskModelId,selectedModelId:$.selectedModelId,permissionMode:$.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,communicationStyleDigest:$.communicationStyleDigest,projectInstructionsDigest:$.projectInstructionsDigest,taskRetryAvailable:$.taskRetryAvailable,taskRetriedFrom:$.taskRetriedFrom,taskDelivery:$.taskDelivery,taskIsolation:$.taskIsolation,taskSourceProjectPath:$.taskSourceProjectPath,taskWorktreePath:$.taskWorktreePath,taskWorktreeBranch:$.taskWorktreeBranch,taskBaseCommit:$.taskBaseCommit,taskDiffStat:$.taskDiffStat,taskQueuePosition:O?.status==="queued"?O.taskQueuePosition:J==="queued"?$.taskQueuePosition:void 0,taskQueueDepth:O?.status==="queued"?O.taskQueueDepth:J==="queued"?$.taskQueueDepth:void 0,taskConcurrencyLimit:O?.taskConcurrencyLimit??$.taskConcurrencyLimit,archivedAt:$.archivedAt,archivedBySessionId:$.archivedBySessionId,pendingInteraction:O?.pendingPermission?{type:O.pendingPermission.details.type==="askUserQuestion"?"question":O.pendingPermission.details.type==="mcpElicitation"?"elicitation":"permission",requestId:O.pendingPermission.permissionId}:$.pendingInteraction,agentType:void 0,model:void 0,messageCount:$.messages.length,firstMessageTime:$.createdAt.toISOString(),lastMessageTime:$.updatedAt.toISOString(),hasErrors:!1,isActive:!0}}async function Z0($,O){if(p$($),O!==void 0){let Z=T0({sessionId:$,projectPath:Q$(O)});if(l.has(P(Z)))return Z;let Y=await R.findSessionMetadata(Z.sessionId,Z.projectPath);if(!Y)throw new I("Session",$);return T0({sessionId:Y.sessionId,projectPath:Y.projectPath})}let J=new Map;for(let Z of l.values()){if(Z.id!==$)continue;let Y=e(Z);J.set(P(Y),Y)}for(let Z of await R.listSessions()){if(Z.sessionId!==$)continue;let Y=T0({sessionId:Z.sessionId,projectPath:Z.projectPath});J.set(P(Y),Y)}if(J.size===0)try{let Z=await R.findSessionMetadata($);if(!Z)throw new I("Session",$);return T0({sessionId:Z.sessionId,projectPath:Z.projectPath})}catch(Z){if(Z instanceof I)throw Z;if(Z instanceof Error&&Z.message.startsWith("Ambiguous session ID:"))throw new N0;throw Z}if(J.size>1)throw new N0;return J.values().next().value}function u$($){if(typeof $==="string")return $;return $.filter((O)=>O.type==="text").map((O)=>O.text).join(`
2
- `)}function hO($,O){let J=(O??[]).filter((Y)=>Y.type==="image"&&typeof Y.content==="string").map((Y)=>({type:"image_url",image_url:{url:Y.content}}));if(J.length===0)return $;let Z=[];if($.trim())Z.push({type:"text",text:$});return Z.push(...J),Z}var Q1=()=>{o4();let $=new m4;$.onError((x,G)=>{if(x instanceof s)return G.json(x.toObject(),x.statusCode);return S.error("[SessionRoutes] Unhandled route error:",x),G.json({error:{code:"INTERNAL_ERROR",message:"Internal server error"}},500)});let O=new Map,J=new Map,Z=new Map,Y=new Map,X=new Map,K=new Map,N=(x)=>{let G=P(x),Q=X.get(G);if(!Q)Q=new yO,X.set(G,Q);return Q},W=(x)=>{let G=P(x),Q=K.get(G);if(!Q)Q=new yO,K.set(G,Q);return Q},H=async(x,G={})=>{let Q=P(e(x));await Z.get(Q);let V=O.get(Q);if(V)return V;let z=J.get(Q);if(!z){let F=G.communicationStyle??x.communicationStyle;z=z$.create({sessionId:x.id,workspaceRoot:x.projectPath,...x.selectedModelId??x.taskModelId?{modelId:x.selectedModelId??x.taskModelId}:{},permissionMode:G.permissionMode??x.permissionMode??"default",...x.reasoningEffort?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier?{serviceTier:x.serviceTier}:{},...x.responseVerbosity?{responseVerbosity:x.responseVerbosity}:{},...F?{communicationStyle:F}:{},...F===x.communicationStyle&&x.communicationStyleDigest?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest?{projectInstructionsDigest:x.projectInstructionsDigest}:{},...x.taskWorktree?{taskWorktree:x.taskWorktree}:{},...x.taskIsolation?{taskIsolation:x.taskIsolation}:{},...x.messages.length>0?{sessionStart:{isResume:!0,resumeSessionId:x.id}}:{}}),J.set(Q,z)}try{let F=await z;return O.set(Q,F),F}finally{if(J.get(Q)===z)J.delete(Q)}},E=async(x,G)=>{let Q=P(e(x)),V=Z.get(Q);if(!V)V=(async()=>{let z=J.get(Q);if(z)await z.catch(()=>{return});J.delete(Q);let F=G??O.get(Q);if(O.delete(Q),F){for(let[D,w]of O)if(w===F)O.delete(D)}await F?.dispose()})().finally(()=>{if(Z.get(Q)===V)Z.delete(Q)}),Z.set(Q,V);await V},C=async(x)=>{let G=P(x),Q=l.get(G);if(Q)return Q;let V=Y.get(G);if(!V)V=(async()=>{let z=await R.findSessionMetadata(x.sessionId,x.projectPath);if(!z)throw new I("Session",x.sessionId);let[F,D]=await Promise.all([R.loadSession(x.sessionId,x.projectPath),R.findSessionTaskWorktree(x.sessionId,x.projectPath)]),w=x$(z,F,D);return l.set(G,w),w})(),Y.set(G,V);try{return await V}finally{if(Y.get(G)===V)Y.delete(G)}},T=async(x,G)=>{let Q=await Z0(x,G);try{await R.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(V){if(V instanceof y$)throw new j(V.message);throw V}return C(Q)},c=async(x,G)=>{if(x.permissionMode===G)return;let Q=await R.setSessionPermissionMode(x.id,x.projectPath,G);x.permissionMode=Q.permissionMode,x.updatedAt=new Date(Q.lastMessageTime),b.publish(e(x),"session.updated",{permissionMode:G})},r=(x,G,Q,V={})=>{let z=c0(12),F={id:z,sessionId:x.id,projectPath:x.projectPath,status:"running",abortController:new AbortController,disposeRuntimeOnSettle:V.taskRuntime!==void 0,createdAt:new Date};if(V.taskRuntime){let D=V.taskRuntime,w=u0.admit({key:`${x.projectPath}\x00${x.id}`,...D.getTaskAdmissionLimits(),signal:F.abortController.signal,onUpdate:(A)=>{F.status=A.state,F.taskQueuePosition=A.queuePosition,F.taskQueueDepth=A.queueDepth,F.taskConcurrencyLimit=A.maxConcurrent,x.taskStatus=A.state,x.taskQueuePosition=A.queuePosition,x.taskQueueDepth=A.queueDepth,x.taskConcurrencyLimit=A.maxConcurrent,F.taskAdmissionUpdate=(F.taskAdmissionUpdate??Promise.resolve()).then(async()=>{await D.setTaskAdmission(A)}).catch((B)=>{S.warn(`[SessionRoutes] Failed to persist admission for ${x.id}:`,B)})}});F.taskAdmission=w;let M=w.getSnapshot();F.status=M.state,F.taskQueuePosition=M.queuePosition,F.taskQueueDepth=M.queueDepth,F.taskConcurrencyLimit=M.maxConcurrent}return M0.set(z,F),x.currentRunId=z,F.completion=t4(F,x,G,Q,H,{pendingInputOnly:V.pendingInputOnly,preparedInputTurn:V.preparedInputTurn,goalContinuationOnly:V.goalContinuationOnly,outputSchema:V.outputSchema,taskAdmission:F.taskAdmission,disposeRuntime:E}).catch((D)=>{S.error(`[SessionRoutes] Run ${z} failed:`,D)}),F},L=async(x)=>{let G;if(x.outputSchema)try{G=S$(x.outputSchema).schema}catch(q){throw new _(q instanceof Error?q.message:"Invalid output schema")}let Q=P$("task",12),V=Q$(x.sourceProjectPath),z=x.modelId?.trim(),F=o();if(!F)throw new _("Config not initialized");let[D,w]=await Promise.all([H$(V,F),x0(V)]);if(z&&!D.config.models.some((q)=>q.id===z))throw new _(`Task model not found: ${z}`);let M=z||D.config.models.find((q)=>q.id===D.config.currentModelId)?.id||D.config.models[0]?.id;if(!M)throw new _("No model is configured. Add or select a model before dispatching a task.");let A=D.config.models.find((q)=>q.id===M);if(!A)throw new _(`Task model not found: ${M}`);let B=x.reasoningEffort??"off",n=x.serviceTier??"auto",q0=x.responseVerbosity??"auto",K0=x.communicationStyle??"auto",V0,k=w.projectRules?.staticRules(V),v=k&&k.files.length>0?k.provenanceSha256:void 0;try{let q=D.catalog.resolveConfig(A);pO(q,B),vO(q,n),gO(q,q0);let h=uO(K0,w.communicationStyles);V0=h.source==="built-in"?void 0:h.contentSha256}catch(q){throw new _(q instanceof Error?q.message:"Invalid reasoning effort")}let e0={version:1,prompt:x.prompt,...x.title?{title:x.title}:{},sourceProjectPath:V,isolation:x.isolation,permissionMode:x.permissionMode,modelId:M,reasoningEffort:B,serviceTier:n,responseVerbosity:q0,communicationStyle:K0,...V0?{communicationStyleDigest:V0}:{},...v?{projectInstructionsDigest:v}:{},...x.attachments?{attachments:x.attachments.map((q)=>({...q}))}:{},...G?{outputSchema:G}:{}},H0,y;try{let q=await rO.createSessionTask({sessionId:Q,prompt:x.prompt,title:x.title,sourceProjectPath:V,isolation:x.isolation,dispatch:e0,retriedFrom:x.retriedFrom}),{metadata:h}=q;H0=q.taskWorktree,y=x$(h,[],H0);let $0=e(y);l.set(P($0),y),b.publish($0,"task.status",{taskStatus:h.taskStatus,updatedAt:h.lastMessageTime});let t=hO(x.prompt,x.attachments),i=await H(y),F0=G?await i.prepareInputTurn(t,{outputSchema:G}):await i.prepareInputTurn(t);if(!F0.accepted)throw new j(`Task prompt was not accepted: ${F0.reason}`);let B0=r(y,t,x.permissionMode,{preparedInputTurn:F0,taskRuntime:i,outputSchema:G});return await B0.taskAdmissionUpdate,{session:l0(y),runId:B0.id,messageId:F0.messageId,status:B0.status==="queued"?"queued":"running",queuePosition:B0.taskQueuePosition,queueDepth:B0.taskQueueDepth,maxConcurrentTasks:B0.taskConcurrencyLimit}}catch(q){if(q instanceof v$&&y){let h=e(y),$0=P(h);if(H0)await A0.exit({sessionId:y.id,action:"remove",discardChanges:!0}).catch(()=>{return});throw await O.get($0)?.dispose().catch(()=>{return}),O.delete($0),await R.deleteSession(y.id,y.projectPath).catch(()=>{return}),l.delete($0),new v0("Task admission queue is full")}if(y){let h=await R.findSessionMetadata(y.id,y.projectPath).catch(()=>{return});if(!h||h.taskStatus==="queued"){let $0=L$(q),t=await R.updateSessionMetadata(y.id,y.projectPath,{taskStatus:"failed",taskStatusReason:$0.message,taskFailure:$0,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null}).catch(()=>{return});y.taskStatus=t?.taskStatus??"failed",y.taskStatusReason=t?.taskStatusReason??$0.message,y.taskFailure=t?.taskFailure??$0,y.taskCompletedAt=t?.taskCompletedAt}else y.taskStatus=h.taskStatus,y.taskStatusReason=h.taskStatusReason,y.taskFailure=h.taskFailure,y.taskCompletedAt=h.taskCompletedAt}throw q}},a=async(x,G)=>{let Q=await Z0(x,G),V=await R.findSessionMetadata(Q.sessionId,Q.projectPath);if(!V)throw new I("Session",Q.sessionId);if(!["failed","interrupted","cancelled"].includes(V.taskStatus))throw new j(`Task cannot be retried while status is ${V.taskStatus}`);let z=await R.findSessionTaskDispatch(Q.sessionId,Q.projectPath);if(!z)throw new j("Task retry payload is unavailable");return L({prompt:z.prompt,title:z.title,sourceProjectPath:z.sourceProjectPath,isolation:z.isolation,permissionMode:z.permissionMode,modelId:z.modelId,reasoningEffort:z.reasoningEffort,serviceTier:z.serviceTier,responseVerbosity:z.responseVerbosity,communicationStyle:z.communicationStyle,attachments:z.attachments,outputSchema:z.outputSchema,retriedFrom:Q})},m=async(x,G)=>{let Q=await T(x,G);if(!Q.taskWorktree)throw new _("Session does not have a task worktree");try{await A0.restoreSession(Q.taskWorktree);let V=await A0.getDiffArtifact(Q.id);if(!V)throw new j("Task diff artifact is unavailable");return{sessionId:Q.id,projectPath:Q.projectPath,...V}}catch(V){if(V instanceof j)throw V;throw S.error("[SessionRoutes] Failed to load task diff artifact:",V),new j("Task diff artifact is unavailable")}},O0=async(x,G,Q)=>{let V=await Z0(x,Q);return W(V).runExclusive(async()=>{let z=await T(V.sessionId,V.projectPath);if(["queued","running"].includes(z.taskStatus))throw new j(`Task artifacts cannot be delivered while status is ${z.taskStatus}`);if(z.taskDelivery?.status==="applied")throw new j("Task changes have already been applied");if(z.taskDelivery?.status==="discarded")throw new j("Task changes have already been discarded");if(!z.taskWorktree)throw new j("Task worktree is unavailable");let F=async(D,w=!1)=>{let M=await R.updateSessionMetadata(z.id,z.projectPath,{taskDelivery:D,...w?{taskWorktree:null}:{}});if(X$(z,M),w)z.taskWorktree=void 0;return b.publish(V,"task.delivery",{taskDelivery:D,...w?{taskWorktreeRemoved:!0}:{},updatedAt:M.lastMessageTime}),l0(z)};try{if(G==="discard"){try{await A0.restoreSession(z.taskWorktree)}catch(M){return S.warn(`[SessionRoutes] Abandoning unavailable task worktree for ${z.id}:`,M),F({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:z.taskDiffStat?.changedFiles??0,message:"Task artifact discarded; worktree was unavailable"},!0)}let w=await A0.exit({sessionId:z.id,action:"remove",discardChanges:!0});return F({status:"discarded",updatedAt:new Date().toISOString(),changedFiles:w.discardedFiles??0,message:"Task worktree removed"},!0)}try{await A0.restoreSession(z.taskWorktree)}catch(w){throw S.warn(`[SessionRoutes] Task worktree is unavailable for ${z.id}:`,w),new g$("artifact_unavailable","Task worktree is unavailable")}let D=await A0.apply(z.id);return F({status:"applied",updatedAt:new Date().toISOString(),sourceCommit:D.sourceCommit,changedFiles:D.changedFiles,message:"Task changes applied to the source workspace"})}catch(D){if(D instanceof g$)throw await F({status:"conflicted",updatedAt:new Date().toISOString(),message:D.message}),new j(D.message);throw D}})},Q0=async(x)=>{let G=z0(x.currentRunId);if(W0(G))return;if(x.taskIsolation&&x.taskStatus!=="queued"&&x.taskStatus!=="running")return;let Q=await z$.hasPendingInbox(x.projectPath,x.id),V=!Q&&await z$.hasActiveGoal(x.projectPath,x.id);if(!Q&&!V)return;let z=await H(x),F=z0(x.currentRunId);if(W0(F))return;if(Q&&z.getPendingSteeringCount()===0)await z.reloadPendingInbox();let D=z.getPendingSteeringCount()>0,M=(D?null:await z.getGoal())?.status==="active"||V;if(!D&&!M||z.hasTurnOwner())return;r(x,"",x.permissionMode??"default",{pendingInputOnly:D,goalContinuationOnly:M,...x.taskIsolation?{taskRuntime:z}:{}})};w$=Q0;let W$=async()=>{let x={scheduled:0,failed:0,deferred:0},G=(await R.listSessions()).filter((Q)=>Q.taskStatus==="queued"&&Q.taskIsolation!==void 0).sort((Q,V)=>Q.firstMessageTime.localeCompare(V.firstMessageTime)||Q.projectPath.localeCompare(V.projectPath)||Q.sessionId.localeCompare(V.sessionId));for(let[Q,V]of G.entries()){let z={sessionId:V.sessionId,projectPath:V.projectPath};try{if(!await z$.hasPendingInbox(V.projectPath,V.sessionId)){let D=L$("Queued task input is missing");await R.updateSessionMetadata(V.sessionId,V.projectPath,{taskStatus:"failed",taskStatusReason:D.message,taskFailure:D,taskCompletedAt:new Date().toISOString(),taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}),x.failed++;continue}let F=await C(z);if(await Q0(F),F.currentRunId)x.scheduled++}catch(F){if(F instanceof v$){x.deferred+=G.length-Q;break}S.warn(`[SessionRoutes] Failed to recover queued task ${V.sessionId}:`,F),x.deferred++}}return x};return $.get("/",async(x)=>{try{let G=await R.listSessions(),Q=new Set(G.filter((A)=>A.relationType==="subagent").map((A)=>P({sessionId:A.sessionId,projectPath:A.projectPath}))),V=Array.from(l.values()).filter((A)=>!Q.has(P(e(A)))&&A.relationType!=="subagent").map((A)=>l0(A)),z=new Set(V.map((A)=>P({sessionId:A.sessionId,projectPath:A.projectPath}))),F=G.filter((A)=>{if(A.relationType==="subagent")return!1;return!z.has(P({sessionId:A.sessionId,projectPath:A.projectPath}))}),D=new Set(z),w=F.filter((A)=>{let B=P({sessionId:A.sessionId,projectPath:A.projectPath});if(D.has(B))return!1;return D.add(B),!0}),M=[...V,...w];return x.json(M)}catch(G){throw S.error("[SessionRoutes] Failed to list sessions:",G),new d("Failed to list sessions")}}),$.get("/catalog",async(x)=>{try{let G=x.req.query("limit"),Q=G===void 0?void 0:Number(G),V=x.req.query("cursor"),z=x.req.query("projectPath"),F=x.req.query("archived");if(F!==void 0&&F!=="true"&&F!=="false")throw new _("archived must be true or false");let D=F==="true",w=await R.listSessionPage({...z?{cwd:Q$(z)}:{},...V?{cursor:V}:{},...Q===void 0?{}:{limit:Q},includeSubagents:!1,archived:D}),M=new Map((D?[]:Array.from(l.values())).filter((A)=>A.relationType!=="subagent").map((A)=>[P(e(A)),l0(A)]));return x.json({sessions:w.sessions.map((A)=>M.get(P({sessionId:A.sessionId,projectPath:A.projectPath}))??A),...w.nextCursor?{nextCursor:w.nextCursor}:{}})}catch(G){if(G instanceof _)throw G;if(G instanceof Error&&(G.message.startsWith("Invalid session cursor")||G.message.startsWith("Session cursor scope")||G.message.startsWith("Session catalog")))throw new _(G.message);throw S.error("[SessionRoutes] Failed to list session catalog:",G),new d("Failed to list session catalog")}}),$.post("/",async(x)=>{try{let G=await x.req.json(),Q=f(v4,G);if(!Q.success)throw new _("Invalid request body");let{title:V,projectPath:z}=Q.data,F=P$("web",12),D=Q$(z||x.get("directory")||g(),z?"projectPath":"directory"),w=await R.createSessionMetadata(F,D,{title:V,taskStatus:"completed"}),M=x$(w,[]),A=e(M);return l.set(P(A),M),b.publish(A,"session.created",{}),x.json({...l0(M),status:void 0,agentType:void 0,model:void 0})}catch(G){if(S.error("[SessionRoutes] Failed to create session:",G),G instanceof _)throw G;throw new d("Failed to create session")}}),$.get("/:sessionId/export",async(x)=>{let G=x.req.param("sessionId");try{let Q=x.req.query("includeReasoning");if(Q!==void 0&&Q!=="true"&&Q!=="false")throw new _("includeReasoning must be true or false");let V=await Z0(G,x.req.query("projectPath")),z=await R.exportSessionMarkdown(V.sessionId,V.projectPath,{includeReasoning:Q==="true"});return x.body(z.markdown,200,{"Cache-Control":"no-store","Content-Disposition":`attachment; filename="${z.filename}"`,"Content-Length":String(Buffer.byteLength(z.markdown,"utf8")),"Content-Type":"text/markdown; charset=utf-8","X-Blade-Content-Sha256":z.contentSha256,"X-Blade-Export-Activities":String(z.activityCount),"X-Blade-Export-Messages":String(z.messageCount),"X-Blade-Export-Redactions":String(z.redactionCount)})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof N0)throw Q;if(Q instanceof Error&&Q.message==="No conversation content to export")throw new j(Q.message);throw S.error("[SessionRoutes] Failed to export session:",Q),new d("Failed to export session")}}),$.post("/:sessionId/fork",async(x)=>{let G=x.req.param("sessionId");try{p$(G);let Q=await x.req.json(),V=f(d4,Q);if(!V.success)throw new _("Invalid request body");let z=Q$(V.data.projectPath),F=await R.findSessionMetadata(G,z);if(!F)throw new I("Session",G);let D=await R.forkSession(G,{sourceProjectPath:F.projectPath,targetProjectPath:F.projectPath}),w=x$(D.metadata,D.messages),M=e(w);return l.set(P(M),w),b.publish(M,"task.status",{taskStatus:D.metadata.taskStatus,...D.metadata.taskCompletedAt?{taskCompletedAt:D.metadata.taskCompletedAt}:{},updatedAt:D.metadata.lastMessageTime}),x.json({session:D.metadata,messages:f$(D.messages)},201)}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof j)throw Q;if(Q instanceof oO)throw new j("Session has no durable creation record");throw S.error("[SessionRoutes] Failed to fork session:",Q),new d("Failed to fork session")}}),$.get("/:sessionId",async(x)=>{let G=x.req.param("sessionId");try{let Q=await Z0(G,x.req.query("projectPath")),V=l.get(P(Q));if(V)return x.json(l0(V));let z=await R.findSessionMetadata(Q.sessionId,Q.projectPath);if(!z)throw new I("Session",G);return x.json(z)}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof N0)throw Q;throw S.error("[SessionRoutes] Failed to get session:",Q),new d("Failed to get session")}}),$.patch("/:sessionId",async(x)=>{let G=x.req.param("sessionId");try{let Q=await x.req.json(),V=f(u4,Q);if(!V.success)throw new _("Invalid request body");if(V.data.title===void 0)throw new _("title is required");let z=await Z0(G,V.data.projectPath),F=await R.updateSessionMetadata(z.sessionId,z.projectPath,{title:V.data.title}),D=l.get(P(z));if(D)D.title=F.title??D.title,D.updatedAt=new Date(F.lastMessageTime);if(F.title)b.publish(z,"session.updated",{title:F.title});return x.json({success:!0,title:F.title})}catch(Q){if(S.error("[SessionRoutes] Failed to update session:",Q),Q instanceof _||Q instanceof I||Q instanceof N0)throw Q;throw new d("Failed to update session")}}),$.get("/:sessionId/rewind",async(x)=>{let G=await T(x.req.param("sessionId"),x.req.query("projectPath")),Q=await H(G);return x.json({checkpoints:await Q.listRewindCheckpoints()})}),$.post("/:sessionId/rewind",async(x)=>{let G=f(eO,await x.req.json());if(!G.success)throw new _("Invalid rewind request");let Q=await T(x.req.param("sessionId"),x.req.query("projectPath")),V=e(Q);return N(V).runExclusive(async()=>{let z=z0(Q.currentRunId);if(W0(z))throw new j("Cannot rewind while a run is active");let F=await H(Q),D;try{D=await F.rewindSession(G.data)}catch(M){if(M instanceof Error&&M.message.startsWith("Cannot rewind while"))throw new j(M.message);throw M}Q.messages=[...D.messages],Q.updatedAt=new Date;let w=f$(D.messages);return b.publish(V,"session.rewound",{targetMessageId:D.checkpoint.messageId,mode:D.mode,removedTurns:D.removedTurns,restoredFiles:D.restoredFiles,messages:w}),x.json({...D,messages:w})})}),$.get("/:sessionId/review",async(x)=>{let G=x.req.param("sessionId"),Q=await Z0(G,x.req.query("projectPath")),V=await C0.list(Q.projectPath,Q.sessionId);return x.json({reviews:V.map((z)=>({...z,content:z.completion?lO(z.start,z.completion):void 0}))})}),$.post("/:sessionId/review",async(x)=>{let G=x.req.param("sessionId"),Q=f(Z1,await x.req.json());if(!Q.success)throw new _("Invalid code review request");let V=await T(G,Q.data.projectPath),z=e(V),F=P(z);return N(z).runExclusive(async()=>{if(W0(z0(V.currentRunId)))throw new j("Cannot start a review during an active turn");if(b0.has(F))throw new j("Session already has an active review");let D=await H(V);if(await C0.recoverInterrupted(z.projectPath,z.sessionId,D),Q.data.modelId&&!D.getModelById(Q.data.modelId))throw new _(`Model not found: ${Q.data.modelId}`);if(Q.data.modelId&&D.getCurrentModelId()!==Q.data.modelId)await D.refresh({modelId:Q.data.modelId});if(Q.data.modelId&&V.selectedModelId!==Q.data.modelId){let B=await R.updateSessionMetadata(V.id,V.projectPath,{selectedModelId:Q.data.modelId});X$(V,B)}let w=new AbortController,M;try{M=await C0.start({sessionId:z.sessionId,projectPath:z.projectPath,runtime:D,request:{kind:Q.data.kind,...Q.data.ref?{ref:Q.data.ref}:{},...Q.data.instructions?{instructions:Q.data.instructions}:{}},signal:w.signal,onEvent:(B)=>{if(B.kind==="tool_start")b.publish(z,"review.tool.started",{reviewId:M?.reviewId,toolCallId:B.toolCall.id,toolName:B.toolCall.function.name});else if(B.kind==="tool_progress")b.publish(z,"review.tool.progress",{reviewId:M?.reviewId,toolCallId:B.toolCall.id,message:B.update.message.slice(0,1000)});else if(B.kind==="tool_result")b.publish(z,"review.tool.completed",{reviewId:M?.reviewId,toolCallId:B.toolCall.id,success:B.result.success})}})}catch(B){if(B instanceof Error&&(B.message.includes("active review")||B.message.includes("interrupted review")||B.message.includes("active turn")))throw new j(B.message);if(B instanceof Error&&(B.message.includes("review")||B.message.includes("Git")||B.message.includes("changes")||B.message.includes("ref")))throw new _(B.message);throw B}if(!M)throw new d("Code review failed to start");await S0(V),b.publish(z,"review.started",{reviewId:M.reviewId,kind:Q.data.kind}),b.publish(z,"task.status",{taskStatus:V.taskStatus,...V.taskStatusReason?{taskStatusReason:V.taskStatusReason}:{},...V.taskStartedAt?{taskStartedAt:V.taskStartedAt}:{},...V.taskPromptSummary?{taskPromptSummary:V.taskPromptSummary}:{},updatedAt:new Date().toISOString()});let A=M.completion.then(async(B)=>{V.messages=await R.loadSession(z.sessionId,z.projectPath),await S0(V),b.publish(z,"task.status",{taskStatus:V.taskStatus,...V.taskStatusReason?{taskStatusReason:V.taskStatusReason}:{},...V.taskFailure?{taskFailure:V.taskFailure}:{},...V.taskStartedAt?{taskStartedAt:V.taskStartedAt}:{},...V.taskCompletedAt?{taskCompletedAt:V.taskCompletedAt}:{},...V.taskPromptSummary?{taskPromptSummary:V.taskPromptSummary}:{},updatedAt:new Date().toISOString()}),b.publish(z,"review.completed",{reviewId:M.reviewId,status:B.status,findings:B.findings.length})}).catch((B)=>{S.error(`[SessionRoutes] Code review ${M.reviewId} failed:`,B)}).finally(()=>{if(b0.get(F)?.reviewId===M.reviewId)b0.delete(F)});return b0.set(F,{reviewId:M.reviewId,controller:w,completion:A}),x.json({reviewId:M.reviewId,status:"running"},202)})}),$.get("/:sessionId/subagents",async(x)=>{let G=await T(x.req.param("sessionId"),x.req.query("projectPath")),Q=await H(G);return x.json({subagents:Q.listSubagents().map(B$)})}),$.post("/:sessionId/subagents/:agentId/resume",async(x)=>{p$(x.req.param("agentId"));let G=$1.safeParse(await x.req.json());if(!G.success)throw new _("Invalid subagent resume request");let Q=await T(x.req.param("sessionId"),x.req.query("projectPath")),V=e(Q);return N(V).runExclusive(async()=>{let z=z0(Q.currentRunId);if(W0(z))throw new j("Cannot resume a subagent while a parent run is active");let F=await H(Q),D=!1,w,M=(B)=>{b.publish(V,"subagent.complete",{subagentSessionId:B.id,success:B.status==="completed",status:B.status,summary:B.result?.message?.slice(0,500),type:B.subagentType,verificationVerdict:B.result?.verificationVerdict,resumedFrom:B.resumedFrom,rootAgentId:B.rootAgentId,resumeDepth:B.resumeDepth})},A;try{A=F.resumeSubagent({agentId:x.req.param("agentId"),prompt:G.data.prompt,onEvent:(B,n)=>{n4(V,n,B)},onCompleted:(B)=>{if(D)M(B);else w=B}})}catch(B){if(B instanceof Error&&(B.message.startsWith("Cannot resume")||B.message.startsWith("Subagent cannot")))throw new j(B.message);if(B instanceof Error&&B.message.startsWith("Subagent not found"))throw new I(B.message);throw B}if(b.publish(V,"subagent.start",{subagentSessionId:A.session.id,type:A.session.subagentType,description:A.session.description,resumedFrom:A.source.id,rootAgentId:A.session.rootAgentId,resumeDepth:A.session.resumeDepth}),D=!0,w)M(w);return x.json({source:B$(A.source),session:B$(A.session)})})}),$.get("/:sessionId/goal",async(x)=>{let G=await T(x.req.param("sessionId"),x.req.query("projectPath"));return x.json({goal:await new nO(G.projectPath,G.id).get()})}),$.put("/:sessionId/goal",async(x)=>{let G=f(l4,await x.req.json());if(!G.success)throw new _("Invalid goal request");let Q=await T(x.req.param("sessionId"),x.req.query("projectPath")),V=e(Q);return N(V).runExclusive(async()=>{let z=z0(Q.currentRunId);if(W0(z))return x.json({status:"rejected",reason:"run_active"},409);let D=G.data.permissionMode??Q.permissionMode??"default";if(Q.permissionMode!==D)await c(Q,D);let w=await H(Q),M=await w.createGoal(G.data);b.publish(V,"goal.updated",{goal:M});let A=r(Q,"",D,{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:w}:{}});return await A.taskAdmissionUpdate,x.json({status:A.status==="queued"?"queued":"running",runId:A.id,goal:M,queuePosition:A.taskQueuePosition,queueDepth:A.taskQueueDepth,maxConcurrentTasks:A.taskConcurrencyLimit},202)})}),$.patch("/:sessionId/goal",async(x)=>{let G=f(c4,await x.req.json());if(!G.success)throw new _("Invalid goal update");let Q=await T(x.req.param("sessionId"),x.req.query("projectPath")),V=e(Q);return N(V).runExclusive(async()=>{let z=await H(Q),F;if(G.data.action==="pause")F=await z.pauseGoal();else if(G.data.action==="edit")F=await z.editGoal(G.data.objective);else F=await z.resumeGoal();if(b.publish(V,"goal.updated",{goal:F}),F.status==="active"&&!W0(z0(Q.currentRunId))){let D=r(Q,"","default",{goalContinuationOnly:!0,...Q.taskIsolation?{taskRuntime:z}:{}});return await D.taskAdmissionUpdate,x.json({status:D.status==="queued"?"queued":"running",runId:D.id,goal:F,queuePosition:D.taskQueuePosition,queueDepth:D.taskQueueDepth,maxConcurrentTasks:D.taskConcurrencyLimit},202)}return x.json({status:F.status,goal:F})})}),$.delete("/:sessionId/goal",async(x)=>{let G=await T(x.req.param("sessionId"),x.req.query("projectPath")),Q=e(G),z=await(await H(G)).clearGoal();if(z)b.publish(Q,"goal.cleared",{});return x.json({cleared:z})}),$.post("/:sessionId/archive",async(x)=>{let G=x.req.param("sessionId");try{let Q=await Z0(G,x.req.query("projectPath")),V=await R.listSessionArchiveMembers(Q.sessionId,Q.projectPath);for(let F of V){let D=T0({sessionId:F.sessionId,projectPath:F.projectPath}),w=l.get(P(D));if(W0(z0(w?.currentRunId)))throw new j(`Stop session ${F.sessionId} before archiving this session tree`)}for(let F of V){let D=T0({sessionId:F.sessionId,projectPath:F.projectPath}),w=l.get(P(D));if(w)await E(w)}let z=await R.archiveSession(Q.sessionId,Q.projectPath);for(let F of V){let D=T0({sessionId:F.sessionId,projectPath:F.projectPath}),w=P(D);l.delete(w),Y.delete(w),J.delete(w),X.delete(w),b.publish(D,"session.archived",{archiveRootId:Q.sessionId,archivedAt:z.archivedAt})}if(O.size===0)await X0.getInstance().disconnectAll();return x.json({session:z,archivedSessionIds:V.map((F)=>F.sessionId)})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof N0||Q instanceof j)throw Q;if(Q instanceof m$)throw new j(Q.message);throw S.error("[SessionRoutes] Failed to archive session:",Q),new d("Failed to archive session")}}),$.post("/:sessionId/unarchive",async(x)=>{let G=x.req.param("sessionId");try{let Q=await Z0(G,x.req.query("projectPath")),V=await R.listSessionArchiveMembers(Q.sessionId,Q.projectPath),z=await R.unarchiveSession(Q.sessionId,Q.projectPath),F=V.filter((D)=>D.sessionId===Q.sessionId||D.archivedBySessionId===Q.sessionId).map((D)=>D.sessionId);for(let D of F)b.publish({sessionId:D,projectPath:Q.projectPath},"session.unarchived",{archiveRootId:Q.sessionId});return x.json({session:z,restoredSessionIds:F})}catch(Q){if(Q instanceof _||Q instanceof I||Q instanceof N0)throw Q;if(Q instanceof m$)throw new j(Q.message);throw S.error("[SessionRoutes] Failed to unarchive session:",Q),new d("Failed to unarchive session")}}),$.delete("/:sessionId",async(x)=>{let G=x.req.param("sessionId"),Q=x.req.query("projectPath");try{let V=await Z0(G,Q),z=P(V),F=l.get(z),D=O.get(z),w=F?.taskWorktree??await R.findSessionTaskWorktree(V.sessionId,V.projectPath),M;if(F?.currentRunId){let B=z0(F.currentRunId);if(B)A$(B),await B.completion,M=B.id}let A=b0.get(z);if(A)A.controller.abort("session-delete"),await A.completion;if(D)await D.clearGoal().catch((B)=>{S.warn("[SessionRoutes] Failed to clear session goal:",B)});if(await R.deleteSession(V.sessionId,V.projectPath),b.publish(V,"session.deleted",{}),M)a4(M);if(l.delete(z),Y.delete(z),J.delete(z),X.delete(z),D){if(await D.dispose(),O.delete(z),O.size===0)await X0.getInstance().disconnectAll()}if(w)try{await A0.restoreSession(w),await A0.exit({sessionId:V.sessionId,action:"remove",discardChanges:!0})}catch(B){S.warn(`[SessionRoutes] Failed to remove deleted task worktree ${V.sessionId}:`,B)}return x.json({success:!0})}catch(V){if(S.error("[SessionRoutes] Failed to delete session:",V),V instanceof _||V instanceof I||V instanceof N0)throw V;throw new d("Failed to delete session")}}),$.get("/:sessionId/message",async(x)=>{let G=x.req.param("sessionId");try{let Q=await Z0(G,x.req.query("projectPath")),V=l.get(P(Q)),z=V?.messages?V.messages:await R.loadSession(Q.sessionId,Q.projectPath);return x.json(f$(z))}catch(Q){if(S.error("[SessionRoutes] Failed to get messages:",Q),Q instanceof _||Q instanceof I||Q instanceof N0)throw Q;throw new d("Failed to get messages")}}),$.get("/:sessionId/events",async(x)=>{let G=x.req.param("sessionId"),Q=await Z0(G,x.req.query("projectPath"));try{await R.assertSessionWritable(Q.sessionId,Q.projectPath)}catch(w){if(w instanceof y$)throw new j(w.message);throw w}let V=await C(Q),z=x.req.header("Last-Event-ID")??x.req.query("lastEventId"),F=z?Number.parseInt(z,10):Number.NaN,D=Number.isInteger(F)?F+1:void 0;return h4(x,async(w)=>{let A,B,n=!1,q0=()=>{if(B!==void 0)clearInterval(B),B=void 0;A?.(),A=void 0},K0=()=>{if(n)return;n=!0,q0()},V0=new Set;w.onAbort(K0),A=b.subscribe((k)=>{if(k.sessionId!==Q.sessionId||k.projectPath!==Q.projectPath)return;let v=k.properties.requestId;if((k.type==="permission.asked"||k.type==="question.required"||k.type==="elicitation.required")&&typeof v==="string"){if(V0.has(v))return;V0.add(v)}w.writeSSE({...typeof k.seq==="number"?{id:String(k.seq)}:{},data:JSON.stringify({type:k.type,...typeof k.seq==="number"?{seq:k.seq}:{},properties:{...k.properties,sessionId:k.sessionId,projectPath:k.projectPath}})}).catch(K0)});try{if(w.aborted||n)return;let k=z0(V.currentRunId),v=W0(k)?await H(V):void 0,e0=v?.getPendingSteeringCount()??0;if(await w.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:Q.sessionId,projectPath:Q.projectPath,timestamp:Date.now(),status:W0(k)?k.status:"idle",runId:W0(k)?k.id:void 0,queued:e0,pendingInputDelivery:e0>0?v?.hasActiveTurn()?"current_turn":"next_turn":null,recovered:v?.getRecoveredSteeringCount()??0}})}).catch((q)=>{throw K0(),q}),w.aborted||n)return;if(D!==void 0){if(await tO.for(Q.sessionId,Q.projectPath).replay({onCommitted:(h)=>{if(w.aborted||n)return;w.writeSSE({...typeof h.seq==="number"?{id:String(h.seq)}:{},data:JSON.stringify({type:`committed.${h.type}`,...typeof h.seq==="number"?{seq:h.seq}:{},properties:{event:h,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}},D),w.aborted||n)return}if(!k&&!b0.has(P(Q))){let h=(await C0.list(Q.projectPath,Q.sessionId)).some(($0)=>$0.completion===void 0)?await C0.recoverInterrupted(Q.projectPath,Q.sessionId,await H(V)):void 0;if(h)V.messages=await R.loadSession(Q.sessionId,Q.projectPath),await S0(V),b.publish(Q,"review.completed",{reviewId:h.reviewId,status:h.status,findings:0,recovered:!0})}if(!k)await P0.recoverResponded(Q.projectPath,Q.sessionId);let H0=k?void 0:await P0.findPending(Q.projectPath,Q.sessionId),y=k?.pendingPermission??(H0?{permissionId:H0.request.requestId,details:P0.confirmationDetails(H0),resolve:()=>{return}}:void 0);if(y){V0.add(y.permissionId);let q=Y1(y,!0);await w.writeSSE({data:JSON.stringify({type:q.type,properties:{...q.properties,sessionId:Q.sessionId,projectPath:Q.projectPath}})})}Q0(V).catch((q)=>{S.error(`[SessionRoutes] Failed to resume pending input for ${G}:`,q)}),B=setInterval(()=>{if(!w.aborted)w.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(K0)},15000);while(!w.aborted&&!n)await new Promise((q)=>setTimeout(q,1000))}finally{K0()}})}),$.post("/:sessionId/message",async(x)=>{let G=x.req.param("sessionId"),Q=await x.req.json(),V=f(p4,Q);if(!V.success)throw new _("Invalid message format");let{content:z,attachments:F,modelId:D,reasoningEffort:w,serviceTier:M,responseVerbosity:A,communicationStyle:B,permissionMode:n,projectPath:q0,outputSchema:K0}=V.data,V0;if(K0)try{V0=S$(K0).schema}catch(t){throw new _(t instanceof Error?t.message:"Invalid output schema")}let k=B,v=D?.trim();if((F??[]).reduce((t,i)=>t+(typeof i.content==="string"?Buffer.byteLength(i.content):0),0)>M$)throw new _("Message attachments exceed the 5 MiB limit");let H0=n,y=hO(z,F),q=await T(G,q0??x.req.query("projectPath")),h=H0??q.permissionMode??"default",$0=e(q);return N($0).runExclusive(async()=>{let t=z0(q.currentRunId);if(W0(t)){if(V0)throw new j("Wait for the active turn to finish before setting an output schema");let p=await H(q);if(v&&!p.getModelById(v))throw new _(`Model not found: ${v}`);if(v&&p.getCurrentModelId()!==v)throw new j("Wait for the active turn to finish before switching models");if(w&&p.getReasoningConfiguration().selection!==w)throw new j("Wait for the active turn to finish before switching reasoning effort");if(M&&p.getServiceTierConfiguration().selection!==M)throw new j("Wait for the active turn to finish before switching service tier");if(A&&p.getResponseVerbosityConfiguration().selection!==A)throw new j("Wait for the active turn to finish before switching response verbosity");if(k&&p.getCommunicationStyleConfiguration().selection!==k)throw new j("Wait for the active turn to finish before switching communication style");if(H0&&q.permissionMode!==H0)throw new j("Wait for the active turn to finish before switching permission mode");let L0=await p.enqueueSteering(y,{allowBeforeTurn:!0});if(!L0.accepted)return x.json({status:"rejected",reason:L0.reason??"turn_unavailable"},409);let T$=L0.messageId??c0(12),FO=L0.queued;b.publish($0,"message.created",{messageId:T$,role:"user",content:u$(y)});let N4=L0.delivery==="next_turn"?"follow_up.queued":"steering.queued";if(b.publish($0,N4,{runId:t.id,messageId:T$,queued:FO}),L0.delivery==="next_turn"&&t.status!=="running"&&t.status!=="waiting_permission")Q0(q).catch((G4)=>{S.error(`[SessionRoutes] Failed to wake queued follow-up for ${G}:`,G4)});if(L0.delivery==="next_turn")t.pendingFollowUpRequested=!0;return x.json({runId:t.id,messageId:T$,status:L0.delivery==="next_turn"?"follow_up_queued":"steering_queued",queued:FO},202)}if(q.permissionMode!==h)await c(q,h);let i=await H(q,{permissionMode:h,...k&&!k.includes(":")?{communicationStyle:k}:{}});if(v&&!i.getModelById(v))throw new _(`Model not found: ${v}`);if(w)try{i.resolveReasoningConfiguration(w,v)}catch(p){throw new _(p instanceof Error?p.message:"Invalid reasoning effort")}if(M)try{i.resolveServiceTierConfiguration(M,v)}catch(p){throw new _(p instanceof Error?p.message:"Invalid service tier")}if(A)try{i.resolveResponseVerbosityConfiguration(A,v)}catch(p){throw new _(p instanceof Error?p.message:"Invalid response verbosity")}let F0=k?i.resolveCommunicationStyleConfiguration(k):void 0;if(F0?.source!==void 0&&F0.source!=="built-in"&&!F0.contentSha256)throw new _("Custom communication style has no provenance");let B0=i.getCurrentModelId(),zO=i.getReasoningConfiguration(),QO=i.getServiceTierConfiguration(),xO=i.getResponseVerbosityConfiguration(),XO=i.getCommunicationStyleConfiguration(),KO=Boolean(v)&&B0!==v,VO=Boolean(w)&&zO.selection!==w,NO=Boolean(M)&&QO.selection!==M,GO=Boolean(A)&&xO.selection!==A,WO=Boolean(k)&&XO.selection!==k;if(KO||VO||NO||GO||WO)await i.refresh({...v?{modelId:v}:{},...w?{reasoningEffort:w}:{},...M?{serviceTier:M}:{},...A?{responseVerbosity:A}:{},...k?{communicationStyle:k}:{}});let C$={...v&&q.selectedModelId!==v?{selectedModelId:v}:{},...w&&q.reasoningEffort!==w?{reasoningEffort:w}:{},...M&&q.serviceTier!==M?{serviceTier:M}:{},...A&&q.responseVerbosity!==A?{responseVerbosity:A}:{},...F0&&(q.communicationStyle!==k||q.communicationStyleDigest!==F0.contentSha256)?{communicationStyle:k,communicationStyleDigest:F0.source==="built-in"?null:F0.contentSha256}:{}};if(Object.keys(C$).length>0)try{let p=await R.updateSessionMetadata(q.id,q.projectPath,C$);q.permissionMode=p.permissionMode,q.selectedModelId=p.selectedModelId,q.reasoningEffort=p.reasoningEffort,q.serviceTier=p.serviceTier,q.responseVerbosity=p.responseVerbosity,q.communicationStyle=p.communicationStyle,q.communicationStyleDigest=p.communicationStyleDigest,q.updatedAt=new Date(p.lastMessageTime),b.publish($0,"session.updated",C$)}catch(p){if(KO||VO||NO||GO||WO)await i.refresh({...B0?{modelId:B0}:{},reasoningEffort:zO.selection,serviceTier:QO.selection,responseVerbosity:xO.selection,communicationStyle:XO.selection}).catch((L0)=>S.error("[SessionRoutes] Failed to roll back non-durable model settings:",L0));throw p}let $$=V0?await i.prepareInputTurn(y,{outputSchema:V0}):await i.prepareInputTurn(y);if(!$$.accepted)return x.json({status:"rejected",reason:$$.reason},$$.reason==="queue_full"?429:409);let h0=r(q,y,h,{preparedInputTurn:$$,outputSchema:V0,...q.taskIsolation?{taskRuntime:i}:{}});return await h0.taskAdmissionUpdate,x.json({runId:h0.id,messageId:$$.messageId,status:h0.status==="queued"?"queued":"running",queuePosition:h0.taskQueuePosition,queueDepth:h0.taskQueueDepth,maxConcurrentTasks:h0.taskConcurrencyLimit},202)})}),$.post("/:sessionId/shell",async(x)=>{let G=x.req.param("sessionId"),Q=f(J1,await x.req.json());if(!Q.success)throw new _("Invalid user shell command");let V=await T(G,Q.data.projectPath??x.req.query("projectPath")),z=e(V),F=P(z);return N(z).runExclusive(async()=>{if(i0.has(F))throw new j("A user shell command is already running in this Session");let D=await H(V),w=new AbortController,M,A=new Promise((B)=>{M=B});i0.set(F,{controller:w,completion:A});try{let B=await D.executeUserShellCommand(Q.data.command,{signal:w.signal});V.messages=await R.loadSession(V.id,V.projectPath),V.updatedAt=new Date;let n=z0(V.currentRunId);if(B.delivery==="next_turn"&&W0(n))n.pendingFollowUpRequested=!0;return x.json({executionId:B.executionId,messageId:B.messageId,record:B.record,auxiliary:B.auxiliary,...B.delivery?{delivery:B.delivery}:{},...B.queued!==void 0?{queued:B.queued}:{}})}finally{i0.delete(F),M()}})}),$.post("/:sessionId/abort",async(x)=>{let G=x.req.param("sessionId"),Q=await Z0(G,x.req.query("projectPath")),V=l.get(P(Q));if(V?.currentRunId){let D=z0(V.currentRunId);if(D)A$(D),await D.completion}let z=i0.get(P(Q));if(z)z.controller.abort("user-cancel"),await z.completion;let F=b0.get(P(Q));if(F)F.controller.abort("user-cancel"),await F.completion;return x.json({success:!0})}),$.get("/:sessionId/status",async(x)=>{let G=x.req.param("sessionId"),Q=await Z0(G,x.req.query("projectPath")),V=l.get(P(Q)),z=b0.get(P(Q));if(z)return x.json({sessionId:G,projectPath:Q.projectPath,reviewId:z.reviewId,status:"reviewing"});if(!V?.currentRunId)return x.json({sessionId:G,projectPath:Q.projectPath,status:"idle"});let F=z0(V.currentRunId);return x.json({sessionId:G,projectPath:Q.projectPath,runId:V.currentRunId,status:F?.status||"idle"})}),{app:$,dispatchTask:L,retryTask:a,getTaskDiff:m,deliverTask:O0,recoverQueuedTasks:W$}};async function t4($,O,J,Z,Y,X={}){let{abortController:K,sessionId:N,id:W}=$,H=X.preparedInputTurn?.messageId??c0(12),C=X.pendingInputOnly===!0||X.preparedInputTurn?.mode==="pending"||X.goalContinuationOnly===!0?void 0:c0(12),T,c,r=e(O),L=(m,O0)=>{b.publish(r,m,O0)},a=async()=>{let m=String(K.signal.reason||"Task run cancelled");if(O.taskIsolation){let O0=T??await Y(O).catch(()=>{return});if(m==="user-cancel")await O0?.discardPendingInput().catch((W$)=>{S.warn(`[SessionRoutes] Failed to discard cancelled input for ${O.id}:`,W$)});let Q0=await O0?.setTaskStatus("cancelled",m).catch(()=>{return});if(Q0)X$(O,Q0);else await S0(O).catch(()=>{return})}O.taskStatus="cancelled",O.taskStatusReason=m,O.taskCompletedAt??=new Date().toISOString()};try{if(X.taskAdmission){if(await X.taskAdmission.ready,await $.taskAdmissionUpdate,K.signal.aborted)throw Error(String(K.signal.reason||"Task run cancelled"))}if(O.taskStatus="running",O.taskStatusReason=void 0,O.taskStartedAt=new Date().toISOString(),O.taskCompletedAt=void 0,!X.pendingInputOnly&&!X.goalContinuationOnly)L("message.created",{messageId:H,role:"user",content:u$(J)});if(L("session.status",{status:"running"}),C)L("message.created",{messageId:C,role:"assistant",content:""});T=await Y(O);let m=T,O0=Boolean(X.outputSchema??m.getPendingSteeringMessages().find((z)=>z.outputSchema)?.outputSchema);c=await sO.createWithRuntime(m,{sessionId:N,...O.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}});let Q0=async(z)=>{let F=z.interactionRequestId??c0(12),D=300000;$.status="waiting_permission";let w=new Promise((n)=>{let q0=setTimeout(()=>{S.warn(`[SessionRoutes] Permission ${F} timed out after 300000ms`),L("permission.timeout",{requestId:F}),n({approved:!1,reason:"timeout"})},300000);$.pendingPermission={permissionId:F,resolve:(K0)=>{clearTimeout(q0),n(K0)},details:z}}),M=$.pendingPermission;if(!M)throw Error("Permission request was not registered");let A=Y1(M);L(A.type,A.properties),S.info(`[SessionRoutes] Permission request created: ${F}, runId: ${W}`);let B=await w;if(S.info(`[SessionRoutes] Permission response received: ${F}, approved: ${B.approved}`),!K.signal.aborted)$.status="running";if($.pendingPermission===M)$.pendingPermission=void 0;return L("interaction.resolved",{requestId:F}),B},x={messages:await R.loadSessionModelContext(O.id,O.projectPath),userId:"web-user",sessionId:N,workspaceRoot:O.projectPath,signal:K.signal,permissionMode:Z,onPermissionModeChange:async(z)=>{O.permissionMode=z,O.updatedAt=new Date,L("session.updated",{permissionMode:z})},...O.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:Q0}},G=()=>{if(!C)C=c0(12),L("message.created",{messageId:C,role:"assistant",content:""});return C},Q=async(z)=>{switch(z.kind){case"content_delta":if(O0)break;L("message.delta",{messageId:G(),delta:z.delta});break;case"structured_output":L("structured.output",{messageId:G(),output:z.output,schemaDigest:z.schemaDigest});break;case"thinking_delta":L("thinking.delta",{messageId:G(),delta:z.delta});break;case"tool_start":if("function"in z.toolCall){if(z.toolCall.function.name===a0)break;L("tool.start",{messageId:G(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,arguments:z.toolCall.function.arguments,toolKind:z.toolKind})}break;case"tool_result":if("function"in z.toolCall){if(z.toolCall.function.name===a0)break;L("tool.result",{messageId:G(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,success:z.result.success,summary:z.result.metadata?.summary,output:l$(d$(z.toolCall.function.name,z.result)),metadata:z1(z.result.metadata)})}break;case"tool_progress":if("function"in z.toolCall){if(z.toolCall.function.name===a0)break;L("tool.progress",{messageId:G(),toolName:z.toolCall.function.name,toolCallId:z.toolCall.id,...z.update})}break;case"token_usage":L("token.usage",{...z.usage});break;case"turn_start":L("turn.started",{turn:z.turn,maxTurns:z.maxTurns});break;case"provider_retry":L("provider.retry",{phase:z.phase,attempt:z.attempt,maxRetries:z.maxRetries,reason:z.reason,statusCode:z.statusCode,delayMs:z.delayMs,nextRetryAt:z.nextRetryAt});break;case"provider_stall":L("provider.stall",{phase:z.phase,stallCount:z.stallCount,durationMs:z.durationMs,warningAfterMs:z.warningAfterMs,timeoutMs:z.timeoutMs,outputStarted:z.outputStarted});break;case"action_stationarity":L("action.stationarity",{phase:z.phase,toolName:z.toolName,runLength:z.runLength,nudgeThreshold:z.nudgeThreshold,haltThreshold:z.haltThreshold,progressAware:z.progressAware});break;case"mcp_catalog_changed":L("mcp.catalog.changed",{messageId:G(),revision:z.revision,serverName:z.serverName,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_content_changed":L("mcp.content.changed",{messageId:G(),revision:z.revision,serverName:z.serverName,contentKind:z.contentKind,added:z.added,removed:z.removed,updated:z.updated});break;case"mcp_resource_updated":L("mcp.resource.updated",{messageId:G(),revision:z.revision,serverName:z.serverName,uri:z.uri});break;case"mcp_connection_changed":L("mcp.connection.changed",{messageId:G(),revision:z.revision,serverName:z.serverName,phase:z.phase,reason:z.reason,attempt:z.attempt,maxAttempts:z.maxAttempts,nextRetryAt:z.nextRetryAt,error:z.error});break;case"mcp_log":L("mcp.log",{messageId:G(),revision:z.revision,serverName:z.serverName,level:z.level,logger:z.logger,message:z.message,projectedBytes:z.projectedBytes,dataSha256:z.dataSha256,truncated:z.truncated,detailsOmitted:z.detailsOmitted,timestamp:z.timestamp,synthetic:z.synthetic});break;case"mcp_instructions_changed":L("mcp.instructions.changed",{messageId:G(),revision:z.revision,serverName:z.serverName,action:z.action,reason:z.reason,text:z.text,sourceBytes:z.sourceBytes,projectedBytes:z.projectedBytes,sha256:z.sha256,truncated:z.truncated,detailsOmitted:z.detailsOmitted});break;case"mcp_task_changed":L("mcp.task.changed",{messageId:G(),revision:z.revision,taskId:z.taskId,serverName:z.serverName,toolName:z.toolName,status:z.status,statusMessage:z.statusMessage,createdAt:z.createdAt,updatedAt:z.updatedAt,completedAt:z.completedAt,hasResult:z.hasResult,error:z.error});break;case"project_rules_loaded":L("project.rules.loaded",{messageId:G(),files:z.files,triggerPaths:z.triggerPaths,blockedWrite:z.blockedWrite});break;case"steering_applied":L("steering.applied",{runId:W,messageIds:z.messageIds,count:z.count,recovered:z.recovered,delivery:z.delivery,queued:m.getPendingSteeringCount()});break;case"follow_up_started":{if(C)L("message.complete",{messageId:C}),C=void 0;for(let F of z.messages){if(!F.recovered||F.persisted)continue;L("message.created",{messageId:F.id,role:"user",content:u$(F.content),recovered:!0})}L("follow_up.started",{runId:W,queued:z.queued,recovered:z.recovered}),G();break}case"goal_updated":L("goal.updated",{goal:z.goal});break;case"goal_continuation_started":L("goal.continuation.started",{goal:z.goal,continuation:z.continuation}),G();break;case"compaction":L(z.phase==="start"?"compaction.started":"compaction.completed",{...z.reason?{reason:z.reason}:{},...z.strategy?{strategy:z.strategy}:{},...z.outcome?{outcome:z.outcome}:{},...z.preTokens!==void 0?{preTokens:z.preTokens}:{},...z.postTokens!==void 0?{postTokens:z.postTokens}:{}});break;case"model_fallback":L("model.fallback",{});break;case"task_update":L("task.updated",{tasks:z.tasks});break;default:break}},V=await h$(c.chatStream(J,x,{stream:!0,pendingInputOnly:X.pendingInputOnly,preparedInputTurn:X.preparedInputTurn,goalContinuationOnly:X.goalContinuationOnly,outputSchema:X.outputSchema,taskAdmission:X.taskAdmission}),Q);if(!V.success)throw Error(V.error?.message??"Agent run failed");for(let z=0;z<20;z++){let F=$.pendingFollowUpRequested===!0;if($.pendingFollowUpRequested=!1,m.getPendingSteeringCount()===0){if(!F)break;continue}if(K.signal.aborted)break;if(V=await h$(c.chatStream("",x,{stream:!0,pendingInputOnly:!0,taskAdmission:X.taskAdmission}),Q),!V.success)throw Error(V.error?.message??"Agent follow-up failed")}if(O.messages=await R.loadSession(O.id,O.projectPath),O.updatedAt=new Date,await S0(O),K.signal.aborted||$.status==="cancelled"){await a(),L("session.status",{status:"idle"});return}if(C)L("message.complete",{messageId:C});L("thinking.completed",{}),$.status="completed",O.taskStatus="completed",O.taskCompletedAt??=new Date().toISOString(),L("session.completed",{runId:W,outputTruncated:V.metadata?.outputTruncated??!1}),L("session.status",{status:"idle"})}catch(m){if(T&&X.preparedInputTurn)await T.finishTurn(X.preparedInputTurn.handle).catch(()=>{return});if(K.signal.aborted||$.status==="cancelled"){A$($,"runtime-abort"),await a(),L("session.status",{status:"idle"});return}await S0(O).catch(()=>{return}),S.error("[SessionRoutes] Agent execution error:",m),$.status="failed",O.taskStatus="failed",O.taskCompletedAt??=new Date().toISOString();let O0=L$(m);if(!O.taskFailure){let Q0=T?await T.setTaskStatus("failed",m).catch(()=>{return}):await R.updateSessionMetadata(O.id,O.projectPath,{taskStatus:"failed",taskStatusReason:O0.message,taskFailure:O0,taskCompletedAt:O.taskCompletedAt,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null}).catch(()=>{return});if(Q0)X$(O,Q0)}O.taskStatusReason??=O0.message,O.taskFailure??=O0,L("session.error",{error:O.taskFailure.message,taskFailure:O.taskFailure}),L("session.status",{status:"error"})}finally{if(X.taskAdmission?.release(),X.taskAdmission){let m=u0.getStats();L("task.status",{taskStatus:O.taskStatus,...O.taskStatusReason?{taskStatusReason:O.taskStatusReason}:{},...O.taskFailure?{taskFailure:O.taskFailure}:{},...O.taskStartedAt?{taskStartedAt:O.taskStartedAt}:{},...O.taskCompletedAt?{taskCompletedAt:O.taskCompletedAt}:{},...O.taskDiffStat?{taskDiffStat:O.taskDiffStat}:{},taskQueueDepth:m.queued,taskConcurrencyLimit:m.maxConcurrent,taskInFlight:m.inFlight,updatedAt:new Date().toISOString()})}if(await c?.destroy().catch(()=>{return}),$.disposeRuntimeOnSettle&&X.disposeRuntime)await X.disposeRuntime(O,T).catch((m)=>{S.warn(`[SessionRoutes] Failed to dispose terminal task runtime ${O.id}:`,m)});i4($)}}async function x1($,O,J){S.info(`[SessionRoutes] Looking for permission ${O} in session ${$.sessionId}`),S.info(`[SessionRoutes] Active runs: ${M0.size}`);for(let[X,K]of M0.entries())if(S.info(`[SessionRoutes] Checking run ${X}: sessionId=${K.sessionId}, projectPath=${K.projectPath}, pendingPermission=${K.pendingPermission?.permissionId}`),K.sessionId===$.sessionId&&K.projectPath===$.projectPath&&K.pendingPermission?.permissionId===O){if(K.pendingPermission.details.interactionRequestId)await P0.respond($.projectPath,$.sessionId,O,J);return K.pendingPermission.resolve(J),S.info(`[SessionRoutes] Permission ${O} responded, runId: ${K.id}`),!0}let Z=await P0.findPending($.projectPath,$.sessionId);if(!Z||Z.request.requestId!==O)return S.error(`[SessionRoutes] Permission not found: ${O}`),!1;await P0.respondAndRecover($.projectPath,$.sessionId,O,J);let Y=l.get(P($));if(!Y){let X=await R.findSessionMetadata($.sessionId,$.projectPath);if(!X)return!1;let[K,N]=await Promise.all([R.loadSession($.sessionId,$.projectPath),R.findSessionTaskWorktree($.sessionId,$.projectPath)]);Y=x$(X,K,N),l.set(P($),Y)}else await S0(Y);if(b.publish($,"interaction.resolved",{requestId:O}),w$)w$(Y).catch((X)=>{S.error(`[SessionRoutes] Failed to resume recovered interaction ${O}:`,X)});return!0}var c$=u("Service"),r4=U.Object({approved:U.Boolean(),remember:U.Optional(U.Boolean()),scope:U.Optional(Y0(["once","session","project"])),targetMode:U.Optional(Y0(["default","autoEdit","plan","yolo"])),feedback:U.Optional(U.String({maxLength:4000})),answers:U.Optional(U.Record(U.String({maxLength:80}),U.Union([U.String({maxLength:4000}),U.Array(U.String({maxLength:1000}),{maxItems:4})]),{maxProperties:4})),elicitation:U.Optional(U.Object({action:Y0(["accept","decline","cancel"]),content:U.Optional(U.Record(U.String(),U.Union([U.String({maxLength:4000}),U.Number(),U.Boolean(),U.Array(U.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))}),X1=()=>{let $=new s4;return $.post("/:permissionId",async(O)=>{let J=O.req.param("permissionId"),Z=O.req.query("sessionId"),Y=O.req.query("projectPath");c$.info(`[PermissionRoutes] Received permission response: permissionId=${J}, sessionId=${Z}`);try{let X=await O.req.json(),K=f(r4,X);if(!K.success)throw new _("Invalid permission response format");let{approved:N,remember:W,scope:H,targetMode:E,feedback:C,answers:T,elicitation:c}=K.data;if(!Z)throw new _("sessionId query parameter is required");let r=await Z0(Z,Y);if(!await x1(r,J,{approved:N,reason:C,scope:H,targetMode:E,feedback:C,answers:T,elicitation:c}))throw new I("Permission request",J);return c$.info(`[PermissionRoutes] Permission ${J} ${N?"approved":"denied"}`),O.json({success:!0,approved:N,remember:W})}catch(X){if(c$.error("[PermissionRoutes] Failed to respond to permission:",X),X instanceof _||X instanceof N0||X instanceof I||X instanceof s)throw X;throw X}}),$};import K1 from"node:path";import{Hono as e4}from"hono";var $2=U.Object({projectPath:U.String({minLength:1}),enabled:U.Boolean(),scope:U.Optional(Y0(["local","project","global"]))}),O2=U.Object({projectPath:U.String({minLength:1})}),J2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),trust:U.Literal(!0),ref:U.Optional(U.String({minLength:1}))}),Z2=U.Object({projectPath:U.String({minLength:1}),trust:U.Literal(!0)}),Y2=U.Object({projectPath:U.String({minLength:1}),confirm:U.Literal(!0)}),z2=U.Object({projectPath:U.String({minLength:1}),source:U.String({minLength:1}),ref:U.Optional(U.String({minLength:1}))}),V1=U.Object({projectPath:U.String({minLength:1}),confirm:U.Optional(U.Literal(!0))}),Q2=U.Object({projectPath:U.String({minLength:1}),scope:U.Optional(Y0(["local","project","global"])),policy:U.Object({restrictToAllowedSources:U.Boolean(),requireGitCommitSha:U.Boolean(),allowedGitHosts:U.Array(U.String()),allowedMarketplaces:U.Array(U.String()),allowedLocalRoots:U.Array(U.String())})});function D0($){if(!$||!K1.isAbsolute($))throw new _("projectPath must be absolute");return K1.resolve($)}async function N1($){let[O,J]=await Promise.all([x0($),J$.getInstance().loadWorkspacePluginSettingsResolution($)]);return O.plugins.getAll().map((Z)=>({name:Z.manifest.name,description:Z.manifest.description,version:Z.manifest.version,source:Z.source,enabled:Z.status==="active",status:Z.status,commands:Z.commands.length,skills:Z.skills.length,agents:Z.agents.length,hooks:Z.hooks?Object.values(Z.hooks).reduce((Y,X)=>Y+(Array.isArray(X)?X.length:0),0):0,mcpServers:Object.keys(Z.mcpServers??{}).length,configurable:Z.source!=="cli",managed:Z.installation!==void 0,marketplace:Z.installation?.source.type==="marketplace"?Z.installation.source.marketplace:void 0,revision:Z.installation?.revision,installedAt:Z.installation?.installedAt,updatedAt:Z.installation?.updatedAt,compatibilityIssues:Z.compatibilityIssues??[],effectiveScope:Z.source==="cli"?"invocation":J.settings[Z.manifest.name]?.effectiveScope??"default",settingLayers:Z.source==="cli"?{invocation:!0}:J.settings[Z.manifest.name]?.layers??{}}))}async function x2(){let $=G1(),[O,J]=await Promise.all([$.listCatalogs(),$.listInstallationRecords()]),Z=new Map(J.map((Y)=>[Y.name,Y]));return O.map(({marketplace:Y,manifest:X})=>({name:Y.name,description:X.description??X.metadata?.description??"",sourceType:Y.source.type,revision:Y.revision,updatedAt:Y.updatedAt,plugins:X.plugins.map((K)=>{let N=Z.get(K.name);return{name:K.name,description:K.description??"",version:K.version,category:K.category,tags:K.tags??[],installed:N!==void 0,installedVersion:N?.version}})}))}function o0($,O){if(!$.success)throw new _($.error??O)}var A1=()=>{let $=new e4;return $.get("/",async(O)=>{let J=D0(O.req.query("projectPath"));return O.json(await N1(J))}),$.post("/refresh",async(O)=>{let J=f(O2,await O.req.json());if(!J.success)throw new _("Invalid plugin refresh request");let Z=D0(J.data.projectPath),Y=await F1(Z);return O.json({plugins:await N1(Z),errors:Y.discovery.errors.map((X)=>({code:X.code??"LOAD_ERROR",error:X.error}))})}),$.get("/catalog",async(O)=>{return D0(O.req.query("projectPath")),O.json(await x2())}),$.get("/policy",async(O)=>{let J=D0(O.req.query("projectPath")),Z=await J$.getInstance().loadWorkspacePluginSourcePolicy(J);return O.json({policy:Z,environmentRequiresSha:process.env.BLADE_PLUGIN_REQUIRE_SHA==="1"||process.env.BLADE_PLUGIN_REQUIRE_SHA==="true"})}),$.post("/policy",async(O)=>{let J=f(Q2,await O.req.json());if(!J.success)throw new _("Invalid plugin source policy request");let Z=D0(J.data.projectPath),Y=await U1(Z,J.data.policy,J.data.scope??"global");return O.json({policy:Y})}),$.post("/install",async(O)=>{let J=f(J2,await O.req.json());if(!J.success)throw new _("Invalid plugin install request; explicit source trust is required");let Z=D0(J.data.projectPath),{result:Y}=await D1(Z,J.data.source,{trusted:J.data.trust,ref:J.data.ref});return o0(Y,"Plugin installation failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,installedDependencies:Y.installedDependencies??[]})}),$.post("/marketplaces",async(O)=>{let J=f(z2,await O.req.json());if(!J.success)throw new _("Invalid marketplace add request");let Z=D0(J.data.projectPath),Y=await B1(Z,J.data.source,J.data.ref);return o0(Y,"Marketplace installation failed"),O.json({name:Y.marketplace?.name,plugins:Y.manifest?.plugins.length??0,revision:Y.marketplace?.revision,changed:Y.changed})}),$.post("/marketplaces/:name/refresh",async(O)=>{let J=f(V1,await O.req.json());if(!J.success)throw new _("Invalid marketplace refresh request");let Z=await L1(D0(J.data.projectPath),O.req.param("name"));return o0(Z,"Marketplace refresh failed"),O.json({name:Z.marketplace?.name,plugins:Z.manifest?.plugins.length??0,revision:Z.marketplace?.revision,changed:Z.changed})}),$.post("/marketplaces/:name/remove",async(O)=>{let J=f(V1,await O.req.json());if(!J.success||J.data.confirm!==!0)throw new _("Invalid marketplace removal request; explicit confirmation is required");D0(J.data.projectPath);let Z=await w1(O.req.param("name"),!0);return o0(Z,"Marketplace removal failed"),O.json({name:Z.marketplace?.name,removed:!0})}),$.post("/:name/update",async(O)=>{let J=f(Z2,await O.req.json());if(!J.success)throw new _("Invalid plugin update request; explicit source trust is required");let Z=D0(J.data.projectPath),{result:Y}=await _1(Z,O.req.param("name"),{trusted:J.data.trust});return o0(Y,"Plugin update failed"),O.json({name:Y.pluginName,version:Y.manifest?.version,revision:Y.installation?.revision,changed:Y.changed,updatedDependencies:Y.updatedDependencies??[]})}),$.post("/:name/uninstall",async(O)=>{let J=f(Y2,await O.req.json());if(!J.success)throw new _("Invalid plugin uninstall request; explicit confirmation is required");let Z=D0(J.data.projectPath),{result:Y}=await H1(Z,O.req.param("name"),J.data.confirm);return o0(Y,"Plugin uninstall failed"),O.json({name:Y.pluginName,removed:!0})}),$.post("/:name/state",async(O)=>{let J=f($2,await O.req.json());if(!J.success)throw new _("Invalid plugin state request");let Z=D0(J.data.projectPath),Y=O.req.param("name"),K=(await x0(Z)).plugins.get(Y);if(!K)throw new I("Plugin",Y);if(K.source==="cli")throw new _(`Plugin "${Y}" was loaded with --plugin-dir and is invocation-scoped`);let N=await W1(Z,Y,J.data.enabled,J.data.scope??"local");return O.json(N)}),$};import{Hono as G2}from"hono";import{execFile as X2}from"node:child_process";import K2 from"node:path";var o$="__BLADE_DIRECTORY_PICKER_CANCELLED__",V2=900000;function N2($,O){return new Promise((J)=>{X2($,[...O],{timeout:V2,maxBuffer:65536,windowsHide:!0},(Z,Y,X)=>{let K=Z?.code;J({stdout:Y,stderr:X,exitCode:typeof K==="number"?K:Z?1:0,...typeof K==="string"?{errorCode:K}:{}})})})}function i$($){let O=$.replace(/[\r\n]+$/,"");if(!O||O===o$)return{cancelled:!0};if(!K2.isAbsolute(O))throw Error("The folder picker returned an invalid path");return{cancelled:!1,path:O}}function a$($){return $.exitCode!==0||Boolean($.errorCode)}class M1{platform;runCommand;activeSelection=null;constructor($={}){this.platform=$.platform??process.platform,this.runCommand=$.runCommand??N2}pick(){if(this.activeSelection)return this.activeSelection;let $=this.pickForPlatform().finally(()=>{this.activeSelection=null});return this.activeSelection=$,$}async pickForPlatform(){switch(this.platform){case"darwin":return this.pickOnMac();case"win32":return this.pickOnWindows();case"linux":return this.pickOnLinux();default:throw Error("Native folder selection is unavailable on this system")}}async pickOnMac(){let $=["try",'set selectedFolder to choose folder with prompt "Choose a project folder"',"return POSIX path of selectedFolder","on error number -128",`return "${o$}"`,"end try"].join(`
3
- `),O=await this.runCommand("osascript",["-e",$]);if(a$(O))throw Error("Unable to open the macOS folder picker");return i$(O.stdout)}async pickOnWindows(){let $=["Add-Type -AssemblyName System.Windows.Forms","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog",'$dialog.Description = "Choose a project folder"',"$dialog.ShowNewFolderButton = $true","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {"," [Console]::Out.Write($dialog.SelectedPath)","} else {",` [Console]::Out.Write("${o$}")`,"}"].join("; "),O=await this.runCommand("powershell.exe",["-NoProfile","-STA","-Command",$]);if(a$(O))throw Error("Unable to open the Windows folder picker");return i$(O.stdout)}async pickOnLinux(){let $=[{command:"zenity",args:["--file-selection","--directory","--title=Choose a project folder"]},{command:"kdialog",args:["--getexistingdirectory",".","--title","Choose a project folder"]}];for(let O of $){let J=await this.runCommand(O.command,O.args);if(J.errorCode==="ENOENT")continue;if(J.exitCode===1&&!J.stdout.trim()&&!J.stderr.trim())return{cancelled:!0};if(a$(J))throw Error("Unable to open the Linux folder picker");return i$(J.stdout)}throw Error("Install zenity or kdialog to use native folder selection")}}var q1=new M1;var W2=U.Object({path:U.String({minLength:1})});function F2($){if(!$)return!1;if($==="tauri://localhost"||$==="http://tauri.localhost")return!0;try{let O=new URL($).hostname;return O==="localhost"||O==="127.0.0.1"||O==="::1"||O==="[::1]"}catch{return!1}}var E1=($={})=>{let O=new G2,J=$.pickDirectory??(()=>q1.pick()),Z=$.allowDirectoryPickerRequest??F2;return O.get("/",async(Y)=>{return Y.json(await E$.list(g()))}),O.post("/",async(Y)=>{let X;try{X=await Y.req.json()}catch{throw new _("A valid JSON body is required")}let K=f(W2,X);if(!K.success)throw new _("A project path is required");try{let N=await E$.bind(K.data.path,g());return Y.json(N,201)}catch(N){throw new _(N instanceof Error?N.message:"Failed to bind project")}}),O.post("/pick",async(Y)=>{if(!Z(Y.req.header("Origin")))throw new s("LOCAL_ACCESS_REQUIRED","Folder selection is only available from this machine",403);try{return Y.json(await J())}catch(X){throw new _(X instanceof Error?X.message:"Failed to select a folder")}}),O.delete("/",async(Y)=>{let X=Y.req.query("path");if(!X)throw new _("A project path is required");try{let K=await E$.unbind(X);return Y.json({success:!0,removed:K})}catch(K){throw new _(K instanceof Error?K.message:"Failed to unbind project")}}),O};import{Hono as U2}from"hono";var b1=u("Service"),j1=()=>{let $=new U2;return $.get("/",async(O)=>{try{let J=await T1();return O.json(J)}catch(J){return b1.error("[ProviderRoutes] Failed to list providers:",J),O.json([])}}),$.get("/:provider/models",async(O)=>{let J=O.req.param("provider");try{let Z=await R1(J);return O.json(Z)}catch(Z){return b1.error("[ProviderRoutes] Failed to list models:",Z),O.json([])}}),$.put("/:provider/credential",async(O)=>{let J=O.req.param("provider"),Z=await O.req.json();if(!Z.apiKey?.trim())throw new _("apiKey is required");return await f0().setApiKey(J,Z.apiKey.trim()),O.json({success:!0})}),$.delete("/:provider/credential",async(O)=>{return await f0().clearCredential(O.req.param("provider")),O.json({success:!0})}),$.put("/:provider",async(O)=>{let J=O.req.param("provider"),Z=o(),Y=Z?.modelProviders[J];if(!Z||!Y)throw new I("Model provider",J);let X=await O.req.json();if(!X.name||!X.baseUrl||!X.wireApi)throw new _("name, baseUrl and wireApi are required");let K="apiKeyEnv"in X?X.apiKeyEnv?.trim():Y.apiKeyEnv,N={name:X.name,baseUrl:X.baseUrl,wireApi:X.wireApi,...K?{apiKeyEnv:K}:{}},W=f0(),H=X.apiKey?.trim()?await W.credentials.read(J):void 0;if(X.apiKey?.trim())await W.setApiKey(J,X.apiKey.trim());try{return await G0().updateModelProvider(J,N),O.json({success:!0})}catch(E){if(X.apiKey?.trim())if(H)await W.credentials.modify(J,async()=>H);else await W.credentials.delete(J);if(E instanceof Error&&(E.message.includes("modelProviders.")||E.message.includes("built-in provider")))throw new _(E.message);throw E}}),$.delete("/:provider",async(O)=>{let J=O.req.param("provider");if(!o()?.modelProviders[J])throw new I("Model provider",J);let Y=O.req.query("removeModels");if(Y!==void 0&&Y!=="true"&&Y!=="false")throw new _("removeModels must be true or false");try{let X=await G0().removeModelProvider(J,{removeModels:Y==="true"});return O.json({success:!0,...X})}catch(X){if(X instanceof Error&&(X.message.includes("still referenced")||X.message.includes("owns the only model")))throw new j(X.message);throw X}}),$.post("/:provider/probe",async(O)=>{let J=O.req.param("provider"),Z=o();if(!Z?.modelProviders[J])throw new I("Model provider",J);let Y=await O.req.json().catch(()=>({})),X=Z.models.filter((N)=>N.provider===J),K=Y.modelId?X.find((N)=>N.id===Y.modelId):X[0];if(!K)throw new _(Y.modelId?"modelId does not reference this provider":"Model provider has no configured model to probe");return O.json(await C1(K,Z))}),$};import{Hono as D2}from"hono";var _2=u("Service"),P1=($,O)=>{let J=new D2;return J.onError((Z,Y)=>{if(Z instanceof s)return Y.json(Z.toObject(),Z.statusCode);return _2.error("[ScheduleRoutes] Unhandled route error:",Z),Y.json(new d("Schedule request failed").toObject(),500)}),J.get("/",async(Z)=>{let Y=await $.list();return Z.json(f1.parse({schedules:Y}))}),J.post("/",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let X=f(k1,Y);if(!X.success)throw new _("Invalid schedule request");let K=X.data.projectPath||Z.get("directory")||g();try{let N=await $.create({...X.data,projectPath:K});return Z.json(y0.parse(N),201)}catch(N){throw new _(N instanceof Error?N.message:"Failed to create schedule")}}),J.get("/:id",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new I("Schedule not found");return Z.json(y0.parse(Y))}),J.patch("/:id",async(Z)=>{let Y;try{Y=await Z.req.json()}catch{throw new _("Invalid request body")}let X=f(I1,Y);if(!X.success)throw new _("Invalid schedule update");let{modelId:K,reasoningEffort:N,serviceTier:W,responseVerbosity:H,communicationStyle:E,isolation:C,permissionMode:T,...c}=X.data,r={...K!==void 0?{modelId:K}:{},...N!==void 0?{reasoningEffort:N}:{},...W!==void 0?{serviceTier:W}:{},...H!==void 0?{responseVerbosity:H}:{},...E!==void 0?{communicationStyle:E}:{},...C!==void 0?{isolation:C}:{},...T!==void 0?{permissionMode:T}:{}};try{let L=await $.update(Z.req.param("id"),{...c,...Object.keys(r).length>0?{dispatch:r}:{}});if(!L)throw new I("Schedule not found");return Z.json(y0.parse(L))}catch(L){if(L instanceof s)throw L;throw new _(L instanceof Error?L.message:"Failed to update schedule")}}),J.delete("/:id",async(Z)=>{if(!await $.remove(Z.req.param("id")))throw new I("Schedule not found");return Z.json({ok:!0})}),J.post("/:id/enable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!0);if(!Y)throw new I("Schedule not found");return Z.json(y0.parse(Y))}),J.post("/:id/disable",async(Z)=>{let Y=await $.setEnabled(Z.req.param("id"),!1);if(!Y)throw new I("Schedule not found");return Z.json(y0.parse(Y))}),J.post("/:id/run",async(Z)=>{let Y=await $.get(Z.req.param("id"));if(!Y)throw new I("Schedule not found");if(!O)throw new d("Scheduler is not running in this process");await O.fire(Y,new Date,{manual:!0});let X=await $.get(Y.id);return Z.json(y0.parse(X??Y),202)}),J};import*as j0 from"node:fs/promises";import{homedir as h1}from"node:os";import*as _0 from"node:path";import{Hono as H2}from"hono";var m0=u("Service"),S1=_0.join(h1(),".blade","skills"),n$=_0.join(h1(),".blade","skills-config.json");async function g1(){try{let $=await j0.readFile(n$,"utf-8");return JSON.parse($)}catch{return{disabled:[]}}}async function B2($){await j0.mkdir(_0.dirname(n$),{recursive:!0}),await j0.writeFile(n$,JSON.stringify($,null,2))}async function L2($,O){let J=await g1();if(O)J.disabled=J.disabled.filter((Z)=>Z!==$);else if(!J.disabled.includes($))J.disabled.push($);await B2(J)}var R0=null,w2=300000,A2=6;async function M2(){if(R0&&Date.now()-R0.timestamp<w2)return R0.data;try{let $=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!$.ok){if(m0.warn(`GitHub API returned ${$.status}`),R0)return R0.data;throw Error(`GitHub skills catalog returned ${$.status}`)}let J=(await $.json()).filter((K)=>K.type==="dir"),Z=Array(J.length),Y=0,X=Math.min(A2,J.length);return await Promise.all(Array.from({length:X},async()=>{while(Y<J.length){let K=Y++,N=J[K];if(!N)continue;let W=`Official ${N.name} skill`;try{let H=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${N.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(H.ok){let C=(await H.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(C)W=C[1].trim().slice(0,100)}}catch{}Z[K]={name:N.name,description:W,tag:"Official",author:"Anthropic"}}})),R0={data:Z,timestamp:Date.now()},Z}catch($){if(m0.warn("Failed to fetch skills catalog from GitHub:",$),R0)return R0.data;throw $}}var v1=()=>{let $=new H2;return $.get("/",async(O)=>{try{let J=O.get("directory")||g(),Y=(await x0(J)).skills.getAll(),X=await g1(),K=Y.map((N)=>({id:N.name,name:N.name,enabled:!X.disabled.includes(N.name),description:N.description||"",version:N.version||"1.0.0",provider:"Local",location:N.source==="builtin"?"Built-in":N.basePath,removable:N.source==="user"&&_0.dirname(_0.resolve(N.basePath))===_0.resolve(S1),capabilities:["prompts"],allowedTools:N.allowedTools||[]}));return O.json(K)}catch(J){return m0.error("[SkillsRoutes] Failed to get skills:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills"},500)}}),$.post("/:name/toggle",async(O)=>{try{let J=O.req.param("name"),Z=await O.req.json();return await L2(J,Z.enabled),O.json({success:!0,enabled:Z.enabled})}catch(J){return m0.error("[SkillsRoutes] Failed to toggle skill:",J),O.json({success:!1,error:J.message},500)}}),$.delete("/:name",async(O)=>{try{let J=O.req.param("name"),Z=O.get("directory")||g(),Y=(await x0(Z)).skills,X=Y.get(J);if(!X)return O.json({success:!1,error:"Skill not found"},404);let K=_0.resolve(X.basePath),N=_0.resolve(S1);if(X.source!=="user"||_0.dirname(K)!==N)return O.json({success:!1,error:"Only Blade user skills can be uninstalled"},400);return await j0.rm(K,{recursive:!0,force:!0}),await Y.refresh(),Y$(Z),await Z$(Z),O.json({success:!0})}catch(J){return m0.error("[SkillsRoutes] Failed to uninstall skill:",J),O.json({success:!1,error:J.message},500)}}),$.post("/install",async(O)=>{try{let J=await O.req.json(),Z=y1(),Y=O.get("directory")||g(),X=m1({cwd:Y}),K=!1;if(J.source==="catalog"&&J.name){if(K=await Z.installOfficialSkill(J.name),!K)return O.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(J.source==="repo"&&J.url){if(K=await Z.installFromRepo(J.url,J.name),!K)return O.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(J.source==="local"&&J.path){if(K=await Z.installFromLocal(J.path,J.name),!K)return O.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return O.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await X.refresh(),Y$(Y),await Z$(Y),O.json({success:!0})}catch(J){return m0.error("[SkillsRoutes] Failed to install skill:",J),O.json({success:!1,error:J.message},500)}}),$.get("/catalog",async(O)=>{try{let J=await M2();return O.json(J)}catch(J){return m0.error("[SkillsRoutes] Failed to get catalog:",J),O.json({error:J instanceof Error?J.message:"Failed to get skills catalog"},502)}}),$};import{execSync as q2}from"node:child_process";import{readdir as E2}from"node:fs/promises";import b$ from"node:path";import b2 from"fast-glob";import{Hono as C2}from"hono";var K$=u("Service"),T2=($)=>{try{return q2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},R2=[...n0.map(($)=>`${$}/**`),...n0,...n0.map(($)=>`**/${$}/**`),...n0.map(($)=>`**/${$}`),...t$.map(($)=>`**/${$}`)],j2=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),d1=()=>{let $=new C2;return $.get("/commands",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||g();await x0(Z);let Y=u1(J,Z).filter((X)=>!j2.has(X.command));return O.json(Y)}catch(J){return K$.error("[SuggestionsRoutes] Failed to get command suggestions:",J),O.json([])}}),$.get("/files",async(O)=>{try{let J=O.req.query("q")||"",Z=O.get("directory")||g(),Y=Math.min(Number(O.req.query("limit"))||100,1000),X=O.req.query("type")==="file",N=(await b2("**/*",{cwd:Z,dot:!1,followSymbolicLinks:!1,onlyFiles:X,markDirectories:!0,unique:!0,ignore:R2})).map((E)=>E.replace(/\\/g,"/"));if(!J)return O.json(N.slice(0,Y));let W=J.toLowerCase(),H=N.filter((E)=>E.toLowerCase().includes(W)).slice(0,Y);return O.json(H)}catch(J){return K$.error("[SuggestionsRoutes] Failed to get file suggestions:",J),O.json([])}}),$.get("/files/tree",async(O)=>{try{let J=O.get("directory")||g(),Z=O.req.query("path")||"",Y=Z?b$.join(J,Z):J,K=(await E2(Y,{withFileTypes:!0})).map((H)=>({name:H.name,path:Z?`${Z}/${H.name}`:H.name,type:H.isDirectory()?"dir":"file"}));K.sort((H,E)=>{if(H.type!==E.type)return H.type==="dir"?-1:1;return H.name.localeCompare(E.name)});let N=new Set(n0),W=K.filter((H)=>{let E=H.name;if(E.startsWith("."))return!1;if(N.has(E))return!1;for(let C of t$)if(E.match(new RegExp(C.replace("*",".*"))))return!1;return!0});return O.json(W)}catch(J){return K$.error("[SuggestionsRoutes] Failed to get file tree:",J),O.json([])}}),$.get("/files/content",async(O)=>{try{let J=O.req.query("path");if(!J)return O.json({error:"Missing file path"},400);let Z=O.get("directory")||g(),Y=b$.resolve(Z,J),X=b$.relative(Z,Y);if(X.startsWith("..")||b$.isAbsolute(X))return O.json({error:"Invalid file path"},400);let K=p1(),N=await K.stat(Y);if(!N?.isFile)return O.json({error:"File not found"},404);let W=200000,H=await K.readTextFile(Y),E=H.length>W;return O.json({path:J,content:E?H.slice(0,W):H,truncated:E,size:N.size})}catch(J){return K$.error("[SuggestionsRoutes] Failed to get file content:",J),O.json({error:"Failed to read file"},500)}}),$.get("/git-info",async(O)=>{try{let J=O.get("directory")||g(),Z=T2(J);return O.json({branch:Z})}catch(J){return K$.error("[SuggestionsRoutes] Failed to get git info:",J),O.json({branch:null})}}),$};import{Hono as k2}from"hono";var V$=u("Service"),o1=($)=>{let O=new k2;return O.onError((J,Z)=>{if(J instanceof s)return Z.json(J.toObject(),J.statusCode);return V$.error("[TaskRoutes] Unhandled route error:",J),Z.json(new d("Failed to dispatch task").toObject(),500)}),O.post("/",async(J)=>{let Z;try{Z=await J.req.json()}catch{throw new _("Invalid request body")}let Y=f(i1,Z);if(!Y.success)throw new _("Invalid task request");if((Y.data.attachments??[]).reduce((K,N)=>K+(typeof N.content==="string"?Buffer.byteLength(N.content):0),0)>M$)throw new _("Task attachments exceed the 5 MiB limit");try{let K=await $.dispatchTask({prompt:Y.data.prompt,title:Y.data.title,sourceProjectPath:Y.data.projectPath||J.get("directory")||g(),isolation:Y.data.isolation,permissionMode:Y.data.permissionMode,modelId:Y.data.modelId,reasoningEffort:Y.data.reasoningEffort,serviceTier:Y.data.serviceTier,responseVerbosity:Y.data.responseVerbosity,communicationStyle:Y.data.communicationStyle,attachments:Y.data.attachments,outputSchema:Y.data.outputSchema});return J.json(s$.parse(K),202)}catch(K){if(K instanceof _||K instanceof j||K instanceof v0)throw K;throw V$.error("[TaskRoutes] Failed to dispatch task:",K),new d("Failed to dispatch task")}}),O.post("/:sessionId/retry",async(J)=>{try{let Z=await $.retryTask(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(s$.parse(Z),202)}catch(Z){if(Z instanceof _||Z instanceof I||Z instanceof j||Z instanceof v0)throw Z;throw V$.error("[TaskRoutes] Failed to retry task:",Z),new d("Failed to retry task")}}),O.get("/:sessionId/diff",async(J)=>{try{let Z=await $.getTaskDiff(J.req.param("sessionId"),J.req.query("projectPath"));return J.json(l1.parse(Z))}catch(Z){if(Z instanceof _||Z instanceof I||Z instanceof j)throw Z;throw V$.error("[TaskRoutes] Failed to load task diff:",Z),new d("Failed to load task diff")}}),O.post("/:sessionId/delivery",async(J)=>{let Z;try{Z=await J.req.json()}catch{throw new _("Invalid request body")}let Y=f(a1,Z);if(!Y.success)throw new _("Invalid task delivery request");try{let X=await $.deliverTask(J.req.param("sessionId"),Y.data.action,J.req.query("projectPath"));return J.json(c1.parse(X))}catch(X){if(X instanceof _||X instanceof I||X instanceof j)throw X;throw V$.error("[TaskRoutes] Failed to deliver task:",X),new d("Failed to deliver task")}}),O};import{Hono as I2}from"hono";var k0=u("Service"),t0=new Map,n1=2097152,t1=65536;function s1(){return typeof globalThis.Bun<"u"}async function f2($,O,J){if(s1()){let{spawn:X}=await import("bun-pty"),K=X($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env});return{pid:K.pid,write:(N)=>K.write(N),resize:(N,W)=>K.resize(N,W),kill:()=>K.kill(),onData:(N)=>K.onData(N),onExit:(N)=>K.onExit(N)}}let Y=(await import("node-pty")).spawn($,O,{name:"xterm-256color",cwd:J.cwd,env:J.env,cols:80,rows:24});return{pid:Y.pid,write:(X)=>Y.write(X),resize:(X,K)=>Y.resize(X,K),kill:()=>Y.kill(),onData:(X)=>{Y.onData(X)},onExit:(X)=>{Y.onExit(X)}}}var $O=void 0,e$;if(s1())try{let{createBunWebSocket:$}=await import("hono/bun"),O=$();e$=O.upgradeWebSocket,$O=O.websocket}catch($){k0.warn("[Terminal] Failed to initialize Bun WebSocket support:",$)}async function r1($,O){let J=`term-${Date.now()}`;k0.info(`[Terminal] New connection: ${J}, cwd: ${$}`);let Z=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",Y=Z.endsWith("sh")?["-l"]:[],X=await f2(Z,Y,{cwd:$,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),K={id:J,process:X,cwd:$,buffer:"",subscribers:new Set};if(t0.set(J,K),K.subscribers.add(O),X.onData((N)=>{let W=!1;for(let H of K.subscribers)try{H.send(N),W=!0}catch{K.subscribers.delete(H)}if(W)return;if(K.buffer+=N,K.buffer.length>n1)K.buffer=K.buffer.slice(-n1)}),X.onExit(({exitCode:N})=>{k0.info(`[Terminal] Process exited: ${J}, code: ${N}`);for(let W of K.subscribers)try{W.close()}catch{}t0.delete(J)}),K.buffer){let N=K.buffer;K.buffer="";for(let W=0;W<N.length;W+=t1)O.send(N.slice(W,W+t1))}return{session:K,cleanup:()=>{if(k0.info(`[Terminal] Connection closed: ${J}`),K.subscribers.delete(O),K.subscribers.size===0){try{K.process.kill()}catch{}t0.delete(J)}}}}function e1($,O){$.on("connection",async(J,Z)=>{let Y=new URL(Z.url||"/",`http://${Z.headers.host}`);if(!Y.pathname.endsWith("/terminal/ws")){J.close();return}let X=Y.searchParams.get("cwd")||O()||g();try{let{session:K,cleanup:N}=await r1(X,{send:(W)=>J.send(W),close:()=>J.close()});J.on("message",(W)=>{try{K.process.write(String(W))}catch(H){k0.error("[Terminal] Failed to write to PTY:",H)}}),J.on("close",N),J.on("error",N)}catch(K){k0.error("[Terminal] Failed to spawn PTY:",K),J.close()}})}var $4=()=>{let $=new I2;if($.get("/status",(O)=>{let J=Array.from(t0.values()).map((Z)=>({id:Z.id,cwd:Z.cwd}));return O.json({active:J.length,terminals:J})}),$.post("/kill/:terminalId",(O)=>{let J=O.req.param("terminalId"),Z=t0.get(J);if(Z){try{Z.process.kill()}catch{}for(let Y of Z.subscribers)Y.close();return t0.delete(J),O.json({success:!0})}return O.json({success:!1,error:"Terminal not found"},404)}),e$)$.get("/ws",e$((O)=>{let J=O.req.query("cwd")||O.get("directory")||g(),Z;return{async onOpen(Y,X){try{Z=await r1(J,{send:(K)=>X.send(K),close:()=>X.close()})}catch(K){k0.error("[Terminal] Failed to spawn PTY:",K),X.close()}},onMessage(Y){if(!Z)return;try{Z.session.process.write(String(Y.data))}catch(X){k0.error("[Terminal] Failed to write to PTY:",X)}},onClose(){Z?.cleanup()}}}));else $.get("/ws",(O)=>{return O.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return $};import P2 from"node:path";import{Hono as S2}from"hono";var y2=U.Object({projectPath:U.String({minLength:1}),action:Y0(["trust","revoke"])});function O4($){if(!P2.isAbsolute($))throw new _("projectPath must be absolute")}var Z4=()=>{let $=new S2;return $.get("/",async(O)=>{let J=O.req.query("projectPath");if(!J)throw new _("projectPath query parameter is required");return O4(J),O.json(await OO.getInstance().getStatus(J))}),$.post("/",async(O)=>{let J=f(y2,await O.req.json());if(!J.success)throw new _("Invalid workspace trust request");let{projectPath:Z,action:Y}=J.data;O4(Z);let X=OO.getInstance(),K=Y==="trust"?await X.trust(Z):await X.revoke(Z);return await J4(),O.json({...K,reloadRequired:K.sensitiveSources>0})}),$};var J0=u("Service"),YO=[],N$,s0,r0,Y4=new Map,z4=new Map,o2=new Set([".css",".html",".js",".json",".svg"]),n2=1024,t2=3600000;function s2($,O){if(!$)return 0;let J=$.split(",").map((Z)=>{let[Y,...X]=Z.trim().toLowerCase().split(";"),K=X.find((W)=>W.trim().startsWith("q=")),N=K?Number(K.trim().slice(2)):1;return{name:Y,quality:Number.isFinite(N)?Math.max(0,Math.min(1,N)):0}});return J.find((Z)=>Z.name===O)?.quality??J.find((Z)=>Z.name==="*")?.quality??0}function Q4(){if(r0)return;let $=()=>{R.collectStaleEmptySessions().then((O)=>{if(O>0)J0.info(`[SessionGC] removed ${O} stale empty session(s)`)}).catch((O)=>{J0.warn("[SessionGC] failed to collect stale empty sessions:",O)})};$(),r0=setInterval($,t2),r0.unref?.()}function x4(){if(!r0)return;clearInterval(r0),r0=void 0}function r2($){return["br","gzip"].map((J)=>({encoding:J,quality:s2($,J)})).filter((J)=>J.quality>0).sort((J,Z)=>Z.quality-J.quality||(J.encoding==="br"?-1:1))[0]?.encoding}function e2($){let O=Y4.get($);if(O)return O;let J=G$($);return Y4.set($,J),J}function $5($,O,J){let Z=`${J}:${$}`,Y=z4.get(Z);if(Y)return Y;let X=J==="br"?u2(O,{params:{[l2.BROTLI_PARAM_QUALITY]:5}}):d2(O,{level:6});return z4.set(Z,X),X}function O5(){let $=g2(p2(import.meta.url)),O=[I0($,"web"),I0(g(),"dist/web"),I0(g(),"packages/cli/dist/web")];for(let J of O){let Z=I0(J,"index.html");if(ZO(Z)){if(G$(Z,"utf-8").includes("/assets/"))return J0.debug(`[Server] Found web dist at: ${J}`),J}}return null}function J5(){let $=new c2;$.onError((Z,Y)=>{if(J0.error("[Server] Request error:",Z),Z instanceof s)return Y.json(Z.toObject(),Z.statusCode);let X=Z instanceof Error?Z.message:String(Z);return Y.json({error:{code:"INTERNAL_ERROR",message:X}},500)}),$.use(async(Z,Y)=>{let X=process.env.BLADE_SERVER_PASSWORD;if(!X)return Y();let K=Z.req.path;if(K==="/"||K==="/favicon.svg"||K.startsWith("/assets/")||K.endsWith(".html")||K.endsWith(".js")||K.endsWith(".css"))return Y();let N=Z.req.header("Authorization");if(!N?.startsWith("Basic "))return Z.header("WWW-Authenticate",'Basic realm="Blade Server"'),Z.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let W=Buffer.from(N.slice(6),"base64").toString(),[H,E]=W.split(":"),C=process.env.BLADE_SERVER_USERNAME??"blade";if(H!==C||E!==X)return Z.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return Y()}),$.use(async(Z,Y)=>{let X=Z.req.path==="/health"||Z.req.path==="/global/health"||Z.req.path.startsWith("/assets/");if(!X)J0.debug(`[Server] ${Z.req.method} ${Z.req.path}`);let K=Date.now();if(await Y(),!X){let N=Date.now()-K;J0.debug(`[Server] ${Z.req.method} ${Z.req.path} - ${Z.res.status} (${N}ms)`)}}),$.use(i2({origin(Z){if(!Z)return;if(Z.startsWith("http://localhost:"))return Z;if(Z.startsWith("http://127.0.0.1:"))return Z;if(Z==="tauri://localhost"||Z==="http://tauri.localhost")return Z;if(YO.includes(Z))return Z;return}})),$.use(async(Z,Y)=>{let X=Z.req.query("directory")||Z.req.header("x-blade-directory")||g();try{X=decodeURIComponent(X)}catch{}return Z.set("directory",X),Y()});let O=Q1();N$=O.recoverQueuedTasks,s0=new j$({dispatch:(Z)=>O.dispatchTask(Z),store:JO}),$.route("/global",BO()),$.route("/events",_O()),$.route("/sessions",O.app),$.route("/tasks",o1(O)),$.route("/schedules",P1(JO,s0)),$.route("/configs",DO()),$.route("/permissions",X1()),$.route("/plugins",A1()),$.route("/hooks",EO()),$.route("/workspace-trust",Z4()),$.route("/providers",j1()),$.route("/models",PO()),$.route("/projects",E1()),$.route("/suggestions",d1()),$.route("/terminal",$4()),$.route("/mcp",TO()),$.route("/skills",v1()),$.get("/health",(Z)=>{return Z.json({healthy:!0,version:p0()})});let J=O5();if(J)J0.info(`[Server] Serving static files from ${J}`),$.get("/favicon.svg",()=>{let Z=I0(J,"favicon.svg");if(!ZO(Z))return new Response(null,{status:404});return new Response(G$(Z),{headers:{"Content-Type":"image/svg+xml","Cache-Control":"public, max-age=86400"}})}),$.get("/assets/*",(Z)=>{let Y=I0(J,Z.req.path);if(!ZO(Y))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Z.req.path}`}},404);let X=e2(Y),K=v2(Y).toLowerCase(),W={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[K]||"application/octet-stream",H=o2.has(K)&&X.byteLength>=n2?r2(Z.req.header("Accept-Encoding")):void 0,E=H?$5(Y,X,H):X;return new Response(new Uint8Array(E),{headers:{"Content-Type":W,"Content-Length":String(E.byteLength),"Cache-Control":"public, max-age=31536000, immutable",Vary:"Accept-Encoding",...H?{"Content-Encoding":H}:{}}})}),$.get("/",(Z)=>{let Y=I0(J,"index.html"),X=G$(Y,"utf-8");return Z.html(X,200,{"Cache-Control":"no-cache"})}),$.get("*",(Z)=>{let Y=Z.req.path;if(Y.includes("."))return Z.json({error:{code:"NOT_FOUND",message:`File not found: ${Y}`}},404);let X=I0(J,"index.html"),K=G$(X,"utf-8");return Z.html(K,200,{"Cache-Control":"no-cache"})});else J0.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),$.get("/",(Z)=>{return Z.json({message:"Blade API Server",version:p0(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),$.all("*",(Z)=>{return Z.json({error:{code:"NOT_FOUND",message:`Route not found: ${Z.req.path}`}},404)});return $}function Z5(){let $=h2(),O=[];for(let J of Object.keys($)){let Z=$[J];if(!Z)continue;for(let Y of Z){if(Y.internal||Y.family!=="IPv4")continue;if(Y.address.startsWith("172."))continue;O.push(Y.address)}}return O}function X4(){return typeof globalThis.Bun<"u"}function K4($,O){let J=globalThis.Bun,Z=(X)=>{try{return J.serve({hostname:O.hostname,port:X,fetch:$.fetch,idleTimeout:0,websocket:$O})}catch(K){J0.error("Failed to start Bun server:",K);return}},Y=O.port===0?Z(4096)??Z(0):Z(O.port);if(!Y)throw Error(`Failed to start Bun server on port ${O.port}`);return{url:Y.url,port:Y.port,hostname:Y.hostname,stop:async()=>{Y.stop(!0)}}}function Y5($,O){return new Promise((J,Z)=>{let Y=m2(async(H,E)=>{let C=new URL(H.url||"/",`http://${H.headers.host}`),T=new Headers;for(let[L,a]of Object.entries(H.headers))if(a)if(Array.isArray(a))for(let m of a)T.append(L,m);else T.set(L,a);let c;if(H.method!=="GET"&&H.method!=="HEAD")c=(await new Promise((a)=>{let m=[];H.on("data",(O0)=>m.push(O0)),H.on("end",()=>a(Buffer.concat(m)))})).toString();let r=new Request(C.toString(),{method:H.method,headers:T,body:c});try{let L=await $.fetch(r);if(E.statusCode=L.status,L.headers.forEach((a,m)=>{E.setHeader(m,a)}),L.body){let a=L.body.getReader(),m=async()=>{let{done:O0,value:Q0}=await a.read();if(O0){E.end();return}return E.write(Q0),m()};await m()}else{let a=await L.text();E.end(a)}}catch(L){J0.error("[Server] Node request error:",L),E.statusCode=500,E.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),X=new a2({noServer:!0}),K=g();e1(X,()=>K),Y.on("upgrade",(H,E,C)=>{if(new URL(H.url||"/",`http://${H.headers.host}`).pathname==="/terminal/ws")X.handleUpgrade(H,E,C,(c)=>{X.emit("connection",c,H)});else E.destroy()});let N=(H)=>{return new Promise((E,C)=>{Y.once("error",(T)=>{if(T.code==="EADDRINUSE")C(T);else C(T)}),Y.listen(H,O.hostname,()=>{let T=Y.address();if(T&&typeof T==="object")E(T.port);else E(H)})})};(async()=>{let H;if(O.port===0)try{H=await N(4096)}catch{H=await N(0)}else H=await N(O.port);let E=new URL(`http://${O.hostname==="0.0.0.0"?"localhost":O.hostname}:${H}`);J({url:E,port:H,hostname:O.hostname,stop:async()=>{return new Promise((C)=>{X.close(()=>{Y.close(()=>C())})})}})})().catch(Z)})}var V4;((V6)=>{let $,O;function J(){if(!O)O=J5();return O}V6.getApp=J;function Z(K){YO=K.cors??[];let N=J();if(X4())$=K4(N,K),J0.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let W=$;return N$?.().catch((H)=>{J0.warn("[Server] Failed to recover queued tasks:",H)}),s0?.start(),Q4(),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if($)s0?.stop(),x4(),await $.stop(),$=void 0,O=void 0,N$=void 0,J0.info("[Server] Blade server stopped")}}}V6.listen=Z;async function Y(K){YO=K.cors??[];let N=J();if(X4())$=K4(N,K),J0.info(`[Server] Blade server listening on ${$.url} (Bun runtime)`);else $=await Y5(N,K),J0.info(`[Server] Blade server listening on ${$.url} (Node.js runtime)`);let W=$;try{await N$?.()}catch(H){J0.warn("[Server] Failed to recover queued tasks:",H)}return s0?.start(),Q4(),{url:W.url,port:W.port,hostname:W.hostname,stop:async()=>{if($)s0?.stop(),x4(),await $.stop(),$=void 0,O=void 0,N$=void 0,J0.info("[Server] Blade server stopped")}}}V6.listenAsync=Y;function X(){return $!==void 0}V6.isRunning=X})(V4||={});export{z5 as f,Q5 as g,Z5 as h,V4 as i};
@@ -1 +0,0 @@
1
- import{Cc as a,Dc as b}from"./chunk-y0c3knp9.js";import"./chunk-1pjvzcrj.js";import"./chunk-z3kc23wz.js";export{a as globalOptions,b as cliConfig};
@@ -1 +0,0 @@
1
- import{Wd as a,Xd as b,Yd as c,Zd as d,_d as e}from"./chunk-q24xmkqy.js";import"./chunk-0vsaphkr.js";import"./chunk-eeg6jn2c.js";import"./chunk-bmxzx4xg.js";import"./chunk-14hspehn.js";import"./chunk-k6gsac91.js";import"./chunk-z4d3t2bb.js";import"./chunk-b9akah7k.js";import"./chunk-j4gvwm9w.js";import"./chunk-wzxkfpec.js";import"./chunk-sp1j3ng5.js";import"./chunk-d893y03w.js";import"./chunk-1c4j6q7j.js";import"./chunk-cx5daedg.js";import"./chunk-1pjvzcrj.js";import"./chunk-39yvdt2g.js";import"./chunk-76fnqb4r.js";import"./chunk-00ta2sme.js";import"./chunk-z3kc23wz.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
@@ -1,22 +0,0 @@
1
- import{r as E}from"./chunk-ezarz0ye.js";import{s as YJ}from"./chunk-1zsz19bn.js";import{$ as o,F as m,I as d,J as l,L as i,Z as r,_ as a,aa as n,v as A}from"./chunk-z2kfx8g0.js";import{ka as WJ}from"./chunk-gwxwpwqk.js";import"./chunk-emwawshv.js";import{$a as p,Ma as c,ib as v}from"./chunk-a09g8k55.js";import{tb as T}from"./chunk-4dnvydyv.js";import{Mb as f,Xb as M,Yb as u,_b as R,bc as g,gc as N,jc as D}from"./chunk-kbpg9amg.js";import"./chunk-600hfjag.js";import"./chunk-e1r2zqv3.js";import"./chunk-7v0w3625.js";import"./chunk-v508x7cg.js";import{od as ZJ}from"./chunk-ymgnh4an.js";import"./chunk-17k72zar.js";import"./chunk-18ck4nnw.js";import{zd as $J}from"./chunk-h79p49hc.js";import"./chunk-jvg2vnc3.js";import"./chunk-q24xmkqy.js";import"./chunk-0vsaphkr.js";import{ee as zJ}from"./chunk-eeg6jn2c.js";import"./chunk-bmxzx4xg.js";import"./chunk-14hspehn.js";import"./chunk-k6gsac91.js";import"./chunk-z4d3t2bb.js";import"./chunk-b9akah7k.js";import"./chunk-j4gvwm9w.js";import{mf as I,nf as S,of as y}from"./chunk-wzxkfpec.js";import{sf as e}from"./chunk-sp1j3ng5.js";import{wf as b}from"./chunk-d893y03w.js";import"./chunk-1c4j6q7j.js";import{Df as JJ,Gf as QJ}from"./chunk-cx5daedg.js";import"./chunk-1pjvzcrj.js";import"./chunk-39yvdt2g.js";import"./chunk-76fnqb4r.js";import"./chunk-00ta2sme.js";import"./chunk-z3kc23wz.js";import{Readable as VJ,Writable as wJ}from"node:stream";import*as x from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as BJ}from"@agentclientprotocol/sdk";import s from"node:path";import{RequestError as GJ}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var j=b("Agent");function C(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function XJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:C(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:C("headers"in J?J.headers:void 0)};return null}function jJ(J){let Z={};for(let Q of J){let Y=XJ(Q);if(Y)Z[Q.name]=Y}return Z}function t(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function DJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:M(Z)}]:t(J.content)}function LJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}mapPermissionModeToMode(J){switch(J){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return i.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?jJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await m.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(G)=>$.onOutput?.("stdout",G)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.error==="Command timed out",aborted:F.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await a(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=c.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of DJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);j.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async($)=>{if(await this.setServiceTier($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async($)=>{if(await this.setResponseVerbosity($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async($)=>{if(await this.setCommunicationStyle($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=!1,X,L=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},B=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(G)L(W);else X=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.session.id,status:"in_progress",title:`Resuming ${B.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${B.source.id} at depth ${B.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),G=!0,X)L(X);return B}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,G)},complete:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,G)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(B)=>{if(B.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.toolCall.id,status:"in_progress",title:`Review: ${B.toolCall.function.name}`,content:[],kind:this.mapToolKind(B.toolKind)});else if(B.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.toolCall.id,status:B.result.success?"completed":"failed",content:[]})}}),X=await G.completion,L=(await E.list(this.cwd,this.id)).find((B)=>B.start.reviewId===G.reviewId);if(!L)throw Error(`Review not found: ${G.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:G.reviewId,status:X.status,findings:X.findings.length,content:f(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,G)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(G);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:L})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await o(J,Q),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(Q){return j.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=n(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),j.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((G)=>G.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=g(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let G=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!G.accepted)throw Error(G.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${G.queued})`),G.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),r(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let G={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}},X=await p(this.agent.chatStream(Y,G,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let w=W.toolCall,_=w.function.name;if(_===R)break;let q=this.mapToolKind(W.toolKind),V=`Executing ${_}`;if(_==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:q});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let _=W.result,q=[],V=_.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;q.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))q.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,HJ=l(d(K,_));q.push({type:"content",content:{type:"text",text:HJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=_.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:q});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
3
- `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
4
- `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
5
- `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
6
- `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
7
- `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
8
- `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
9
- `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
10
- `}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:W.phase,attempt:W.attempt,maxRetries:W.maxRetries,reason:W.reason,...W.statusCode!==void 0?{statusCode:W.statusCode}:{},...W.delayMs!==void 0?{delayMs:W.delayMs}:{},...W.nextRetryAt!==void 0?{nextRetryAt:W.nextRetryAt}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:W.phase,stallCount:W.stallCount,durationMs:W.durationMs,warningAfterMs:W.warningAfterMs,timeoutMs:W.timeoutMs,outputStarted:W.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:W.phase,toolName:W.toolName,runLength:W.runLength,nudgeThreshold:W.nudgeThreshold,haltThreshold:W.haltThreshold,progressAware:W.progressAware}}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let w of W.messages){if(!w.recovered||w.persisted)continue;for(let _ of t(w.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:_})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
11
- `}});break;case"goal_updated":if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
12
- `}});break;case"goal_continuation_started":break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:W.phase,...W.reason?{reason:W.reason}:{},...W.strategy?{strategy:W.strategy}:{},...W.outcome?{outcome:W.outcome}:{},...W.preTokens!==void 0?{preTokens:W.preTokens}:{},...W.postTokens!==void 0?{postTokens:W.postTokens}:{}}}});break;default:break}});this.contextMessages=[...G.messages];let L=await D.loadSession(this.id,this.cwd);if(this.messages=L.length>0?L:[...G.messages],!X.success){let W=X.error?.type??"unknown";throw GJ.internalError({failureType:W},`Agent turn failed (${W})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let B={...X.metadata?.structuredOutput?{structuredOutput:X.metadata.structuredOutput,outputSchemaDigest:X.metadata.structuredOutputSchemaDigest}:{},...X.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:X.metadata.goalVerificationVerdict,...X.metadata.goalVerifierSessionId?{verifierSessionId:X.metadata.goalVerifierSessionId}:{},...X.metadata.goalVerificationEvidenceSha256?{evidenceSha256:X.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(B).length>0?{_meta:B}:{}}}catch(G){if(F.signal.aborted||G instanceof Error&&G.name==="AbortError")return{stopReason:"cancelled"};throw j.error(`[AcpSession ${this.id}] Prompt error:`,G),G}finally{if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let Y,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async(F)=>{if(Y=F.executionId,F.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.executionId,status:"in_progress",title:`! ${F.command}`,content:[],kind:"execute"});return}if(F.type==="output"){H+=F.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:F.chunk}}]});return}let G=M(F.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:F.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?LJ(F.record):G}}]})}}),$={role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}};if(this.messages.push($),this.contextMessages.push($),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){j.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)j.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",Y=this.mapModeIdToPermissionMode(Q);await D.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=Q,j.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(j.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await D.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof N)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof N)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof N)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof N)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await D.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(Y){if(!(Y instanceof N)&&Y.code!=="ENOENT")throw Y;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,Y=async(H)=>{try{await H()}catch(z){Q??=z}};if(await Y(()=>this.cancel()),J)await Y(()=>J.destroy());if(Z)await Y(()=>Z.dispose());if(await Y(()=>A.destroySession(this.id)),j.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,H=0,z=0,$=(G)=>{if(Q.length>0)Q.push({type:"text",text:`
13
- `}),z+=1;if(Q.push(G),G.type==="text")z+=G.text.length};for(let G of J)if(G.type==="text")Z.push(G.text),$({type:"text",text:G.text});else if(G.type==="image"){let X=`data:${G.mimeType};base64,${G.data}`;Y+=1,H+=X.length,Z.push(`[Image: ${G.mimeType}]`),$({type:"image_url",image_url:{url:X}})}else if(G.type==="resource"){let X=G.resource;if("text"in X){let L=`<file path="${X.uri}">
14
- ${X.text}
15
- </file>`;Z.push(L),$({type:"text",text:L})}}else if(G.type==="resource_link"){let X=`[Resource: ${G.uri}]`;Z.push(X),$({type:"text",text:X})}if(Y>I)throw Error(`ACP prompt contains more than ${I} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>y)throw Error(`ACP prompt text exceeds ${y} characters`);let F=Z.join(`
16
- `);return{content:Y>0?Q:F,displayText:F}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{j.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));j.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return j.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return j.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=h(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
17
- - ${J.risks.join(`
18
- - `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},F=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!F)return{approved:!1,reason:T};let G=F.outcome;if(G.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let X=G.optionId;if(X==="allow_always")return{approved:!0,scope:"project"};if(X==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=X==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(Y){return j.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[H,z]of Q.entries()){let $=z.options.map((L,B)=>`answer:${H}:${B}`),F=`answer:${H}:cancel`,G=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((L,B)=>({optionId:$[B],name:L.label,kind:"allow_once"})),{optionId:F,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((L)=>`${L.label}: ${L.description}`)].join(`
19
- `)}}]}}),Z);if(!G)return{approved:!1,reason:T};if(G.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let X=$.indexOf(G.outcome.optionId);if(X<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[z.header]=z.options[X].label}return{approved:!0,answers:Y}}catch(H){return j.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
- `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)Y[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return j.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),Y=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
21
- `),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Y==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===Y);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
22
- `),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,Y){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,Y)=>{let H=!1,z=(F)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),F()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((F)=>z(()=>Q(F)),(F)=>z(()=>Y(F)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var U=b("Agent");class k{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return U.info("[BladeAgent] Initializing ACP connection"),U.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:BJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=ZJ("acp"),Q=J.cwd||e(),Y=J._meta?.["blade/taskIsolation"],H=Y==="local"||Y==="worktree"?Y:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await YJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,F=$?.metadata.projectPath??Q;U.info(`[BladeAgent] Creating new session: ${Z}`),U.debug(`[BladeAgent] Session cwd: ${F}`);let G=new O(Z,F,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await G.initialize(),this.assertNotDestroyed()}catch(X){throw await G.destroy().catch(()=>{return}),X}return this.sessions.set(Z,G),U.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),G.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,G.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!s.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await D.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!s.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await D.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new O(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),U.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),Y=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,Y);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===Y)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await D.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,Y]=await Promise.all([D.loadSession(J.sessionId,J.cwd),D.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let H=new O(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:Y.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],Y=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){U.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)U.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else U.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){U.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")U.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&$J(J.value))U.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&QJ(J.value))U.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&JJ(J.value))U.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&zJ(J.value))U.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await WJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function eJ(){let J=wJ.toWeb(process.stdout),Z=VJ.toWeb(process.stdin),Q=x.ndJsonStream(J,Z);await new x.AgentSideConnection((H)=>new k(H),Q).closed}export{eJ as runAcpIntegration};
@@ -1 +0,0 @@
1
- import{$c as c,Zc as a,_c as b,ad as d,bd as e,cd as f,dd as g,ed as h,fd as i,gd as j,hd as k,id as l,jd as m,kd as n,ld as o,md as p,nd as q}from"./chunk-7v0w3625.js";import"./chunk-v508x7cg.js";import"./chunk-ymgnh4an.js";import"./chunk-z4d3t2bb.js";import"./chunk-b9akah7k.js";import"./chunk-j4gvwm9w.js";import"./chunk-wzxkfpec.js";import"./chunk-sp1j3ng5.js";import"./chunk-d893y03w.js";import"./chunk-1c4j6q7j.js";import"./chunk-cx5daedg.js";import"./chunk-1pjvzcrj.js";import"./chunk-39yvdt2g.js";import"./chunk-76fnqb4r.js";import"./chunk-00ta2sme.js";import"./chunk-z3kc23wz.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};