blade-code 0.10.32 → 0.10.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-6r89cn2n.js → chunk-00gwp388.js} +2 -2
  3. package/dist/{chunk-7xytd1h7.js → chunk-0kqp5z4v.js} +2 -2
  4. package/dist/{chunk-b0mha3tr.js → chunk-1142vwqa.js} +2 -2
  5. package/dist/{chunk-ntmfefxh.js → chunk-16449n3m.js} +2 -2
  6. package/dist/{chunk-mwae107k.js → chunk-1ep6bcpc.js} +1 -1
  7. package/dist/{chunk-3bhh4v42.js → chunk-1qj0qms6.js} +1 -1
  8. package/dist/chunk-2c8d4q3y.js +1 -0
  9. package/dist/{chunk-tx77qaz8.js → chunk-2gca6fvf.js} +2 -2
  10. package/dist/{chunk-s61wcay9.js → chunk-2sdbj0zz.js} +2 -2
  11. package/dist/{chunk-xh1y705a.js → chunk-3ctcv013.js} +2 -2
  12. package/dist/{chunk-80r40y6k.js → chunk-3j6bsp1q.js} +2 -2
  13. package/dist/{chunk-774excyf.js → chunk-58gk92k3.js} +1 -1
  14. package/dist/chunk-5f956qbf.js +1 -0
  15. package/dist/{chunk-r68y2q62.js → chunk-5knt529c.js} +2 -2
  16. package/dist/{chunk-rakyf5b7.js → chunk-5v642sh3.js} +2 -2
  17. package/dist/{chunk-w49crtzx.js → chunk-64f79ce5.js} +2 -2
  18. package/dist/{chunk-cdkrdsbw.js → chunk-7a8k7ck4.js} +1 -1
  19. package/dist/{chunk-g2gvcp09.js → chunk-7afbvxqt.js} +1 -1
  20. package/dist/{chunk-75y3mb0z.js → chunk-7ryqs453.js} +2 -2
  21. package/dist/chunk-87ge6dkk.js +2 -0
  22. package/dist/chunk-958rac3y.js +1 -0
  23. package/dist/{chunk-q4q0r97b.js → chunk-95jjpdh9.js} +2 -2
  24. package/dist/{chunk-7bpwnpfx.js → chunk-ag0z1q2q.js} +2 -2
  25. package/dist/chunk-ap5qpeh4.js +1 -0
  26. package/dist/{chunk-e66zyvph.js → chunk-b9y9mc7f.js} +1 -1
  27. package/dist/{chunk-2tb3qm3v.js → chunk-ba2dky3s.js} +1 -1
  28. package/dist/{chunk-799zdv81.js → chunk-bx99mx3k.js} +1 -1
  29. package/dist/{chunk-3ck3fxff.js → chunk-c23bewtt.js} +1 -1
  30. package/dist/chunk-c6fq52m9.js +1 -0
  31. package/dist/{chunk-bcs58pet.js → chunk-crwa61tq.js} +1 -1
  32. package/dist/{chunk-yekzckgm.js → chunk-d3gx05ph.js} +3 -3
  33. package/dist/{chunk-xhdm1b4g.js → chunk-d90tnjst.js} +1 -1
  34. package/dist/{chunk-c7b5wmpm.js → chunk-dsxjgty6.js} +2 -2
  35. package/dist/{chunk-7fgx7ztz.js → chunk-dvf4cfye.js} +1 -1
  36. package/dist/chunk-dvyv53nz.js +1 -0
  37. package/dist/chunk-ecsj4njh.js +1 -0
  38. package/dist/chunk-epyys9aw.js +6 -0
  39. package/dist/{chunk-azcjz03h.js → chunk-fb80q06q.js} +2 -2
  40. package/dist/{chunk-bmsv08sa.js → chunk-fjbptkh2.js} +2 -2
  41. package/dist/chunk-fw1fm9cn.js +2 -0
  42. package/dist/{chunk-fp1892aa.js → chunk-g0gqxn3c.js} +1 -1
  43. package/dist/{chunk-x0x5e65d.js → chunk-h34g9v9z.js} +1 -1
  44. package/dist/chunk-h3cvnbah.js +1 -0
  45. package/dist/{chunk-cjgnf6qy.js → chunk-jdms602t.js} +1 -1
  46. package/dist/chunk-jh6b81rb.js +10 -0
  47. package/dist/chunk-mr0xs5t4.js +22 -0
  48. package/dist/{chunk-wmsak7d3.js → chunk-mxffhqe5.js} +239 -239
  49. package/dist/{chunk-nah8b1gv.js → chunk-nq1wqpsx.js} +1 -1
  50. package/dist/chunk-p01t6c78.js +4 -0
  51. package/dist/{chunk-8y2nh9sm.js → chunk-pgy1mtgw.js} +1 -1
  52. package/dist/{chunk-y5rsamex.js → chunk-pnjftj8t.js} +2 -2
  53. package/dist/{chunk-fb514tmd.js → chunk-prqgpq92.js} +1 -1
  54. package/dist/{chunk-b0en9trj.js → chunk-qd7r2w39.js} +1 -1
  55. package/dist/chunk-qr8j2mr6.js +1 -0
  56. package/dist/{chunk-6gngfvwt.js → chunk-rjg5rq90.js} +1 -1
  57. package/dist/{chunk-jtk2t4wy.js → chunk-s1j86hhh.js} +19 -19
  58. package/dist/chunk-s3sv04hf.js +1 -0
  59. package/dist/{chunk-aspqajv2.js → chunk-sexhm0r5.js} +1 -1
  60. package/dist/{chunk-qgvgd1kq.js → chunk-sgyk3gq1.js} +2 -2
  61. package/dist/chunk-sjc7bm23.js +1 -0
  62. package/dist/{chunk-t23t9yff.js → chunk-t1z46fqz.js} +1 -1
  63. package/dist/chunk-tvrxzsna.js +1 -0
  64. package/dist/{chunk-b4xcn24b.js → chunk-v6x80gdg.js} +1 -1
  65. package/dist/{chunk-z1qa6vm5.js → chunk-vfecv6cv.js} +1 -1
  66. package/dist/chunk-vhpvt5v8.js +1 -0
  67. package/dist/{chunk-14zhd8qs.js → chunk-vqqxjgf2.js} +1 -1
  68. package/dist/chunk-wz6atg87.js +8 -0
  69. package/dist/{chunk-5mszemkz.js → chunk-y9a1jwnv.js} +2 -2
  70. package/dist/{chunk-7m4qc5vv.js → chunk-ysr3frmw.js} +1 -1
  71. package/dist/chunk-zp9p9tk6.js +1 -0
  72. package/dist/web/assets/{ChatView-D2g5ADlO.js → ChatView-B7_Um8KR.js} +2 -2
  73. package/dist/web/assets/{CodeBlockHighlighter-CheLBzlr.js → CodeBlockHighlighter-JzE91vkT.js} +1 -1
  74. package/dist/web/assets/{FilePreview-DWiuoQOM.js → FilePreview-BTbtoUBJ.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-C8h_WRI9.js → MarkdownRenderer-IaPtOh2w.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-CKIKFL6a.js → SettingsModal-CPgWPfZ2.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-DMaOLa_m.js → TaskSwitcher-D4RZxQKp.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-BXLKU2zU.js → TerminalPanel-yWbQfbYa.js} +1 -1
  79. package/dist/web/assets/{index-CxwsVMYL.js → index-BnCT8SxR.js} +8 -8
  80. package/dist/web/assets/{session-events-BZdQ71sF.js → session-events-BZao_jMQ.js} +20 -20
  81. package/dist/web/index.html +2 -2
  82. package/package.json +1 -1
  83. package/dist/chunk-191xtaca.js +0 -1
  84. package/dist/chunk-273ak5v8.js +0 -10
  85. package/dist/chunk-2969c7yb.js +0 -22
  86. package/dist/chunk-2jr254j7.js +0 -4
  87. package/dist/chunk-42ns4a92.js +0 -1
  88. package/dist/chunk-758hxypj.js +0 -2
  89. package/dist/chunk-9r0fxre0.js +0 -1
  90. package/dist/chunk-fd5dzcht.js +0 -1
  91. package/dist/chunk-gs18nx4h.js +0 -1
  92. package/dist/chunk-gy51z423.js +0 -1
  93. package/dist/chunk-hdje6ywy.js +0 -1
  94. package/dist/chunk-jdq05trf.js +0 -3
  95. package/dist/chunk-mspp2qpn.js +0 -1
  96. package/dist/chunk-qe49h8e0.js +0 -6
  97. package/dist/chunk-rzxk60wq.js +0 -1
  98. package/dist/chunk-sfhevsq1.js +0 -1
  99. package/dist/chunk-t23a5yvk.js +0 -1
  100. package/dist/chunk-txqctnca.js +0 -1
  101. package/dist/chunk-w0wzx47n.js +0 -1
  102. package/dist/chunk-x1r4b7pt.js +0 -2
  103. package/dist/chunk-yvwmfddz.js +0 -1
@@ -0,0 +1,6 @@
1
+ import{m as fq,n as Eq,o as Iq,p as Lq,q as Wq,r as Sq}from"./chunk-crwa61tq.js";import{t as Jq,u as r,v as o,w as n,x as m,y as t}from"./chunk-fw1fm9cn.js";import{L as Uq,N as _q,O as Mq,Q as qq,S as Pq}from"./chunk-mxffhqe5.js";import"./chunk-ag0z1q2q.js";import"./chunk-00gwp388.js";import{Ua as zq,hb as jq,qb as Hq}from"./chunk-s1j86hhh.js";import"./chunk-pgy1mtgw.js";import{Yb as Gq,ac as Dq,lc as g,wc as l}from"./chunk-16449n3m.js";import"./chunk-g0gqxn3c.js";import"./chunk-2sdbj0zz.js";import{Sc as Aq}from"./chunk-64f79ce5.js";import{Uc as xq,Vc as Rq,Wc as bq}from"./chunk-1142vwqa.js";import{Xc as Nq}from"./chunk-5v642sh3.js";import"./chunk-5knt529c.js";import{vd as Kq}from"./chunk-2gca6fvf.js";import"./chunk-v508x7cg.js";import"./chunk-d90tnjst.js";import"./chunk-y9a1jwnv.js";import"./chunk-dsxjgty6.js";import"./chunk-b9y9mc7f.js";import"./chunk-fjbptkh2.js";import"./chunk-3j6bsp1q.js";import"./chunk-t1z46fqz.js";import"./chunk-prqgpq92.js";import"./chunk-ysr3frmw.js";import"./chunk-d3gx05ph.js";import"./chunk-bx99mx3k.js";import"./chunk-3ctcv013.js";import{vf as Xq}from"./chunk-1ep6bcpc.js";import{Bf as U,wf as Bq,yf as q,zf as e}from"./chunk-c23bewtt.js";import"./chunk-87ge6dkk.js";import{If as h}from"./chunk-dvf4cfye.js";import"./chunk-7ryqs453.js";import"./chunk-pnjftj8t.js";import"./chunk-nq1wqpsx.js";import"./chunk-fb80q06q.js";import"./chunk-0kqp5z4v.js";import"./chunk-jdms602t.js";import"./chunk-95jjpdh9.js";import"./chunk-sexhm0r5.js";import AZ from"yargs";import{hideBin as xZ}from"yargs/helpers";function p($,V,D){if($.off){$.off(V,D);return}$.removeListener?.(V,D)}function Tq($,V){if(!$.once&&!$.on||!$.off&&!$.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((D,Q)=>{let Z=!1,Y=()=>{p($,"drain",_),p($,"error",M),V.removeEventListener("abort",x)},j=(b)=>{if(Z)return;Z=!0,Y(),b()},_=()=>j(D),M=(b)=>j(()=>Q(b??Error("Writable emitted an error"))),x=()=>j(()=>Q(V.reason??Error("Writable drain aborted")));if(V.aborted){x();return}let R=$.once?.bind($)??$.on?.bind($);R?.("drain",_),R?.("error",M),V.addEventListener("abort",x,{once:!0})})}async function gq($,V,D){if($.destroyed||$.writableEnded)throw Error("Writable is already closed");if($.write(V)===!1)await Tq($,D)}class u{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new m("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor($,V={}){this.options=V;let D=(Q)=>new t({maxPendingItems:V.maxPendingItems??r,maxPendingBytes:V.maxPendingBytes??o,writeTimeoutMs:V.writeTimeoutMs??n,sizeOf:(Z)=>Buffer.byteLength(Z),write:(Z,Y)=>gq($[Q],Z,Y),onFailure:(Z)=>this.fail(Z)});if(this.queues={stdout:D("stdout"),stderr:D("stderr")},this.observeSinkErrors($.stdout),$.stderr!==$.stdout)this.observeSinkErrors($.stderr);if(V.signal?.addEventListener("abort",this.handleAbort,{once:!0}),V.signal?.aborted)this.handleAbort()}write($,V){return this.queues[$].offer(V).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close($){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close($),this.queues.stderr.close($)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors($){if(!$.on||!$.off&&!$.removeListener)return;let V=(D)=>{this.fail(new m("write_failed","Headless writable failed",{cause:D??Error("Writable emitted an error")}))};$.on("error",V),this.sinkErrorListeners.push({writer:$,listener:V})}fail($){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close($),this.queues.stderr.close($),this.options.onFailure?.($)}removeSinkErrorListeners(){for(let{writer:$,listener:V}of this.sinkErrorListeners.splice(0))p($,"error",V)}}var Zq=1;function z($){return q.Object({event_version:q.Literal(Zq),...$})}var wq=z({type:q.Literal("content_delta"),delta:q.String()}),cq=z({type:q.Literal("thinking_delta"),delta:q.String()}),dq=z({type:q.Literal("thinking"),content:q.String()}),mq=z({type:q.Literal("stream_end")}),pq=z({type:q.Literal("content"),content:q.String()}),uq=z({type:q.Literal("structured_output"),output:q.Record(q.String(),q.Unknown()),schema_digest:q.String({pattern:"^[a-f0-9]{64}$"})}),$q=U(["readonly","write","execute"]),lq=z({type:q.Literal("tool_start"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional($q)}),vq=z({type:q.Literal("tool_progress"),tool_name:q.String(),message:q.String(),progress:q.Optional(q.Number()),total:q.Optional(q.Number())}),sq=z({type:q.Literal("tool_result"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional($q),success:q.Optional(q.Boolean()),error_type:q.Optional(q.String()),error_message:q.Optional(q.String())}),iq=z({type:q.Literal("mcp_catalog_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),aq=z({type:q.Literal("mcp_content_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),content_kind:U(["resources","resource_templates","prompts"]),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),rq=z({type:q.Literal("mcp_resource_updated"),revision:q.Integer({minimum:1}),server_name:q.String(),uri:q.String()}),oq=z({type:q.Literal("mcp_connection_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),phase:U(["reconnecting","recovered","failed"]),reason:q.String(),attempt:q.Integer({minimum:0}),max_attempts:q.Integer({minimum:0}),next_retry_at:q.Optional(q.Integer({minimum:0})),error:q.Optional(q.String())}),nq=z({type:q.Literal("mcp_log"),revision:q.Integer({minimum:1}),server_name:q.String(),level:U(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:q.Optional(q.String()),message:q.String(),projected_bytes:q.Integer({minimum:0}),data_sha256:q.String(),truncated:q.Boolean(),details_omitted:q.Boolean(),timestamp:q.Integer({minimum:0}),synthetic:q.Optional(q.Boolean())}),tq=z({type:q.Literal("mcp_instructions_changed"),revision:q.Integer({minimum:0}),server_name:q.String(),action:U(["added","removed"]),reason:U(["snapshot","connection","disconnection"]),text:q.Optional(q.String()),source_bytes:q.Optional(q.Integer({minimum:0})),projected_bytes:q.Optional(q.Integer({minimum:0})),sha256:q.Optional(q.String()),truncated:q.Optional(q.Boolean()),details_omitted:q.Optional(q.Boolean())}),eq=z({type:q.Literal("mcp_task_changed"),revision:q.Integer({minimum:0}),task_id:q.String(),server_name:q.String(),tool_name:q.String(),status:U(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:q.Optional(q.String()),created_at:q.Integer({minimum:0}),updated_at:q.Integer({minimum:0}),completed_at:q.Optional(q.Integer({minimum:0})),has_result:q.Boolean(),error:q.Optional(q.String())}),qZ=z({type:q.Literal("project_rules_loaded"),files:q.Array(q.Object({id:q.String(),relative_path:q.String(),source:U(["project","local"]),conditional:q.Boolean(),content_sha256:q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:q.Array(q.String()),blocked_write:q.Boolean()}),ZZ=z({type:q.Literal("user_shell_started"),execution_id:q.String(),command:q.String(),auxiliary:q.Boolean()}),$Z=z({type:q.Literal("user_shell_output"),execution_id:q.String(),stream:U(["stdout","stderr"]),chunk:q.String(),stream_truncated:q.Boolean()}),VZ=z({type:q.Literal("user_shell_completed"),execution_id:q.String(),message_id:q.String(),status:U(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:q.Union([q.Integer(),q.Null()]),duration_ms:q.Number({minimum:0}),stdout:q.String(),stderr:q.String(),truncated:q.Boolean(),auxiliary:q.Boolean()}),YZ=z({type:q.Literal("phase"),phase:U(["turn","searching","inspecting","target_hit","executing","completed"]),status:U(["ongoing","hit","done"]),message:q.String(),turn:q.Optional(q.Number()),tool_name:q.Optional(q.String()),target:q.Optional(q.String())}),QZ=z({type:q.Literal("tool_detail"),tool_name:q.String(),detail:q.String()}),XZ=z({type:q.Literal("task_update"),tasks:q.Array(qq)}),BZ=z({type:q.Literal("goal"),state:U(["updated","cleared"]),goal_id:q.Optional(q.String()),status:q.Optional(U(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:q.Optional(q.Integer({minimum:1})),verification_status:q.Optional(U(["pending","pass","fail","partial"])),verifier_session_id:q.Optional(q.String()),verification_evidence_sha256:q.Optional(q.String({pattern:"^[a-f0-9]{64}$"}))}),KZ=z({type:q.Literal("subagent"),state:U(["spawned","completed"]),session_id:q.String(),subagent_type:q.Optional(q.String()),success:q.Optional(q.Boolean()),summary:q.Optional(q.String()),verification_verdict:q.Optional(U(["pass","fail","partial"])),resumed_from:q.Optional(q.String()),root_agent_id:q.Optional(q.String()),resume_depth:q.Optional(q.Integer({minimum:0}))}),GZ=z({type:q.Literal("token_usage"),input_tokens:q.Number(),output_tokens:q.Number(),total_tokens:q.Number(),max_context_tokens:q.Number(),cache_read_tokens:q.Optional(q.Number()),cache_write_tokens:q.Optional(q.Number()),cost_usd:q.Optional(q.Number())}),DZ=z({type:q.Literal("compacting"),state:U(["started","completed"]),reason:q.Optional(U(["threshold","context_limit","turn_limit","manual"])),strategy:q.Optional(U(["llm","fallback","snip"])),outcome:q.Optional(U(["completed","fallback","failed"])),pre_tokens:q.Optional(q.Number({minimum:0})),post_tokens:q.Optional(q.Number({minimum:0}))}),zZ=z({type:q.Literal("provider_retry"),phase:U(["scheduled","attempt","recovered","exhausted"]),attempt:q.Integer({minimum:0}),max_retries:q.Integer({minimum:0}),reason:U(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:q.Optional(q.Integer({minimum:100,maximum:599})),delay_ms:q.Optional(q.Integer({minimum:0})),next_retry_at:q.Optional(q.Integer({minimum:0}))}),jZ=z({type:q.Literal("provider_stall"),phase:U(["detected","recovered"]),stall_count:q.Integer({minimum:1}),duration_ms:q.Integer({minimum:0}),warning_after_ms:q.Integer({minimum:1}),timeout_ms:q.Integer({minimum:1}),output_started:q.Boolean()}),HZ=z({type:q.Literal("action_stationarity"),phase:U(["detected","recovered","halted"]),tool_name:q.String(),run_length:q.Integer({minimum:1}),nudge_threshold:q.Integer({minimum:1}),halt_threshold:q.Integer({minimum:1}),progress_aware:q.Boolean()}),UZ=z({type:q.Literal("turn_limit"),turns_count:q.Number(),action:q.Literal("continue")}),_Z=z({type:q.Literal("task_session"),session_id:q.String(),project_path:q.String(),source_project_path:q.String(),isolation:U(["local","worktree"]),worktree_branch:q.Optional(q.String()),base_commit:q.Optional(q.String())}),MZ=z({type:q.Literal("task_admission"),state:U(["queued","running"]),queue_position:q.Optional(q.Integer({minimum:1})),queue_depth:q.Integer({minimum:0}),in_flight:q.Integer({minimum:0}),max_concurrent_tasks:q.Integer({minimum:1})}),PZ=z({type:q.Literal("output"),content:q.String(),exit_code:q.Number()}),NZ=z({type:q.Literal("error"),message:q.String()}),cZ=e(q.Union([wq,cq,dq,mq,pq,uq,lq,vq,sq,iq,aq,rq,oq,nq,tq,eq,qZ,ZZ,$Z,VZ,YZ,QZ,XZ,BZ,KZ,GZ,DZ,zZ,jZ,HZ,UZ,_Z,MZ,PZ,NZ]));function Vq($,V){return{event_version:Zq,type:$,...V}}function RZ($){let V=new AbortController,D=(Y)=>{if(!V.signal.aborted)V.abort(Y)},Q=()=>D("interrupt"),Z=()=>D($?.signal?.reason);if($?.signal){if($.signal.addEventListener("abort",Z,{once:!0}),$.signal.aborted)Z()}else process.once("SIGINT",Q),process.once("SIGTERM",Q);return{signal:V.signal,abort:D,dispose:()=>{$?.signal?.removeEventListener("abort",Z),process.removeListener("SIGINT",Q),process.removeListener("SIGTERM",Q)}}}var bZ=U(["text","jsonl"]),JZ=q.Object({headless:q.Optional(q.Boolean()),message:q.Optional(q.String()),_:q.Optional(q.Array(q.Union([q.String(),q.Number()]))),model:q.Optional(q.String()),systemPrompt:q.Optional(q.String()),appendSystemPrompt:q.Optional(q.String()),verificationAgent:q.Optional(q.Boolean()),maxTurns:q.Optional(q.Refine(q.Integer(),($)=>$===-1||$>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:q.Optional(q.Enum(Xq)),mcpConfig:q.Optional(q.Array(q.String())),strictMcpConfig:q.Optional(q.Boolean()),sessionId:q.Optional(q.String()),allowedTools:q.Optional(q.Array(q.String())),disallowedTools:q.Optional(q.Array(q.String())),agents:q.Optional(q.String()),continue:q.Optional(q.Boolean()),resume:q.Optional(q.Union([q.String(),q.Boolean()])),forkSession:q.Optional(q.Boolean()),taskIsolation:q.Optional(U(["local","worktree"])),outputFormat:q.Optional(bZ),jsonSchema:q.Optional(q.String()),outputSchema:q.Optional(q.String())});class Cq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened($){this.openedThinking=$}hasOpenThinking(){return this.openedThinking}completeStream(){let $={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,$}}function fZ($){return $.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function EZ($){let V=Bq(JZ,$);if(!V.success)throw Error(`Invalid headless options: ${fZ(V.error)}`);return V.data}function IZ($){return $.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(V)=>V.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(V)=>{if(!V.headless)return;let D=await hZ(V);process.exit(D)})}function H($,V=""){$.write(`${V}
2
+ `)}function LZ($){return`[task] [${$.status}] ${$.subject}`}function WZ(){return{requestConfirmation:async($)=>$.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:$.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function SZ($){if(!($ instanceof Error))return"Unknown error";let Q=$.lastError??$;if(Q.responseBody)try{let j=JSON.parse(Q.responseBody)?.error?.message;if(j)return Q.statusCode?`${j} (HTTP ${Q.statusCode})`:j}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function CZ($){return $==="jsonl"?"jsonl":"text"}function Yq($,V){let D=(...Q)=>{for(let Z of Q){let Y=V[Z];if(typeof Y==="string"&&Y.trim()!=="")return Y}return};switch($){case"Read":case"Edit":case"Write":case"UndoEdit":return D("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return D("notebook_path");case"Grep":return D("path","pattern");case"Glob":return D("pattern");case"WebFetch":return D("url");case"WebSearch":return D("query");case"Bash":return D("command","description");case"Task":return D("description");case"LSP":return D("filePath","operation");case"EnterWorktree":return D("name");case"ExitWorktree":return D("action");default:return}}function OZ($,V,D,Q){let Z=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: ${V}`,shouldLockTarget:!0};if(Q.targetLocked)return{phase:"executing",status:"hit",message:D?`Working within target: ${V}`:`Executing: ${V}`,shouldLockTarget:!1};if(Z.has($))return{phase:"searching",status:"ongoing",message:`Still searching: ${V}`,shouldLockTarget:!1};if(Y.has($))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${V}`,shouldLockTarget:!1};return{phase:"executing",status:Q.targetLocked?"hit":"ongoing",message:`Executing: ${V}`,shouldLockTarget:!1}}function Qq($,V,D=!1){let Q=(Z,Y)=>{$.stdout.write(`${JSON.stringify(Vq(Z,Y))}
3
+ `)};return{contentDelta(Z){if(V==="jsonl"){Q("content_delta",{delta:Z});return}if(D)return;$.stdout.write(Z)},thinkingDelta(Z,Y){if(V==="jsonl")return Q("thinking_delta",{delta:Z}),Y;if(!Y)$.stderr.write("[thinking] ");return $.stderr.write(Z),!0},thinking(Z){if(V==="jsonl"){Q("thinking",{content:Z});return}H($.stderr,`[thinking] ${Z}`)},streamEnd(Z,Y){if(V==="jsonl"){Q("stream_end",{});return}if(Y)$.stderr.write(`
4
+ `);if(Z)$.stdout.write(`
5
+ `)},content(Z){if(V==="jsonl"){Q("content",{content:Z});return}H($.stdout,Z)},structuredOutput(Z){if(V==="jsonl"){Q("structured_output",{output:Z.output,schema_digest:Z.schemaDigest});return}H($.stdout,JSON.stringify(Z.output))},toolStart(Z,Y,j,_){if(V==="jsonl"){Q("tool_start",{tool_name:Z,summary:Y,target:j,tool_kind:_});return}H($.stderr,`[tool:start] ${Y}`)},toolProgress(Z,Y,j,_){if(V==="jsonl"){Q("tool_progress",{tool_name:Z,message:Y,progress:j,total:_});return}H($.stderr,`[tool:progress] ${Z}: ${Y}`)},toolResult(Z,Y,j,_,M){if(V==="jsonl"){Q("tool_result",{tool_name:Z,summary:Y,target:j,tool_kind:_,success:M?.success,error_type:M?.errorType,error_message:M?.errorMessage});return}H($.stderr,`[tool:result] ${Y}`)},mcpCatalogChanged(Z){if(V==="jsonl"){Q("mcp_catalog_changed",{revision:Z.revision,server_name:Z.serverName,added:Z.added,removed:Z.removed,updated:Z.updated});return}H($.stderr,`[mcp:catalog] r${Z.revision} ${Z.serverName} +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}`)},mcpContentChanged(Z){if(V==="jsonl"){Q("mcp_content_changed",{revision:Z.revision,server_name:Z.serverName,content_kind:Z.contentKind==="resourceTemplates"?"resource_templates":Z.contentKind,added:Z.added,removed:Z.removed,updated:Z.updated});return}H($.stderr,`[mcp:${Z.contentKind}] r${Z.revision} ${Z.serverName} +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}`)},mcpResourceUpdated(Z){if(V==="jsonl"){Q("mcp_resource_updated",{revision:Z.revision,server_name:Z.serverName,uri:Z.uri});return}H($.stderr,`[mcp:resource] r${Z.revision} ${Z.serverName} updated ${Z.uri}`)},mcpConnectionChanged(Z){if(V==="jsonl"){Q("mcp_connection_changed",{revision:Z.revision,server_name:Z.serverName,phase:Z.phase,reason:Z.reason,attempt:Z.attempt,max_attempts:Z.maxAttempts,...Z.nextRetryAt!==void 0?{next_retry_at:Z.nextRetryAt}:{},...Z.error?{error:Z.error}:{}});return}H($.stderr,`[mcp:connection] r${Z.revision} ${Z.serverName} ${Z.phase} ${Z.attempt}/${Z.maxAttempts}`)},mcpLog(Z){if(V==="jsonl"){Q("mcp_log",{revision:Z.revision,server_name:Z.serverName,level:Z.level,logger:Z.logger,message:Z.message,projected_bytes:Z.projectedBytes,data_sha256:Z.dataSha256,truncated:Z.truncated,details_omitted:Z.detailsOmitted,timestamp:Z.timestamp,synthetic:Z.synthetic});return}H($.stderr,`[mcp:log] ${Z.level} ${Z.serverName}${Z.logger?` logger=${Z.logger}`:""}: ${Z.message}`)},mcpInstructionsChanged(Z){if(V==="jsonl"){Q("mcp_instructions_changed",{revision:Z.revision,server_name:Z.serverName,action:Z.action,reason:Z.reason,text:Z.text,source_bytes:Z.sourceBytes,projected_bytes:Z.projectedBytes,sha256:Z.sha256,truncated:Z.truncated,details_omitted:Z.detailsOmitted});return}H($.stderr,`[mcp:instructions] ${Z.action} ${Z.serverName}${Z.truncated?" (truncated)":""}`)},mcpTaskChanged(Z){if(V==="jsonl"){Q("mcp_task_changed",{revision:Z.revision,task_id:Z.taskId,server_name:Z.serverName,tool_name:Z.toolName,status:Z.status,status_message:Z.statusMessage,created_at:Z.createdAt,updated_at:Z.updatedAt,completed_at:Z.completedAt,has_result:Z.hasResult,error:Z.error});return}H($.stderr,`[mcp:task] ${Z.taskId} ${Z.serverName}/${Z.toolName} `+Z.status)},projectRulesLoaded(Z){if(V==="jsonl"){Q("project_rules_loaded",{files:Z.files.map((Y)=>({id:Y.id,relative_path:Y.relativePath,source:Y.source,conditional:Y.conditional,content_sha256:Y.contentSha256})),trigger_paths:Z.triggerPaths,blocked_write:Z.blockedWrite});return}H($.stderr,`[project-rules] loaded ${Z.files.length} file(s)${Z.blockedWrite?" before write":""}`)},userShellStarted(Z,Y,j){if(V==="jsonl"){Q("user_shell_started",{execution_id:Z,command:Y,auxiliary:j});return}H($.stderr,`[user-shell:start] ${Y}`)},userShellOutput(Z,Y,j,_){if(V==="jsonl"){Q("user_shell_output",{execution_id:Z,stream:Y,chunk:j,stream_truncated:_});return}(Y==="stderr"?$.stderr:$.stdout).write(j)},userShellCompleted(Z){if(V==="jsonl"){Q("user_shell_completed",{execution_id:Z.executionId,message_id:Z.messageId,status:Z.record.status,exit_code:Z.record.exitCode,duration_ms:Z.record.durationMs,stdout:Z.record.stdout,stderr:Z.record.stderr,truncated:Z.record.truncated,auxiliary:Z.auxiliary});return}H($.stderr,`[user-shell:${Z.record.status}] exit=${Z.record.exitCode??"null"} ${Z.record.durationMs}ms`)},phase(Z,Y,j,_={}){if(V==="jsonl"){Q("phase",{phase:Z,status:Y,message:j,turn:_.turn,tool_name:_.toolName,target:_.target});return}H($.stderr,`[phase:${Z}] ${j}`)},toolDetail(Z,Y){if(V==="jsonl"){Q("tool_detail",{tool_name:Z,detail:Y});return}H($.stderr,Y)},taskUpdate(Z){if(V==="jsonl"){Q("task_update",{tasks:Z});return}for(let Y of Z)H($.stderr,LZ(Y))},goal(Z){if(V==="jsonl"){Q("goal",{state:Z.goal?"updated":"cleared",goal_id:Z.goal?.goalId,status:Z.goal?.status,verification_attempt:Z.goal?.completionVerification?.attempt,verification_status:Z.goal?.completionVerification?.status,verifier_session_id:Z.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:Z.goal?.completionVerification?.evidenceSha256});return}if(Z.goal)H($.stderr,`[goal:${Z.goal.status}] ${Z.goal.objective}`);else H($.stderr,"[goal:cleared]")},subagent(Z){let Y=Z.kind==="subagent_spawned";if(V==="jsonl"){Q("subagent",{state:Y?"spawned":"completed",session_id:Z.sessionId,subagent_type:Z.type,success:Y?void 0:Z.success,summary:Y?void 0:Z.summary,verification_verdict:Y?void 0:Z.verificationVerdict,resumed_from:Z.resumedFrom,root_agent_id:Z.rootAgentId,resume_depth:Z.resumeDepth});return}H($.stderr,`[subagent:${Y?"spawned":"completed"}] ${Z.sessionId}${Z.resumedFrom?` resumed from ${Z.resumedFrom}`:""}`)},tokenUsage(Z){if(V==="jsonl"){Q("token_usage",{input_tokens:Z.inputTokens,output_tokens:Z.outputTokens,total_tokens:Z.totalTokens,max_context_tokens:Z.maxContextTokens,cache_read_tokens:Z.cacheReadTokens,cache_write_tokens:Z.cacheWriteTokens,cost_usd:Z.costUsd});return}H($.stderr,`[tokens] in=${Z.inputTokens} out=${Z.outputTokens} total=${Z.totalTokens} / ${Z.maxContextTokens}`)},compacting(Z){let Y=Z.phase==="start";if(V==="jsonl"){Q("compacting",{state:Y?"started":"completed",reason:Z.reason,strategy:Z.strategy,outcome:Z.outcome,pre_tokens:Z.preTokens,post_tokens:Z.postTokens});return}H($.stderr,Y?`[context] compacting started${Z.reason?` (${Z.reason})`:""}`:`[context] compacting ${Z.outcome??"completed"}`)},providerRetry(Z){if(V==="jsonl"){Q("provider_retry",{phase:Z.phase,attempt:Z.attempt,max_retries:Z.maxRetries,reason:Z.reason,status_code:Z.statusCode,delay_ms:Z.delayMs,next_retry_at:Z.nextRetryAt});return}let Y=Z.delayMs!==void 0?` in ${Math.max(0,Math.ceil(Z.delayMs/1000))}s`:"";H($.stderr,`[provider-retry:${Z.phase}] ${Z.attempt}/${Z.maxRetries} ${Z.reason}${Y}`)},providerStall(Z){if(V==="jsonl"){Q("provider_stall",{phase:Z.phase,stall_count:Z.stallCount,duration_ms:Z.durationMs,warning_after_ms:Z.warningAfterMs,timeout_ms:Z.timeoutMs,output_started:Z.outputStarted});return}H($.stderr,`[provider-stall:${Z.phase}] ${Z.durationMs}ms / ${Z.timeoutMs}ms`)},actionStationarity(Z){if(V==="jsonl"){Q("action_stationarity",{phase:Z.phase,tool_name:Z.toolName,run_length:Z.runLength,nudge_threshold:Z.nudgeThreshold,halt_threshold:Z.haltThreshold,progress_aware:Z.progressAware});return}H($.stderr,`[action-stationarity:${Z.phase}] ${Z.toolName} ${Z.runLength}/${Z.haltThreshold}`)},turnLimit(Z){if(V==="jsonl"){Q("turn_limit",{turns_count:Z,action:"continue"});return}H($.stderr,`[turn-limit] continuing after ${Z} turns`)},taskSession(Z){if(V==="jsonl"){Q("task_session",{session_id:Z.sessionId,project_path:Z.projectPath,source_project_path:Z.sourceProjectPath,isolation:Z.isolation,worktree_branch:Z.worktreeBranch,base_commit:Z.baseCommit});return}H($.stderr,`[task:${Z.isolation}] ${Z.sessionId} ${Z.sourceProjectPath} -> ${Z.projectPath}${Z.worktreeBranch?` (${Z.worktreeBranch})`:""}`)},taskAdmission(Z){if(V==="jsonl"){Q("task_admission",{state:Z.state,queue_position:Z.queuePosition,queue_depth:Z.queueDepth,in_flight:Z.inFlight,max_concurrent_tasks:Z.maxConcurrentTasks});return}H($.stderr,Z.state==="queued"?`[task:queued] position ${Z.queuePosition??1}/${Z.queueDepth} (running ${Z.inFlight}/${Z.maxConcurrentTasks})`:`[task:running] admitted (running ${Z.inFlight}/${Z.maxConcurrentTasks})`)},output(Z,Y=0){if(V==="jsonl"){Q("output",{content:Z,exit_code:Y});return}H(Y===0?$.stdout:$.stderr,Z)},error(Z){if(V==="jsonl"){Q("error",{message:Z});return}H($.stderr,Z)}}}async function hZ($,V={stdout:process.stdout,stderr:process.stderr},D){let Q="text",Z=new Cq,Y={targetLocked:!1},j,_,M=RZ(D),x=!1,R=new u(V,{signal:M.signal,onFailure:(B)=>{x=!0,M.abort(B)}}),b={stdout:{write:(B)=>R.write("stdout",B)},stderr:{write:(B)=>R.write("stderr",B)}},K=Qq(b,Q),w=async()=>{try{return await R.flush(),!x}catch{return!1}},f=async(B)=>{return _?.(),_=void 0,await w()?B:1};try{let B=EZ($);Q=CZ(B.outputFormat);let E=await Wq(B);K=Qq(b,Q,Boolean(E)),await fq();let v=B.forkSession!==!0&&(B.continue===!0||typeof B.resume==="string"&&B.resume.length>0)?await Iq({message:B.message,_:B._,stdin:D?.stdin}):await Eq({...B,stdin:D?.stdin}),S=v===void 0,N=S?{mode:"agent",content:""}:await Lq(v);if(N.mode==="output"){if(N.content)K.output(N.content,N.exitCode??0);return await f(N.exitCode??0)}let k=N.content.trimStart().startsWith("!")?N.content.trimStart().slice(1).trim():void 0;if(k!==void 0&&B.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(k!==void 0&&E)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:A,messages:s,metadata:i}=await Sq({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),C=B.permissionMode??i?.permissionMode??"yolo",a=B.model&&B.model!=="inherit"?B.model:Kq()?.id,P=B.taskIsolation?await Jq.createSessionTask({sessionId:A,prompt:N.content,sourceProjectPath:h(),isolation:B.taskIsolation,dispatch:{version:1,prompt:N.content,sourceProjectPath:h(),isolation:B.taskIsolation,permissionMode:C,...a?{modelId:a}:{},...E?{outputSchema:E}:{}}}):void 0,J=P?.metadata.projectPath??i?.projectPath??h();if(!P)await l.setSessionPermissionMode(A,J,C);let Oq=P?!1:await Hq.cancelPendingNonInteractive(J,A);if(P)K.taskSession({sessionId:A,projectPath:J,sourceProjectPath:P.metadata.taskSourceProjectPath??h(),isolation:B.taskIsolation,worktreeBranch:P.metadata.taskWorktreeBranch,baseCommit:P.metadata.taskBaseCommit}),_=zq.subscribe((X)=>{if(X.type!=="task.status"||X.sessionId!==A||X.projectPath!==J||!["queued","running"].includes(String(X.properties.taskStatus))||typeof X.properties.taskQueueDepth!=="number"||typeof X.properties.taskInFlight!=="number"||typeof X.properties.taskConcurrencyLimit!=="number")return;K.taskAdmission({state:X.properties.taskStatus,queuePosition:typeof X.properties.taskQueuePosition==="number"?X.properties.taskQueuePosition:void 0,queueDepth:X.properties.taskQueueDepth,inFlight:X.properties.taskInFlight,maxConcurrentTasks:X.properties.taskConcurrencyLimit})});let hq={messages:Oq?await l.loadSessionModelContext(A,J):[...s],userId:"cli-user",sessionId:A,workspaceRoot:J,permissionMode:C,signal:M.signal,...P?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:WZ()};j=await Uq.create({sessionId:A,workspaceRoot:J,modelId:B.model,permissionMode:C,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?Nq(B.agents):void 0,...P?.taskWorktree?{taskWorktree:P.taskWorktree}:{},...P?.metadata.taskIsolation?{taskIsolation:P.metadata.taskIsolation}:{},...s.length>0?{sessionStart:{isResume:!0,resumeSessionId:A}}:{}});let F=S&&j.getPendingSteeringCount()>0,y=S&&!F?await j.getGoal():null,c=y?.status==="active"||y?.status==="verifying",I=S&&!F&&!c?await j.getRecoveredFinalResponse():void 0;if(S&&!F&&!c){if(!I)throw Error("No unfinished turn or active goal to resume");if(y)K.goal({kind:"goal_updated",goal:y});if(I.structuredOutput&&I.structuredOutputSchemaDigest)K.structuredOutput({kind:"structured_output",output:I.structuredOutput,schemaDigest:I.structuredOutputSchemaDigest});else K.content(I.content);return K.phase("completed","done","Recovered headless run completed"),await f(0)}if(k!==void 0){let X=await j.executeUserShellCommand(k,{signal:M.signal,onEvent:async(G)=>{if(G.type==="started")K.userShellStarted(G.executionId,G.command,G.auxiliary);else if(G.type==="output")K.userShellOutput(G.executionId,G.stream,G.chunk,G.streamTruncated);await w()}});return K.userShellCompleted(X),await f(X.record.status==="completed"?0:X.record.status==="aborted"?130:X.record.exitCode??1)}let kq=B.maxTurns??j.getConfig().maxTurns,Fq=P?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,yq=await Pq.createWithRuntime(j,{sessionId:A,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:C,toolWhitelist:B.allowedTools,toolBlacklist:Fq,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),d=await jq(yq.chatStream(N.content,hq,{stream:!0,signal:M.signal,maxTurns:B.maxTurns,builtinVerification:B.verificationAgent!==!1,outputSchema:E,pendingInputOnly:F,goalContinuationOnly:c,...kq===-1?{onTurnLimitReached:async(X)=>{return K.turnLimit(X.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(X)=>{switch(X.kind){case"content_delta":if(!E||Q==="jsonl")Z.markAssistantContent();K.contentDelta(X.delta);break;case"thinking_delta":Z.setThinkingOpened(K.thinkingDelta(X.delta,Z.hasOpenThinking()));break;case"stream_end":{let G=Z.completeStream();K.streamEnd(G.wroteAssistantContent,G.openedThinking);break}case"tool_start":{let G=X.toolCall;if(!("function"in G))break;if(G.function.name===g)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(G.function.name))break;try{let L=JSON.parse(G.function.arguments),W=_q(G.function.name,L),O=Yq(G.function.name,L),T=OZ(G.function.name,W,O,Y);if(T.shouldLockTarget)Y.targetLocked=!0;K.phase(T.phase,T.status,T.message,{toolName:G.function.name,target:O}),K.toolStart(G.function.name,W,O,X.toolKind)}catch{K.phase(Y.targetLocked?"executing":"searching",Y.targetLocked?"hit":"ongoing",Y.targetLocked?`Working within target: ${G.function.name}`:`Still searching: ${G.function.name}`,{toolName:G.function.name}),K.toolStart(G.function.name,G.function.name,void 0,X.toolKind)}break}case"tool_progress":{let G=X.toolCall;if(!("function"in G))break;if(G.function.name===g)break;K.toolProgress(G.function.name,X.update.message,X.update.progress,X.update.total);break}case"tool_result":{let G=X.toolCall;if(!("function"in G))break;if(G.function.name===g)break;let L;try{let O=JSON.parse(G.function.arguments);L=Yq(G.function.name,O)}catch{L=void 0}let W=Dq(Mq(G.function.name,X.result),Gq);if(K.toolResult(G.function.name,W.summary,L,void 0,{success:X.result.success,errorType:X.result.error?.type,errorMessage:X.result.error?.message}),W.detail)K.toolDetail(G.function.name,W.detail);break}case"token_usage":K.tokenUsage(X.usage);break;case"compaction":K.compacting(X);break;case"task_update":K.taskUpdate(X.tasks);break;case"structured_output":K.structuredOutput(X);break;case"mcp_catalog_changed":K.mcpCatalogChanged(X);break;case"mcp_content_changed":K.mcpContentChanged(X);break;case"mcp_resource_updated":K.mcpResourceUpdated(X);break;case"mcp_connection_changed":K.mcpConnectionChanged(X);break;case"mcp_log":K.mcpLog(X);break;case"mcp_instructions_changed":K.mcpInstructionsChanged(X);break;case"mcp_task_changed":K.mcpTaskChanged(X);break;case"project_rules_loaded":K.projectRulesLoaded(X);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":K.goal(X);break;case"subagent_spawned":case"subagent_completed":K.subagent(X);break;case"model_fallback":break;case"provider_retry":K.providerRetry(X);break;case"provider_stall":K.providerStall(X);break;case"action_stationarity":K.actionStationarity(X);break;case"turn_start":if(X.turn===1)Y.targetLocked=!1;K.phase("turn",Y.targetLocked?"hit":"ongoing",`Turn ${X.turn} started`,{turn:X.turn});break;default:{let G=X}}await w()});if(d.metadata?.outputTruncated)K.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!d.success)return K.error(`Error: ${d.error?.message??"Agent execution failed"}`),await f(1);return K.phase("completed","done","Headless run completed"),await f(0)}catch(B){if(!x){if(Z.hasOpenThinking()&&Q==="text")b.stderr.write(`
6
+ `);K.error(`Error: ${SZ(B)}`)}return await f(1)}finally{_?.();try{await j?.dispose()}finally{R.close(),M.dispose()}}}async function z0(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:D,"output-format":Q,"system-prompt":Z,"append-system-prompt":Y,"max-turns":j,..._}=Aq,M=AZ(xZ(process.argv)).scriptName("blade").strict(!1).options(_).middleware([Rq,xq,bq]);return IZ(M),await M.parse(),!0}export{hZ as runHeadless,z0 as handleHeadlessMode,JZ as HeadlessOptionsSchema};
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as a}from"node:path";import{fileURLToPath as u}from"node:url";var t={name:"blade-code",version:"0.10.32",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(u(import.meta.url));for(let n=0;n<5;n++){try{let e=JSON.parse(l(a(i,"package.json"),"utf8"));if(e.name===t.name&&typeof e.version==="string"&&typeof e.description==="string")return s=e,s}catch{}i=o(i)}return s={name:t.name,version:process.env.BLADE_VERSION??t.version,description:t.description},s}function v(){return{...r()}}function p(){return r().version}function h(){return r().name}function w(){return r().description}function f(){return`v${p()}`}function g(){return`v${p()} © 2025 Blade Code`}
2
- export{v as Tf,p as Uf,h as Vf,w as Wf,f as Xf,g as Yf};
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as a}from"node:path";import{fileURLToPath as u}from"node:url";var t={name:"blade-code",version:"0.10.34",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(u(import.meta.url));for(let n=0;n<5;n++){try{let e=JSON.parse(l(a(i,"package.json"),"utf8"));if(e.name===t.name&&typeof e.version==="string"&&typeof e.description==="string")return s=e,s}catch{}i=o(i)}return s={name:t.name,version:process.env.BLADE_VERSION??t.version,description:t.description},s}function v(){return{...r()}}function p(){return r().version}function h(){return r().name}function w(){return r().description}function f(){return`v${p()}`}function g(){return`v${p()} © 2025 Blade Code`}
2
+ export{v as Zf,p as _f,h as $f,w as ag,f as bg,g as cg};
@@ -1,2 +1,2 @@
1
- import{nf as F}from"./chunk-xh1y705a.js";import{Lf as D,Mf as E}from"./chunk-y5rsamex.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
- export{H as Ld,Q as Md,T as Nd};
1
+ import{tf as F}from"./chunk-3ctcv013.js";import{Rf as D,Sf as E}from"./chunk-pnjftj8t.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
+ export{H as Rd,Q as Sd,T as Td};
@@ -0,0 +1,2 @@
1
+ import{I}from"./chunk-mxffhqe5.js";import{wc as D}from"./chunk-16449n3m.js";import w from"node:path";function C(a){let t=a.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function P(a){let t=a.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function S(a){return`task/${a.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class z{static async createSessionTask(a){if(!a.prompt.trim())throw Error("Task prompt must not be blank");if(!w.isAbsolute(a.sourceProjectPath))throw Error("Task source project path must be absolute");let t=w.resolve(a.sourceProjectPath),s;try{return s=a.isolation==="worktree"?await I.enter({sessionId:a.sessionId,workspaceRoot:t,name:S(a.sessionId)}):void 0,{metadata:await D.createSessionMetadata(a.sessionId,s?.workspaceRoot??t,{title:a.title?.trim()||C(a.prompt),taskPromptSummary:P(a.prompt),taskDispatch:a.dispatch,taskModelId:a.dispatch?.modelId,selectedModelId:a.dispatch?.modelId,permissionMode:a.dispatch?.permissionMode,reasoningEffort:a.dispatch?.reasoningEffort,serviceTier:a.dispatch?.serviceTier,responseVerbosity:a.dispatch?.responseVerbosity,communicationStyle:a.dispatch?.communicationStyle,communicationStyleDigest:a.dispatch?.communicationStyleDigest,projectInstructionsDigest:a.dispatch?.projectInstructionsDigest,taskRetriedFrom:a.retriedFrom,taskIsolation:a.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(k){if(s)await I.exit({sessionId:a.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var N=256,Z=8388608,_=30000;class c extends Error{kind;pendingItems;pendingBytes;constructor(a,t,s){super(t,s);this.kind=a;this.name="BoundedSerialEgressError",this.pendingItems=s?.pendingItems,this.pendingBytes=s?.pendingBytes}}function m(a){a.catch(()=>{return})}class F{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(a){this.options=a;if(this.assertPositiveInteger(a.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(a.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(a.writeTimeoutMs,"writeTimeoutMs"),a.signal?.addEventListener("abort",this.handleAbort,{once:!0}),a.signal?.aborted)this.handleAbort()}offer(a){if(this.closed)return{accepted:!1,error:this.failure??new c("closed","Egress is already closed")};let t;try{t=this.options.sizeOf(a)}catch(i){return this.rejectAdmission(new c("invalid_size","Egress size calculation failed",{cause:i}))}if(!Number.isSafeInteger(t)||t<0)return this.rejectAdmission(new c("invalid_size","Egress size must be a non-negative safe integer"));if(t>this.options.maxPendingBytes)return this.rejectAdmission(new c("oversized",`Egress value requires ${t} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+t>this.options.maxPendingBytes)return this.rejectAdmission(new c("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let s,k,h=new Promise((i,f)=>{s=i,k=f});return m(h),this.nextSequence+=1,this.pending.push({value:a,bytes:t,sequence:this.nextSequence,resolve:s,reject:k,completion:h}),this.pendingBytes+=t,this.startDrain(),{accepted:!0,completion:h}}flush(){if(this.failure){let h=Promise.reject(this.failure);return m(h),h}let a=this.nextSequence;if(a<=this.completedSequence)return Promise.resolve();let t,s,k=new Promise((h,i)=>{t=h,s=i});return m(k),this.flushWaiters.push({targetSequence:a,resolve:t,reject:s}),k}close(a){let t=a instanceof c?a:new c("closed","Egress was closed",{cause:a});this.fail(t)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new c("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(a){return this.fail(a),{accepted:!1,error:a}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let a=this.drain();m(a)}async drain(){try{while(!this.closed){let a=this.pending[0];if(!a)return;try{await this.writeOne(a.value)}catch(t){this.fail(this.normalizeWriteError(t));return}if(this.closed||this.pending[0]!==a)return;this.pending.shift(),this.pendingBytes-=a.bytes,this.completedSequence=a.sequence,a.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(a){let t=new AbortController;this.activeWriteAbort=t;let s,k,h=new Promise((W,T)=>{k=T});m(h),this.activeWriteStop=k;let i=Promise.resolve().then(()=>this.options.write(a,t.signal));m(i);let f=new Promise((W,T)=>{s=setTimeout(()=>{let M=new c("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);t.abort(M),T(M)},this.options.writeTimeoutMs),this.activeWriteTimeout=s});m(f);try{await Promise.race([i,f,h])}finally{if(s!==void 0)clearTimeout(s);if(this.activeWriteTimeout===s)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===t)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(a){if(a instanceof c)return a;return new c("write_failed","Egress write failed",{cause:a})}fail(a){if(this.closed)return;if(a.pendingItems??=this.pending.length,a.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=a,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(a),this.activeWriteStop?.(a),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let t=this.pending.splice(0);this.pendingBytes=0;for(let s of t)s.reject(a);for(let s of this.flushWaiters.splice(0))s.reject(a);try{this.options.onFailure?.(a)}catch{}}settleFlushWaiters(){for(let a=0;a<this.flushWaiters.length;){let t=this.flushWaiters[a];if(t.targetSequence>this.completedSequence){a+=1;continue}this.flushWaiters.splice(a,1),t.resolve()}}assertPositiveInteger(a,t){if(!Number.isSafeInteger(a)||a<=0)throw RangeError(`${t} must be a positive safe integer`)}}
2
+ export{z as t,N as u,Z as v,_ as w,c as x,F as y};
@@ -1,2 +1,2 @@
1
1
  function c(b){return b!==void 0&&typeof b.pattern==="string"&&typeof b.search_path==="string"}function f(b){return b!==void 0&&b.kind==="edit"&&typeof b.matches_found==="number"}function g(b){return b==="readonly"}
2
- export{c as rc,f as sc,g as tc};
2
+ export{c as xc,f as yc,g as zc};
@@ -1,2 +1,2 @@
1
- import{Mf as o}from"./chunk-y5rsamex.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
1
+ import{Sf as o}from"./chunk-pnjftj8t.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
2
2
  export{e as j,i as k};
@@ -0,0 +1 @@
1
+ import{Ld as a}from"./chunk-y9a1jwnv.js";import"./chunk-7ryqs453.js";import"./chunk-pnjftj8t.js";import"./chunk-nq1wqpsx.js";import"./chunk-95jjpdh9.js";import"./chunk-sexhm0r5.js";export{a as createChatServiceAsync};
@@ -1,2 +1,2 @@
1
1
  import{promises as A}from"node:fs";import q from"node:path";var J=new Map;async function L(B){let b=B;while(!0){try{return await A.lstat(q.join(b,".git")),b}catch(H){if(H.code!=="ENOENT")return}let E=q.dirname(b);if(E===b)return;b=E}}async function M(B){let b=q.join(B,".git"),E=await A.lstat(b);if(E.isDirectory())return B;if(!E.isFile())return;let H=await A.readFile(b,"utf8"),F=/^gitdir:\s*(.+)\s*$/im.exec(H);if(!F)return;let z=await A.realpath(q.isAbsolute(F[1])?F[1]:q.resolve(B,F[1])),I=z;try{let x=(await A.readFile(q.join(z,"commondir"),"utf8")).trim();if(x)I=await A.realpath(q.resolve(z,x))}catch(x){if(x.code!=="ENOENT")throw x}return q.basename(I)===".git"?A.realpath(q.dirname(I)):void 0}async function S(B){if(!q.isAbsolute(B))throw Error("Workspace path must be absolute");let b=await A.realpath(B),E=J.get(b);if(E)return E;let H=b;try{let z=await L(b);if(z){let I=await M(z),x=q.relative(z,b);if(I&&(x===""||!x.startsWith(`..${q.sep}`)&&x!==".."&&!q.isAbsolute(x))){let K=q.resolve(I,x);H=await A.realpath(K).catch(()=>K)}}}catch{}let F={projectPath:b,trustRoot:H};if(J.size>=512){let z=J.keys().next().value;if(z)J.delete(z)}return J.set(b,F),F}
2
- export{S as _f};
2
+ export{S as eg};
@@ -0,0 +1,10 @@
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-wz6atg87.js";import"./chunk-h34g9v9z.js";import"./chunk-1qj0qms6.js";import"./chunk-7a8k7ck4.js";import"./chunk-fw1fm9cn.js";import"./chunk-mxffhqe5.js";import"./chunk-ag0z1q2q.js";import"./chunk-00gwp388.js";import"./chunk-s1j86hhh.js";import"./chunk-pgy1mtgw.js";import"./chunk-16449n3m.js";import"./chunk-g0gqxn3c.js";import"./chunk-2sdbj0zz.js";import{Zc as R}from"./chunk-p01t6c78.js";import"./chunk-5knt529c.js";import{td as Q}from"./chunk-2gca6fvf.js";import"./chunk-v508x7cg.js";import"./chunk-d90tnjst.js";import"./chunk-y9a1jwnv.js";import"./chunk-dsxjgty6.js";import"./chunk-b9y9mc7f.js";import"./chunk-fjbptkh2.js";import"./chunk-3j6bsp1q.js";import"./chunk-t1z46fqz.js";import"./chunk-prqgpq92.js";import"./chunk-ysr3frmw.js";import"./chunk-d3gx05ph.js";import"./chunk-bx99mx3k.js";import"./chunk-3ctcv013.js";import"./chunk-1ep6bcpc.js";import"./chunk-c23bewtt.js";import"./chunk-87ge6dkk.js";import"./chunk-dvf4cfye.js";import"./chunk-7ryqs453.js";import"./chunk-pnjftj8t.js";import"./chunk-nq1wqpsx.js";import{_f as M}from"./chunk-fb80q06q.js";import"./chunk-0kqp5z4v.js";import"./chunk-jdms602t.js";import"./chunk-95jjpdh9.js";import"./chunk-sexhm0r5.js";import m from"chalk";import K from"open";var A=`
2
+ ____ _ _
3
+ | __ )| | __ _ __| | ___
4
+ | _ \\| |/ _\` |/ _\` |/ _ \\
5
+ | |_) | | (_| | (_| | __/
6
+ |____/|_|\\__,_|\\__,_|\\___|
7
+ `,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
8
+ `));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
9
+ `)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
10
+ `));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
@@ -0,0 +1,22 @@
1
+ import{s as T}from"./chunk-7a8k7ck4.js";import{t as jz,u as t,v as s,w as e,x as zz,y as Hz}from"./chunk-fw1fm9cn.js";import{B as P,L as r,O as a,P as o,S as n,ea as Jz,fa as Qz,ga as Zz,ha as $z}from"./chunk-mxffhqe5.js";import{ra as _z}from"./chunk-ag0z1q2q.js";import"./chunk-00gwp388.js";import{Ua as m,hb as l,qb as i}from"./chunk-s1j86hhh.js";import{zb as h}from"./chunk-pgy1mtgw.js";import{Sb as g,Zb as c,ac as v,ic as S,jc as p,lc as q,oc as d,tc as N,wc as _}from"./chunk-16449n3m.js";import"./chunk-g0gqxn3c.js";import"./chunk-2sdbj0zz.js";import{Zc as Gz}from"./chunk-p01t6c78.js";import"./chunk-5knt529c.js";import"./chunk-2gca6fvf.js";import"./chunk-v508x7cg.js";import{Ed as Lz}from"./chunk-d90tnjst.js";import"./chunk-y9a1jwnv.js";import"./chunk-dsxjgty6.js";import{Pd as Bz}from"./chunk-b9y9mc7f.js";import"./chunk-fjbptkh2.js";import"./chunk-3j6bsp1q.js";import"./chunk-t1z46fqz.js";import{ue as Uz}from"./chunk-prqgpq92.js";import"./chunk-ysr3frmw.js";import"./chunk-d3gx05ph.js";import"./chunk-bx99mx3k.js";import"./chunk-3ctcv013.js";import"./chunk-1ep6bcpc.js";import"./chunk-c23bewtt.js";import{Cf as y,Df as u,Ef as I}from"./chunk-87ge6dkk.js";import{If as Xz}from"./chunk-dvf4cfye.js";import{Mf as x}from"./chunk-7ryqs453.js";import"./chunk-pnjftj8t.js";import{Tf as Yz,Wf as Fz}from"./chunk-nq1wqpsx.js";import"./chunk-fb80q06q.js";import"./chunk-0kqp5z4v.js";import"./chunk-jdms602t.js";import"./chunk-95jjpdh9.js";import"./chunk-sexhm0r5.js";import{Readable as Ez,Writable as qz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Wz from"node:path";import{PROTOCOL_VERSION as Pz}from"@agentclientprotocol/sdk";import{RequestError as Az}from"@agentclientprotocol/sdk";import{nanoid as M}from"nanoid";var U=x("Agent");function f(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function Kz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:f(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:f("headers"in z?z.headers:void 0)};return null}function Rz(z){let J={};for(let H of z){let D=Kz(H);if(D)J[H.name]=D}return J}function Dz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,D=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!D)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:D[1]??"image/png",data:D[2]??""}]})}function Nz(z){let J=p(z.metadata);return J?[{type:"text",text:S(J)}]:Dz(z.content)}function Oz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}class E{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,D,W={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=D;this.options=W;this.messages=[...W.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(W.permissionMode),this.updateEgress=new Hz({maxPendingItems:t,maxPendingBytes:s,writeTimeoutMs:e,signal:H.signal,sizeOf:(Q)=>Buffer.byteLength(JSON.stringify(Q)),write:async(Q)=>{await H.sessionUpdate(Q)},onFailure:(Q)=>this.handleUpdateEgressFailure(Q)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([_.loadSession(this.id,this.cwd),_.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await _.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return n.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await _.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),P.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(Q)=>{await this.sendUpdateAndWait(Q)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await i.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(Q)=>this.requestPermission(Q)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?Rz(this.options.mcpServers):void 0,H=P.getInstance().getTerminalService(this.id);if(this.runtime=await r.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Q,Z)=>{let X=await H.execute(Q,{cwd:Z.cwd,env:Z.env,timeout:Z.timeoutMs,signal:Z.signal,allowLocalFallback:!1,onOutput:(Y)=>Z.onOutput?.("stdout",Y)});return{exitCode:X.exitCode,stdout:X.stdout,stderr:X.stderr,...X.error?{error:X.error}:{},timedOut:X.failureKind==="timeout",aborted:X.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await T.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=m.subscribe((Q)=>{if(Q.sessionId!==this.id||Q.projectPath!==this.cwd)return;if(Q.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Q.properties}}),this.schedulePendingResume();return}if(Q.type==="task.delivery"){if(!Q.properties.taskDelivery||typeof Q.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Q.properties.updatedAt==="string"?Q.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Q.properties.taskDelivery,...Q.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Q.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Q.properties.updatedAt==="string"?Q.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Q.properties.taskStatus,...typeof Q.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Q.properties.taskStatusReason}:{},...Q.properties.taskFailure&&typeof Q.properties.taskFailure==="object"?{"blade/taskFailure":Q.properties.taskFailure}:{},...typeof Q.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Q.properties.taskStartedAt}:{},...typeof Q.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Q.properties.taskCompletedAt}:{},...Q.properties.taskDiffStat&&typeof Q.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Q.properties.taskDiffStat}:{},...typeof Q.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Q.properties.taskQueuePosition}:{},...typeof Q.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Q.properties.taskQueueDepth}:{},...typeof Q.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Q.properties.taskConcurrencyLimit}:{},...typeof Q.properties.taskInFlight==="number"?{"blade/taskInFlight":Q.properties.taskInFlight}:{}}})});let W=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||W?.status==="active"||W?.status==="verifying")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 H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let D of Nz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:D}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);U.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await this.runtime.rewindSession(Z);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Z)=>{if(await this.setServiceTier(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Z)=>{if(await this.setResponseVerbosity(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Z)=>{if(await this.setCommunicationStyle(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let Y=!1,F,L=(A)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:A.id,status:A.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:A.result?.message||A.result?.error||`Subagent ${A.status}`}}]})},B=this.runtime.resumeSubagent({agentId:Z,prompt:X,onCompleted:(A)=>{if(Y)L(A);else F=A}});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")}),Y=!0,F)L(F);return B}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,X,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,X,Y)},complete:async(Z,X,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,X,Y)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,X)},getLogs:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,X)},setLoggingLevel:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let Y=await T.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:X,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:[]})}}),F=await Y.completion,L=(await T.list(this.cwd,this.id)).find((B)=>B.start.reviewId===Y.reviewId);if(!L)throw Error(`Review not found: ${Y.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:Y.reviewId,status:F.status,findings:F.findings.length,content:g(L.start,F)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,X,Y)=>{let F=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(Y);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:L})},sendToolResult:(Z,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},D=await Zz(z,H),W=D.data?.action;if(W==="start_goal"||W==="resume_goal")this.schedulePendingResume();if(W==="rewind_session"&&Array.isArray(D.data?.messages))this.messages=[...D.data.messages],this.contextMessages=await this.loadModelContextOr(D.data.messages);if((D.message==="compact_completed"||D.message==="compact_fallback")&&D.data?.compactedMessages){this.contextMessages=[...D.data.compactedMessages];let Z=await _.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let Q=D.content||D.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(D.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${D.error}`}});return await this.flushUpdates(),{stopReason:D.success?"end_turn":"cancelled"}}catch(H){return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=$z(this.cwd),J=["model","permissions","theme","config","exit","ide"],D=z.filter((W)=>!J.includes(W.name)).map((W)=>{let Q;if(W.usage){let Z=W.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Q=Z}if(W.aliases?.length){let Z=`Aliases: ${W.aliases.join(", ")}`;Q=Q?`${Q} | ${Z}`:Z}return{name:W.name,description:W.description,input:Q?{hint:Q}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(D.map((W)=>W.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:D}),U.info(`[AcpSession ${this.id}] Sent ${D.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(P.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),D=H.content,W=H.displayText,Q=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((L)=>L.outputSchema)?.outputSchema:void 0),Z;if(Q!==void 0)Z=d(Q).schema;if(W.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(W)}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(W.trim()))return this.handleSlashCommand(W,this.pendingPrompt.signal);let L=await this.runtime.enqueueSteering(D,{allowBeforeTurn:!0});if(!L.accepted)throw Error(L.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${L.queued})`),L.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let X=new AbortController,Y,F=new Promise((L)=>{Y=L});this.pendingPrompt=X,this.pendingPromptCompletion=F;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${W.slice(0,100)}...`),Jz(W)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(W,X.signal)}let L={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:X.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},B=await l(this.agent.chatStream(D,L,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async($)=>{switch($.kind){case"content_delta":if(Z)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let G=$.toolCall,K=G.function.name;if(K===q)break;let R=this.mapToolKind($.toolKind),j=`Executing ${K}`;if(K==="Task"&&"function"in G)try{let O=JSON.parse(G.function.arguments),V=O.resume_from??O.resume;if(typeof V==="string")j=`Resuming ${String(O.subagent_type||"subagent")} from ${V}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.id,status:"in_progress",title:j,content:[],kind:R});break}case"tool_progress":{let G=$.toolCall;if(G.function.name===q)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let G=$.toolCall;if(G.function.name===q)break;let K=$.result,R=[],j=K.metadata;if(j?.kind==="patch"&&Array.isArray(j.changes))for(let V of j.changes){if(!V||typeof V!=="object"||!("path"in V)||typeof V.path!=="string")continue;R.push({type:"diff",path:V.path,oldText:"oldContent"in V&&typeof V.oldContent==="string"?V.oldContent:null,newText:"newContent"in V&&typeof V.newContent==="string"?V.newContent:null})}else if(j?.kind==="edit"&&typeof j.file_path==="string"&&typeof j.oldContent==="string"&&(typeof j.newContent==="string"||j.newContent===void 0))R.push({type:"diff",path:j.file_path,oldText:j.oldContent,newText:j.newContent??null});else{let V=G.function.name,Vz=o(v(a(V,K),c));R.push({type:"content",content:{type:"text",text:Vz}})}if(G.function.name==="Task"&&(j?.verificationVerdict==="pass"||j?.verificationVerdict==="fail"||j?.verificationVerdict==="partial"))R.unshift({type:"content",content:{type:"text",text:`Verification result: ${j.verificationVerdict.toUpperCase()}`}});let O=K.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:O,content:R});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
+ `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
+ `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
5
+ `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
6
+ `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
7
+ `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
8
+ `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
9
+ `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
10
+ `}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":for(let G of $.messages){if(!G.recovered||G.persisted)continue;for(let K of Dz(G.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:K})}if($.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${$.recovered} queued instruction${$.recovered===1?"":"s"} recovered after restart]
11
+ `}});break;case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.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:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{}}}});break;default:break}if(!await this.flushUpdates())X.abort("acp-egress-failed")});if(!await this.flushUpdates())X.abort("acp-egress-failed");this.contextMessages=[...L.messages];let A=await _.loadSession(this.id,this.cwd);if(this.messages=A.length>0?A:[...L.messages],!B.success){let $=B.error?.type??"unknown";throw Az.internalError({failureType:$},`Agent turn failed (${$})`)}if(X.signal.aborted)return{stopReason:"cancelled"};let C={...B.metadata?.structuredOutput?{structuredOutput:B.metadata.structuredOutput,outputSchemaDigest:B.metadata.structuredOutputSchemaDigest}:{},...B.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:B.metadata.goalVerificationVerdict,...B.metadata.goalVerifierSessionId?{verifierSessionId:B.metadata.goalVerifierSessionId}:{},...B.metadata.goalVerificationEvidenceSha256?{evidenceSha256:B.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(C).length>0?{_meta:C}:{}}}catch(L){if(X.signal.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};throw U.error(`[AcpSession ${this.id}] Prompt error:`,L),L}finally{if(Y(),this.pendingPromptCompletion===F)this.pendingPromptCompletion=null;if(this.pendingPrompt===X){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let H=new AbortController,D,W=new Promise((X)=>{D=X});this.pendingUserShell=H,this.pendingUserShellCompletion=W;let Q,Z="";try{let X=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(F)=>{if(Q=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"){Z+=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 L=S(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:Z?Oz(F.record):L}}]})}}),Y={role:"user",content:X.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(X.record))}};if(this.messages.push(Y),this.contextMessages.push(Y),X.delivery==="next_turn")this.schedulePendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:X.record.status==="aborted"?"cancelled":"end_turn"}}catch(X){if(Q)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Q,status:"failed",content:[{type:"content",content:{type:"text",text:X instanceof Error?X.message:String(X)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw X}finally{if(D(),this.pendingUserShellCompletion===W)this.pendingUserShellCompletion=null;if(this.pendingUserShell===H)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 z=this.runtime.getPendingSteeringCount()>0,J=z?null:await this.runtime.getGoal(),H=J?.status==="active"||J?.status==="verifying";if(!z&&!H){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:z,goalContinuationOnly:H}).catch((D)=>{U.error(`[AcpSession ${this.id}] Failed to resume pending input:`,D)})}cancel(){U.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let z=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(!z)U.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"].includes(z)?z:"default",D=this.mapModeIdToPermissionMode(H);await _.setSessionPermissionMode(this.id,this.cwd,D),this.mode=H,U.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(U.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await _.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(H){if(!(H instanceof N)&&H.code!=="ENOENT")throw H;await _.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(H){if(J&&J!==z)await this.agent.switchModel(J).catch((D)=>{U.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,D)});throw H}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await _.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(H){if(!(H instanceof N)&&H.code!=="ENOENT")throw H;await _.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(H){throw await this.runtime.refresh({reasoningEffort:J.selection}),H}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await _.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(H){if(!(H instanceof N)&&H.code!=="ENOENT")throw H;await _.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(H){throw await this.runtime.refresh({serviceTier:J.selection}),H}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await _.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(H){if(!(H instanceof N)&&H.code!=="ENOENT")throw H;await _.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(H){throw await this.runtime.refresh({responseVerbosity:J.selection}),H}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),H=this.runtime.resolveCommunicationStyleConfiguration(z);if(H.source!=="built-in"&&!H.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await _.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:H.source==="built-in"?null:H.contentSha256})}catch(D){if(!(D instanceof N)&&D.code!=="ENOENT")throw D;await _.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...H.source!=="built-in"&&H.contentSha256?{communicationStyleDigest:H.contentSha256}:{}})}}catch(D){throw await this.runtime.refresh({communicationStyle:J.selection}),D}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}destroy(){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources().finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(){if(this.destroyed=!0,this.updateEgress.close(new zz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let z=this.agent,J=this.runtime,H=this.pendingPromptCompletion,D=this.pendingUserShellCompletion;this.agent=null,this.runtime=null;let W,Q=async(Z)=>{try{await Z()}catch(X){W??=X}};if(await Q(()=>this.cancel()),H)await Q(()=>H);if(D)await Q(()=>D);if(z)await Q(()=>z.destroy());if(J)await Q(()=>J.dispose());if(await Q(()=>P.destroySession(this.id)),U.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let J=[],H=[],D=0,W=0,Q=0,Z=(Y)=>{if(H.length>0)H.push({type:"text",text:`
13
+ `}),Q+=1;if(H.push(Y),Y.type==="text")Q+=Y.text.length};for(let Y of z)if(Y.type==="text")J.push(Y.text),Z({type:"text",text:Y.text});else if(Y.type==="image"){let F=`data:${Y.mimeType};base64,${Y.data}`;D+=1,W+=F.length,J.push(`[Image: ${Y.mimeType}]`),Z({type:"image_url",image_url:{url:F}})}else if(Y.type==="resource"){let F=Y.resource;if("text"in F){let L=`<file path="${F.uri}">
14
+ ${F.text}
15
+ </file>`;J.push(L),Z({type:"text",text:L})}}else if(Y.type==="resource_link"){let F=`[Resource: ${Y.uri}]`;J.push(F),Z({type:"text",text:F})}if(D>y)throw Error(`ACP prompt contains more than ${y} images`);if(W>u)throw Error("ACP prompt images exceed the 5 MiB limit");if(Q>I)throw Error(`ACP prompt text exceeds ${I} characters`);let X=J.join(`
16
+ `);return{content:D>0?H:X,displayText:X}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;U.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));U.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let H=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(H))return U.debug(`[AcpSession ${this.id}] Auto-approving ${H} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(H==="write"||H==="execute"))return U.debug(`[AcpSession ${this.id}] Rejecting ${H} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let D=M(),W=[];if(z.message)W.push({type:"content",content:{type:"text",text:z.message}});if(z.details)W.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)W.push({type:"content",content:{type:"text",text:`Risks:
17
+ - ${z.risks.join(`
18
+ - `)}`}});let Q=this.mapToolKind(H),Z={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:D,status:"pending",title:z.title||"Permission Required",content:W,kind:Q}},X=await this.waitForClientInteraction(this.connection.requestPermission(Z),J);if(!X)return{approved:!1,reason:h};let Y=X.outcome;if(Y.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let F=Y.optionId;if(F==="allow_always")return{approved:!0,scope:"project"};if(F==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=F==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(D){return U.warn(`[AcpSession ${this.id}] Permission request failed:`,D),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let H=z.questions??[];if(H.length===0)return{approved:!1,reason:"No structured questions were provided"};if(H.some((W)=>W.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let D={};try{for(let[W,Q]of H.entries()){let Z=Q.options.map((L,B)=>`answer:${W}:${B}`),X=`answer:${W}:cancel`,Y=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.options.map((L,B)=>({optionId:Z[B],name:L.label,kind:"allow_once"})),{optionId:X,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:M(),status:"pending",title:Q.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Q.question,...Q.options.map((L)=>`${L.label}: ${L.description}`)].join(`
19
+ `)}}]}}),J);if(!Y)return{approved:!1,reason:h};if(Y.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let F=Z.indexOf(Y.outcome.optionId);if(F<0)return{approved:!1,reason:"User cancelled the question prompt"};D[Q.header]=Q.options[F].label}return{approved:!0,answers:D}}catch(W){return U.warn(`[AcpSession ${this.id}] Question request failed:`,W),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let H=z.mcpElicitation;if(!H)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(H.mode==="url"){let W=await this.requestElicitationChoice("MCP external authorization",[H.message,`Server: ${H.serverName}`,`Domain: ${H.domain??"unknown"}`,`URL: ${H.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
+ `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(W==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:W==="decline"?"User declined URL":"User cancelled",elicitation:{action:W==="decline"?"decline":"cancel"}}}let D=Object.create(null);for(let W of H.fields??[]){let Q=await this.collectAcpElicitationField(W,J);if(Q.cancelled)return{approved:!1,reason:Q.reason,elicitation:{action:"cancel"}};if(Q.value!==void 0)D[W.name]=Q.value}return{approved:!0,elicitation:{action:"accept",content:D}}}catch(D){return U.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,D),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let H=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((Q,Z)=>({id:`option:${Z}`,label:Q.label,value:Q.value})),D=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
21
+ `),[...H.map((Q)=>({id:Q.id,label:Q.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(D==="skip")return{cancelled:!1};let W=H.find((Q)=>Q.id===D);if(!W)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:W.value}}if(z.defaultValue!==void 0){let H=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
22
+ `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(H==="default")return{cancelled:!1,value:z.defaultValue};if(H==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,H,D){let W=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.map((Q)=>({optionId:Q.id,name:Q.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:M(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),D);return W?.outcome.outcome==="selected"?W.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,D)=>{let W=!1,Q=(X)=>{if(W)return;W=!0,J.removeEventListener("abort",Z),X()},Z=()=>Q(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then((X)=>Q(()=>H(X)),(X)=>Q(()=>D(X)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var w=x("Agent");class k{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}async initialize(z){return w.info("[BladeAgent] Initializing ACP connection"),w.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,{protocolVersion:Pz,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=Lz("acp"),H=z.cwd||Xz(),D=z._meta?.["blade/taskIsolation"],W=D==="local"||D==="worktree"?D:void 0,Q=z._meta?.["blade/taskPrompt"],Z=W?await jz.createSessionTask({sessionId:J,prompt:typeof Q==="string"&&Q.trim()?Q:"ACP task session",sourceProjectPath:H,isolation:W}):void 0,X=Z?.metadata.projectPath??H;w.info(`[BladeAgent] Creating new session: ${J}`),w.debug(`[BladeAgent] Session cwd: ${X}`);let Y=new E(J,X,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...Z?.taskWorktree?{taskWorktree:Z.taskWorktree}:{},...Z?.metadata.taskIsolation?{taskIsolation:Z.metadata.taskIsolation}:{}});try{await Y.initialize(),this.assertNotDestroyed()}catch(F){throw await Y.destroy().catch(()=>{return}),F}return this.sessions.set(J,Y),w.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),Y.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,Z?.metadata,Y.getModelConfiguration())}async listSessions(z){if(z.cwd!=null&&!Wz.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await _.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskFailure?{"blade/taskFailure":H.taskFailure}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{},...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskIsolation?{"blade/taskIsolation":H.taskIsolation}:{},...H.taskSourceProjectPath?{"blade/taskSourceProjectPath":H.taskSourceProjectPath}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{},...H.taskDiffStat?{"blade/taskDiffStat":H.taskDiffStat}:{},...H.taskQueuePosition?{"blade/taskQueuePosition":H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{"blade/taskQueueDepth":H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":H.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Wz.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=await _.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd});this.assertNotDestroyed();let H=new E(J.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:J.messages,permissionMode:J.metadata.permissionMode,mcpServers:z.mcpServers});try{await H.initialize(),this.assertNotDestroyed()}catch(D){throw await H.destroy().catch(()=>{return}),D}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J.sessionId,J.metadata,H.getModelConfiguration())}async loadSession(z){this.assertNotDestroyed(),w.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),D=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,D);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===D)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await _.assertSessionWritable(z.sessionId,z.cwd);let J=this.sessions.get(z.sessionId);if(J)try{await J.destroy()}finally{if(this.sessions.get(z.sessionId)===J)this.sessions.delete(z.sessionId)}let[H,D]=await Promise.all([_.loadSession(z.sessionId,z.cwd),_.findSessionMetadata(z.sessionId,z.cwd)]);if(!D)throw Error(`Session not found: ${z.sessionId}`);let W=new E(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H,permissionMode:D.permissionMode,mcpServers:z.mcpServers});try{await W.initialize(),await W.replayHistory(),this.assertNotDestroyed()}catch(Q){throw await W.destroy().catch(()=>{return}),Q}return this.sessions.set(z.sessionId,W),W.sendAvailableCommandsDelayed(),this.buildSessionSetup(W.getModelConfiguration(),W.getMode())}buildChildSessionResponse(z,J,H){return{sessionId:z,...this.buildSessionSetup(H,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(z,J="default"){let H=z?.models??[],D=(z?.currentModelId&&H.some((Z)=>Z.id===z.currentModelId)?z.currentModelId:void 0)??H[0]?.id,W=[{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"}],Q=[];if(H.length>0)Q.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:D,options:H.map((Z)=>({value:Z.id,name:Z.displayName??Z.model,description:`${z?.modelProviders[Z.provider]?.name??Z.provider} · ${Z.model}`}))});if(z?.reasoning)Q.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="off"?"Disable model reasoning":`Use ${Z} reasoning effort`}))]});if(z?.serviceTier)Q.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="fast"?"Use the provider priority tier":Z==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)Q.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:`Use ${Z} response verbosity`}))]});if(z?.communicationStyle)Q.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Z)=>({value:Z.id,name:Z.name,description:`${Z.description} · ${Z.source}`}))});return{modes:{availableModes:W,currentModeId:J},configOptions:Q.length>0?Q:void 0}}async prompt(z){let J=this.sessions.get(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);return J.prompt(z)}async cancel(z){w.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.sessions.get(z.sessionId);if(J)w.info("[BladeAgent] Found session, calling session.cancel()"),J.cancel();else w.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){w.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.sessions.get(z.sessionId);if(J)await J.setMode(z.modeId);return{}}async setSessionConfigOption(z){let J=this.sessions.get(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);if(z.configId==="model"&&"value"in z&&typeof z.value==="string")w.info(`[BladeAgent] Setting session model: ${z.value}`),await J.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&Bz(z.value))w.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await J.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Fz(z.value))w.info(`[BladeAgent] Setting service tier: ${z.value}`),await J.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&Yz(z.value))w.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await J.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&Uz(z.value))w.info(`[BladeAgent] Setting communication style: ${z.value}`),await J.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(J.getModelConfiguration(),J.getMode()).configOptions??[]}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of this.sessions.values())try{await J.destroy()}catch(H){z??=H}this.sessions.clear();try{await _z.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function BH(){let z=qz.toWeb(process.stdout),J=Ez.toWeb(process.stdin),H=b.ndJsonStream(z,J),D,W=new b.AgentSideConnection((Z)=>{return D=new k(Z),D},H),Q=Gz(async()=>{await D?.destroy()});try{await W.closed}finally{Q(),await D?.destroy()}}export{BH as runAcpIntegration};