blade-code 0.10.33 → 0.10.35

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 (105) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-015fx09x.js +4 -0
  3. package/dist/{chunk-91sne4g4.js → chunk-031n82db.js} +2 -2
  4. package/dist/{chunk-20qedxrp.js → chunk-0g7cjx1t.js} +1 -1
  5. package/dist/{chunk-23bkpq26.js → chunk-0hdsbwhf.js} +2 -2
  6. package/dist/{chunk-g2yj0chw.js → chunk-0zs3mn75.js} +1 -1
  7. package/dist/{chunk-40654rh3.js → chunk-132q0hyf.js} +2 -2
  8. package/dist/{chunk-189drzww.js → chunk-1jagjybs.js} +1 -1
  9. package/dist/{chunk-3r0yfspg.js → chunk-2kzg80r3.js} +1 -1
  10. package/dist/{chunk-6bqd2hkz.js → chunk-2y4qyct0.js} +1 -1
  11. package/dist/{chunk-qj6gafse.js → chunk-38ca5c9f.js} +1 -1
  12. package/dist/chunk-39wa7cfr.js +1 -0
  13. package/dist/{chunk-ztyt12kf.js → chunk-3nn4rth6.js} +2 -2
  14. package/dist/{chunk-f20mb84y.js → chunk-3qmawdwf.js} +2 -2
  15. package/dist/{chunk-f5yx8s8t.js → chunk-4en93rc4.js} +1 -1
  16. package/dist/{chunk-kqe9y6ka.js → chunk-4ncddyay.js} +2 -2
  17. package/dist/{chunk-vp7n0w9w.js → chunk-4s6w24r3.js} +2 -2
  18. package/dist/chunk-51b7jb2s.js +1 -0
  19. package/dist/{chunk-f9graf2n.js → chunk-6b1vvq1f.js} +1 -1
  20. package/dist/chunk-6r9jb465.js +8 -0
  21. package/dist/{chunk-97mzk53w.js → chunk-6v51xb9r.js} +1 -1
  22. package/dist/chunk-7cbe8yjn.js +1 -0
  23. package/dist/{chunk-9qj6y0sj.js → chunk-7jja0242.js} +1 -1
  24. package/dist/{chunk-d3h8cgs8.js → chunk-7m5az521.js} +1 -1
  25. package/dist/{chunk-k9px24b5.js → chunk-83w81bma.js} +1 -1
  26. package/dist/{chunk-zvjvbhc4.js → chunk-9h41rm97.js} +2 -2
  27. package/dist/{chunk-91vwv4ph.js → chunk-a1wjgf44.js} +2 -2
  28. package/dist/{chunk-w45ngpy1.js → chunk-aytg9gw0.js} +2 -2
  29. package/dist/chunk-b7xdtjh8.js +1610 -0
  30. package/dist/{chunk-3j57nm6f.js → chunk-ck9r8h1h.js} +2 -2
  31. package/dist/chunk-cz1hb799.js +1 -0
  32. package/dist/chunk-d4hcy6p1.js +2 -0
  33. package/dist/{chunk-5fm0qywg.js → chunk-dbwa9rwr.js} +2 -2
  34. package/dist/{chunk-bvnxztsj.js → chunk-eqj58q4r.js} +1 -1
  35. package/dist/chunk-fbxgxwfm.js +1 -0
  36. package/dist/chunk-gcyd5s5h.js +1 -0
  37. package/dist/{chunk-tzragyzm.js → chunk-gg179pdx.js} +1 -1
  38. package/dist/chunk-h7v23pw2.js +1 -0
  39. package/dist/chunk-hk36a59x.js +1 -0
  40. package/dist/{chunk-mxyb9hn6.js → chunk-hq8cbzfv.js} +1 -1
  41. package/dist/{chunk-4kratdhc.js → chunk-hymw69m4.js} +1 -1
  42. package/dist/{chunk-vzf17snk.js → chunk-js5whev4.js} +2 -2
  43. package/dist/{chunk-ctn675zn.js → chunk-k5gv2phs.js} +2 -2
  44. package/dist/chunk-mkmcwc5r.js +1 -0
  45. package/dist/{chunk-vm0w0jt9.js → chunk-nwtgx6p6.js} +1 -1
  46. package/dist/{chunk-mt3nrz7x.js → chunk-pf8rybpm.js} +2 -2
  47. package/dist/{chunk-8vxxmdhd.js → chunk-pgy1mtgw.js} +1 -1
  48. package/dist/{chunk-y1bb5391.js → chunk-pmxqjb29.js} +1 -1
  49. package/dist/chunk-pn2e99pn.js +1 -0
  50. package/dist/{chunk-zhbpatxr.js → chunk-q30azbe2.js} +1 -1
  51. package/dist/{chunk-hs3yryjm.js → chunk-qf357j45.js} +2 -2
  52. package/dist/chunk-qhfbdp5e.js +1 -0
  53. package/dist/{chunk-k05xt45s.js → chunk-r84jsjnc.js} +1 -1
  54. package/dist/chunk-r9j56qcs.js +1 -0
  55. package/dist/{chunk-wzjhwr2p.js → chunk-rcp5maxt.js} +3 -3
  56. package/dist/{chunk-mdrdafpa.js → chunk-rwtgrs8d.js} +1 -1
  57. package/dist/chunk-sbyyg6qg.js +204 -0
  58. package/dist/chunk-se9krwes.js +6 -0
  59. package/dist/{chunk-amm23yvd.js → chunk-sqp79c1a.js} +2 -2
  60. package/dist/{chunk-zftb9s2h.js → chunk-t1zs40rj.js} +2 -2
  61. package/dist/chunk-tencwrxf.js +1 -0
  62. package/dist/{chunk-h9v4tzdt.js → chunk-vpe44cnj.js} +2 -2
  63. package/dist/chunk-wf7ycftn.js +1 -0
  64. package/dist/{chunk-0k0k5qjr.js → chunk-wmvj44cr.js} +2 -2
  65. package/dist/{chunk-vybzvxf9.js → chunk-xf03b657.js} +1 -1
  66. package/dist/chunk-y5kp6fmy.js +22 -0
  67. package/dist/{chunk-m06gcr4k.js → chunk-ytec29ph.js} +1 -1
  68. package/dist/chunk-z45qe8dg.js +2 -0
  69. package/dist/chunk-zhr1btfv.js +10 -0
  70. package/dist/{chunk-z2k6q0k1.js → chunk-zj29g9rc.js} +2 -2
  71. package/dist/{chunk-2rsr3bte.js → chunk-znp4bexg.js} +1 -1
  72. package/dist/web/assets/{ChatView-B7_Um8KR.js → ChatView-Dx9j7CGg.js} +2 -2
  73. package/dist/web/assets/{CodeBlockHighlighter-JzE91vkT.js → CodeBlockHighlighter-CZADKR6S.js} +1 -1
  74. package/dist/web/assets/{FilePreview-BTbtoUBJ.js → FilePreview-BOIDa_oJ.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-IaPtOh2w.js → MarkdownRenderer-DXsfHVUX.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-CPgWPfZ2.js → SettingsModal-lQveNhC6.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-D4RZxQKp.js → TaskSwitcher-BSrmpJ2u.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-yWbQfbYa.js → TerminalPanel-BFre9Shc.js} +1 -1
  79. package/dist/web/assets/{index-BnCT8SxR.js → index-DGZjm9wT.js} +4 -4
  80. package/dist/web/assets/{session-events-BZao_jMQ.js → session-events-Dk20sSDo.js} +19 -19
  81. package/dist/web/index.html +2 -2
  82. package/package.json +1 -1
  83. package/dist/chunk-08fww0yh.js +0 -1
  84. package/dist/chunk-23bhwgwm.js +0 -204
  85. package/dist/chunk-25j7tjr6.js +0 -1
  86. package/dist/chunk-2s24zvjm.js +0 -22
  87. package/dist/chunk-5hn788xk.js +0 -2
  88. package/dist/chunk-6b2w2132.js +0 -2
  89. package/dist/chunk-74js4dnw.js +0 -1
  90. package/dist/chunk-7dt49b6q.js +0 -8
  91. package/dist/chunk-7ncx3vzw.js +0 -1
  92. package/dist/chunk-9c4fvem6.js +0 -1
  93. package/dist/chunk-agw7bq0h.js +0 -1
  94. package/dist/chunk-bhj7dqe8.js +0 -1
  95. package/dist/chunk-dkz757cv.js +0 -1
  96. package/dist/chunk-gmpgmh7s.js +0 -1
  97. package/dist/chunk-gw51xyz9.js +0 -4
  98. package/dist/chunk-m6srq209.js +0 -1
  99. package/dist/chunk-np2vrjpc.js +0 -10
  100. package/dist/chunk-sfvt4ef0.js +0 -1610
  101. package/dist/chunk-wgnzghhc.js +0 -6
  102. package/dist/chunk-xfpne7cm.js +0 -1
  103. package/dist/chunk-ycvwc7hb.js +0 -1
  104. package/dist/chunk-z7s2138c.js +0 -1
  105. package/dist/chunk-zfezz6ew.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-q30azbe2.js";import{t as Jq,u as o,v as n,w as t,x as m,y as e}from"./chunk-7jja0242.js";import{L as Uq,N as _q,O as Mq,Q as Zq,S as Pq}from"./chunk-b7xdtjh8.js";import"./chunk-k5gv2phs.js";import"./chunk-3nn4rth6.js";import{Ua as zq,hb as jq,qb as Hq}from"./chunk-sbyyg6qg.js";import"./chunk-pgy1mtgw.js";import{Yb as Gq,ac as Dq,lc as g,wc as v}from"./chunk-031n82db.js";import"./chunk-d4hcy6p1.js";import"./chunk-4s6w24r3.js";import{Tc as Aq}from"./chunk-9h41rm97.js";import{Vc as xq,Wc as Rq,Xc as bq}from"./chunk-dbwa9rwr.js";import{Yc as Nq}from"./chunk-qf357j45.js";import"./chunk-vpe44cnj.js";import{wd as Kq}from"./chunk-ck9r8h1h.js";import"./chunk-v508x7cg.js";import"./chunk-xf03b657.js";import"./chunk-aytg9gw0.js";import"./chunk-t1zs40rj.js";import"./chunk-pmxqjb29.js";import"./chunk-pf8rybpm.js";import"./chunk-zj29g9rc.js";import"./chunk-ytec29ph.js";import"./chunk-1jagjybs.js";import"./chunk-hq8cbzfv.js";import"./chunk-rcp5maxt.js";import"./chunk-eqj58q4r.js";import"./chunk-js5whev4.js";import{wf as Xq}from"./chunk-r84jsjnc.js";import{Af as qq,Cf as H,xf as Bq,zf as q}from"./chunk-38ca5c9f.js";import"./chunk-z45qe8dg.js";import{Jf as h}from"./chunk-znp4bexg.js";import"./chunk-sqp79c1a.js";import"./chunk-132q0hyf.js";import"./chunk-83w81bma.js";import"./chunk-a1wjgf44.js";import"./chunk-0hdsbwhf.js";import"./chunk-0g7cjx1t.js";import"./chunk-3qmawdwf.js";import"./chunk-7m5az521.js";import xZ from"yargs";import{hideBin as RZ}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",M),p($,"error",_),V.removeEventListener("abort",x)},j=(b)=>{if(Z)return;Z=!0,Y(),b()},M=()=>j(D),_=(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",M),R?.("error",_),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 e({maxPendingItems:V.maxPendingItems??o,maxPendingBytes:V.maxPendingBytes??n,writeTimeoutMs:V.writeTimeoutMs??t,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 $q=1;function z($){return q.Object({event_version:q.Literal($q),...$})}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}$"})}),l=H(["readonly","write","execute"]),lq=q.Object({kind:l,scope:H(["global","session"]),queue_position:q.Integer({minimum:1}),in_flight:q.Integer({minimum:0}),limit:q.Integer({minimum:1})}),vq=z({type:q.Literal("tool_start"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(l)}),sq=z({type:q.Literal("tool_progress"),tool_name:q.String(),message:q.String(),progress:q.Optional(q.Number()),total:q.Optional(q.Number()),admission:q.Optional(lq)}),aq=z({type:q.Literal("tool_result"),tool_name:q.String(),summary:q.String(),target:q.Optional(q.String()),tool_kind:q.Optional(l),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())}),rq=z({type:q.Literal("mcp_content_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),content_kind:H(["resources","resource_templates","prompts"]),added:q.Array(q.String()),removed:q.Array(q.String()),updated:q.Array(q.String())}),oq=z({type:q.Literal("mcp_resource_updated"),revision:q.Integer({minimum:1}),server_name:q.String(),uri:q.String()}),nq=z({type:q.Literal("mcp_connection_changed"),revision:q.Integer({minimum:1}),server_name:q.String(),phase:H(["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())}),tq=z({type:q.Literal("mcp_log"),revision:q.Integer({minimum:1}),server_name:q.String(),level:H(["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())}),eq=z({type:q.Literal("mcp_instructions_changed"),revision:q.Integer({minimum:0}),server_name:q.String(),action:H(["added","removed"]),reason:H(["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())}),qZ=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:H(["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())}),ZZ=z({type:q.Literal("project_rules_loaded"),files:q.Array(q.Object({id:q.String(),relative_path:q.String(),source:H(["project","local"]),conditional:q.Boolean(),content_sha256:q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:q.Array(q.String()),blocked_write:q.Boolean()}),$Z=z({type:q.Literal("user_shell_started"),execution_id:q.String(),command:q.String(),auxiliary:q.Boolean()}),VZ=z({type:q.Literal("user_shell_output"),execution_id:q.String(),stream:H(["stdout","stderr"]),chunk:q.String(),stream_truncated:q.Boolean()}),YZ=z({type:q.Literal("user_shell_completed"),execution_id:q.String(),message_id:q.String(),status:H(["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()}),QZ=z({type:q.Literal("phase"),phase:H(["turn","searching","inspecting","target_hit","executing","completed"]),status:H(["ongoing","hit","done"]),message:q.String(),turn:q.Optional(q.Number()),tool_name:q.Optional(q.String()),target:q.Optional(q.String())}),XZ=z({type:q.Literal("tool_detail"),tool_name:q.String(),detail:q.String()}),BZ=z({type:q.Literal("task_update"),tasks:q.Array(Zq)}),KZ=z({type:q.Literal("goal"),state:H(["updated","cleared"]),goal_id:q.Optional(q.String()),status:q.Optional(H(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:q.Optional(q.Integer({minimum:1})),verification_status:q.Optional(H(["pending","pass","fail","partial"])),verifier_session_id:q.Optional(q.String()),verification_evidence_sha256:q.Optional(q.String({pattern:"^[a-f0-9]{64}$"}))}),GZ=z({type:q.Literal("subagent"),state:H(["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(H(["pass","fail","partial"])),resumed_from:q.Optional(q.String()),root_agent_id:q.Optional(q.String()),resume_depth:q.Optional(q.Integer({minimum:0}))}),DZ=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())}),zZ=z({type:q.Literal("compacting"),state:H(["started","completed"]),reason:q.Optional(H(["threshold","context_limit","turn_limit","manual"])),strategy:q.Optional(H(["llm","fallback","snip"])),outcome:q.Optional(H(["completed","fallback","failed"])),pre_tokens:q.Optional(q.Number({minimum:0})),post_tokens:q.Optional(q.Number({minimum:0}))}),jZ=z({type:q.Literal("provider_retry"),phase:H(["scheduled","attempt","recovered","exhausted"]),attempt:q.Integer({minimum:0}),max_retries:q.Integer({minimum:0}),reason:H(["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}))}),HZ=z({type:q.Literal("provider_stall"),phase:H(["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()}),UZ=z({type:q.Literal("action_stationarity"),phase:H(["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()}),_Z=z({type:q.Literal("turn_limit"),turns_count:q.Number(),action:q.Literal("continue")}),MZ=z({type:q.Literal("task_session"),session_id:q.String(),project_path:q.String(),source_project_path:q.String(),isolation:H(["local","worktree"]),worktree_branch:q.Optional(q.String()),base_commit:q.Optional(q.String())}),PZ=z({type:q.Literal("task_admission"),state:H(["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})}),NZ=z({type:q.Literal("output"),content:q.String(),exit_code:q.Number()}),AZ=z({type:q.Literal("error"),message:q.String()}),dZ=qq(q.Union([wq,cq,dq,mq,pq,uq,vq,sq,aq,iq,rq,oq,nq,tq,eq,qZ,ZZ,$Z,VZ,YZ,QZ,XZ,BZ,KZ,GZ,DZ,zZ,jZ,HZ,UZ,_Z,MZ,PZ,NZ,AZ]));function Vq($,V){return{event_version:$q,type:$,...V}}function bZ($){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 JZ=H(["text","jsonl"]),fZ=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(H(["local","worktree"])),outputFormat:q.Optional(JZ),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 EZ($){return $.issues.map((V)=>`${V.path.join(".")||"options"}: ${V.message}`).join("; ")}function IZ($){let V=Bq(fZ,$);if(!V.success)throw Error(`Invalid headless options: ${EZ(V.error)}`);return V.data}function LZ($){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 kZ(V);process.exit(D)})}function U($,V=""){$.write(`${V}
2
+ `)}function WZ($){return`[task] [${$.status}] ${$.subject}`}function SZ(){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 CZ($){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 OZ($){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 hZ($,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}U($.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}U($.stdout,Z)},structuredOutput(Z){if(V==="jsonl"){Q("structured_output",{output:Z.output,schema_digest:Z.schemaDigest});return}U($.stdout,JSON.stringify(Z.output))},toolStart(Z,Y,j,M){if(V==="jsonl"){Q("tool_start",{tool_name:Z,summary:Y,target:j,tool_kind:M});return}U($.stderr,`[tool:start] ${Y}`)},toolProgress(Z,Y,j,M,_){if(V==="jsonl"){Q("tool_progress",{tool_name:Z,message:Y,progress:j,total:M,admission:_?{kind:_.kind,scope:_.scope,queue_position:_.queuePosition,in_flight:_.inFlight,limit:_.limit}:void 0});return}U($.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:M,success:_?.success,error_type:_?.errorType,error_message:_?.errorMessage});return}U($.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}U($.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}U($.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}U($.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}U($.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}U($.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}U($.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}U($.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}U($.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}U($.stderr,`[user-shell:start] ${Y}`)},userShellOutput(Z,Y,j,M){if(V==="jsonl"){Q("user_shell_output",{execution_id:Z,stream:Y,chunk:j,stream_truncated:M});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}U($.stderr,`[user-shell:${Z.record.status}] exit=${Z.record.exitCode??"null"} ${Z.record.durationMs}ms`)},phase(Z,Y,j,M={}){if(V==="jsonl"){Q("phase",{phase:Z,status:Y,message:j,turn:M.turn,tool_name:M.toolName,target:M.target});return}U($.stderr,`[phase:${Z}] ${j}`)},toolDetail(Z,Y){if(V==="jsonl"){Q("tool_detail",{tool_name:Z,detail:Y});return}U($.stderr,Y)},taskUpdate(Z){if(V==="jsonl"){Q("task_update",{tasks:Z});return}for(let Y of Z)U($.stderr,WZ(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)U($.stderr,`[goal:${Z.goal.status}] ${Z.goal.objective}`);else U($.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}U($.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}U($.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}U($.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`:"";U($.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}U($.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}U($.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}U($.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}U($.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}U($.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}U(Y===0?$.stdout:$.stderr,Z)},error(Z){if(V==="jsonl"){Q("error",{message:Z});return}U($.stderr,Z)}}}async function kZ($,V={stdout:process.stdout,stderr:process.stderr},D){let Q="text",Z=new Cq,Y={targetLocked:!1},j,M,_=bZ(D),x=!1,R=new u(V,{signal:_.signal,onFailure:(B)=>{x=!0,_.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 M?.(),M=void 0,await w()?B:1};try{let B=IZ($);Q=OZ(B.outputFormat);let E=await Wq(B);K=Qq(b,Q,Boolean(E)),await fq();let s=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=s===void 0,N=S?{mode:"agent",content:""}:await Lq(s);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:a,metadata:i}=await Sq({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),C=B.permissionMode??i?.permissionMode??"yolo",r=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,...r?{modelId:r}:{},...E?{outputSchema:E}:{}}}):void 0,J=P?.metadata.projectPath??i?.projectPath??h();if(!P)await v.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}),M=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 v.loadSessionModelContext(A,J):[...a],userId:"cli-user",sessionId:A,workspaceRoot:J,permissionMode:C,signal:_.signal,...P?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:SZ()};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}:{},...a.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:_.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:_.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=hZ(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,X.update.admission);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: ${CZ(B)}`)}return await f(1)}finally{M?.();try{await j?.dispose()}finally{R.close(),_.dispose()}}}async function j0(){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,...M}=Aq,_=xZ(RZ(process.argv)).scriptName("blade").strict(!1).options(M).middleware([Rq,xq,bq]);return LZ(_),await _.parse(),!0}export{kZ as runHeadless,j0 as handleHeadlessMode,fZ as HeadlessOptionsSchema};
@@ -1,3 +1,3 @@
1
- import{mg as j}from"./chunk-f20mb84y.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
1
+ import{og as j}from"./chunk-3qmawdwf.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
2
2
  `)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
3
- export{m as If,I as Jf,M as Kf,V as Lf,h as Mf};
3
+ export{m as Kf,I as Lf,M as Mf,V as Nf,h as Of};
@@ -1,2 +1,2 @@
1
- import{Pd as B}from"./chunk-y1bb5391.js";import{Rf as Y}from"./chunk-40654rh3.js";import{Uf as Z,Xf as $}from"./chunk-k9px24b5.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
- export{K as Ld,O as Md,E as Nd};
1
+ import{Rd as B}from"./chunk-pmxqjb29.js";import{Tf as Y}from"./chunk-132q0hyf.js";import{Wf as Z,Zf as $}from"./chunk-83w81bma.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
+ export{K as Nd,O as Od,E as Pd};
@@ -0,0 +1 @@
1
+ import{Md as a}from"./chunk-aytg9gw0.js";import"./chunk-sqp79c1a.js";import"./chunk-132q0hyf.js";import"./chunk-83w81bma.js";import"./chunk-3qmawdwf.js";import"./chunk-7m5az521.js";export{a as createChatServiceAsync};
@@ -1,4 +1,4 @@
1
- import{Ef as L,Hf as _}from"./chunk-2rsr3bte.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
1
+ import{Gf as L,Jf as _}from"./chunk-znp4bexg.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
2
2
  You have been invoked in the following environment:
3
3
  - Primary working directory: ${B.workingDirectory}
4
4
  - Is a git repository: ${$?"true":"false"}
@@ -25,4 +25,4 @@ ${I.join(`
25
25
 
26
26
  Project root directory listing:
27
27
  ${K}`}return N}function f(z){let q=z,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??z}function x(z,q){let M=j(z)?z:R(q||process.cwd(),z),W;try{W=b(M)}catch{W=M}L(W)}
28
- export{v as $c,f as ad,x as bd};
28
+ export{v as bd,f as cd,x as dd};
@@ -0,0 +1 @@
1
+ import{Sd as a,Td as b,Ud as c}from"./chunk-pf8rybpm.js";import"./chunk-js5whev4.js";import"./chunk-r84jsjnc.js";import"./chunk-38ca5c9f.js";import"./chunk-z45qe8dg.js";import"./chunk-znp4bexg.js";import"./chunk-sqp79c1a.js";import"./chunk-132q0hyf.js";import"./chunk-83w81bma.js";import"./chunk-a1wjgf44.js";import"./chunk-0hdsbwhf.js";import"./chunk-0g7cjx1t.js";import"./chunk-3qmawdwf.js";import"./chunk-7m5az521.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{sf as Q}from"./chunk-vzf17snk.js";import"./chunk-k05xt45s.js";import"./chunk-qj6gafse.js";import"./chunk-5hn788xk.js";import{Hf as L}from"./chunk-2rsr3bte.js";import"./chunk-amm23yvd.js";import"./chunk-40654rh3.js";import"./chunk-k9px24b5.js";import"./chunk-91vwv4ph.js";import"./chunk-23bkpq26.js";import"./chunk-20qedxrp.js";import"./chunk-f20mb84y.js";import{og as F}from"./chunk-d3h8cgs8.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-7ncx3vzw.js"),{SessionService:B}=await import("./chunk-ycvwc7hb.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-v508x7cg.js";import{uf as Q}from"./chunk-js5whev4.js";import"./chunk-r84jsjnc.js";import"./chunk-38ca5c9f.js";import"./chunk-z45qe8dg.js";import{Jf as L}from"./chunk-znp4bexg.js";import"./chunk-sqp79c1a.js";import"./chunk-132q0hyf.js";import"./chunk-83w81bma.js";import"./chunk-a1wjgf44.js";import"./chunk-0hdsbwhf.js";import"./chunk-0g7cjx1t.js";import"./chunk-3qmawdwf.js";import{qg as F}from"./chunk-7m5az521.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-39wa7cfr.js"),{SessionService:B}=await import("./chunk-qhfbdp5e.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1,2 +1,2 @@
1
1
  import{nanoid as q}from"nanoid";var u=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function B(j="session",m=21){if(!u.test(j))throw Error(`Invalid session ID prefix: ${j}`);return`${j}-${q(m)}`}
2
- export{B as Dd};
2
+ export{B as Fd};
@@ -0,0 +1,22 @@
1
+ import{s as T}from"./chunk-2kzg80r3.js";import{t as jz,u as t,v as s,w as e,x as zz,y as Hz}from"./chunk-7jja0242.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-b7xdtjh8.js";import{ra as _z}from"./chunk-k5gv2phs.js";import"./chunk-3nn4rth6.js";import{Ua as m,hb as l,qb as i}from"./chunk-sbyyg6qg.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-031n82db.js";import"./chunk-d4hcy6p1.js";import"./chunk-4s6w24r3.js";import{_c as Gz}from"./chunk-015fx09x.js";import"./chunk-vpe44cnj.js";import"./chunk-ck9r8h1h.js";import"./chunk-v508x7cg.js";import{Fd as Lz}from"./chunk-xf03b657.js";import"./chunk-aytg9gw0.js";import"./chunk-t1zs40rj.js";import{Qd as Bz}from"./chunk-pmxqjb29.js";import"./chunk-pf8rybpm.js";import"./chunk-zj29g9rc.js";import"./chunk-ytec29ph.js";import{ve as Uz}from"./chunk-1jagjybs.js";import"./chunk-hq8cbzfv.js";import"./chunk-rcp5maxt.js";import"./chunk-eqj58q4r.js";import"./chunk-js5whev4.js";import"./chunk-r84jsjnc.js";import"./chunk-38ca5c9f.js";import{Df as y,Ef as u,Ff as I}from"./chunk-z45qe8dg.js";import{Jf as Xz}from"./chunk-znp4bexg.js";import{Nf as x}from"./chunk-sqp79c1a.js";import"./chunk-132q0hyf.js";import{Uf as Yz,Xf as Fz}from"./chunk-83w81bma.js";import"./chunk-a1wjgf44.js";import"./chunk-0hdsbwhf.js";import"./chunk-0g7cjx1t.js";import"./chunk-3qmawdwf.js";import"./chunk-7m5az521.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};
@@ -1,2 +1,2 @@
1
1
  var i="verification",E="goal-verification",e="review";function t(n){return n==="verification"||n==="goal-verification"}function o(n){return t(n)||n==="review"}
2
- export{i as oe,E as pe,e as qe,t as re,o as se};
2
+ export{i as qe,E as re,e as se,t as te,o as ue};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as Df,T as Ef,A as Ff};
@@ -0,0 +1,10 @@
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-6r9jb465.js";import"./chunk-hymw69m4.js";import"./chunk-0zs3mn75.js";import"./chunk-2kzg80r3.js";import"./chunk-7jja0242.js";import"./chunk-b7xdtjh8.js";import"./chunk-k5gv2phs.js";import"./chunk-3nn4rth6.js";import"./chunk-sbyyg6qg.js";import"./chunk-pgy1mtgw.js";import"./chunk-031n82db.js";import"./chunk-d4hcy6p1.js";import"./chunk-4s6w24r3.js";import{_c as R}from"./chunk-015fx09x.js";import"./chunk-vpe44cnj.js";import{ud as Q}from"./chunk-ck9r8h1h.js";import"./chunk-v508x7cg.js";import"./chunk-xf03b657.js";import"./chunk-aytg9gw0.js";import"./chunk-t1zs40rj.js";import"./chunk-pmxqjb29.js";import"./chunk-pf8rybpm.js";import"./chunk-zj29g9rc.js";import"./chunk-ytec29ph.js";import"./chunk-1jagjybs.js";import"./chunk-hq8cbzfv.js";import"./chunk-rcp5maxt.js";import"./chunk-eqj58q4r.js";import"./chunk-js5whev4.js";import"./chunk-r84jsjnc.js";import"./chunk-38ca5c9f.js";import"./chunk-z45qe8dg.js";import"./chunk-znp4bexg.js";import"./chunk-sqp79c1a.js";import"./chunk-132q0hyf.js";import"./chunk-83w81bma.js";import{$f as M}from"./chunk-a1wjgf44.js";import"./chunk-0hdsbwhf.js";import"./chunk-0g7cjx1t.js";import"./chunk-3qmawdwf.js";import"./chunk-7m5az521.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};
@@ -1,4 +1,4 @@
1
- import{oe as L1,pe as Z0,qe as G1}from"./chunk-m06gcr4k.js";import{ue as $O,ve as HO}from"./chunk-189drzww.js";import{ye as Y1}from"./chunk-mxyb9hn6.js";import{Be as M0,ze as B0}from"./chunk-wzjhwr2p.js";import{hf as V0,if as o1,sf as S0}from"./chunk-vzf17snk.js";import{Af as R1,vf as u,xf as W}from"./chunk-qj6gafse.js";import{Hf as b}from"./chunk-2rsr3bte.js";import{Lf as h,Mf as z}from"./chunk-amm23yvd.js";import{Zf as p0}from"./chunk-91vwv4ph.js";import{cg as w}from"./chunk-23bkpq26.js";import J1 from"node:path";import Y$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import zO from"yaml";var u$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function c$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
1
+ import{qe as L1,re as Z0,se as G1}from"./chunk-ytec29ph.js";import{we as $O,xe as HO}from"./chunk-1jagjybs.js";import{Ae as Y1}from"./chunk-hq8cbzfv.js";import{Be as B0,De as M0}from"./chunk-rcp5maxt.js";import{jf as V0,kf as o1,uf as S0}from"./chunk-js5whev4.js";import{Cf as R1,xf as u,zf as W}from"./chunk-38ca5c9f.js";import{Jf as b}from"./chunk-znp4bexg.js";import{Nf as h,Of as z}from"./chunk-sqp79c1a.js";import{$f as p0}from"./chunk-a1wjgf44.js";import{eg as w}from"./chunk-0hdsbwhf.js";import J1 from"node:path";import Y$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import zO from"yaml";var u$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function c$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -707,4 +707,4 @@ ${q.join(`
707
707
  </${Q}>`:"";return{content:J,files:[...O],references:O.map(k$),triggerPaths:[...$],contentBytes:Buffer.byteLength(J,"utf8"),provenanceSha256:_0(O.map((K)=>`${K.id}:${K.contentSha256}`).join(`
708
708
  `))}}function WO(O,$){let Q=$,q=[];for(let Z=O.length-1;Z>=0;Z-=1){let J=O[Z];if(!J)continue;let K=Buffer.byteLength(J.content,"utf8");if(K>Q)continue;q.push(J),Q-=K}return q.reverse()}class d{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=O1(O),this.definitions=Object.freeze([...$].sort(Q1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=_0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
709
709
  `))}static empty(O){return new d(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new d(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=T$){if(this.definitions.length===0)return $0([],[],"project-instructions");let Q=this.relativeSourcePath(O),q=this.definitions.filter((Z)=>!Z.conditional&&$1(Z.scopeDirectory,Q));return $0(WO(q,$),[],"project-instructions")}contextualRules(O,$,Q,q=C$){if(this.definitions.length===0)return $0([],[],"contextual-project-instructions");let Z=this.relativeSourcePath(O),J=[...new Set($.map((G)=>q1(B.relative(this.projectRoot,O1(G)))).filter(Z1))].sort(),K=new Map;for(let G of J)for(let L of this.definitions){if(Q.has(L.id))continue;if(!$1(L.scopeDirectory,G))continue;if(L.conditional){let Y=B.posix.relative(L.scopeDirectory||".",G);if(!L.patterns?.some((V)=>XO(V,{dot:!0})(Y)))continue}else if($1(L.scopeDirectory,Z))continue;K.set(L.id,L)}let X=WO([...K.values()].sort(Q1),q);return $0(X,J,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let q=this.byId.get(Q.id);if(!q||q.contentSha256!==Q.contentSha256||q.relativePath!==Q.relativePath||q.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return q});return $0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(Q1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=q1(B.relative(this.projectRoot,O1(O)));if($&&!Z1($))throw Error("Project instruction source is outside the catalog root");return $}}async function P$(O,$){let Q=await m.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>ZO)throw Error(`Project rule exceeds ${ZO} bytes`);let q=await m.realpath($),Z=q1(B.relative(O,q));if(!Z1(Z))throw Error("Project rule escapes its repository root");let J=await m.readFile(q,"utf8");if(LO(J))throw Error("Project rule contains hidden control characters");let K=w$(J),X=K.content.trim();if(!X)throw Error("Project rule content must not be empty");let G=f$(K.data.paths),L=h$(Z),Y=_0(JSON.stringify({relativePath:Z,patterns:G??[],content:X}));return{id:`${L.source}:${_0(Z).slice(0,20)}`,relativePath:Z,source:L.source,kind:L.kind,scopeDirectory:L.scopeDirectory,priority:L.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:X,contentSha256:Y}}async function YO(O,$){let Q=E$(O);if(!$.projectTrusted)return d.empty(Q);let q=await m.realpath(Q),Z=_$.stream([...y$],{cwd:q,absolute:!0,dot:!0,deep:D$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...v$]}),J=[];for await(let L of Z)if(J.push(L.toString()),J.length>qO)throw Error(`Project rule catalog exceeds ${qO} files`);J.sort();let K=new Set(J.filter((L)=>B.basename(L)==="AGENTS.override.md").map((L)=>B.dirname(L))),X=[],G=0;for(let L of J){if(B.basename(L)==="AGENTS.md"&&K.has(B.dirname(L)))continue;try{let Y=await P$(q,L);if(G+=Buffer.byteLength(Y.content,"utf8"),G>JO)throw Error(`Project rule catalog exceeds ${JO} bytes`);X.push(Y)}catch(Y){R$.warn(`[ProjectRules] Ignoring rule: ${Y instanceof Error?Y.message:String(Y)}`)}}return new d(q,X)}var Q0=new Map,FO=[];async function p$(O){let $=await w.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await e0(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function d$(O){let $={...O};for(let Q of Object.values(B0))$[Q]=(O[Q]??[]).map((q)=>({...q,matcher:q.matcher?{...q.matcher}:void 0,hooks:q.hooks.map((Z)=>({...Z}))}));return $}function f2(O){FO=[...new Set(O.map(($)=>J1.resolve($)))]}async function h2(O,$={}){let Q=J1.resolve(O),q=Q0.get(Q);if(!q)q=(async()=>{let J=await w.getInstance().getStatus(Q),K=i(Q),X=P({cwd:Q}),G=T.getInstance(Q),L=z0(Q);if(K.getAllNames().length===0)K.loadFromStandardLocations(J.state==="trusted");await Promise.all([X.initialize(),G.isInitialized()?void 0:G.initialize(Q),L.isInitialized()?void 0:L.initialize(Q,[...$.cliPluginDirs??FO])]),x0(Q),await a0(Q);let Y=await e0(Q,{projectTrusted:J.state==="trusted",plugins:L.getActive()}),V=await YO(Q,{projectTrusted:J.state==="trusted"});return{workspaceRoot:Q,subagents:K,skills:X,commands:G,plugins:L,communicationStyles:Y,projectRules:V}})().catch((J)=>{throw Q0.delete(Q),J}),Q0.set(Q,q);let Z=await q;if($.reconcilePlugins)x0(Q),await a0(Q),await p$(Z);return Z}function k2(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:J1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??HO.snapshot(),projectRules:O.projectRules?.snapshot()??d.empty($),hooks:d$("hooks"in O&&O.hooks?O.hooks:M0.getInstance().getConfig($))}}function P2(){for(let O of Q0.keys())x0(O);Q0.clear(),v.resetInstances(),k.resetInstance(),T.resetInstance(),f.resetInstance()}
710
- export{u$ as Td,c$ as Ud,W1 as Vd,i$ as Wd,t$ as Xd,i as Yd,H4 as Zd,U1 as _d,P as $d,DO as ae,T as be,o0 as ce,j0 as de,f as ee,z0 as fe,a0 as ge,x0 as he,d as ie,p$ as je,f2 as ke,h2 as le,k2 as me,P2 as ne};
710
+ export{u$ as Vd,c$ as Wd,W1 as Xd,i$ as Yd,t$ as Zd,i as _d,H4 as $d,U1 as ae,P as be,DO as ce,T as de,o0 as ee,j0 as fe,f as ge,z0 as he,a0 as ie,x0 as je,d as ke,p$ as le,f2 as me,h2 as ne,k2 as oe,P2 as pe};
@@ -1,2 +1,2 @@
1
1
  import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
2
- export{N as Ef,D as Ff,P as Gf,V as Hf};
2
+ export{N as Gf,D as Hf,P as If,V as Jf};
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-IaPtOh2w.js","assets/index-BnCT8SxR.js","assets/vendor-react-DG5dkZ_t.js","assets/vendor-radix-DXRuAJHH.js","assets/vendor-icons-ICv1v-tf.js","assets/session-events-BZao_jMQ.js","assets/index-7zaeanZL.css"])))=>i.map(i=>d[i]);
2
- import{r as b,j as e}from"./vendor-react-DG5dkZ_t.js";import{u as D,a as y,b as ue,s as Ee,c as He,d as J,D as Te,e as Ae,f as Ke,g as Fe,h as Me,i as De,j as A,k as O,B as de,_ as ze,S as qe,l as Ge,m as We,C as Je,n as Qe}from"./index-BnCT8SxR.js";import{Q as be,O as Ye,G as Xe,Y as Ze,L as M,z as et,T as ee,C as se,Z as tt,v as st,_ as rt,B as at,$ as Re,y as re,m as me,R as he,s as nt,H as it,a0 as Ie,U as ot,a1 as lt,a2 as ct,a3 as dt,P as $e,a4 as ut,X as mt,a5 as ht,a6 as xt,f as Be,a7 as pt,W as ft,a as bt}from"./vendor-icons-ICv1v-tf.js";import{k as gt,g as vt,l as kt,e as jt,t as yt,j as wt}from"./session-events-BZao_jMQ.js";import{j as Nt,k as St,l as Ct,m as _e}from"./vendor-radix-DXRuAJHH.js";function ge(t){return t.split("/").filter(Boolean).at(-1)||t}function Et(){const t=D(),s=y(w=>w.sessions),r=y(w=>w.currentSessionRef),a=y(w=>w.taskDeliveryActions),o=y(w=>w.deliverTask),n=ue(w=>w.openFilePreview),[m,f]=b.useState(!1),d=s.find(w=>Ee({sessionId:w.sessionId,projectPath:w.projectPath},r));if(!(d!=null&&d.taskIsolation))return null;const l=d.taskDiffStat,v=d.taskIsolation==="worktree",i=He(d),u=a[J(i)],c=d.taskDelivery,j=(c==null?void 0:c.status)==="conflicted",N=!!(l&&(l.changedFiles>0||l.commits>0)),p=!["queued","running"].includes(d.taskStatus),E=(c==null?void 0:c.status)==="applied"||(c==null?void 0:c.status)==="discarded",k=v&&N&&p&&!E,x=l?l.additions+l.deletions:0,h=x>0&&l?l.additions/x*100:0,C=w=>{o(i,w).catch(()=>{})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/60 px-3 py-1.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:px-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e.jsx(be,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:ge(d.taskSourceProjectPath||d.projectPath)})]}),e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[v?e.jsx(Ye,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(be,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:v?"text-[hsl(var(--deck-accent))]":void 0,children:t(v?"artifact.env.isolated":"artifact.env.local")})]}),d.taskWorktreeBranch&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 truncate",title:d.taskWorktreeBranch,children:[e.jsx(Xe,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:d.taskWorktreeBranch})]})]})]}),l&&e.jsxs("div",{className:"ml-auto flex max-w-full items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(Ze,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:l.changedFiles})]}),x>0&&e.jsxs("span",{className:"relative hidden h-1.5 w-14 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:inline-flex","aria-hidden":"true",children:[e.jsx("span",{className:"h-full bg-[hsl(var(--deck-accent))]",style:{width:`${h}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-h}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",l.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",l.deletions]}),l.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:l.commits})}),N&&(c==null?void 0:c.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:()=>n({tab:"diff"}),className:"inline-flex items-center gap-1 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 py-1 text-[hsl(var(--deck-ink))] transition hover:border-[hsl(var(--deck-accent)/0.55)] hover:text-[hsl(var(--deck-accent))]",children:t("artifact.review")}),k&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!u,onClick:()=>C("apply"),className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2 py-1 font-semibold text-white transition hover:brightness-95 disabled:cursor-wait disabled:opacity-65",children:[u==="apply"?e.jsx(M,{className:"h-3 w-3 animate-spin"}):e.jsx(et,{className:"h-3 w-3"}),t(u==="apply"?"artifact.applying":j?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!u,onClick:()=>f(!0),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-[hsl(var(--deck-ink-faint))] transition hover:bg-red-500/10 hover:text-red-600 disabled:cursor-wait disabled:opacity-50 dark:hover:text-red-400","aria-label":t("artifact.discard"),title:t("artifact.discard"),children:u==="discard"?e.jsx(M,{className:"h-3 w-3 animate-spin"}):e.jsx(ee,{className:"h-3 w-3"})})]}),(c==null?void 0:c.status)==="applied"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-emerald-500/10 px-2 py-1 font-semibold text-emerald-700 dark:text-emerald-300",children:[e.jsx(se,{className:"h-3 w-3"}),t("artifact.applied")]}),(c==null?void 0:c.status)==="discarded"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-surface-2))] px-2 py-1 text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(ee,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(c==null?void 0:c.status)==="conflicted"&&e.jsxs("div",{className:"flex w-full items-start gap-1.5 border-t border-amber-500/20 pt-1.5 text-amber-700 dark:text-amber-300",role:"alert",children:[e.jsx(tt,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 space-y-0.5",children:[e.jsx("span",{className:"block",children:c.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(Te,{open:m,onOpenChange:f,children:e.jsxs(Ae,{className:"w-[calc(100%_-_2rem)] max-w-md border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] text-[hsl(var(--deck-ink))]",children:[e.jsxs(Ke,{children:[e.jsx(Fe,{children:t("artifact.discardDialog.title")}),e.jsx(Me,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:ge(d.taskSourceProjectPath||d.projectPath),count:(l==null?void 0:l.changedFiles)??0})})]}),e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs leading-relaxed text-red-700 dark:text-red-300",children:t("artifact.discardDialog.warning")}),e.jsxs(De,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>f(!1),className:"rounded-md border border-[hsl(var(--deck-border))] px-3 py-2 text-sm hover:bg-[hsl(var(--deck-surface-2))]",children:t("artifact.discardDialog.cancel")}),e.jsxs("button",{type:"button",onClick:()=>{f(!1),C("discard")},className:"inline-flex items-center justify-center gap-1.5 rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white hover:bg-red-700",children:[e.jsx(ee,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const Tt=new Set(["completed","stale","failed","aborted","interrupted"]),At={completed:"chat.review.status.completed",stale:"chat.review.status.stale",failed:"chat.review.status.failed",aborted:"chat.review.status.aborted",interrupted:"chat.review.status.interrupted"},Ft={completed:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",stale:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",failed:"bg-red-500/10 text-red-700 dark:text-red-300 border-red-500/20",aborted:"bg-zinc-500/10 text-zinc-700 dark:text-zinc-300 border-zinc-500/20",interrupted:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20"};function te(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Mt(t){const s=te(t),r=te(s==null?void 0:s.codeLocation),a=s==null?void 0:s.priority,o=s==null?void 0:s.confidenceScore,n=r==null?void 0:r.lineStart,m=r==null?void 0:r.lineEnd;if(!(typeof(s==null?void 0:s.title)!="string"||typeof s.body!="string"||a!==0&&a!==1&&a!==2&&a!==3||typeof o!="number"||!Number.isFinite(o)||typeof(r==null?void 0:r.path)!="string"||!Number.isInteger(n)||!Number.isInteger(m)))return{title:s.title,body:s.body,priority:a,confidenceScore:o,codeLocation:{path:r.path,lineStart:n,lineEnd:m}}}function Dt(t){const s=te(t),r=te(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!Tt.has(s.status)||typeof(r==null?void 0:r.label)!="string"||r.kind!=="uncommitted"&&r.kind!=="base"&&r.kind!=="commit"||typeof s.overallExplanation!="string"||!Array.isArray(s.findings))return;const a=s.findings.map(Mt);if(!a.some(o=>o===void 0))return{status:s.status,target:{kind:r.kind,label:r.label,...typeof r.reference=="string"?{reference:r.reference}:{}},overallExplanation:s.overallExplanation,findings:a,...typeof s.error=="string"?{error:s.error}:{}}}function Rt(t){const{path:s,lineStart:r,lineEnd:a}=t.codeLocation;return r===a?`${s}:L${r}`:`${s}:L${r}-${a}`}function It({report:t}){const s=D(),r=t.target.kind==="uncommitted"?s("chat.review.target.uncommitted"):t.target.kind==="base"?s("chat.review.target.base",{ref:t.target.reference??t.target.label}):s("chat.review.target.commit",{ref:t.target.reference??t.target.label});return e.jsxs("section",{"data-code-review-report":!0,className:"overflow-hidden rounded-xl border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface-2))]/60 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.review.title")}),e.jsxs("p",{className:"mt-0.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-faint))]",children:[s("chat.review.target"),": ",r]})]}),e.jsxs("span",{className:A("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Ft[t.status]),children:[s("chat.review.status"),": ",s(At[t.status])]})]}),e.jsxs("div",{className:"space-y-4 px-4 py-3.5",children:[e.jsx("p",{className:"whitespace-pre-wrap text-[13px] leading-6 text-[hsl(var(--deck-ink-muted))]",children:t.overallExplanation}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("h4",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.findings")}),e.jsx("span",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:t.findings.length})]}),t.findings.length===0?e.jsx("div",{className:"rounded-lg bg-[hsl(var(--deck-surface-2))] px-3 py-2.5 text-[12px] text-[hsl(var(--deck-ink-muted))]",children:s("chat.review.noFindings")}):e.jsx("ol",{className:"space-y-2",children:t.findings.map((a,o)=>e.jsxs("li",{className:"rounded-lg border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))] px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsx("h5",{className:"text-[12.5px] font-medium leading-5 text-[hsl(var(--deck-ink))]",children:a.title}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.confidence",{value:a.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:Rt(a)}),e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:a.body})]},`${a.codeLocation.path}:${a.codeLocation.lineStart}:${o}`))})]}),t.error&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-[11px] text-red-700 dark:text-red-300",children:[e.jsxs("span",{className:"font-medium",children:[s("chat.review.error"),":"]})," ",t.error]})]})]})}function $t({elicitation:t,messageId:s}){const r=D(),a=y(k=>k.currentSessionRef),o=y(k=>k.setElicitation),[n,m]=b.useState(()=>_t(t.details.fields??[])),[f,d]=b.useState(()=>Pt(t.details.fields??[])),[l,v]=b.useState(!1),[i,u]=b.useState(),c=t.details.fields??[],j=b.useMemo(()=>c.every(k=>{var h;if(!k.required)return!0;if(ae(k))return!!((h=f[k.name])!=null&&h.trim()||k.defaultValue!==void 0);const x=n[k.name]??k.defaultValue;return Array.isArray(x)?x.length>0:x!==void 0}),[c,f,n]);if(t.status!=="pending")return e.jsx("div",{className:"rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:r(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const N=async(k,x)=>{if(!(!a||l)){v(!0),u(void 0);try{await O.respondToElicitation(a,t.toolCallId,{action:k,...x?{content:x}:{}}),o(s,{...t,status:"responded"})}catch(h){u(h instanceof Error?h.message:r("interaction.elicitation.failed"))}finally{v(!1)}}},p=async()=>{try{await N("accept",Lt(c,n,f))}catch(k){u(k instanceof Error?k.message:String(k))}},E=()=>{const k=t.details.url;if(!k){u("MCP URL is unavailable");return}if(!window.open(k,"_blank","noopener,noreferrer")){u("The browser blocked the external window");return}N("accept")};return e.jsxs("div",{"data-pending-interaction":"elicitation",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(st,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"font-mono text-[12px] font-semibold text-[hsl(var(--deck-ink))]",children:[r("interaction.elicitation.title")," · ",t.details.serverName]}),e.jsx("div",{className:"font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:t.details.message}),e.jsx("div",{className:"font-mono text-[11px] text-amber-700 dark:text-amber-300",children:r("interaction.elicitation.warning")})]})]}),t.details.mode==="url"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] p-3 font-mono text-[11px]",children:[e.jsx("div",{className:"text-[hsl(var(--deck-ink-muted))]",children:t.details.domain}),e.jsx("div",{className:"mt-1 break-all text-[hsl(var(--deck-ink))]",children:t.details.url})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(K,{onClick:E,disabled:l,primary:!0,label:r("interaction.elicitation.open"),icon:e.jsx(rt,{className:"h-3.5 w-3.5"})}),e.jsx(K,{onClick:()=>void N("decline"),disabled:l,label:r("interaction.elicitation.decline")}),e.jsx(K,{onClick:()=>void N("cancel"),disabled:l,label:r("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[c.map(k=>e.jsx(Bt,{field:k,value:n[k.name],rawValue:f[k.name]??"",onValueChange:x=>m(h=>({...h,[k.name]:x})),onRawChange:x=>d(h=>({...h,[k.name]:x}))},k.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(K,{onClick:()=>void p(),disabled:l||!j,primary:!0,label:r("interaction.elicitation.submit"),icon:l?e.jsx(M,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(K,{onClick:()=>void N("decline"),disabled:l,label:r("interaction.elicitation.decline")}),e.jsx(K,{onClick:()=>void N("cancel"),disabled:l,label:r("interaction.elicitation.cancel")})]})]}),i&&e.jsx("div",{className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:i})]})}function Bt({field:t,value:s,rawValue:r,onValueChange:a,onRawChange:o}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:`mcp-elicitation-${t.name}`,className:"block font-mono text-[12px] font-medium text-[hsl(var(--deck-ink))]",children:[t.title,t.required?" *":""]}),t.description&&e.jsx("div",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-faint))]",children:t.description}),t.type==="select"||t.type==="multi-select"||t.type==="boolean"?e.jsx("div",{id:`mcp-elicitation-${t.name}`,className:"flex flex-wrap gap-2",children:Vt(t).map(n=>{const m=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":m,onClick:()=>{if(t.type==="multi-select"){const f=Array.isArray(s)?s:[];a(f.includes(n.value)?f.filter(d=>d!==n.value):[...f,n.value])}else a(n.typedValue)},className:A("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",m?"border-emerald-500 bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200":"border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:n.label},n.value)})}):e.jsx("input",{id:`mcp-elicitation-${t.name}`,type:Ot(t),value:r,onChange:n=>o(n.target.value),min:t.minimum,max:t.maximum,minLength:t.minLength,maxLength:t.maxLength,required:t.required,placeholder:t.defaultValue===void 0?t.required?"Required":"Optional":String(t.defaultValue),className:"w-full rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink))] outline-none transition-colors focus:border-amber-500 focus:ring-1 focus:ring-amber-500"})]})}function K({onClick:t,disabled:s,primary:r=!1,label:a,icon:o}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:A("inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 py-1.5 font-mono text-[12px] transition-colors disabled:cursor-wait disabled:opacity-50",r?"bg-amber-600 text-white hover:bg-amber-700":"border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:[o,a]})}function _t(t){return Object.fromEntries(t.filter(s=>!ae(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function Pt(t){return Object.fromEntries(t.filter(s=>ae(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Lt(t,s,r){var o;const a={};for(const n of t){if(ae(n)){const f=((o=r[n.name])==null?void 0:o.trim())??"";if(!f){if(n.defaultValue!==void 0)a[n.name]=n.defaultValue;else if(n.required)throw new Error(`${n.title} is required`);continue}if(n.type==="number"||n.type==="integer"){const d=Number(f);if(!Number.isFinite(d))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(d))throw new Error(`${n.title} must be a safe integer`);a[n.name]=d}else a[n.name]=f;continue}const m=s[n.name]??n.defaultValue;if(m===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(m)){if(n.minItems!==void 0&&m.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&m.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}a[n.name]=m}return a}function Vt(t){return t.type==="boolean"?[{value:"true",label:"Yes",typedValue:!0},{value:"false",label:"No",typedValue:!1}]:(t.options??[]).map(s=>({...s,typedValue:s.value}))}function ae(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function Ot(t){return t.type==="number"||t.type==="integer"?"number":t.format==="email"?"email":t.format==="uri"?"url":t.format==="date"?"date":t.format==="date-time"?"datetime-local":"text"}function Ut(t){if(!t||typeof t!="object"||Array.isArray(t))return;const s=t;if(!(!s.output||typeof s.output!="object"||Array.isArray(s.output)))return{output:s.output,...typeof s.schemaDigest=="string"?{schemaDigest:s.schemaDigest}:{}}}function Ht({report:t}){const s=D(),[r,a]=b.useState(!1),o=JSON.stringify(t.output,null,2),n=async()=>{try{await navigator.clipboard.writeText(o),a(!0),window.setTimeout(()=>a(!1),1400)}catch{}};return e.jsxs("section",{"data-structured-output":!0,className:"overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex min-h-9 items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(at,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsx("span",{className:"font-mono text-[11px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.structuredOutput.title")}),t.schemaDigest&&e.jsxs("span",{title:t.schemaDigest,className:"truncate font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["sha256:",t.schemaDigest.slice(0,10)]})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":s("chat.structuredOutput.copy"),title:s("chat.structuredOutput.copy"),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:r?e.jsx(se,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Re,{className:"h-3.5 w-3.5"})})]}),e.jsx("pre",{className:"max-h-[440px] overflow-auto whitespace-pre p-3 font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink))]",children:o})]})}const Kt=b.lazy(()=>ze(()=>import("./MarkdownRenderer-IaPtOh2w.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function ve({text:t,label:s}){const[r,a]=b.useState(!1);if(!t.trim())return null;const o=async()=>{try{await navigator.clipboard.writeText(t),a(!0),window.setTimeout(()=>a(!1),1400)}catch{}};return e.jsx("button",{type:"button","aria-label":s,title:s,onClick:o,className:"flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:r?e.jsx(se,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Re,{className:"h-3.5 w-3.5"})})}function zt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] shadow-[0_1px_0_hsl(var(--deck-hairline))]",children:e.jsx(de,{size:20,pulse:!1})})}function qt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-full border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas-veil))]",children:e.jsx("span",{className:"font-mono text-[11px] font-medium text-[hsl(var(--deck-ink))]",children:"U"})})}function ke(t){let s=t;return s=s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),s=s.replace(/<file path="[^"]*">[\s\S]*?<\/file>/g,""),s=s.replace(/<attached_files>[\s\S]*?<\/attached_files>/g,""),s=s.trim(),s}function Gt(t){if(typeof t=="string")return{text:ke(t),images:[]};const s=t.filter(a=>a.type==="text").map(a=>a.text).join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-DXsfHVUX.js","assets/index-DGZjm9wT.js","assets/vendor-react-DG5dkZ_t.js","assets/vendor-radix-DXRuAJHH.js","assets/vendor-icons-ICv1v-tf.js","assets/session-events-Dk20sSDo.js","assets/index-7zaeanZL.css"])))=>i.map(i=>d[i]);
2
+ import{r as b,j as e}from"./vendor-react-DG5dkZ_t.js";import{u as D,a as y,b as ue,s as Ee,c as He,d as J,D as Te,e as Ae,f as Ke,g as Fe,h as Me,i as De,j as A,k as O,B as de,_ as ze,S as qe,l as Ge,m as We,C as Je,n as Qe}from"./index-DGZjm9wT.js";import{Q as be,O as Ye,G as Xe,Y as Ze,L as M,z as et,T as ee,C as se,Z as tt,v as st,_ as rt,B as at,$ as Re,y as re,m as me,R as he,s as nt,H as it,a0 as Ie,U as ot,a1 as lt,a2 as ct,a3 as dt,P as $e,a4 as ut,X as mt,a5 as ht,a6 as xt,f as Be,a7 as pt,W as ft,a as bt}from"./vendor-icons-ICv1v-tf.js";import{k as gt,g as vt,l as kt,e as jt,t as yt,j as wt}from"./session-events-Dk20sSDo.js";import{j as Nt,k as St,l as Ct,m as _e}from"./vendor-radix-DXRuAJHH.js";function ge(t){return t.split("/").filter(Boolean).at(-1)||t}function Et(){const t=D(),s=y(w=>w.sessions),r=y(w=>w.currentSessionRef),a=y(w=>w.taskDeliveryActions),o=y(w=>w.deliverTask),n=ue(w=>w.openFilePreview),[m,f]=b.useState(!1),d=s.find(w=>Ee({sessionId:w.sessionId,projectPath:w.projectPath},r));if(!(d!=null&&d.taskIsolation))return null;const l=d.taskDiffStat,v=d.taskIsolation==="worktree",i=He(d),u=a[J(i)],c=d.taskDelivery,j=(c==null?void 0:c.status)==="conflicted",N=!!(l&&(l.changedFiles>0||l.commits>0)),p=!["queued","running"].includes(d.taskStatus),E=(c==null?void 0:c.status)==="applied"||(c==null?void 0:c.status)==="discarded",k=v&&N&&p&&!E,x=l?l.additions+l.deletions:0,h=x>0&&l?l.additions/x*100:0,C=w=>{o(i,w).catch(()=>{})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/60 px-3 py-1.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:px-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e.jsx(be,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:ge(d.taskSourceProjectPath||d.projectPath)})]}),e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[v?e.jsx(Ye,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(be,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:v?"text-[hsl(var(--deck-accent))]":void 0,children:t(v?"artifact.env.isolated":"artifact.env.local")})]}),d.taskWorktreeBranch&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[hsl(var(--deck-ink-faint))]/60",children:"/"}),e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 truncate",title:d.taskWorktreeBranch,children:[e.jsx(Xe,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:d.taskWorktreeBranch})]})]})]}),l&&e.jsxs("div",{className:"ml-auto flex max-w-full items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(Ze,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:l.changedFiles})]}),x>0&&e.jsxs("span",{className:"relative hidden h-1.5 w-14 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:inline-flex","aria-hidden":"true",children:[e.jsx("span",{className:"h-full bg-[hsl(var(--deck-accent))]",style:{width:`${h}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-h}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",l.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",l.deletions]}),l.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:l.commits})}),N&&(c==null?void 0:c.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:()=>n({tab:"diff"}),className:"inline-flex items-center gap-1 rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-2 py-1 text-[hsl(var(--deck-ink))] transition hover:border-[hsl(var(--deck-accent)/0.55)] hover:text-[hsl(var(--deck-accent))]",children:t("artifact.review")}),k&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!u,onClick:()=>C("apply"),className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2 py-1 font-semibold text-white transition hover:brightness-95 disabled:cursor-wait disabled:opacity-65",children:[u==="apply"?e.jsx(M,{className:"h-3 w-3 animate-spin"}):e.jsx(et,{className:"h-3 w-3"}),t(u==="apply"?"artifact.applying":j?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!u,onClick:()=>f(!0),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-[hsl(var(--deck-ink-faint))] transition hover:bg-red-500/10 hover:text-red-600 disabled:cursor-wait disabled:opacity-50 dark:hover:text-red-400","aria-label":t("artifact.discard"),title:t("artifact.discard"),children:u==="discard"?e.jsx(M,{className:"h-3 w-3 animate-spin"}):e.jsx(ee,{className:"h-3 w-3"})})]}),(c==null?void 0:c.status)==="applied"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-emerald-500/10 px-2 py-1 font-semibold text-emerald-700 dark:text-emerald-300",children:[e.jsx(se,{className:"h-3 w-3"}),t("artifact.applied")]}),(c==null?void 0:c.status)==="discarded"&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-[hsl(var(--deck-surface-2))] px-2 py-1 text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(ee,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(c==null?void 0:c.status)==="conflicted"&&e.jsxs("div",{className:"flex w-full items-start gap-1.5 border-t border-amber-500/20 pt-1.5 text-amber-700 dark:text-amber-300",role:"alert",children:[e.jsx(tt,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 space-y-0.5",children:[e.jsx("span",{className:"block",children:c.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(Te,{open:m,onOpenChange:f,children:e.jsxs(Ae,{className:"w-[calc(100%_-_2rem)] max-w-md border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] text-[hsl(var(--deck-ink))]",children:[e.jsxs(Ke,{children:[e.jsx(Fe,{children:t("artifact.discardDialog.title")}),e.jsx(Me,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:ge(d.taskSourceProjectPath||d.projectPath),count:(l==null?void 0:l.changedFiles)??0})})]}),e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs leading-relaxed text-red-700 dark:text-red-300",children:t("artifact.discardDialog.warning")}),e.jsxs(De,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>f(!1),className:"rounded-md border border-[hsl(var(--deck-border))] px-3 py-2 text-sm hover:bg-[hsl(var(--deck-surface-2))]",children:t("artifact.discardDialog.cancel")}),e.jsxs("button",{type:"button",onClick:()=>{f(!1),C("discard")},className:"inline-flex items-center justify-center gap-1.5 rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white hover:bg-red-700",children:[e.jsx(ee,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const Tt=new Set(["completed","stale","failed","aborted","interrupted"]),At={completed:"chat.review.status.completed",stale:"chat.review.status.stale",failed:"chat.review.status.failed",aborted:"chat.review.status.aborted",interrupted:"chat.review.status.interrupted"},Ft={completed:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",stale:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",failed:"bg-red-500/10 text-red-700 dark:text-red-300 border-red-500/20",aborted:"bg-zinc-500/10 text-zinc-700 dark:text-zinc-300 border-zinc-500/20",interrupted:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20"};function te(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Mt(t){const s=te(t),r=te(s==null?void 0:s.codeLocation),a=s==null?void 0:s.priority,o=s==null?void 0:s.confidenceScore,n=r==null?void 0:r.lineStart,m=r==null?void 0:r.lineEnd;if(!(typeof(s==null?void 0:s.title)!="string"||typeof s.body!="string"||a!==0&&a!==1&&a!==2&&a!==3||typeof o!="number"||!Number.isFinite(o)||typeof(r==null?void 0:r.path)!="string"||!Number.isInteger(n)||!Number.isInteger(m)))return{title:s.title,body:s.body,priority:a,confidenceScore:o,codeLocation:{path:r.path,lineStart:n,lineEnd:m}}}function Dt(t){const s=te(t),r=te(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!Tt.has(s.status)||typeof(r==null?void 0:r.label)!="string"||r.kind!=="uncommitted"&&r.kind!=="base"&&r.kind!=="commit"||typeof s.overallExplanation!="string"||!Array.isArray(s.findings))return;const a=s.findings.map(Mt);if(!a.some(o=>o===void 0))return{status:s.status,target:{kind:r.kind,label:r.label,...typeof r.reference=="string"?{reference:r.reference}:{}},overallExplanation:s.overallExplanation,findings:a,...typeof s.error=="string"?{error:s.error}:{}}}function Rt(t){const{path:s,lineStart:r,lineEnd:a}=t.codeLocation;return r===a?`${s}:L${r}`:`${s}:L${r}-${a}`}function It({report:t}){const s=D(),r=t.target.kind==="uncommitted"?s("chat.review.target.uncommitted"):t.target.kind==="base"?s("chat.review.target.base",{ref:t.target.reference??t.target.label}):s("chat.review.target.commit",{ref:t.target.reference??t.target.label});return e.jsxs("section",{"data-code-review-report":!0,className:"overflow-hidden rounded-xl border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface-2))]/60 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.review.title")}),e.jsxs("p",{className:"mt-0.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-faint))]",children:[s("chat.review.target"),": ",r]})]}),e.jsxs("span",{className:A("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Ft[t.status]),children:[s("chat.review.status"),": ",s(At[t.status])]})]}),e.jsxs("div",{className:"space-y-4 px-4 py-3.5",children:[e.jsx("p",{className:"whitespace-pre-wrap text-[13px] leading-6 text-[hsl(var(--deck-ink-muted))]",children:t.overallExplanation}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("h4",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.findings")}),e.jsx("span",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:t.findings.length})]}),t.findings.length===0?e.jsx("div",{className:"rounded-lg bg-[hsl(var(--deck-surface-2))] px-3 py-2.5 text-[12px] text-[hsl(var(--deck-ink-muted))]",children:s("chat.review.noFindings")}):e.jsx("ol",{className:"space-y-2",children:t.findings.map((a,o)=>e.jsxs("li",{className:"rounded-lg border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))] px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsx("h5",{className:"text-[12.5px] font-medium leading-5 text-[hsl(var(--deck-ink))]",children:a.title}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.confidence",{value:a.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:Rt(a)}),e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:a.body})]},`${a.codeLocation.path}:${a.codeLocation.lineStart}:${o}`))})]}),t.error&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-[11px] text-red-700 dark:text-red-300",children:[e.jsxs("span",{className:"font-medium",children:[s("chat.review.error"),":"]})," ",t.error]})]})]})}function $t({elicitation:t,messageId:s}){const r=D(),a=y(k=>k.currentSessionRef),o=y(k=>k.setElicitation),[n,m]=b.useState(()=>_t(t.details.fields??[])),[f,d]=b.useState(()=>Pt(t.details.fields??[])),[l,v]=b.useState(!1),[i,u]=b.useState(),c=t.details.fields??[],j=b.useMemo(()=>c.every(k=>{var h;if(!k.required)return!0;if(ae(k))return!!((h=f[k.name])!=null&&h.trim()||k.defaultValue!==void 0);const x=n[k.name]??k.defaultValue;return Array.isArray(x)?x.length>0:x!==void 0}),[c,f,n]);if(t.status!=="pending")return e.jsx("div",{className:"rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:r(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const N=async(k,x)=>{if(!(!a||l)){v(!0),u(void 0);try{await O.respondToElicitation(a,t.toolCallId,{action:k,...x?{content:x}:{}}),o(s,{...t,status:"responded"})}catch(h){u(h instanceof Error?h.message:r("interaction.elicitation.failed"))}finally{v(!1)}}},p=async()=>{try{await N("accept",Lt(c,n,f))}catch(k){u(k instanceof Error?k.message:String(k))}},E=()=>{const k=t.details.url;if(!k){u("MCP URL is unavailable");return}if(!window.open(k,"_blank","noopener,noreferrer")){u("The browser blocked the external window");return}N("accept")};return e.jsxs("div",{"data-pending-interaction":"elicitation",tabIndex:-1,role:"alert",className:"space-y-4 rounded-lg border border-amber-300/70 bg-amber-50/70 p-4 outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(st,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"font-mono text-[12px] font-semibold text-[hsl(var(--deck-ink))]",children:[r("interaction.elicitation.title")," · ",t.details.serverName]}),e.jsx("div",{className:"font-mono text-[12px] text-[hsl(var(--deck-ink-muted))]",children:t.details.message}),e.jsx("div",{className:"font-mono text-[11px] text-amber-700 dark:text-amber-300",children:r("interaction.elicitation.warning")})]})]}),t.details.mode==="url"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] p-3 font-mono text-[11px]",children:[e.jsx("div",{className:"text-[hsl(var(--deck-ink-muted))]",children:t.details.domain}),e.jsx("div",{className:"mt-1 break-all text-[hsl(var(--deck-ink))]",children:t.details.url})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(K,{onClick:E,disabled:l,primary:!0,label:r("interaction.elicitation.open"),icon:e.jsx(rt,{className:"h-3.5 w-3.5"})}),e.jsx(K,{onClick:()=>void N("decline"),disabled:l,label:r("interaction.elicitation.decline")}),e.jsx(K,{onClick:()=>void N("cancel"),disabled:l,label:r("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[c.map(k=>e.jsx(Bt,{field:k,value:n[k.name],rawValue:f[k.name]??"",onValueChange:x=>m(h=>({...h,[k.name]:x})),onRawChange:x=>d(h=>({...h,[k.name]:x}))},k.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(K,{onClick:()=>void p(),disabled:l||!j,primary:!0,label:r("interaction.elicitation.submit"),icon:l?e.jsx(M,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(K,{onClick:()=>void N("decline"),disabled:l,label:r("interaction.elicitation.decline")}),e.jsx(K,{onClick:()=>void N("cancel"),disabled:l,label:r("interaction.elicitation.cancel")})]})]}),i&&e.jsx("div",{className:"rounded-md border border-red-300/70 bg-red-50 px-2.5 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/70 dark:bg-red-950/35 dark:text-red-300",children:i})]})}function Bt({field:t,value:s,rawValue:r,onValueChange:a,onRawChange:o}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:`mcp-elicitation-${t.name}`,className:"block font-mono text-[12px] font-medium text-[hsl(var(--deck-ink))]",children:[t.title,t.required?" *":""]}),t.description&&e.jsx("div",{className:"font-mono text-[11px] text-[hsl(var(--deck-ink-faint))]",children:t.description}),t.type==="select"||t.type==="multi-select"||t.type==="boolean"?e.jsx("div",{id:`mcp-elicitation-${t.name}`,className:"flex flex-wrap gap-2",children:Vt(t).map(n=>{const m=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":m,onClick:()=>{if(t.type==="multi-select"){const f=Array.isArray(s)?s:[];a(f.includes(n.value)?f.filter(d=>d!==n.value):[...f,n.value])}else a(n.typedValue)},className:A("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",m?"border-emerald-500 bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200":"border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:n.label},n.value)})}):e.jsx("input",{id:`mcp-elicitation-${t.name}`,type:Ot(t),value:r,onChange:n=>o(n.target.value),min:t.minimum,max:t.maximum,minLength:t.minLength,maxLength:t.maxLength,required:t.required,placeholder:t.defaultValue===void 0?t.required?"Required":"Optional":String(t.defaultValue),className:"w-full rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2 font-mono text-[12px] text-[hsl(var(--deck-ink))] outline-none transition-colors focus:border-amber-500 focus:ring-1 focus:ring-amber-500"})]})}function K({onClick:t,disabled:s,primary:r=!1,label:a,icon:o}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:A("inline-flex min-h-8 items-center gap-1.5 rounded-md px-3 py-1.5 font-mono text-[12px] transition-colors disabled:cursor-wait disabled:opacity-50",r?"bg-amber-600 text-white hover:bg-amber-700":"border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))] hover:text-[hsl(var(--deck-ink))]"),children:[o,a]})}function _t(t){return Object.fromEntries(t.filter(s=>!ae(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function Pt(t){return Object.fromEntries(t.filter(s=>ae(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Lt(t,s,r){var o;const a={};for(const n of t){if(ae(n)){const f=((o=r[n.name])==null?void 0:o.trim())??"";if(!f){if(n.defaultValue!==void 0)a[n.name]=n.defaultValue;else if(n.required)throw new Error(`${n.title} is required`);continue}if(n.type==="number"||n.type==="integer"){const d=Number(f);if(!Number.isFinite(d))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(d))throw new Error(`${n.title} must be a safe integer`);a[n.name]=d}else a[n.name]=f;continue}const m=s[n.name]??n.defaultValue;if(m===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(m)){if(n.minItems!==void 0&&m.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&m.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}a[n.name]=m}return a}function Vt(t){return t.type==="boolean"?[{value:"true",label:"Yes",typedValue:!0},{value:"false",label:"No",typedValue:!1}]:(t.options??[]).map(s=>({...s,typedValue:s.value}))}function ae(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function Ot(t){return t.type==="number"||t.type==="integer"?"number":t.format==="email"?"email":t.format==="uri"?"url":t.format==="date"?"date":t.format==="date-time"?"datetime-local":"text"}function Ut(t){if(!t||typeof t!="object"||Array.isArray(t))return;const s=t;if(!(!s.output||typeof s.output!="object"||Array.isArray(s.output)))return{output:s.output,...typeof s.schemaDigest=="string"?{schemaDigest:s.schemaDigest}:{}}}function Ht({report:t}){const s=D(),[r,a]=b.useState(!1),o=JSON.stringify(t.output,null,2),n=async()=>{try{await navigator.clipboard.writeText(o),a(!0),window.setTimeout(()=>a(!1),1400)}catch{}};return e.jsxs("section",{"data-structured-output":!0,className:"overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("header",{className:"flex min-h-9 items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(at,{className:"h-3.5 w-3.5 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsx("span",{className:"font-mono text-[11px] font-semibold text-[hsl(var(--deck-ink))]",children:s("chat.structuredOutput.title")}),t.schemaDigest&&e.jsxs("span",{title:t.schemaDigest,className:"truncate font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["sha256:",t.schemaDigest.slice(0,10)]})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":s("chat.structuredOutput.copy"),title:s("chat.structuredOutput.copy"),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-[hsl(var(--deck-ink-faint))] hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:r?e.jsx(se,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Re,{className:"h-3.5 w-3.5"})})]}),e.jsx("pre",{className:"max-h-[440px] overflow-auto whitespace-pre p-3 font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink))]",children:o})]})}const Kt=b.lazy(()=>ze(()=>import("./MarkdownRenderer-DXsfHVUX.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function ve({text:t,label:s}){const[r,a]=b.useState(!1);if(!t.trim())return null;const o=async()=>{try{await navigator.clipboard.writeText(t),a(!0),window.setTimeout(()=>a(!1),1400)}catch{}};return e.jsx("button",{type:"button","aria-label":s,title:s,onClick:o,className:"flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:r?e.jsx(se,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(Re,{className:"h-3.5 w-3.5"})})}function zt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] shadow-[0_1px_0_hsl(var(--deck-hairline))]",children:e.jsx(de,{size:20,pulse:!1})})}function qt(){return e.jsx("div",{className:"flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-full border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas-veil))]",children:e.jsx("span",{className:"font-mono text-[11px] font-medium text-[hsl(var(--deck-ink))]",children:"U"})})}function ke(t){let s=t;return s=s.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,""),s=s.replace(/<file path="[^"]*">[\s\S]*?<\/file>/g,""),s=s.replace(/<attached_files>[\s\S]*?<\/attached_files>/g,""),s=s.trim(),s}function Gt(t){if(typeof t=="string")return{text:ke(t),images:[]};const s=t.filter(a=>a.type==="text").map(a=>a.text).join(`
3
3
  `),r=t.filter(a=>a.type==="image_url").map(a=>a.image_url.url);return{text:ke(s),images:r}}function xe(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
4
4
  `)}function Wt(t){const s=t.agentContent;return s?gt(s):xe(t.content)}function je({content:t,syntaxHighlight:s=!0}){return e.jsx(b.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(Kt,{content:t,syntaxHighlight:s})})}function pe({status:t}){if(!t)return null;const s={running:"bg-[#FEF3C7] text-[#92400E] dark:bg-[#F59E0B]/20 dark:text-[#FBBF24]",success:"bg-[#DCFCE7] text-[#15803D] dark:bg-[#22C55E]/20 dark:text-[#22C55E]",error:"bg-[#FEE2E2] text-[#b91c1c] dark:bg-[#EF4444]/20 dark:text-[#fca5a5]",pending:"bg-[#E5E7EB] text-[#6B7280] dark:bg-[#27272a] dark:text-[#a1a1aa]",info:"bg-[#DBEAFE] text-[#1D4ED8] dark:bg-[#3B82F6]/20 dark:text-[#60A5FA]"},r={running:"Running",success:"Success",error:"Error",pending:"Pending",info:"Info"};return e.jsx("span",{className:A("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:r[t]})}function Jt(t){if(!t)return"";if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return JSON.stringify(t,null,2)}const ye=500;function Pe(t,s){if(t.length<=s)return t;let r=Math.max(0,s);return r>0&&/[\uD800-\uDBFF]/.test(t.charAt(r-1))&&(r-=1),t.slice(0,r)}function we(t,s){if(t.length<=s)return t;let r=Math.max(0,t.length-s);return/[\uDC00-\uDFFF]/.test(t.charAt(r))&&(r+=1),t.slice(r)}function oe(t,s){if(t.length<=s)return t;if(s<=0)return"";const r=`
5
5
  ... (display clipped) ...