blade-code 0.10.138 → 0.10.140

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 (130) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-6qhbdcse.js → chunk-08z32sky.js} +2 -2
  3. package/dist/{chunk-egadh3e9.js → chunk-0c2y17xy.js} +1 -1
  4. package/dist/{chunk-mjnkxem3.js → chunk-0kghtvxj.js} +2 -2
  5. package/dist/{chunk-3eskgvpy.js → chunk-0sx7ak0b.js} +1 -1
  6. package/dist/{chunk-d11mqbqk.js → chunk-15fpc0qg.js} +1 -1
  7. package/dist/{chunk-2t0wp7gm.js → chunk-19zsecpx.js} +2 -2
  8. package/dist/{chunk-byeq45rv.js → chunk-1myft5nb.js} +1 -1
  9. package/dist/chunk-1nreg14s.js +1 -0
  10. package/dist/{chunk-z9qv0d6k.js → chunk-2d3zksr0.js} +1 -1
  11. package/dist/{chunk-ec7ykyqz.js → chunk-2ff55pvt.js} +3 -3
  12. package/dist/{chunk-65c3vjwm.js → chunk-2g8avyq6.js} +1 -1
  13. package/dist/chunk-3kvt23m3.js +1 -0
  14. package/dist/chunk-4rh40xhc.js +1 -0
  15. package/dist/chunk-4xr4hz19.js +2 -0
  16. package/dist/{chunk-fndqbf45.js → chunk-50m1czz9.js} +1 -1
  17. package/dist/{chunk-earhezc8.js → chunk-5cw3bevx.js} +1 -1
  18. package/dist/{chunk-9m7d3ajv.js → chunk-5jq1mrqd.js} +1 -1
  19. package/dist/chunk-61yd46c0.js +1 -0
  20. package/dist/{chunk-8py443a5.js → chunk-6zxm9pen.js} +1 -1
  21. package/dist/{chunk-7vdf66jp.js → chunk-7eepxhcp.js} +34 -34
  22. package/dist/{chunk-jy7k2dwm.js → chunk-85b3kacc.js} +2 -2
  23. package/dist/chunk-8774agqd.js +1 -0
  24. package/dist/chunk-8brb7c6j.js +6 -0
  25. package/dist/{chunk-hrcz179j.js → chunk-8fx20am1.js} +2 -2
  26. package/dist/{chunk-16648v5c.js → chunk-8vqhcx3s.js} +1 -1
  27. package/dist/{chunk-6ezffjq1.js → chunk-9ced7jf0.js} +1 -1
  28. package/dist/chunk-abpmpyqa.js +1 -0
  29. package/dist/{chunk-yvmexv2c.js → chunk-ascjys4e.js} +1 -1
  30. package/dist/chunk-bb0z7c3g.js +1 -0
  31. package/dist/{chunk-5j68055h.js → chunk-c562kd2m.js} +1 -1
  32. package/dist/{chunk-he0f6h5q.js → chunk-cf3dvysj.js} +1 -1
  33. package/dist/{chunk-bq6d0v5b.js → chunk-cww9pp1q.js} +2 -2
  34. package/dist/{chunk-7j4s1nrc.js → chunk-d1qe06f0.js} +1 -1
  35. package/dist/{chunk-atdq9btn.js → chunk-e6j4vzta.js} +2 -2
  36. package/dist/{chunk-92n2p24j.js → chunk-eh901zhx.js} +2 -2
  37. package/dist/{chunk-14j2dbd6.js → chunk-eqe3smcg.js} +2 -2
  38. package/dist/{chunk-a5hkv8er.js → chunk-es0cbtx1.js} +2 -2
  39. package/dist/{chunk-r7bv1hmq.js → chunk-ffkzessq.js} +1 -1
  40. package/dist/{chunk-dv2m2xe5.js → chunk-g38d2ezm.js} +1 -1
  41. package/dist/{chunk-v2fewxvw.js → chunk-g4kydkyz.js} +2 -2
  42. package/dist/{chunk-5bfvdy62.js → chunk-g5scqxq3.js} +2 -2
  43. package/dist/{chunk-8rccn1y2.js → chunk-gq727fet.js} +1 -1
  44. package/dist/{chunk-56py3ryh.js → chunk-hj1yrssp.js} +1 -1
  45. package/dist/{chunk-d64b7wta.js → chunk-hvmrcd84.js} +1 -1
  46. package/dist/{chunk-zx78c1an.js → chunk-kmg8ad2j.js} +1 -1
  47. package/dist/{chunk-5v1pjexj.js → chunk-kxwc5wrx.js} +1 -1
  48. package/dist/chunk-m9dv5177.js +10 -0
  49. package/dist/{chunk-az08pq83.js → chunk-ma1mn6hn.js} +1 -1
  50. package/dist/{chunk-t88sfhjj.js → chunk-mnk0b4nz.js} +1 -1
  51. package/dist/chunk-mwgx87vw.js +1 -0
  52. package/dist/{chunk-nqts5by0.js → chunk-n6tvswa8.js} +2 -2
  53. package/dist/{chunk-fbrdcveb.js → chunk-n8qg68y2.js} +1 -1
  54. package/dist/chunk-ntq4h4jh.js +1 -0
  55. package/dist/{chunk-1bqatrxs.js → chunk-nxsarfy6.js} +1 -1
  56. package/dist/{chunk-ft1bdqbs.js → chunk-pg7cgvs8.js} +2 -2
  57. package/dist/{chunk-y66f1t18.js → chunk-ppmy3n74.js} +219 -218
  58. package/dist/chunk-pw9axk0e.js +5 -0
  59. package/dist/{chunk-2m79vd9p.js → chunk-pwct7cj7.js} +1 -1
  60. package/dist/{chunk-23c4pys6.js → chunk-q9qts6bq.js} +2 -2
  61. package/dist/chunk-r324qme7.js +1 -0
  62. package/dist/{chunk-rhwkvx96.js → chunk-r4q06wbs.js} +1 -1
  63. package/dist/chunk-ra6ksfdy.js +1 -0
  64. package/dist/{chunk-gcg56vaw.js → chunk-rrtptbzv.js} +2 -2
  65. package/dist/{chunk-jb4hmk56.js → chunk-svsgtj41.js} +2 -2
  66. package/dist/{chunk-j21hez8g.js → chunk-tagzy876.js} +6 -6
  67. package/dist/{chunk-516adpx6.js → chunk-tecbx0ek.js} +1 -1
  68. package/dist/chunk-tnts2de5.js +1 -0
  69. package/dist/chunk-w0710yj4.js +1 -0
  70. package/dist/{chunk-npc7jt96.js → chunk-w2m4yczv.js} +1 -1
  71. package/dist/{chunk-nyw686sf.js → chunk-w5057h27.js} +2 -2
  72. package/dist/chunk-we13xwds.js +180 -0
  73. package/dist/{chunk-nnas8tdt.js → chunk-xagh2qb6.js} +2 -2
  74. package/dist/{chunk-k10d8t4f.js → chunk-y5bqd8gh.js} +1 -1
  75. package/dist/{chunk-awheqy52.js → chunk-zfaenqqx.js} +2 -2
  76. package/dist/chunk-zp5097qk.js +2 -0
  77. package/dist/web/assets/ChatView-BlAGPVC-.js +63 -0
  78. package/dist/web/assets/{CodeBlockHighlighter-6-iPmomS.js → CodeBlockHighlighter-BM1MZv6w.js} +1 -1
  79. package/dist/web/assets/{FilePreview-D0aSwNF3.js → FilePreview-P77KS9tr.js} +1 -1
  80. package/dist/web/assets/{KanbanBoard-xPziptbY.js → KanbanBoard-B0c7sE2y.js} +1 -1
  81. package/dist/web/assets/{MarkdownRenderer-TWNqhwrr.js → MarkdownRenderer-DHa0FqU0.js} +3 -3
  82. package/dist/web/assets/{ScrollArea-CSQyGeWr.js → ScrollArea-C6yf2fqq.js} +1 -1
  83. package/dist/web/assets/{SessionHistorySurface-PRpOrUav.js → SessionHistorySurface-CXYBWqlN.js} +1 -1
  84. package/dist/web/assets/{SettingsModal-Ds-Uf-3r.js → SettingsModal-BVjVlENY.js} +1 -1
  85. package/dist/web/assets/{Sidebar-D6VyjkRY.js → Sidebar-DDW9Xs6e.js} +1 -1
  86. package/dist/web/assets/{TaskSwitcher-BEsAgt0k.js → TaskSwitcher-D74_5q1F.js} +1 -1
  87. package/dist/web/assets/{TerminalPanel-C_2lnmKH.js → TerminalPanel-DNEKapEi.js} +1 -1
  88. package/dist/web/assets/{archive-CPBIxP8f.js → archive-Ao0WD7pU.js} +1 -1
  89. package/dist/web/assets/{arrow-left-z3DhPgf-.js → arrow-left-a5_iLemp.js} +1 -1
  90. package/dist/web/assets/{calendar-clock-tYt1E6zR.js → calendar-clock-BKbdz6Cu.js} +1 -1
  91. package/dist/web/assets/{chevron-right-BGTvSaVS.js → chevron-right-8qYRfCj4.js} +1 -1
  92. package/dist/web/assets/{chevrons-up-down-Jw3ElnjQ.js → chevrons-up-down-BXNG4GvK.js} +1 -1
  93. package/dist/web/assets/{clock-3-v0h4RrLK.js → clock-3-DEL1ixyh.js} +1 -1
  94. package/dist/web/assets/{copy-CF3TUa0u.js → copy-Bd5v-KkM.js} +1 -1
  95. package/dist/web/assets/{download-ZG8PfhmH.js → download-CIKvpDBW.js} +1 -1
  96. package/dist/web/assets/{external-link-BKCjDDt-.js → external-link-B33h3DQN.js} +1 -1
  97. package/dist/web/assets/{folder-M-NM2bQG.js → folder-lOczceoh.js} +1 -1
  98. package/dist/web/assets/index-hZ37pkxs.js +203 -0
  99. package/dist/web/assets/{pause-CP_wlUro.js → pause-nnvVbgsj.js} +1 -1
  100. package/dist/web/assets/{pencil-U3n9D8ed.js → pencil-_yfoOmUq.js} +1 -1
  101. package/dist/web/assets/{play-NBWnc2gU.js → play-BilJ7SDs.js} +1 -1
  102. package/dist/web/assets/{plus-CmPqJgff.js → plus-BqqpYKaK.js} +1 -1
  103. package/dist/web/assets/{session-events-DKjIMNKI.js → session-events-FPOvcMBw.js} +19 -19
  104. package/dist/web/assets/{settings-CVFpbh_y.js → settings-CmJXtYTH.js} +1 -1
  105. package/dist/web/assets/{team-B9Na0Ocd.js → team-Bb04o2Tb.js} +1 -1
  106. package/dist/web/assets/{teamService-ZQZLqsjy.js → teamService-B5w9cpsa.js} +1 -1
  107. package/dist/web/assets/{terminal-BdmigqIS.js → terminal-DOjdChj0.js} +1 -1
  108. package/dist/web/index.html +1 -1
  109. package/package.json +1 -1
  110. package/dist/chunk-03zfvfen.js +0 -10
  111. package/dist/chunk-303b3x5q.js +0 -1
  112. package/dist/chunk-3g2z6hae.js +0 -1
  113. package/dist/chunk-3t5r41yh.js +0 -1
  114. package/dist/chunk-59980a8h.js +0 -1
  115. package/dist/chunk-5gy3x011.js +0 -1
  116. package/dist/chunk-5xgyx25z.js +0 -2
  117. package/dist/chunk-8cnxy251.js +0 -1
  118. package/dist/chunk-8cqm87j5.js +0 -1
  119. package/dist/chunk-ar85hxx2.js +0 -5
  120. package/dist/chunk-ddcz0nwv.js +0 -1
  121. package/dist/chunk-e71y87zg.js +0 -1
  122. package/dist/chunk-h2gp7smy.js +0 -1
  123. package/dist/chunk-j58wrt5n.js +0 -171
  124. package/dist/chunk-mc2mr1kn.js +0 -2
  125. package/dist/chunk-n2tfj82m.js +0 -1
  126. package/dist/chunk-pty1ncam.js +0 -6
  127. package/dist/chunk-qdjqbgts.js +0 -1
  128. package/dist/chunk-wv1mnf2m.js +0 -1
  129. package/dist/web/assets/ChatView-CZLmEMBO.js +0 -63
  130. package/dist/web/assets/index-VQVOzFZT.js +0 -203
@@ -1,2 +0,0 @@
1
- var _=20,E=5242880,T=32768,A=1e6,S=4194304;
2
- export{_ as Ni,E as Oi,T as Pi,A as Qi,S as Ri};
@@ -1 +0,0 @@
1
- import{rg as a,sg as b,tg as c,ug as d}from"./chunk-14j2dbd6.js";import"./chunk-atdq9btn.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
@@ -1,6 +0,0 @@
1
- import{p as IH,q as RH,r as gH,s as kH,t as CH,u as hH}from"./chunk-k10d8t4f.js";import{B as bH,C as VH,D as ZH,E as $H,F as l,G as qH}from"./chunk-d11mqbqk.js";import{H as BH,ca as FH,ea as EH,fa as MH,ja as zH}from"./chunk-y66f1t18.js";import"./chunk-16648v5c.js";import"./chunk-2m79vd9p.js";import"./chunk-5xgyx25z.js";import{Ib as t,Ub as GH,bc as PH}from"./chunk-j58wrt5n.js";import"./chunk-3eskgvpy.js";import{Md as UH,Qd as _H,Sd as u,be as n}from"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import{lf as AH}from"./chunk-gcg56vaw.js";import{nf as SH,of as TH,pf as yH}from"./chunk-nyw686sf.js";import{qf as fH}from"./chunk-v2fewxvw.js";import"./chunk-6qhbdcse.js";import{Qf as xH}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import"./chunk-hrcz179j.js";import"./chunk-d64b7wta.js";import"./chunk-14j2dbd6.js";import"./chunk-nnas8tdt.js";import{fh as YH}from"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-atdq9btn.js";import{Li as WH}from"./chunk-npc7jt96.js";import{Qi as s,Ri as r}from"./chunk-mc2mr1kn.js";import{Vi as C}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import{Aj as XH,Cj as Y,xj as jH,zj as H}from"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import mJ from"yargs";import{hideBin as cJ}from"yargs/helpers";function a(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function vH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{a(V,"drain",x),a(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function lH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await vH(V,Q)}class i{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new l("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new qH({maxPendingItems:Z.maxPendingItems??VH,maxPendingBytes:Z.maxPendingBytes??ZH,writeTimeoutMs:Z.writeTimeoutMs??$H,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>lH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new l("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))a(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var aH=L({type:H.Literal("content_delta"),delta:H.String()}),iH=L({type:H.Literal("thinking_delta"),delta:H.String()}),oH=L({type:H.Literal("thinking"),content:H.String()}),sH=L({type:H.Literal("stream_end")}),rH=L({type:H.Literal("content"),content:H.String()}),nH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),o=Y(["readonly","write","execute"]),tH=H.Object({kind:o,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),eH=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(o)}),HJ=L({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(tH)}),JJ=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:Y(["local","acp"])}),KJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(o),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(JJ)}),VJ=L({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),ZJ=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),$J=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),qJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),XJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),YJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),BJ=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),NJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),QJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),DJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),LJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),jJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),xJ=L({type:H.Literal("task_update"),tasks:H.Array(BH)}),UJ=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),_J=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(Y(YH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),GJ=L({type:H.Literal("subagent"),state:Y(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),PJ=L({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:Y(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),FJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"]))}),EJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(Y(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(Y(["attempt_limit","recovery_budget"]))}),MJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),zJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),fJ=L({type:H.Literal("provider_stall"),phase:Y(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),c=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),NH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),AJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:c,to:c,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:NH},{additionalProperties:!1}))},{additionalProperties:!1}),SJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([AJ,H.Null()])},{additionalProperties:!1}),TJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),yJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(TJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),bJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([yJ,H.Null()])},{additionalProperties:!1}),IJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:c,to:c,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:NH},{additionalProperties:!1}),RJ=L({type:H.Literal("action_stationarity"),phase:Y(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),gJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),kJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),CJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),hJ=L({type:H.Literal("task_admission"),state:Y(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),OJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),wJ=L({type:H.Literal("error"),message:H.String()}),XK=XH(H.Union([aH,iH,oH,sH,rH,nH,eH,HJ,KJ,VJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,MJ,zJ,EJ,fJ,SJ,bJ,IJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ]));function QH(V,Z){return{event_version:k,type:V,...Z}}function uJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function dJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var pJ=Y(["text","jsonl"]),vJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(WH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(Y(["local","worktree"])),outputFormat:H.Optional(pJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class OH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function lJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function aJ(V){let Z=jH(vJ,V);if(!Z.success)throw Error(`Invalid headless options: ${lJ(Z.error)}`);return Z.data}function iJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("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(Z)=>{if(!Z.headless)return;let Q=await eJ(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
2
- `)}function oJ(V){return`[task] [${V.status}] ${V.subject}`}function sJ(){return{requestConfirmation:async(V)=>V.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:V.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function rJ(V){if(!(V instanceof Error))return"Unknown error";let q=V.lastError??V;if(q.responseBody)try{let D=JSON.parse(q.responseBody)?.error?.message;if(D)return q.statusCode?`${D} (HTTP ${q.statusCode})`:D}catch{}let J=V.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return V.message}function nJ(V){return V==="jsonl"?"jsonl":"text"}function DH(V,Z){let Q=(...q)=>{for(let J of q){let K=Z[J];if(typeof K==="string"&&K.trim()!=="")return K}return};switch(V){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function tJ(V,Z,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),K=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(V)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(J.has(V))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if(K.has(V))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function LH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(QH(J,K))}
3
- `)};return{contentDelta(J){if(Z==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;V.stdout.write(J)},thinkingDelta(J,K){if(Z==="jsonl")return q("thinking_delta",{delta:J}),K;if(!K)V.stderr.write("[thinking] ");return V.stderr.write(J),!0},thinking(J){if(Z==="jsonl"){q("thinking",{content:J});return}W(V.stderr,`[thinking] ${J}`)},streamEnd(J,K){if(Z==="jsonl"){q("stream_end",{});return}if(K)V.stderr.write(`
4
- `);if(J)V.stdout.write(`
5
- `)},content(J){if(Z==="jsonl"){q("content",{content:J});return}W(V.stdout,J)},structuredOutput(J){if(Z==="jsonl"){q("structured_output",{output:J.output,schema_digest:J.schemaDigest});return}W(V.stdout,JSON.stringify(J.output))},toolStart(J,K,D,x){if(Z==="jsonl"){q("tool_start",{tool_name:J,summary:K,target:D,tool_kind:x});return}W(V.stderr,`[tool:start] ${K}`)},toolProgress(J,K,D,x,j){if(Z==="jsonl"){q("tool_progress",{tool_name:J,message:K,progress:D,total:x,admission:j?{kind:j.kind,scope:j.scope,queue_position:j.queuePosition,in_flight:j.inFlight,limit:j.limit}:void 0});return}W(V.stderr,`[tool:progress] ${J}: ${K}`)},toolResult(J,K,D,x,j){if(Z==="jsonl"){q("tool_result",{tool_name:J,summary:K,target:D,tool_kind:x,success:j?.success,error_type:j?.errorType,error_message:j?.errorMessage,background:j?.background});return}W(V.stderr,`[tool:result] ${K}`)},mcpCatalogChanged(J){if(Z==="jsonl"){q("mcp_catalog_changed",{revision:J.revision,server_name:J.serverName,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:catalog] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpContentChanged(J){if(Z==="jsonl"){q("mcp_content_changed",{revision:J.revision,server_name:J.serverName,content_kind:J.contentKind==="resourceTemplates"?"resource_templates":J.contentKind,added:J.added,removed:J.removed,updated:J.updated});return}W(V.stderr,`[mcp:${J.contentKind}] r${J.revision} ${J.serverName} +${J.added.length} -${J.removed.length} ~${J.updated.length}`)},mcpResourceUpdated(J){if(Z==="jsonl"){q("mcp_resource_updated",{revision:J.revision,server_name:J.serverName,uri:J.uri});return}W(V.stderr,`[mcp:resource] r${J.revision} ${J.serverName} updated ${J.uri}`)},mcpConnectionChanged(J){if(Z==="jsonl"){q("mcp_connection_changed",{revision:J.revision,server_name:J.serverName,phase:J.phase,reason:J.reason,attempt:J.attempt,max_attempts:J.maxAttempts,...J.nextRetryAt!==void 0?{next_retry_at:J.nextRetryAt}:{},...J.error?{error:J.error}:{}});return}W(V.stderr,`[mcp:connection] r${J.revision} ${J.serverName} ${J.phase} ${J.attempt}/${J.maxAttempts}`)},mcpLog(J){if(Z==="jsonl"){q("mcp_log",{revision:J.revision,server_name:J.serverName,level:J.level,logger:J.logger,message:J.message,projected_bytes:J.projectedBytes,data_sha256:J.dataSha256,truncated:J.truncated,details_omitted:J.detailsOmitted,timestamp:J.timestamp,synthetic:J.synthetic});return}W(V.stderr,`[mcp:log] ${J.level} ${J.serverName}${J.logger?` logger=${J.logger}`:""}: ${J.message}`)},mcpInstructionsChanged(J){if(Z==="jsonl"){q("mcp_instructions_changed",{revision:J.revision,server_name:J.serverName,action:J.action,reason:J.reason,text:J.text,source_bytes:J.sourceBytes,projected_bytes:J.projectedBytes,sha256:J.sha256,truncated:J.truncated,details_omitted:J.detailsOmitted});return}W(V.stderr,`[mcp:instructions] ${J.action} ${J.serverName}${J.truncated?" (truncated)":""}`)},mcpTaskChanged(J){if(Z==="jsonl"){q("mcp_task_changed",{revision:J.revision,task_id:J.taskId,server_name:J.serverName,tool_name:J.toolName,status:J.status,status_message:J.statusMessage,created_at:J.createdAt,updated_at:J.updatedAt,completed_at:J.completedAt,has_result:J.hasResult,error:J.error});return}W(V.stderr,`[mcp:task] ${J.taskId} ${J.serverName}/${J.toolName} `+J.status)},projectRulesLoaded(J){if(Z==="jsonl"){q("project_rules_loaded",{files:J.files.map((K)=>({id:K.id,relative_path:K.relativePath,source:K.source,conditional:K.conditional,content_sha256:K.contentSha256})),trigger_paths:J.triggerPaths,blocked_write:J.blockedWrite});return}W(V.stderr,`[project-rules] loaded ${J.files.length} file(s)${J.blockedWrite?" before write":""}`)},userShellStarted(J,K,D){if(Z==="jsonl"){q("user_shell_started",{execution_id:J,command:K,auxiliary:D});return}W(V.stderr,`[user-shell:start] ${K}`)},userShellOutput(J,K,D,x){if(Z==="jsonl"){q("user_shell_output",{execution_id:J,stream:K,chunk:D,stream_truncated:x});return}(K==="stderr"?V.stderr:V.stdout).write(D)},userShellCompleted(J){if(Z==="jsonl"){q("user_shell_completed",{execution_id:J.executionId,message_id:J.messageId,status:J.record.status,exit_code:J.record.exitCode,duration_ms:J.record.durationMs,stdout:J.record.stdout,stderr:J.record.stderr,truncated:J.record.truncated,auxiliary:J.auxiliary});return}W(V.stderr,`[user-shell:${J.record.status}] exit=${J.record.exitCode??"null"} ${J.record.durationMs}ms`)},phase(J,K,D,x={}){if(Z==="jsonl"){q("phase",{phase:J,status:K,message:D,turn:x.turn,tool_name:x.toolName,target:x.target});return}W(V.stderr,`[phase:${J}] ${D}`)},toolDetail(J,K){if(Z==="jsonl"){q("tool_detail",{tool_name:J,detail:K});return}W(V.stderr,K)},taskUpdate(J){if(Z==="jsonl"){q("task_update",{tasks:J});return}for(let K of J)W(V.stderr,oJ(K))},goalFrontier(J){if(Z==="jsonl"){q("goal_frontier",{goal_id:J.goal.goalId,status:J.goal.status,task_list_id:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,in_progress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,next_task:J.frontier.nextTask,digest_sha256:J.frontier.digestSha256,observed_at:J.frontier.observedAt,stall_category:J.goal.frontierStall?.category,stall_count:J.goal.frontierStall?.consecutiveCount});return}let K=J.frontier.nextTask?` next=#${J.frontier.nextTask.id} ${J.frontier.nextTask.subject}`:"";W(V.stderr,`[goal-frontier] ${J.frontier.completed}/${J.frontier.total} completed${K}`)},turnRecovery(J){let K=J.assessment;if(Z==="jsonl"){q("turn_recovery",{state:K.state,turn_id:K.turnId,input_message_count:K.inputMessageCount,reason:K.state==="requires_attention"?K.reason:void 0});return}W(V.stderr,`[turn-recovery:${K.state}] ${K.turnId}`)},goal(J){if(Z==="jsonl"){q("goal",{state:J.goal?"updated":"cleared",goal_id:J.goal?.goalId,status:J.goal?.status,verification_attempt:J.goal?.completionVerification?.attempt,verification_status:J.goal?.completionVerification?.status,verifier_session_id:J.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:J.goal?.completionVerification?.evidenceSha256,verification_summary:J.goal?.completionVerification?.summary,verification_stall_count:J.goal?.verificationStall?.consecutiveCount,premature_stop_pattern:J.goal?.prematureStop?.pattern,premature_stop_count:J.goal?.prematureStop?.consecutiveCount,frontier_stall_category:J.goal?.frontierStall?.category,frontier_stall_count:J.goal?.frontierStall?.consecutiveCount});return}if(J.goal)W(V.stderr,`[goal:${J.goal.status}] ${J.goal.objective}`);else W(V.stderr,"[goal:cleared]")},subagent(J){let K=J.kind==="subagent_spawned";if(Z==="jsonl"){q("subagent",{state:K?"spawned":"completed",session_id:J.sessionId,subagent_type:J.type,success:K?void 0:J.success,summary:K?void 0:J.summary,verification_verdict:K?void 0:J.verificationVerdict,resumed_from:J.resumedFrom,root_agent_id:J.rootAgentId,resume_depth:J.resumeDepth});return}W(V.stderr,`[subagent:${K?"spawned":"completed"}] ${J.sessionId}${J.resumedFrom?` resumed from ${J.resumedFrom}`:""}`)},tokenUsage(J){if(Z==="jsonl"){q("token_usage",{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens,max_context_tokens:J.maxContextTokens,cache_read_tokens:J.cacheReadTokens,cache_write_tokens:J.cacheWriteTokens,prompt_cache_break:J.cacheBreak?{reason:J.cacheBreak.reason,previous_cache_read_tokens:J.cacheBreak.previousCacheReadTokens,cache_read_tokens:J.cacheBreak.cacheReadTokens,cache_write_tokens:J.cacheBreak.cacheWriteTokens,token_drop:J.cacheBreak.tokenDrop,elapsed_ms:J.cacheBreak.elapsedMs,call_number:J.cacheBreak.callNumber,system_prompt_changed:J.cacheBreak.systemPromptChanged,system_char_delta:J.cacheBreak.systemCharDelta,tools_changed:J.cacheBreak.toolsChanged,added_tool_count:J.cacheBreak.addedToolCount,removed_tool_count:J.cacheBreak.removedToolCount,changed_tool_count:J.cacheBreak.changedToolCount,model_changed:J.cacheBreak.modelChanged,request_policy_changed:J.cacheBreak.requestPolicyChanged}:void 0,cost_usd:J.costUsd});return}W(V.stderr,`[tokens] in=${J.inputTokens} out=${J.outputTokens} total=${J.totalTokens} / ${J.maxContextTokens}`)},compacting(J){let K=J.phase==="start";if(Z==="jsonl"){q("compacting",{state:K?"started":"completed",reason:J.reason,strategy:J.strategy,outcome:J.outcome,pre_tokens:J.preTokens,pre_token_source:J.preTokenSource,estimated_pending_tokens:J.estimatedPendingTokens,post_tokens:J.postTokens,sample_attempts:J.sampleAttempts,input_reductions:J.inputReductions,messages_omitted:J.messagesOmitted,files_omitted:J.filesOmitted,images_omitted:J.imagesOmitted,fallback_target_tokens:J.fallbackTargetTokens,fallback_messages_omitted:J.fallbackMessagesOmitted,fallback_messages_truncated:J.fallbackMessagesTruncated,failure_reason:J.failureReason});return}W(V.stderr,K?`[context] compacting started${J.reason?` (${J.reason})`:""}`:`[context] compacting ${J.outcome??"completed"}${J.sampleAttempts!==void 0?` after ${J.sampleAttempts} sample attempt${J.sampleAttempts===1?"":"s"}`:""}${J.inputReductions?` with ${J.inputReductions} input reduction${J.inputReductions===1?"":"s"}`:""}${J.imagesOmitted?` and ${J.imagesOmitted} image${J.imagesOmitted===1?"":"s"} omitted`:""}${J.fallbackTargetTokens!==void 0?`; fallback target ${J.fallbackTargetTokens} tokens, ${J.fallbackMessagesOmitted??0} messages omitted, ${J.fallbackMessagesTruncated??0} truncated`:""}`)},providerAdmission(J){if(Z==="jsonl"){q("provider_admission",{phase:J.phase,request_class:J.requestClass,resource:J.resource,scope:J.scope,reason:J.reason,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,limit:J.limit,wait_ms:J.waitMs,max_wait_ms:J.maxWaitMs,recovery_remaining_ms:J.recoveryRemainingMs});return}W(V.stderr,`[provider-admission:${J.phase}] ${J.resource}/${J.scope} ${J.inFlight}/${J.limit} queue=${J.queuePosition}/${J.queueDepth}`)},providerRetry(J){if(Z==="jsonl"){q("provider_retry",{phase:J.phase,attempt:J.attempt,max_retries:J.maxRetries,reason:J.reason,status_code:J.statusCode,delay_ms:J.delayMs,next_retry_at:J.nextRetryAt,mode:J.mode,recovery_budget_ms:J.recoveryBudgetMs,recovery_elapsed_ms:J.recoveryElapsedMs,recovery_remaining_ms:J.recoveryRemainingMs,exhausted_by:J.exhaustedBy});return}let K=J.delayMs!==void 0?` in ${Math.max(0,Math.ceil(J.delayMs/1000))}s`:"";W(V.stderr,`[provider-retry:${J.phase}] ${J.attempt}/${J.maxRetries} ${J.reason}${K}`)},providerCircuit(J){if(Z==="jsonl"){q("provider_circuit",{phase:J.phase,reason:J.reason,status_code:J.statusCode,retry_after_ms:J.retryAfterMs,next_probe_at:J.nextProbeAt,open_duration_ms:J.openDurationMs,sample_count:J.sampleCount,failure_count:J.failureCount,recovery_remaining_ms:J.recoveryRemainingMs});return}let K=J.retryAfterMs!==void 0?` retry in ${Math.max(0,Math.ceil(J.retryAfterMs/1000))}s`:"";W(V.stderr,`[provider-circuit:${J.phase}] ${J.reason}${K}`)},providerStall(J){if(Z==="jsonl"){q("provider_stall",{phase:J.phase,stall_count:J.stallCount,duration_ms:J.durationMs,warning_after_ms:J.warningAfterMs,timeout_ms:J.timeoutMs,output_started:J.outputStarted});return}W(V.stderr,`[provider-stall:${J.phase}] ${J.durationMs}ms / ${J.timeoutMs}ms`)},providerRecovery(J){let K=J.recovery.snapshot;if(Z==="jsonl"){q("provider_recovery",{generation:J.recovery.generation,revision:J.recovery.revision,snapshot:K?{activity:K.activity,reason:K.reason,updated_at:K.updatedAt,next_action_at:K.nextActionAt,retry:K.retry?{attempt:K.retry.attempt,max_retries:K.retry.maxRetries,status_code:K.retry.statusCode,delay_ms:K.retry.delayMs,recovery_budget_ms:K.retry.recoveryBudgetMs,recovery_elapsed_ms:K.retry.recoveryElapsedMs,recovery_remaining_ms:K.retry.recoveryRemainingMs}:void 0,admission:K.admission?{request_class:K.admission.requestClass,scope:K.admission.scope,resource:K.admission.resource,queue_position:K.admission.queuePosition,queue_depth:K.admission.queueDepth,in_flight:K.admission.inFlight,limit:K.admission.limit,wait_ms:K.admission.waitMs,max_wait_ms:K.admission.maxWaitMs,recovery_remaining_ms:K.admission.recoveryRemainingMs}:void 0,circuit:K.circuit?{phase:K.circuit.phase,status_code:K.circuit.statusCode,retry_after_ms:K.circuit.retryAfterMs,next_probe_at:K.circuit.nextProbeAt,open_duration_ms:K.circuit.openDurationMs,sample_count:K.circuit.sampleCount,failure_count:K.circuit.failureCount,recovery_remaining_ms:K.circuit.recoveryRemainingMs}:void 0,stall:K.stall?{stall_count:K.stall.stallCount,duration_ms:K.stall.durationMs,warning_after_ms:K.stall.warningAfterMs,timeout_ms:K.stall.timeoutMs,output_started:K.stall.outputStarted}:void 0,fallback:K.fallback?{from:K.fallback.from,to:K.fallback.to,candidate:K.fallback.candidate,candidate_count:K.fallback.candidateCount,trigger:K.fallback.trigger.source==="retry"||K.fallback.trigger.source==="circuit"?{source:K.fallback.trigger.source,reason:K.fallback.trigger.reason,status_code:K.fallback.trigger.statusCode}:K.fallback.trigger}:void 0}:null});return}W(V.stderr,K?`[provider-recovery:${K.activity}] ${K.reason}`:"[provider-recovery:clear]")},turnActivity(J){if(Z!=="jsonl")return;let K=J.activity.snapshot;q("turn_activity",{generation:J.activity.generation,revision:J.activity.revision,snapshot:K?{phase:K.phase,started_at:K.startedAt,updated_at:K.updatedAt,turn:K.turn,max_turns:K.maxTurns,output_started:K.outputStarted,tool_calls_started:K.toolCallsStarted,tool_calls_completed:K.toolCallsCompleted,active_tools:K.activeTools.map((D)=>({name:D.name,kind:D.kind,started_at:D.startedAt,progress:D.progress,total:D.total})),active_tool_overflow:K.activeToolOverflow}:null})},modelFallback(J){let K=J.trigger.source==="retry"||J.trigger.source==="circuit"?{source:J.trigger.source,reason:J.trigger.reason,status_code:J.trigger.statusCode}:J.trigger;if(Z==="jsonl"){q("model_fallback",{from:J.from,to:J.to,candidate:J.candidate,candidate_count:J.candidateCount,trigger:K});return}W(V.stderr,`[provider-fallback] ${J.from.model} -> ${J.to.model}`)},actionStationarity(J){if(Z==="jsonl"){q("action_stationarity",{phase:J.phase,tool_name:J.toolName,run_length:J.runLength,nudge_threshold:J.nudgeThreshold,halt_threshold:J.haltThreshold,progress_aware:J.progressAware});return}W(V.stderr,`[action-stationarity:${J.phase}] ${J.toolName} ${J.runLength}/${J.haltThreshold}`)},turnLimit(J){if(Z==="jsonl"){q("turn_limit",{turns_count:J,action:"continue"});return}W(V.stderr,`[turn-limit] continuing after ${J} turns`)},taskSession(J){if(Z==="jsonl"){q("task_session",{session_id:J.sessionId,project_path:J.projectPath,source_project_path:J.sourceProjectPath,isolation:J.isolation,worktree_branch:J.worktreeBranch,base_commit:J.baseCommit});return}W(V.stderr,`[task:${J.isolation}] ${J.sessionId} ${J.sourceProjectPath} -> ${J.projectPath}${J.worktreeBranch?` (${J.worktreeBranch})`:""}`)},taskAdmission(J){if(Z==="jsonl"){q("task_admission",{state:J.state,queue_position:J.queuePosition,queue_depth:J.queueDepth,in_flight:J.inFlight,max_concurrent_tasks:J.maxConcurrentTasks});return}W(V.stderr,J.state==="queued"?`[task:queued] position ${J.queuePosition??1}/${J.queueDepth} (running ${J.inFlight}/${J.maxConcurrentTasks})`:`[task:running] admitted (running ${J.inFlight}/${J.maxConcurrentTasks})`)},output(J,K=0){if(Z==="jsonl"){q("output",{content:J,exit_code:K});return}W(K===0?V.stdout:V.stderr,J)},error(J){if(Z==="jsonl"){q("error",{message:J});return}W(V.stderr,J)}}}async function eJ(V,Z={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new OH,K={targetLocked:!1},D,x,j,P=dJ(Q),T=!1,F=new i(Z,{signal:P.signal,onFailure:(N)=>{T=!0,P.abort(N)}}),d={stdout:{write:(N)=>F.write("stdout",N)},stderr:{write:(N)=>F.write("stderr",N)}},B=LH(d,q),p=async()=>{try{return await F.flush(),!T}catch{return!1}},E=async(N)=>{return x?.(),x=void 0,j?.(),j=void 0,await p()?N:1};try{let N=aJ(V);q=nJ(N.outputFormat);let y=await CH(N);B=LH(d,q,Boolean(y)),await IH();let e=N.forkSession!==!0&&(N.continue===!0||typeof N.resume==="string"&&N.resume.length>0)?await gH({message:N.message,_:N._,stdin:Q?.stdin}):await RH({...N,stdin:Q?.stdin}),M=e===void 0,_=M?{mode:"agent",content:""}:await kH(e);if(_.mode==="output"){if(_.content)B.output(_.content,_.exitCode??0);return await E(_.exitCode??0)}if(!M&&_.content.length>s)throw Error(`User prompt exceeds the ${s}-character durable input limit`);if(!M&&Buffer.byteLength(_.content,"utf8")>r)throw Error(`User prompt exceeds the ${r}-byte durable input limit`);let h=_.content.trimStart().startsWith("!")?_.content.trimStart().slice(1).trim():void 0;if(h!==void 0&&N.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(h!==void 0&&y)throw Error("Output schemas cannot be combined with user shell commands");if(N.taskIsolation&&(N.continue||N.resume||N.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:G,messages:HH,metadata:JH}=await hH({sessionId:N.sessionId,continue:N.continue,resume:N.resume,forkSession:N.forkSession,fallbackSessionPrefix:"headless"}),R=N.permissionMode??JH?.permissionMode??"yolo",KH=N.model&&N.model!=="inherit"?N.model:xH()?.id,U=N.taskIsolation?await bH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,permissionMode:R,...KH?{modelId:KH}:{},...y?{outputSchema:y}:{}}}):void 0,z=U?.metadata.projectPath??JH?.projectPath??C();if(j=t.subscribe(($)=>{if($.type!=="subagent.provider.admission"||$.sessionId!==G||$.projectPath!==z)return;let X=$.properties,f=["queued","admitted","rejected"],A=["foreground","background","internal"],S=["stream","pending_count","pending_bytes"],I=["global","domain","owner","class"],pH=["capacity","queue_full","wait_timeout","closed"];if(!f.includes(X.phase)||!A.includes(X.requestClass)||!S.includes(X.resource)||!I.includes(X.scope)||X.reason!==void 0&&!pH.includes(X.reason)||typeof X.queuePosition!=="number"||typeof X.queueDepth!=="number"||typeof X.inFlight!=="number"||typeof X.limit!=="number"||typeof X.waitMs!=="number"||typeof X.maxWaitMs!=="number"||X.recoveryRemainingMs!==void 0&&typeof X.recoveryRemainingMs!=="number")return;B.providerAdmission({kind:"provider_admission",phase:X.phase,requestClass:X.requestClass,resource:X.resource,scope:X.scope,...X.reason!==void 0?{reason:X.reason}:{},queuePosition:X.queuePosition,queueDepth:X.queueDepth,inFlight:X.inFlight,limit:X.limit,waitMs:X.waitMs,maxWaitMs:X.maxWaitMs,...X.recoveryRemainingMs!==void 0?{recoveryRemainingMs:X.recoveryRemainingMs}:{}})}),!U)await n.setSessionPermissionMode(G,z,R);let wH=U?!1:await PH.cancelPendingNonInteractive(z,G);if(U)B.taskSession({sessionId:G,projectPath:z,sourceProjectPath:U.metadata.taskSourceProjectPath??C(),isolation:N.taskIsolation,worktreeBranch:U.metadata.taskWorktreeBranch,baseCommit:U.metadata.taskBaseCommit}),x=t.subscribe(($)=>{if($.type!=="task.status"||$.sessionId!==G||$.projectPath!==z||!["queued","running"].includes(String($.properties.taskStatus))||typeof $.properties.taskQueueDepth!=="number"||typeof $.properties.taskInFlight!=="number"||typeof $.properties.taskConcurrencyLimit!=="number")return;B.taskAdmission({state:$.properties.taskStatus,queuePosition:typeof $.properties.taskQueuePosition==="number"?$.properties.taskQueuePosition:void 0,queueDepth:$.properties.taskQueueDepth,inFlight:$.properties.taskInFlight,maxConcurrentTasks:$.properties.taskConcurrencyLimit})});let mH={messages:wH?await n.loadSessionModelContext(G,z):[...HH],userId:"cli-user",sessionId:G,workspaceRoot:z,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:sJ()};D=await FH.create({sessionId:G,workspaceRoot:z,modelId:N.model,permissionMode:R,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig,agents:N.agents?fH(N.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...HH.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}});let g=M&&D.getPendingSteeringCount()>0,O=M&&!g?await D.getGoal():null,w=O?.status==="active"||O?.status==="verifying",v=D.getTurnRecoveryAssessment?.()??{state:"none"};if(M&&!g&&!w&&v.state==="requires_attention")return B.turnRecovery({kind:"turn_recovery",assessment:v}),B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);let b=M&&!g&&!w?await D.getRecoveredFinalResponse():void 0;if(M&&!g&&!w){if(!b)throw Error("No unfinished turn or active goal to resume");let $=v;if($.state!=="none")B.turnRecovery({kind:"turn_recovery",assessment:$});if(O)B.goal({kind:"goal_updated",goal:O});if(b.structuredOutput&&b.structuredOutputSchemaDigest)B.structuredOutput({kind:"structured_output",output:b.structuredOutput,schemaDigest:b.structuredOutputSchemaDigest});else B.content(b.content);return B.phase("completed","done","Recovered headless run completed"),await E(0)}if(h!==void 0){let $=await D.executeUserShellCommand(h,{signal:P.signal,onEvent:async(X)=>{if(X.type==="started")B.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")B.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated);await p()}});return B.userShellCompleted($),await E($.record.status==="completed"?0:$.record.status==="aborted"?130:$.record.exitCode??1)}let cH=N.maxTurns??D.getConfig().maxTurns,uH=U?.taskWorktree?[...new Set([...N.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:N.disallowedTools,dH=await zH.createWithRuntime(D,{sessionId:G,systemPrompt:N.systemPrompt,appendSystemPrompt:N.appendSystemPrompt,maxTurns:N.maxTurns,modelId:N.model,permissionMode:R,toolWhitelist:N.allowedTools,toolBlacklist:uH,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig}),m=await GH(dH.chatStream(_.content,mH,{stream:!0,signal:P.signal,maxTurns:N.maxTurns,builtinVerification:N.verificationAgent!==!1,outputSchema:y,pendingInputOnly:g,goalContinuationOnly:w,...cH===-1?{onTurnLimitReached:async($)=>{return B.turnLimit($.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async($)=>{switch($.kind){case"content_delta":if(!y||q==="jsonl")J.markAssistantContent();B.contentDelta($.delta);break;case"thinking_delta":J.setThinkingOpened(B.thinkingDelta($.delta,J.hasOpenThinking()));break;case"stream_end":{let X=J.completeStream();B.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===u)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),A=EH(X.function.name,f),S=DH(X.function.name,f),I=tJ(X.function.name,A,S,K);if(I.shouldLockTarget)K.targetLocked=!0;B.phase(I.phase,I.status,I.message,{toolName:X.function.name,target:S}),B.toolStart(X.function.name,A,S,$.toolKind)}catch{B.phase(K.targetLocked?"executing":"searching",K.targetLocked?"hit":"ongoing",K.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),B.toolStart(X.function.name,X.function.name,void 0,$.toolKind)}break}case"tool_progress":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===u)break;B.toolProgress(X.function.name,$.update.message,$.update.progress,$.update.total,$.update.admission);break}case"tool_result":{let X=$.toolCall;if(!("function"in X))break;if(X.function.name===u)break;let f;try{let S=JSON.parse(X.function.arguments);f=DH(X.function.name,S)}catch{f=void 0}let A=_H(MH(X.function.name,$.result),UH);if(B.toolResult(X.function.name,A.summary,f,void 0,{success:$.result.success,errorType:$.result.error?.type,errorMessage:$.result.error?.message,background:uJ($.result.metadata)}),A.detail)B.toolDetail(X.function.name,A.detail);break}case"token_usage":B.tokenUsage($.usage);break;case"compaction":B.compacting($);break;case"task_update":B.taskUpdate($.tasks);break;case"goal_frontier_updated":B.goalFrontier($);break;case"turn_recovery":B.turnRecovery($);break;case"structured_output":B.structuredOutput($);break;case"mcp_catalog_changed":B.mcpCatalogChanged($);break;case"mcp_content_changed":B.mcpContentChanged($);break;case"mcp_resource_updated":B.mcpResourceUpdated($);break;case"mcp_connection_changed":B.mcpConnectionChanged($);break;case"mcp_log":B.mcpLog($);break;case"mcp_instructions_changed":B.mcpInstructionsChanged($);break;case"mcp_task_changed":B.mcpTaskChanged($);break;case"project_rules_loaded":B.projectRulesLoaded($);break;case"steering_applied":case"follow_up_started":case"follow_up_queue_changed":case"goal_continuation_started":break;case"goal_updated":B.goal($);break;case"subagent_spawned":case"subagent_completed":B.subagent($);break;case"model_fallback":B.modelFallback($);break;case"provider_admission":B.providerAdmission($);break;case"provider_retry":B.providerRetry($);break;case"provider_circuit":B.providerCircuit($);break;case"provider_stall":B.providerStall($);break;case"provider_recovery":B.providerRecovery($);break;case"turn_activity":B.turnActivity($);break;case"action_stationarity":B.actionStationarity($);break;case"turn_start":if($.turn===1)K.targetLocked=!1;B.phase("turn",K.targetLocked?"hit":"ongoing",`Turn ${$.turn} started`,{turn:$.turn});break;default:{let X=$}}await p()});if(m.metadata?.outputTruncated)B.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(m.metadata?.recoveryAttention)return B.error("Error: Turn recovery requires explicit user attention before continuation"),await E(2);if(!m.success)return B.error(`Error: ${m.error?.message??"Agent execution failed"}`),await E(1);return B.phase("completed","done","Headless run completed"),await E(0)}catch(N){if(!T){if(J.hasOpenThinking()&&q==="text")d.stderr.write(`
6
- `);B.error(`Error: ${rJ(N)}`)}return await E(1)}finally{x?.(),j?.();try{await D?.dispose()}finally{F.close(),P.dispose()}}}async function kK(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Q,"output-format":q,"system-prompt":J,"append-system-prompt":K,"max-turns":D,...x}=AH,j=mJ(cJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([TH,SH,yH]);return iJ(j),await j.parse(),!0}export{eJ as runHeadless,kK as handleHeadlessMode,vJ as HeadlessOptionsSchema};
@@ -1 +0,0 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-j21hez8g.js";import"./chunk-fndqbf45.js";import"./chunk-9m7d3ajv.js";import"./chunk-56py3ryh.js";import"./chunk-he0f6h5q.js";import"./chunk-d11mqbqk.js";import"./chunk-y66f1t18.js";import"./chunk-16648v5c.js";import"./chunk-2m79vd9p.js";import"./chunk-5xgyx25z.js";import"./chunk-j58wrt5n.js";import"./chunk-3eskgvpy.js";import"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import{sf as n}from"./chunk-92n2p24j.js";import"./chunk-6qhbdcse.js";import{Of as s}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import"./chunk-hrcz179j.js";import"./chunk-d64b7wta.js";import"./chunk-14j2dbd6.js";import"./chunk-nnas8tdt.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-atdq9btn.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1 +0,0 @@
1
- import{Lb as a,Mb as b,Ob as c,Sb as d,Tb as e,Ub as f,Vb as g,Wb as h,Xb as i,Yb as j,Zb as k,ec as l,fc as m,gc as n,hc as o,jc as p,kc as q,lc as r}from"./chunk-j58wrt5n.js";import"./chunk-3eskgvpy.js";import"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import"./chunk-5j68055h.js";import"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import"./chunk-d64b7wta.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,63 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-TWNqhwrr.js","assets/index-VQVOzFZT.js","assets/vendor-react-DofNRwfy.js","assets/vendor-radix-D6QrtXqd.js","assets/session-events-DKjIMNKI.js","assets/index-DC2p1vGD.css","assets/copy-CF3TUa0u.js"])))=>i.map(i=>d[i]);
2
- import{r as x,j as e}from"./vendor-react-DofNRwfy.js";import{c as J,u as _,a as b,s as He,b as dt,d as ce,H as Ie,P as ut,G as Qe,L as B,S as ze,T as re,C as fe,D as qe,e as Ge,f as mt,g as We,h as Je,i as Ye,j as F,k as ht,l as te,B as xt,m as we,n as de,R as he,F as pt,_ as Xe,o as ft,p as Ze,q as bt,r as et,t as vt,X as tt,v as gt,A as Te,w as kt,x as yt,W as jt,y as wt,z as Nt}from"./index-VQVOzFZT.js";import{_ as Ee,M as ae,Z as O,a2 as St,A as Ct,a3 as Tt,Q as Et,X as Mt,Y as At}from"./session-events-DKjIMNKI.js";import{A as Rt,E as Dt}from"./external-link-BKCjDDt-.js";import{S as Ft}from"./ScrollArea-CSQyGeWr.js";import{C as st}from"./copy-CF3TUa0u.js";import{C as ne}from"./chevron-right-BGTvSaVS.js";import{A as Me,a as It,C as $t}from"./chevrons-up-down-Jw3ElnjQ.js";import{f as Bt,g as _t,h as Pt,i as rt}from"./vendor-radix-D6QrtXqd.js";import{P as Ut}from"./pause-CP_wlUro.js";import{P as Lt}from"./play-NBWnc2gU.js";import{P as at}from"./pencil-U3n9D8ed.js";import{C as Ot}from"./clock-3-v0h4RrLK.js";import{t as P,A as Kt}from"./team-B9Na0Ocd.js";import{teamService as $e}from"./teamService-ZQZLqsjy.js";/**
3
- * @license lucide-react v0.300.0 - ISC
4
- *
5
- * This source code is licensed under the ISC license.
6
- * See the LICENSE file in the root directory of this source tree.
7
- */const Vt=J("Files",[["path",{d:"M15.5 2H8.6c-.4 0-.8.2-1.1.5-.3.3-.5.7-.5 1.1v12.8c0 .4.2.8.5 1.1.3.3.7.5 1.1.5h9.8c.4 0 .8-.2 1.1-.5.3-.3.5-.7.5-1.1V6.5L15.5 2z",key:"cennsq"}],["path",{d:"M3 7.6v12.8c0 .4.2.8.5 1.1.3.3.7.5 1.1.5h9.8",key:"ms809a"}],["path",{d:"M15 2v5h5",key:"qq6kwv"}]]);/**
8
- * @license lucide-react v0.300.0 - ISC
9
- *
10
- * This source code is licensed under the ISC license.
11
- * See the LICENSE file in the root directory of this source tree.
12
- */const Ht=J("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/**
13
- * @license lucide-react v0.300.0 - ISC
14
- *
15
- * This source code is licensed under the ISC license.
16
- * See the LICENSE file in the root directory of this source tree.
17
- */const Qt=J("HelpCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
18
- * @license lucide-react v0.300.0 - ISC
19
- *
20
- * This source code is licensed under the ISC license.
21
- * See the LICENSE file in the root directory of this source tree.
22
- */const zt=J("ListOrdered",[["line",{x1:"10",x2:"21",y1:"6",y2:"6",key:"76qw6h"}],["line",{x1:"10",x2:"21",y1:"12",y2:"12",key:"16nom4"}],["line",{x1:"10",x2:"21",y1:"18",y2:"18",key:"u3jurt"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);/**
23
- * @license lucide-react v0.300.0 - ISC
24
- *
25
- * This source code is licensed under the ISC license.
26
- * See the LICENSE file in the root directory of this source tree.
27
- */const qt=J("LockKeyhole",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]]);/**
28
- * @license lucide-react v0.300.0 - ISC
29
- *
30
- * This source code is licensed under the ISC license.
31
- * See the LICENSE file in the root directory of this source tree.
32
- */const Gt=J("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
33
- * @license lucide-react v0.300.0 - ISC
34
- *
35
- * This source code is licensed under the ISC license.
36
- * See the LICENSE file in the root directory of this source tree.
37
- */const Wt=J("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/**
38
- * @license lucide-react v0.300.0 - ISC
39
- *
40
- * This source code is licensed under the ISC license.
41
- * See the LICENSE file in the root directory of this source tree.
42
- */const Jt=J("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/**
43
- * @license lucide-react v0.300.0 - ISC
44
- *
45
- * This source code is licensed under the ISC license.
46
- * See the LICENSE file in the root directory of this source tree.
47
- */const Yt=J("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function Be(t){return t.split("/").filter(Boolean).at(-1)||t}function Xt(){const t=_(),s=b(w=>w.sessions),r=b(w=>w.currentSessionRef),a=b(w=>w.historySurfaceSelection),i=b(w=>w.taskDeliveryActions),n=b(w=>w.deliverTask),l=Ee(w=>w.openFilePreview),[u,m]=x.useState(!1),o=s.find(w=>He({sessionId:w.sessionId,projectPath:w.projectPath},r));if(ae(a)||!(o!=null&&o.taskIsolation))return null;const g=o.taskDiffStat,v=o.taskIsolation==="worktree",d=dt(o),j=i[ce(d)],f=o.taskDelivery,N=(f==null?void 0:f.status)==="conflicted",h=!!(g&&(g.changedFiles>0||g.commits>0)),T=!["queued","running"].includes(o.taskStatus),k=(f==null?void 0:f.status)==="applied"||(f==null?void 0:f.status)==="discarded",p=v&&h&&T&&!k,c=g?g.additions+g.deletions:0,M=c>0&&g?g.additions/c*100:0,D=w=>{O(b.getState())||n(d,w).catch(()=>{})},R=()=>{O(b.getState())||l({tab:"diff"})};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(Ie,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:Be(o.taskSourceProjectPath||o.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(ut,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(Ie,{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")})]}),o.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:o.taskWorktreeBranch,children:[e.jsx(Qe,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:o.taskWorktreeBranch})]})]})]}),g&&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(Vt,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:g.changedFiles})]}),c>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:`${M}%`}}),e.jsx("span",{className:"h-full bg-red-500/80",style:{width:`${100-M}%`}})]}),e.jsxs("span",{className:"tabular-nums text-[hsl(var(--deck-accent))]",children:["+",g.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",g.deletions]}),g.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:g.commits})}),h&&(f==null?void 0:f.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:R,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")}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!j,onClick:()=>D("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:[j==="apply"?e.jsx(B,{className:"h-3 w-3 animate-spin"}):e.jsx(ze,{className:"h-3 w-3"}),t(j==="apply"?"artifact.applying":N?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!j,onClick:()=>m(!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:j==="discard"?e.jsx(B,{className:"h-3 w-3 animate-spin"}):e.jsx(re,{className:"h-3 w-3"})})]}),(f==null?void 0:f.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(fe,{className:"h-3 w-3"}),t("artifact.applied")]}),(f==null?void 0:f.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(re,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(f==null?void 0:f.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(Rt,{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:f.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(qe,{open:u,onOpenChange:m,children:e.jsxs(Ge,{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(mt,{children:[e.jsx(We,{children:t("artifact.discardDialog.title")}),e.jsx(Je,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:Be(o.taskSourceProjectPath||o.projectPath),count:(g==null?void 0:g.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(Ye,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>m(!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:()=>{m(!1),D("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(re,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}const Zt=new Set(["completed","stale","failed","aborted","interrupted"]),es={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"},ts={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 xe(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function ss(t){const s=xe(t),r=xe(s==null?void 0:s.codeLocation),a=s==null?void 0:s.priority,i=s==null?void 0:s.confidenceScore,n=r==null?void 0:r.lineStart,l=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 i!="number"||!Number.isFinite(i)||typeof(r==null?void 0:r.path)!="string"||!Number.isInteger(n)||!Number.isInteger(l)))return{title:s.title,body:s.body,priority:a,confidenceScore:i,codeLocation:{path:r.path,lineStart:n,lineEnd:l}}}function rs(t){const s=xe(t),r=xe(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!Zt.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(ss);if(!a.some(i=>i===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 as(t){const{path:s,lineStart:r,lineEnd:a}=t.codeLocation;return r===a?`${s}:L${r}`:`${s}:L${r}-${a}`}function ns({report:t}){const s=_(),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:F("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",ts[t.status]),children:[s("chat.review.status"),": ",s(es[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,i)=>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:as(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}:${i}`))})]}),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 is({elicitation:t,messageId:s}){const r=_(),a=b(k=>k.currentSessionRef),i=b(k=>k.setElicitation),[n,l]=x.useState(()=>cs(t.details.fields??[])),[u,m]=x.useState(()=>ls(t.details.fields??[])),[o,g]=x.useState(!1),[v,d]=x.useState(),j=t.details.fields??[],f=x.useMemo(()=>j.every(k=>{var c;if(!k.required)return!0;if(be(k))return!!((c=u[k.name])!=null&&c.trim()||k.defaultValue!==void 0);const p=n[k.name]??k.defaultValue;return Array.isArray(p)?p.length>0:p!==void 0}),[j,u,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,p)=>{if(!O(b.getState())&&!(!a||o)){g(!0),d(void 0);try{await te.respondToElicitation(a,t.toolCallId,{action:k,...p?{content:p}:{}}),i(s,{...t,status:"responded"})}catch(c){d(c instanceof Error?c.message:r("interaction.elicitation.failed"))}finally{g(!1)}}},h=async()=>{try{await N("accept",ds(j,n,u))}catch(k){d(k instanceof Error?k.message:String(k))}},T=()=>{if(O(b.getState()))return;const k=t.details.url;if(!k){d("MCP URL is unavailable");return}if(!window.open(k,"_blank","noopener,noreferrer")){d("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(ht,{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(se,{onClick:T,disabled:o,primary:!0,label:r("interaction.elicitation.open"),icon:e.jsx(Dt,{className:"h-3.5 w-3.5"})}),e.jsx(se,{onClick:()=>void N("decline"),disabled:o,label:r("interaction.elicitation.decline")}),e.jsx(se,{onClick:()=>void N("cancel"),disabled:o,label:r("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[j.map(k=>e.jsx(os,{field:k,value:n[k.name],rawValue:u[k.name]??"",onValueChange:p=>l(c=>({...c,[k.name]:p})),onRawChange:p=>m(c=>({...c,[k.name]:p}))},k.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(se,{onClick:()=>void h(),disabled:o||!f,primary:!0,label:r("interaction.elicitation.submit"),icon:o?e.jsx(B,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(se,{onClick:()=>void N("decline"),disabled:o,label:r("interaction.elicitation.decline")}),e.jsx(se,{onClick:()=>void N("cancel"),disabled:o,label:r("interaction.elicitation.cancel")})]})]}),v&&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:v})]})}function os({field:t,value:s,rawValue:r,onValueChange:a,onRawChange:i}){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:us(t).map(n=>{const l=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":l,onClick:()=>{if(t.type==="multi-select"){const u=Array.isArray(s)?s:[];a(u.includes(n.value)?u.filter(m=>m!==n.value):[...u,n.value])}else a(n.typedValue)},className:F("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",l?"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:ms(t),value:r,onChange:n=>i(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 se({onClick:t,disabled:s,primary:r=!1,label:a,icon:i}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:F("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:[i,a]})}function cs(t){return Object.fromEntries(t.filter(s=>!be(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function ls(t){return Object.fromEntries(t.filter(s=>be(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function ds(t,s,r){var i;const a={};for(const n of t){if(be(n)){const u=((i=r[n.name])==null?void 0:i.trim())??"";if(!u){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 m=Number(u);if(!Number.isFinite(m))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(m))throw new Error(`${n.title} must be a safe integer`);a[n.name]=m}else a[n.name]=u;continue}const l=s[n.name]??n.defaultValue;if(l===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(l)){if(n.minItems!==void 0&&l.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&l.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}a[n.name]=l}return a}function us(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 be(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function ms(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 hs(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 xs({report:t}){const s=_(),[r,a]=x.useState(!1),i=JSON.stringify(t.output,null,2),n=async()=>{try{await navigator.clipboard.writeText(i),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(xt,{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(fe,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(st,{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:i})]})}const ps=x.lazy(()=>Xe(()=>import("./MarkdownRenderer-TWNqhwrr.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function _e({text:t,label:s}){const[r,a]=x.useState(!1);if(!t.trim())return null;const i=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:i,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(fe,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(st,{className:"h-3.5 w-3.5"})})}function fs(){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(we,{size:20,pulse:!1})})}function bs(){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 Pe(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 vs(t){if(typeof t=="string")return{text:Pe(t),images:[]};const s=t.filter(a=>a.type==="text").map(a=>a.text).join(`
48
- `),r=t.filter(a=>a.type==="image_url").map(a=>a.image_url.url);return{text:Pe(s),images:r}}function Ae(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
49
- `)}function gs(t){const s=t.agentContent;return s?St(s):Ae(t.content)}function Ue({content:t,syntaxHighlight:s=!0}){return e.jsx(x.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(ps,{content:t,syntaxHighlight:s})})}function Re({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:F("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:r[t]})}function ks(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 Le=500;function nt(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 Oe(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 ge(t,s){if(t.length<=s)return t;if(s<=0)return"";const r=`
50
- ... (display clipped) ...
51
- `,a=s-r.length;if(a<=0)return Oe(t,s);const i=Math.floor(a/3);return`${nt(t,i)}${r}${Oe(t,a-i)}`}function ys(t){const s=t.split(`
52
- `),r=s.at(-1),a=r!=null&&r.startsWith("Output truncated")?r:void 0,i=a?s.slice(0,-1).join(`
53
- `):t,n=a?`
54
- ${a}`:"",l=Math.max(0,Le-n.length),m=i.indexOf(`
55
- stderr:
56
- `);let o;if(m>=0&&i.includes(`
57
- stdout:
58
- `)){const g=i.slice(0,m),v=i.slice(m+1),d=Math.max(0,l-1),j=Math.floor(d/2);o=`${ge(g,j)}
59
- ${ge(v,d-j)}`}else o=ge(i,l);return{body:nt(o,l),...a?{notice:a}:{},truncated:!!a||t.length>Le}}function js({tool:t}){const[s,r]=x.useState(!1),a=ks(t.arguments),i=t.output?ys(t.output):void 0;return e.jsxs("div",{"data-tool-name":t.toolName,"data-tool-status":t.status,"data-tool-truncated":i!=null&&i.truncated?"true":"false",className:"bg-white dark:bg-[#18181b] border border-[hsl(var(--deck-border))] rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button","aria-expanded":s,"data-tool-call-id":t.toolCallId,onClick:()=>r(n=>!n),className:"w-full flex items-center justify-between px-3 py-2 bg-[hsl(var(--deck-surface-2))] hover:bg-[hsl(var(--deck-surface))] transition-colors",children:[e.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[s?e.jsx(de,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(ne,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}),e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink))] font-mono shrink-0",children:t.toolName}),t.summary&&e.jsx("span",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono truncate",children:t.summary})]}),e.jsx(Re,{status:t.status})]}),t.status==="running"&&t.progressMessage&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-2 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx("span",{className:"truncate",children:t.progressMessage}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsxs("span",{className:"shrink-0",children:[Math.max(0,Math.min(100,Math.round(t.progress/t.progressTotal*100))),"%"]})]}),t.progressTotal!==void 0&&t.progress!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${t.toolName} progress`,"aria-valuemin":0,"aria-valuemax":t.progressTotal,"aria-valuenow":Math.min(t.progress,t.progressTotal),className:"h-1 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,t.progress/t.progressTotal*100))}%`}})})]}),s&&e.jsxs("div",{className:"px-3 py-2 space-y-2 border-t border-[hsl(var(--deck-border))]",children:[a&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Arguments"}),e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:a})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:"Output"}),e.jsxs("pre",{"data-tool-output":!0,className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:[i.body,i.notice&&e.jsxs(e.Fragment,{children:[`
60
- `,e.jsx("span",{"data-tool-truncation-notice":!0,children:i.notice})]})]})]})]})]})}function it({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(s=>e.jsx(js,{tool:s},s.toolCallId))})}function ws({toolCalls:t,toolCallIds:s}){const r=_(),[a,i]=x.useState(!1),n=x.useMemo(()=>new Map(t.map(v=>[v.toolCallId,v])),[t]),l=s.flatMap(v=>{const d=n.get(v);return d?[d]:[]});if(l.length===0)return null;const u=l.filter(v=>v.status==="running").length,m=l.filter(v=>v.status==="error").length,o=[...l].reverse().find(v=>v.status==="running"&&!!v.progressMessage),g=u>0?r(l.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:l.length}):m>0?r(l.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:l.length,errors:m}):r(l.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:l.length});return e.jsxs("div",{"data-agent-tool-group":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>i(v=>!v),className:"group flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[a?e.jsx(de,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(ne,{className:"h-3.5 w-3.5 shrink-0"}),u>0&&e.jsx(B,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{children:g}),(o==null?void 0:o.progressMessage)&&e.jsxs("span",{className:"min-w-0 truncate text-[10.5px] text-[hsl(var(--deck-ink-muted))]",children:[o.progressMessage,o.progress!==void 0&&o.progressTotal!==void 0&&` · ${Math.max(0,Math.min(100,Math.round(o.progress/o.progressTotal*100)))}%`]})]}),(o==null?void 0:o.progress)!==void 0&&o.progressTotal!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${o.toolName} progress`,"aria-valuemin":0,"aria-valuemax":o.progressTotal,"aria-valuenow":Math.min(o.progress,o.progressTotal),className:"mx-1.5 h-0.5 overflow-hidden rounded-full bg-[hsl(var(--deck-border))]",children:e.jsx("div",{className:"h-full rounded-full bg-amber-500 transition-[width] duration-150",style:{width:`${Math.max(0,Math.min(100,o.progress/o.progressTotal*100))}%`}})}),a&&e.jsx("div",{"data-agent-tool-group-details":!0,className:"mt-2 space-y-2 pl-1",children:e.jsx(it,{toolCalls:l})})]})}function Ns({content:t}){const s=_(),[r,a]=x.useState(!1);return t?e.jsxs("div",{"data-agent-thinking":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>a(i=>!i),className:"flex min-h-7 w-full items-center gap-1.5 rounded-md px-1.5 text-left font-mono text-[11.5px] text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface))]/65 hover:text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[r?e.jsx(de,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(ne,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{children:s("chat.timeline.thinking")})]}),r&&e.jsx("div",{className:"ml-1 mt-1 border-l border-[hsl(var(--deck-border))] py-1 pl-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:t})})]}):null}function Ss({tasks:t}){if(t.length===0)return null;const s=t.filter(a=>a.status==="completed").length,r=s===t.length;return e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"flex gap-2 items-center",children:e.jsx("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:r?"✓ All tasks done":`Tasks: ${s}/${t.length}`})})})}function Cs({toolCalls:t}){const s=Ee(n=>n.openFilePreview),r=b(n=>ae(n.historySurfaceSelection)),a=x.useMemo(()=>{const n=new Map,l=["Write","SearchReplace","Edit","ApplyPatch"];for(const u of t){if(u.status!=="success")continue;const m=u.metadata;if(u.toolName==="ApplyPatch"&&Array.isArray(m==null?void 0:m.changes)){for(const g of m.changes)g&&typeof g=="object"&&"path"in g&&typeof g.path=="string"&&n.set(g.path,{path:g.path,toolName:u.toolName});continue}const o=m==null?void 0:m.file_path;o&&l.includes(u.toolName)&&n.set(o,{path:o,toolName:u.toolName})}return Array.from(n.values())},[t]);if(r||a.length===0)return null;const i=n=>{O(b.getState())||s({tab:"diff",targetPath:n})};return e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono mb-1.5",children:["Changed files (",a.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(({path:n})=>{const l=n.split("/").pop()||n;return e.jsxs("button",{onClick:()=>i(n),className:"flex items-center gap-1 px-2 py-1 text-[11px] font-mono bg-[#E5E7EB] dark:bg-[#27272a] text-[hsl(var(--deck-ink))] rounded hover:bg-[#D1D5DB] dark:hover:bg-[#3f3f46] transition-colors",title:n,children:[e.jsx(pt,{className:"w-3 h-3"}),l]},n)})})]})}function Ts({subagent:t}){var Y,W,Z,X;const s=_(),[r,a]=x.useState(null),[i,n]=x.useState(!1),[l,u]=x.useState(null),[m,o]=x.useState(!1),[g,v]=x.useState(""),[d,j]=x.useState(!1),[f,N]=x.useState(null),[h,T]=x.useState(null),[k,p]=x.useState(null),c=b(A=>A.currentSessionRef),M=b(A=>A.isStreaming),D=b(A=>A.isTemporarySession),R=b(A=>ae(A.historySurfaceSelection));if(!t)return null;const w=t.status==="running",U=r!==null?r:w,G=t.toolCalls||l||[],S=t.output||t.thinking||G.length>0||t.sessionId,C=h&&h.status!=="running"?h:k,$=(C==null?void 0:C.id)??t.sessionId,I=((Y=C==null?void 0:C.restartRecovery)==null?void 0:Y.outcome)==="failed",z=!w&&!M&&!D&&!R&&!I&&(h==null?void 0:h.status)!=="running"&&!!($&&c);x.useEffect(()=>{if(R||!U||w||!t.sessionId||!(c!=null&&c.projectPath)||l!==null||t.toolCalls&&t.toolCalls.length>0)return;let A=!0;return n(!0),te.getMessages({sessionId:t.sessionId,projectPath:c.projectPath}).then(q=>{var L,E;if(!A)return;const Q=Et(q),V=new Map;for(const K of Q)if((E=(L=K.agentContent)==null?void 0:L.toolCalls)!=null&&E.length)for(const ie of K.agentContent.toolCalls)V.has(ie.toolCallId)||V.set(ie.toolCallId,ie);u(Array.from(V.values()))}).finally(()=>{A&&n(!1)}),()=>{A=!1}},[U,R,w,t.sessionId,t.toolCalls,l,c==null?void 0:c.projectPath]),x.useEffect(()=>{if(R||!t.sessionId||!c)return;let A=!0;const q=t.rootAgentId??t.sessionId,Q=t.resumeDepth??0;return te.listSubagents(c).then(V=>{if(!A)return;p(V.find(E=>E.id===t.sessionId)??null);const L=V.filter(E=>E.id!==t.sessionId&&E.rootAgentId===q&&E.resumeDepth>Q).sort((E,K)=>K.resumeDepth-E.resumeDepth||K.lastActiveAt-E.lastActiveAt)[0];L&&T(L)}).catch(()=>{}),()=>{A=!1}},[c==null?void 0:c.sessionId,c==null?void 0:c.projectPath,R,t.sessionId,t.rootAgentId,t.resumeDepth]),x.useEffect(()=>{if(R||!h||h.status!=="running"||!c)return;let A=!0;const q=async()=>{try{const L=(await te.listSubagents(c)).find(E=>E.id===h.id);A&&L&&T(L)}catch{}},Q=window.setInterval(()=>{q()},1e3);return()=>{A=!1,window.clearInterval(Q)}},[c,R,h==null?void 0:h.id,h==null?void 0:h.status]);const H=async()=>{if(!O(b.getState())&&!(!c||!$||!g.trim()||d)){j(!0),N(null);try{const A=await te.resumeSubagent(c,$,g.trim());T(A.session),v(""),o(!1),a(!0)}catch(A){N(A instanceof Error?A.message:s("chat.subagent.resumeFailed"))}finally{j(!1)}}};return e.jsxs("div",{"data-subagent-id":t.id,"data-subagent-session-id":t.sessionId,className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:[e.jsxs("button",{type:"button",onClick:()=>a(!U),className:"flex gap-2 justify-between items-center w-full transition-opacity cursor-pointer hover:opacity-80",children:[e.jsxs("div",{className:"flex gap-2 items-center",children:[w&&e.jsx(B,{className:"h-3 w-3 animate-spin text-[hsl(var(--deck-ink-muted))]"}),e.jsxs("span",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[t.type,": ",t.description]}),e.jsx(Re,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:F("rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide",t.verificationVerdict==="pass"?"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400":t.verificationVerdict==="fail"?"bg-red-500/10 text-red-600 dark:text-red-400":"bg-amber-500/10 text-amber-600 dark:text-amber-400"),children:t.verificationVerdict}),t.resumedFrom&&e.jsx("span",{className:"rounded bg-[#EDE9FE] px-1.5 py-0.5 text-[10px] font-mono text-[#6D28D9] dark:bg-[#2E1065] dark:text-[#C4B5FD]",title:s("chat.subagent.resumedFromTitle",{id:t.resumedFrom}),children:s("chat.subagent.resumedDepth",{depth:t.resumeDepth??1})})]}),S&&e.jsx(de,{className:F("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",U&&"rotate-180")})]}),!U&&!w&&t.output&&e.jsx("div",{"data-subagent-output-summary":!0,className:"mt-2 max-h-10 overflow-hidden whitespace-pre-wrap break-words font-mono text-[11px] text-[hsl(var(--deck-ink))]",children:t.output}),U&&e.jsxs("div",{className:"mt-2 space-y-2",children:[(t.output||t.thinking)&&e.jsxs(e.Fragment,{children:[t.output&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[160px] overflow-y-auto",children:t.output}),t.thinking&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink-muted))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[120px] overflow-y-auto",children:t.thinking})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[hsl(var(--deck-ink-muted))] font-mono",children:[e.jsx(B,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.loadingLogs")]}),!i&&G.length>0&&e.jsx(it,{toolCalls:G}),h&&e.jsxs("div",{className:"rounded-md border border-[#DDD6FE] bg-[#F5F3FF] p-2 text-[11px] font-mono text-[#5B21B6] dark:border-[#4C1D95] dark:bg-[#1E1B4B] dark:text-[#C4B5FD]",children:[e.jsx("div",{children:s("chat.subagent.resumedAs",{id:h.id,status:h.status,depth:h.resumeDepth??1})}),(((W=h.result)==null?void 0:W.message)||((Z=h.result)==null?void 0:Z.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:h.result.message||h.result.error})]}),I&&((X=C==null?void 0:C.result)==null?void 0:X.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:C.result.error}),z&&e.jsxs("div",{className:"space-y-2",children:[m?e.jsxs("div",{className:"space-y-2 rounded-md border border-[#E5E7EB] bg-white p-2 dark:border-[#27272a] dark:bg-[#111113]",children:[e.jsx("textarea",{"aria-label":s("chat.subagent.followUpAria"),value:g,onChange:A=>v(A.target.value),placeholder:s("chat.subagent.followUpPlaceholder"),rows:3,className:"w-full resize-y rounded border border-[#D1D5DB] bg-white p-2 text-[11px] text-[#111827] outline-none focus:border-[#8B5CF6] dark:border-[#3f3f46] dark:bg-[#18181b] dark:text-[#f4f4f5]"}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx("button",{type:"button",onClick:()=>{o(!1),N(null)},className:"rounded px-2 py-1 text-[11px] text-[#6B7280] hover:bg-[#F3F4F6] dark:hover:bg-[#27272a]",children:s("chat.subagent.cancel")}),e.jsxs("button",{type:"button",onClick:()=>void H(),disabled:!g.trim()||d,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[d&&e.jsx(B,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.resumeAgent")]})]})]}):e.jsxs("button",{type:"button","aria-label":s("chat.subagent.resumeAria"),onClick:()=>o(!0),className:"flex items-center gap-1.5 rounded-md border border-[#D1D5DB] px-2 py-1 text-[11px] font-medium text-[#374151] transition-colors hover:bg-[#F3F4F6] dark:border-[#3f3f46] dark:text-[#d4d4d8] dark:hover:bg-[#27272a]",children:[e.jsx(he,{className:"w-3 h-3"}),s("chat.subagent.resume")]}),f&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:f})]})]})]})}function Es({confirmation:t,messageId:s}){const r=_(),[a,i]=x.useState(!1),[n,l]=x.useState(null),u=b(g=>g.currentSessionRef),m=b(g=>g.setConfirmation);if(!t)return null;const o=async(g,v)=>{if(!O(b.getState())&&!(!u||a)){i(!0),l(null);try{await te.respondPermission(u,t.toolCallId,{approved:g,scope:v}),m(s,{...t,status:g?"approved":"denied"})}catch(d){l(d instanceof Error?d.message:r("interaction.permission.failed"))}finally{i(!1)}}};return t.status!=="pending"?null:e.jsxs("div",{"data-pending-interaction":"permission",tabIndex:-1,role:"alert",className:"space-y-3 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.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:r("interaction.permission.title",{tool:t.toolName})}),e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:t.description}),t.diff&&e.jsx("pre",{className:"text-[11px] text-[hsl(var(--deck-ink))] bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-md p-2 overflow-x-auto whitespace-pre-wrap font-mono max-h-[200px] overflow-y-auto",children:t.diff}),n&&e.jsx("div",{role:"alert",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:n}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void o(!0,"once"),disabled:a,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:a?e.jsx(B,{className:"h-3.5 w-3.5 animate-spin"}):r("interaction.permission.once")}),t.allowRemember!==!1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void o(!0,"session"),disabled:a,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#3B82F6] text-white rounded-md hover:bg-[#2563EB] disabled:cursor-wait disabled:opacity-50",children:r("interaction.permission.session")}),e.jsx("button",{type:"button",onClick:()=>void o(!0,"project"),disabled:a,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#6366F1] text-white rounded-md hover:bg-[#4F46E5] disabled:cursor-wait disabled:opacity-50",children:r("interaction.permission.project")})]}),e.jsx("button",{type:"button",onClick:()=>void o(!1),disabled:a,className:"min-h-8 px-3 py-1.5 text-[12px] font-mono bg-[#EF4444] text-white rounded-md hover:bg-[#DC2626] disabled:cursor-wait disabled:opacity-50",children:r("interaction.permission.deny")})]})]})}function Ms({question:t,messageId:s}){const r=_(),[a,i]=x.useState({}),[n,l]=x.useState({}),[u,m]=x.useState(!1),[o,g]=x.useState(null),v=b(h=>h.currentSessionRef),d=b(h=>h.setQuestion),j=x.useMemo(()=>t?t.questions.reduce((h,T)=>{var M;const k=(M=n[T.header])==null?void 0:M.trim(),p=a[T.header];if(T.multiSelect){const D=Array.isArray(p)?[...p]:[];return k&&D.push(k),D.length>0&&(h[T.header]=D),h}const c=k||(typeof p=="string"?p:"");return c&&(h[T.header]=c),h},{}):{},[a,n,t]),f=(t==null?void 0:t.questions.every(h=>h.header in j))??!1;if(!t)return null;const N=async()=>{if(!O(b.getState())&&!(!v||u||!f)){m(!0),g(null);try{await te.respondToQuestion(v,t.toolCallId,j),d(s,{...t,status:"answered",answers:j})}catch(h){g(h instanceof Error?h.message:r("interaction.question.failed"))}finally{m(!1)}}};return t.status!=="pending"?e.jsx("div",{className:"bg-[hsl(var(--deck-surface-2))] border border-[hsl(var(--deck-border))] rounded-lg px-3 py-2",children:e.jsx("div",{className:"text-[12px] text-[hsl(var(--deck-ink-muted))] font-mono",children:r("interaction.question.answered")})}):e.jsxs("div",{"data-pending-interaction":"question",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:[t.questions.map((h,T)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:h.question}),e.jsxs("div",{className:"space-y-1",children:[h.options.map((k,p)=>e.jsxs("button",{type:"button",onClick:()=>{if(h.multiSelect){const c=a[h.header]||[],M=c.includes(k.label)?c.filter(D=>D!==k.label):[...c,k.label];i({...a,[h.header]:M})}else i({...a,[h.header]:k.label}),l({...n,[h.header]:""})},className:F("w-full text-left px-3 py-2 rounded-md border text-[12px] font-mono transition-colors","border-[hsl(var(--deck-border))]",(h.multiSelect?(a[h.header]||[]).includes(k.label):a[h.header]===k.label)?"bg-[#DCFCE7] text-[#166534] dark:bg-[#22C55E]/20 dark:text-[#E5E5E5]":"bg-[hsl(var(--deck-surface-2))] text-[hsl(var(--deck-ink-muted))]"),children:[e.jsx("div",{children:k.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:k.description})]},p)),e.jsx("input",{"aria-label":`${h.header} other response`,value:n[h.header]??"",onChange:k=>l({...n,[h.header]:k.target.value}),placeholder:r("interaction.question.other"),className:"w-full rounded-md border border-[#E5E7EB] bg-white px-3 py-2 text-[12px] text-[#111827] outline-none focus:border-[#22C55E] dark:border-[#27272a] dark:bg-[#111113] dark:text-[#E5E5E5]"})]})]},T)),o&&e.jsx("div",{role:"alert",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:o}),e.jsxs("button",{type:"button",onClick:()=>void N(),disabled:u||!f,className:"inline-flex min-h-8 items-center gap-1.5 px-3 py-1.5 text-[12px] font-mono bg-[#22C55E] text-white rounded-md hover:bg-[#16A34A] disabled:cursor-wait disabled:opacity-50",children:[u&&e.jsx(B,{className:"h-3.5 w-3.5 animate-spin"}),r("interaction.question.submit")]})]})}function As({message:t}){const s=t.agentContent,r=b(f=>f.isStreaming&&f.currentAssistantMessageId===t.id);if(!s){const f=Ae(t.content);return f?e.jsx(Ue,{content:f}):null}const{toolCalls:a,tasks:i,confirmation:n,question:l,elicitation:u}=s,m=Ct(s),o=Tt(s);if(!(o.length>0||i.length>0||m.length>0||n||l||u)&&r)return e.jsxs("div",{className:"flex items-center gap-2 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(B,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-[12px] font-mono",children:"Thinking..."})]});const d=a.length>0&&a.every(f=>f.status==="success"||f.status==="error")&&!r,j=!r;return e.jsxs("div",{className:"space-y-3",children:[o.map(f=>f.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(Ns,{content:f.content})},f.id):f.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(Ue,{content:f.content,syntaxHighlight:j})},f.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(ws,{toolCalls:a,toolCallIds:f.toolCallIds})},f.id)),i.length>0&&e.jsx(Ss,{tasks:i}),m.map(f=>e.jsx(Ts,{subagent:f},f.id)),n&&e.jsx(Es,{confirmation:n,messageId:t.id}),l&&e.jsx(Ms,{question:l,messageId:t.id}),u&&e.jsx(is,{elicitation:u,messageId:t.id}),d&&e.jsx(Cs,{toolCalls:a})]})}function Rs({message:t,showAvatar:s=!0}){var u,m,o,g;const r=t.role==="user";if(t.role==="system"){const v=Ae(t.content);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"system",className:"flex justify-center p-2 w-full",children:e.jsx("div",{className:"text-xs text-[hsl(var(--deck-ink-muted))] bg-[#F3F4F6] dark:bg-[#18181b] px-3 py-1 rounded-full font-mono",children:v})})}if(r){const v=(u=t.metadata)!=null&&u.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(m=t.metadata)!=null&&m.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(v){const f=typeof v.command=="string"?v.command:"",N=v.status==="running"?"running":v.status==="completed"?"success":"error",h=typeof v.output=="string"?v.output:[typeof v.stdout=="string"?v.stdout:"",typeof v.stderr=="string"&&v.stderr?`stderr:
61
- ${v.stderr}`:""].filter(Boolean).join(`
62
- `);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"user","data-user-shell-command":!0,className:"flex w-full justify-end p-4",children:e.jsxs("div",{className:"w-full max-w-[85%] overflow-hidden rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface-2))] px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 truncate font-mono text-[12px] text-[hsl(var(--deck-ink))]",children:[e.jsx("span",{className:"mr-2 text-amber-600 dark:text-amber-400",children:"$"}),f]}),e.jsx(Re,{status:N})]}),e.jsx("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap px-3 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:h||"(no output)"}),typeof v.exitCode=="number"&&e.jsxs("div",{className:"border-t border-[hsl(var(--deck-border))] px-3 py-1.5 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:["exit ",v.exitCode,typeof v.durationMs=="number"?` · ${(v.durationMs/1e3).toFixed(3)}s`:"",v.truncated===!0?" · truncated":""]})]})})}const{text:d,images:j}=vs(t.content);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"user",className:"group flex gap-2 justify-end p-4 w-full items-start",children:[e.jsx("div",{className:"mt-1 flex shrink-0 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(_e,{text:d,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[d&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:d}),j.length>0&&e.jsx("div",{className:F("grid gap-2",j.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:j.map((f,N)=>e.jsx("img",{src:f,alt:`attachment-${N+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${f}-${N}`))})]}),e.jsx(bs,{})]})}const i=gs(t),n=rs((o=t.metadata)==null?void 0:o.codeReview),l=hs((g=t.metadata)==null?void 0:g.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:F("group flex gap-4 justify-start w-full",s?"p-4":"px-4 pt-0 pb-3"),children:[s?e.jsx(fs,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[n?e.jsx(ns,{report:n}):l?e.jsx(xs,{report:l}):e.jsx(As,{message:t}),!l&&i.trim()&&e.jsx("div",{className:"mt-1.5 flex opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(_e,{text:i,label:"Copy response"})})]})]})}const Ds=x.memo(Rs);function Fs(t,s,r){return Math.max(0,t+(r-s))}function Is(t,s,r){return Math.min(s,Math.max(0,t)+Math.max(0,r))}function $s(t,s,r,a){const i=new Map(t.filter(l=>!!l.id).map(l=>[l.id,l])),n=new Set(r);for(const l of s){if(!l.id)continue;const u=i.get(l.id);u!==l&&(!u||!a||a(u)!==a(l))&&n.add(l.id)}return n}function Ke(t,s){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(s)}"]`):null}function Bs({turns:t,viewportRef:s,containerRef:r,onRevealTurn:a}){const i=_(),[n,l]=x.useState(null),[u,m]=x.useState(!1),o=x.useRef(null),g=x.useCallback(()=>{var h;const d=s.current,j=r.current;if(!d||!j||t.length===0)return;const f=d.getBoundingClientRect().top;let N=((h=t[0])==null?void 0:h.id)??null;for(const T of t){const k=Ke(j,T.id);if(k)if(k.getBoundingClientRect().top-f<=24)N=T.id;else break}l(N)},[t,s,r]);x.useEffect(()=>{const d=s.current;if(!d)return;const j=()=>{o.current===null&&(o.current=window.requestAnimationFrame(()=>{o.current=null,g()}))};return g(),d.addEventListener("scroll",j,{passive:!0}),()=>{d.removeEventListener("scroll",j),o.current!==null&&(window.cancelAnimationFrame(o.current),o.current=null)}},[g,s]);const v=x.useCallback(d=>{const j=()=>{const N=Ke(r.current,d.id);N&&(N.scrollIntoView({behavior:"smooth",block:"start"}),l(d.id))};a(d.index)?j():window.requestAnimationFrame(()=>window.requestAnimationFrame(j))},[r,a]);return t.length<2?null:e.jsx("nav",{"aria-label":i("chat.turns.aria"),className:"absolute right-1 top-1/2 z-20 hidden -translate-y-1/2 sm:block",onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),onFocusCapture:()=>m(!0),onBlurCapture:d=>{d.currentTarget.contains(d.relatedTarget)||m(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:F("flex flex-col items-center gap-2 py-2 transition-opacity",u?"opacity-0":"opacity-100"),"aria-hidden":u,children:t.map(d=>e.jsx("li",{children:e.jsx("span",{className:F("block rounded-full transition-all",d.id===n?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},d.id))}),e.jsx("div",{className:F("absolute right-0 max-h-[min(70vh,520px)] w-[280px] overflow-y-auto rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]/95 p-1 shadow-xl backdrop-blur transition-all",u?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((d,j)=>e.jsxs("button",{type:"button",onClick:()=>v(d),className:F("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",d.id===n?"bg-[hsl(var(--deck-hairline))]/70 text-[hsl(var(--deck-ink))]":"text-[hsl(var(--deck-ink-muted))] hover:bg-[hsl(var(--deck-hairline))]/50 hover:text-[hsl(var(--deck-ink))]"),children:[e.jsx("span",{className:F("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",d.id===n?"bg-[hsl(var(--deck-accent))]":"bg-[hsl(var(--deck-ink-faint))]/40")}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block font-mono text-[9.5px] uppercase tracking-[0.12em] text-[hsl(var(--deck-ink-faint))]",children:i("chat.turns.label",{n:j+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:d.preview})]})]},d.id))})]})})}const Ve=80;function _s(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s.type==="text").map(s=>s.text).join(" "):""}function Ps(t){const s=_s(t).replace(/\s+/g," ").trim();return s?s.length>Ve?`${s.slice(0,Ve-1)}…`:s:""}function Us(t){const s=[];for(let r=0;r<t.length;r+=1){const a=t[r];if(a.role!=="user"||!a.id)continue;const i=Ps(a.content);i&&s.push({id:a.id,index:r,preview:i})}return s}const ke=120,ye=80,Ls=96;function oe(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function Os(t){return JSON.stringify([t.role,t.content,t.metadata,t.agentContent])}function Ks({messages:t,isLoading:s}){const r=_(),a=x.useRef(null),i=x.useRef(null),n=x.useRef(!0),l=x.useRef(!1),u=x.useRef(t),m=x.useRef(t),o=x.useRef(new Set),g=x.useRef(t.length),v=x.useRef(null),[d,j]=x.useState(ke),[f,N]=x.useState(!1),[h,T]=x.useState(0),k=t.length>0;u.current=t,x.useEffect(()=>{const S=oe(a.current);if(!S||l.current&&!n.current)return;const C=window.requestAnimationFrame(()=>{S.scrollTop=S.scrollHeight,l.current=!0,n.current=!0,o.current=new Set,T(0),N(!1)});return()=>window.cancelAnimationFrame(C)},[t]),x.useEffect(()=>{const S=oe(a.current);if(!S)return;i.current=S;const C=()=>{if(!l.current)return;const I=S.scrollHeight-S.scrollTop-S.clientHeight<=Ls,z=n.current;n.current=I,N(!I),I?(o.current=new Set,T(0)):z&&(m.current=u.current,o.current=new Set,T(0))};return C(),S.addEventListener("scroll",C,{passive:!0}),()=>S.removeEventListener("scroll",C)},[k,s]),x.useEffect(()=>{const S=m.current;if(m.current=t,n.current){o.current.size>0&&(o.current=new Set,T(0));return}const C=$s(S,t,o.current,Os);o.current=C,T(C.size)},[t]),x.useEffect(()=>{const S=g.current;g.current=t.length,j(C=>C>=S&&t.length>S?t.length:Math.min(Math.max(C,ke),t.length||ke))},[t.length]);const p=Math.max(t.length-d,0),c=p,M=x.useMemo(()=>t.slice(c),[t,c]),D=x.useMemo(()=>Us(t),[t]);if(x.useLayoutEffect(()=>{var $;const S=v.current;if(!S)return;const C=oe(a.current);if(v.current=null,!!C){if(($=S.element)!=null&&$.isConnected){const I=S.element.getBoundingClientRect().top-S.viewportTop;C.scrollTop+=I;return}C.scrollTop=Fs(S.scrollTop,S.scrollHeight,C.scrollHeight)}},[d]),s)return e.jsx("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"flex overflow-hidden flex-1 justify-center items-center px-5 py-8 min-h-0",children:e.jsxs("div",{className:"w-full max-w-[560px]",children:[e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 animate-pulse rounded-full bg-[hsl(var(--deck-accent-soft))] blur-xl"}),e.jsx(we,{size:42,className:"relative"})]}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.16em] text-[hsl(var(--deck-accent))]",children:[e.jsx(ft,{className:"w-3 h-3"}),r("chat.list.loading.eyebrow")]}),e.jsx("h2",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:r("chat.list.loading.title")}),e.jsx("p",{className:"mt-1 max-w-sm text-[11.5px] leading-5 text-[hsl(var(--deck-ink-faint))]",children:r("chat.list.loading.hint")})]}),e.jsx("div",{"aria-hidden":"true",className:"mt-7 space-y-4 rounded-xl border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))]/45 px-4 py-5",children:[72,88,64].map((S,C)=>e.jsxs("div",{className:F("flex gap-3",C%2===1&&"flex-row-reverse"),children:[e.jsx("span",{className:"h-7 w-7 shrink-0 animate-pulse rounded-md bg-[hsl(var(--deck-surface-2))]"}),e.jsx("span",{className:"h-10 animate-pulse rounded-lg bg-[hsl(var(--deck-surface-2))]",style:{width:`${S}%`,animationDelay:`${C*120}ms`}})]},S))})]})});if(t.length===0&&!s)return e.jsx("div",{className:"flex flex-1 justify-center items-center",children:e.jsxs("div",{className:"flex flex-col gap-4 items-center text-center",children:[e.jsx(we,{size:44}),e.jsxs("div",{children:[e.jsx("div",{className:"deck-eyebrow text-[hsl(var(--deck-accent))]",children:r("chat.list.empty.eyebrow")}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:r("chat.list.empty.title")}),e.jsx("div",{className:"mt-1 max-w-xs text-[12px] text-[hsl(var(--deck-ink-muted))]",children:r("chat.list.empty.hint")})]})]})});const R=()=>{const S=oe(a.current);S&&(S.scrollTop=S.scrollHeight,n.current=!0,l.current=!0,o.current=new Set,T(0),N(!1))},w=()=>{var C;const S=oe(a.current);if(S){const $=((C=a.current)==null?void 0:C.querySelector("[data-chat-message-id]"))??null;v.current={element:$,viewportTop:($==null?void 0:$.getBoundingClientRect().top)??0,scrollHeight:S.scrollHeight,scrollTop:S.scrollTop}}j($=>Is($,t.length,ye))},U=S=>S>=c?!0:(j(t.length),!1),G=h===1?r("chat.list.unreadMessage"):r("chat.list.unreadMessages",{count:h});return e.jsxs("div",{ref:a,className:"relative flex-1 min-h-0",children:[e.jsx(Ft,{className:"h-full",children:e.jsxs("div",{className:"flex flex-col px-4 pb-4 w-full md:px-6",children:[p>0&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:w,"aria-label":r("chat.list.showEarlierWithRemaining",{count:Math.min(p,ye),remaining:p}),className:"rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] px-3 py-1.5 font-mono text-[12px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:border-[hsl(var(--deck-border-strong))] hover:text-[hsl(var(--deck-ink))]",children:r("chat.list.showEarlier",{count:Math.min(p,ye)})})}),M.map((S,C)=>{const $=c+C,I=$>0?t[$-1]:null,z=!I||I.role!==S.role||I.role==="user";return e.jsx(Ds,{message:S,showAvatar:z},S.id||`msg-${$}`)})]})}),e.jsx(Bs,{turns:D,viewportRef:i,containerRef:a,onRevealTurn:U}),f&&e.jsxs("button",{type:"button",onClick:R,"aria-live":"polite","aria-label":h>0?G:r("chat.list.jumpLatest"),className:"absolute bottom-4 left-1/2 z-10 inline-flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-[hsl(var(--deck-border-strong))] bg-[hsl(var(--deck-surface))]/95 px-3 py-1.5 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] shadow-lg backdrop-blur transition-colors hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[e.jsx(Me,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),h>0?G:r("chat.list.jumpLatest")]})]})}const ot=x.memo(Ks);function Vs({queue:t,mutation:s,onMutate:r,onRefresh:a}){const i=_(),[n,l]=x.useState(!1),u=x.useRef(null),m=x.useRef(null),o=x.useRef(null);x.useLayoutEffect(()=>{var f,N,h;if(s.pending||!u.current)return;const d=u.current;u.current=null,(h=Array.from(((f=m.current)==null?void 0:f.querySelectorAll("[data-follow-up-focus-id]"))??[]).find(T=>T.dataset.followUpFocusId===d)??((N=m.current)==null?void 0:N.querySelector("button")))==null||h.focus()},[s.pending,t==null?void 0:t.version]);const g=x.useCallback(async d=>{u.current=d.messageId,await r(d)},[r]),v=x.useCallback((d,j)=>{g({type:"move",messageId:d,toPosition:j})},[g]);return!t||t.pending===0&&!s.errorMessage?null:e.jsxs("section",{ref:m,"data-blade-follow-up-queue":!0,className:"mx-4 mb-2 overflow-hidden rounded-lg border border-amber-300/70 bg-amber-50/70 shadow-sm dark:border-amber-900/60 dark:bg-amber-950/25 md:mx-6","aria-label":i("chat.followUpQueue.title"),children:[e.jsxs("button",{type:"button","aria-label":i(n?"chat.followUpQueue.hide":"chat.followUpQueue.show"),"aria-expanded":n,onClick:()=>l(d=>!d),className:"flex min-h-10 w-full items-center gap-2 px-3 text-left font-mono text-[11px] text-amber-950 transition-colors hover:bg-amber-100/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-amber-500 dark:text-amber-100 dark:hover:bg-amber-900/35",children:[e.jsx(zt,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),e.jsx("span",{className:"font-semibold",children:i("chat.followUpQueue.count",{count:t.pending})}),t.locked>0&&e.jsx("span",{className:"text-amber-700/80 dark:text-amber-300/75",children:i("chat.followUpQueue.lockedCount",{count:t.locked})}),e.jsx(ne,{className:`ml-auto h-3.5 w-3.5 transition-transform ${n?"rotate-90":""}`,"aria-hidden":!0})]}),n&&e.jsxs("div",{className:"border-t border-amber-300/60 px-2 py-2 dark:border-amber-900/50",children:[s.errorMessage&&e.jsxs("div",{role:"alert",className:"mb-2 flex items-center gap-2 rounded-md border border-red-200 bg-red-50 px-2.5 py-2 text-[11px] text-red-700 dark:border-red-900/60 dark:bg-red-950/35 dark:text-red-300",children:[e.jsx("span",{className:"min-w-0 flex-1",children:s.errorCode==="revision_conflict"?i("chat.followUpQueue.stale"):s.errorMessage}),a&&e.jsx("button",{type:"button","aria-label":i("chat.followUpQueue.refresh"),onClick:()=>void a(),className:"rounded p-1 hover:bg-red-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 dark:hover:bg-red-900/60",children:e.jsx(Ze,{className:"h-3.5 w-3.5","aria-hidden":!0})})]}),e.jsx("ol",{className:"space-y-1.5",children:t.items.map((d,j)=>{const f=t.items[j-1],N=t.items[j+1],h=d.mutable&&(f==null?void 0:f.mutable)===!0,T=d.mutable&&(N==null?void 0:N.mutable)===!0,k=s.pending;return e.jsxs("li",{"data-follow-up-id":d.id,"data-follow-up-state":d.state,"data-follow-up-focus-id":d.id,tabIndex:-1,draggable:d.mutable&&!s.pending,onDragStart:()=>{o.current=d.mutable?d.id:null},onDragOver:p=>{const c=o.current,M=t.items.find(D=>D.id===c);M!=null&&M.mutable&&d.mutable&&p.preventDefault()},onDrop:p=>{p.preventDefault();const c=o.current;o.current=null;const M=t.items.find(w=>w.id===c);if(!(M!=null&&M.mutable)||!d.mutable||M.id===d.id)return;const D=Math.min(M.position,d.position),R=Math.max(M.position,d.position);t.items.slice(D,R+1).some(w=>!w.mutable)||v(M.id,d.position)},onDragEnd:()=>{o.current=null},className:"flex min-w-0 items-center gap-2 rounded-md border border-amber-200/70 bg-white/75 px-2.5 py-2 dark:border-amber-900/50 dark:bg-zinc-950/45",children:[e.jsx("span",{className:"w-5 shrink-0 text-center font-mono text-[10px] text-amber-700 dark:text-amber-400",children:j+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-xs text-[hsl(var(--deck-ink))]",children:d.kind==="internal"?i("chat.followUpQueue.internal"):d.preview||i("chat.followUpQueue.attachmentOnly")}),e.jsxs("div",{className:"mt-0.5 flex items-center gap-2 font-mono text-[9px] uppercase tracking-[0.08em] text-[hsl(var(--deck-ink-faint))]",children:[e.jsx("span",{children:i(`chat.followUpQueue.delivery.${d.delivery}`)}),!d.mutable&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(qt,{className:"h-2.5 w-2.5","aria-hidden":!0}),i("chat.followUpQueue.locked")]}),d.attachmentCount>0&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(bt,{className:"h-2.5 w-2.5","aria-hidden":!0}),d.attachmentCount]})]})]}),k&&s.messageId===d.id?e.jsx(B,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-amber-600"}):e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5",children:[e.jsx("button",{type:"button","aria-label":i("chat.followUpQueue.moveUp",{id:d.id}),disabled:k||!h,onClick:()=>v(d.id,j-1),className:"rounded p-1 text-amber-800 transition-colors hover:bg-amber-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-amber-500 disabled:opacity-30 dark:text-amber-300 dark:hover:bg-amber-900/50",children:e.jsx(It,{className:"h-3.5 w-3.5","aria-hidden":!0})}),e.jsx("button",{type:"button","aria-label":i("chat.followUpQueue.moveDown",{id:d.id}),disabled:k||!T,onClick:()=>v(d.id,j+1),className:"rounded p-1 text-amber-800 transition-colors hover:bg-amber-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-amber-500 disabled:opacity-30 dark:text-amber-300 dark:hover:bg-amber-900/50",children:e.jsx(Me,{className:"h-3.5 w-3.5","aria-hidden":!0})}),e.jsx("button",{type:"button","aria-label":i("chat.followUpQueue.remove",{id:d.id}),disabled:k||!d.mutable,onClick:()=>void g({type:"remove",messageId:d.id}),className:"rounded p-1 text-red-600 transition-colors hover:bg-red-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 disabled:opacity-30 dark:text-red-400 dark:hover:bg-red-950/60",children:e.jsx(re,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})]},d.id)})})]})]})}const Ne=Bt,Se=_t,Ce=Pt,pe=x.forwardRef(({className:t,sideOffset:s=4,...r},a)=>e.jsx(rt,{ref:a,sideOffset:s,className:F("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",t),...r}));pe.displayName=rt.displayName;const Hs={active:{labelKey:"goal.status.active",dot:"bg-[hsl(var(--deck-accent))] shadow-[0_0_6px_hsl(var(--deck-accent-glow)/0.5)]",accent:"text-[hsl(var(--deck-accent))]"},verifying:{labelKey:"goal.status.active",dot:"animate-pulse bg-sky-400",accent:"text-sky-600 dark:text-sky-300"},paused:{labelKey:"goal.status.paused",dot:"bg-amber-400",accent:"text-amber-600 dark:text-amber-300"},blocked:{labelKey:"goal.status.blocked",dot:"bg-rose-500",accent:"text-rose-600 dark:text-rose-300"},usage_limited:{labelKey:"goal.status.usageLimited",dot:"bg-orange-500",accent:"text-orange-600 dark:text-orange-300"},budget_limited:{labelKey:"goal.status.budgetLimited",dot:"bg-orange-500",accent:"text-orange-600 dark:text-orange-300"},complete:{labelKey:"goal.status.complete",dot:"bg-emerald-500",accent:"text-emerald-600 dark:text-emerald-300"}};function ue(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Qs(t){if(t<60)return`${t}s`;const s=Math.floor(t/60),r=t%60;return r===0?`${s}m`:`${s}m ${r}s`}function zs(){var S,C,$,I,z,H,Y,W,Z,X,A,q,Q,V,L;const t=_(),{locale:s}=et(),r=b(E=>E.goal),a=b(E=>E.pauseGoal),i=b(E=>E.resumeGoal),n=b(E=>E.editGoal),l=b(E=>E.clearGoal),u=b(E=>ae(E.historySurfaceSelection)),[m,o]=x.useState(!1),[g,v]=x.useState(!1),[d,j]=x.useState(""),[f,N]=x.useState(null),[h,T]=x.useState(!1);if(x.useEffect(()=>{o(!1),v(!1),j((r==null?void 0:r.objective)??""),T(!1)},[r==null?void 0:r.goalId]),u||!r)return null;const k=Hs[r.status],p=["active","verifying","paused","blocked"].includes(r.status),c=r.status==="active"||r.status==="verifying",M=r.status==="paused"||r.status==="blocked",D=f!==null,R=async(E,K)=>{if(!O(b.getState())){N(E);try{await K()}finally{N(null)}}},w=()=>{j(r.objective),v(!0),o(!0)},U=async E=>{E.preventDefault();const K=d.trim();if(!K||K===r.objective){v(!1);return}await R("edit",()=>n(K)),v(!1)},G=async()=>{await R("delete",l),T(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(Ne,{delayDuration:250,children:e.jsxs("section",{"aria-label":t("goal.aria.section"),className:"mx-3 mb-1 shrink-0","data-blade-goal-status":r.status,"data-blade-goal-recovery":(S=r.prematureStop)==null?void 0:S.consecutiveCount,"data-blade-goal-recovery-pattern":(C=r.prematureStop)==null?void 0:C.pattern,"data-blade-goal-verification-stall":($=r.verificationStall)==null?void 0:$.consecutiveCount,"data-blade-goal-frontier-task-list":(I=r.executionFrontier)==null?void 0:I.taskListId,"data-blade-goal-frontier-total":(z=r.executionFrontier)==null?void 0:z.total,"data-blade-goal-frontier-completed":(H=r.executionFrontier)==null?void 0:H.completed,"data-blade-goal-frontier-in-progress":(Y=r.executionFrontier)==null?void 0:Y.inProgress,"data-blade-goal-frontier-pending":(W=r.executionFrontier)==null?void 0:W.pending,"data-blade-goal-frontier-blocked":(Z=r.executionFrontier)==null?void 0:Z.blocked,"data-blade-goal-frontier-next-task":(A=(X=r.executionFrontier)==null?void 0:X.nextTask)==null?void 0:A.id,"data-blade-goal-frontier-digest":(q=r.executionFrontier)==null?void 0:q.digestSha256.slice(0,16),"data-blade-goal-frontier-stall":(Q=r.frontierStall)==null?void 0:Q.category,"data-blade-goal-frontier-stall-count":(V=r.frontierStall)==null?void 0:V.consecutiveCount,children:[e.jsxs("div",{className:F("flex h-9 items-center gap-2 rounded-lg border px-3 transition-colors","border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 backdrop-blur-sm",m&&"rounded-b-none border-b-0"),children:[r.status==="complete"?e.jsx(vt,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(Wt,{className:F("h-3.5 w-3.5 shrink-0",k.accent)}),e.jsx("span",{className:F("h-1.5 w-1.5 shrink-0 rounded-full",k.dot)}),e.jsx("span",{className:F("shrink-0 text-[10px] font-medium leading-none",k.accent),children:r.status==="verifying"?s==="zh"?"验证中":"Verifying":t(k.labelKey)}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-[hsl(var(--deck-hairline))]"}),e.jsx("button",{type:"button","aria-label":t(m?"goal.action.collapse":"goal.action.expand"),className:"min-w-0 flex-1 truncate text-left text-[12px] leading-5 text-[hsl(var(--deck-ink))]/85 outline-none transition-colors hover:text-[hsl(var(--deck-ink))]",onClick:()=>o(E=>!E),"aria-expanded":m,title:r.objective,children:r.objective}),r.tokensUsed>0&&e.jsxs("span",{className:"hidden shrink-0 text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))] sm:inline",children:[ue(r.tokensUsed),r.tokenBudget!==void 0&&`/${ue(r.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[c&&e.jsx(me,{label:t("goal.action.pause"),disabled:D,onClick:()=>void R("pause",a),children:f==="pause"?e.jsx(B,{className:"animate-spin"}):e.jsx(Ut,{})}),M&&e.jsx(me,{label:t("goal.action.resume"),disabled:D,onClick:()=>void R("resume",i),children:f==="resume"?e.jsx(B,{className:"animate-spin"}):e.jsx(Lt,{})}),e.jsx(me,{label:t(p?"goal.action.edit":"goal.action.expand"),disabled:!p&&!m,onClick:p?w:()=>o(E=>!E),children:p?e.jsx(at,{}):e.jsx($t,{})}),e.jsx(me,{label:t("goal.action.delete"),disabled:D,destructive:!0,onClick:()=>T(!0),children:e.jsx(re,{})})]})]}),m&&e.jsx("div",{className:"rounded-b-lg border border-t-0 border-[hsl(var(--deck-border))]/60 bg-[hsl(var(--deck-surface))]/80 px-4 py-3 backdrop-blur-sm",children:g?e.jsxs("form",{onSubmit:U,children:[e.jsx("textarea",{id:"goal-objective",value:d,onChange:E=>j(E.target.value),onKeyDown:E=>{E.key==="Escape"&&v(!1)},rows:3,autoFocus:!0,className:"w-full resize-none rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas))] px-3 py-2 text-[12px] leading-5 text-[hsl(var(--deck-ink))] outline-none transition-shadow focus:border-[hsl(var(--deck-accent))] focus:ring-1 focus:ring-[hsl(var(--deck-accent-glow))]"}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>v(!1),className:"inline-flex h-7 items-center gap-1 rounded-md px-2.5 text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:bg-[hsl(var(--deck-hairline))]/60",children:[e.jsx(tt,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!d.trim()||f==="edit",className:"inline-flex h-7 items-center gap-1 rounded-md bg-[hsl(var(--deck-accent))] px-2.5 text-[11px] font-medium text-white transition-colors hover:bg-[hsl(var(--deck-accent))]/90 disabled:cursor-not-allowed disabled:opacity-50",children:[f==="edit"?e.jsx(B,{className:"h-3 w-3 animate-spin"}):e.jsx(fe,{className:"h-3 w-3"}),t("goal.action.save")]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink))]/90",children:r.objective}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Ht,{className:"h-3 w-3"}),ue(r.tokensUsed),r.tokenBudget!==void 0&&` / ${ue(r.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Jt,{className:"h-3 w-3"}),Qs(r.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(he,{className:"h-3 w-3"}),r.continuationCount===1?t("goal.metrics.continuationOne",{n:r.continuationCount}):t("goal.metrics.continuationMany",{n:r.continuationCount})]})]}),r.prematureStop&&e.jsxs("div",{className:"mt-2 inline-flex items-center gap-1.5 font-mono text-[10px] text-amber-700 dark:text-amber-300",children:[e.jsx(he,{className:"h-3 w-3"}),s==="zh"?"恢复提示":"Recovery nudge"," ",r.prematureStop.consecutiveCount," ·"," ",r.prematureStop.pattern.replaceAll("_"," ")]}),r.completionVerification&&e.jsxs("div",{"data-goal-verification":r.completionVerification.status,className:"mt-2 rounded-md border border-sky-200/50 bg-sky-50/60 px-2.5 py-2 text-[11px] text-sky-900 dark:border-sky-400/15 dark:bg-sky-400/[0.05] dark:text-sky-100",children:[e.jsxs("p",{className:"font-mono font-medium",children:["#",r.completionVerification.attempt," ·"," ",r.completionVerification.status.toUpperCase()," ·"," ",((L=r.completionVerification.verifierSessionId)==null?void 0:L.slice(0,12))??"-",r.verificationStall?s==="zh"?` · 重复 ${r.verificationStall.consecutiveCount}/3`:` · repeat ${r.verificationStall.consecutiveCount}/3`:""]}),r.completionVerification.summary&&e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap opacity-80",children:r.completionVerification.summary}),r.completionVerification.evidenceSha256&&e.jsxs("p",{className:"mt-1 font-mono text-[10px] opacity-60",children:["sha256:",r.completionVerification.evidenceSha256.slice(0,12)]})]}),r.statusReason&&e.jsx("div",{className:"mt-2 rounded-md border border-amber-200/50 bg-amber-50/60 px-2.5 py-1.5 text-[11px] text-amber-800 dark:border-amber-400/15 dark:bg-amber-400/[0.05] dark:text-amber-200",children:r.statusReason})]})})]})}),e.jsx(qe,{open:h,onOpenChange:T,children:e.jsxs(Ge,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(We,{children:t("goal.dialog.title")}),e.jsx(Je,{children:t("goal.dialog.description")}),e.jsxs(Ye,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>T(!1),className:"inline-flex h-8 items-center justify-center rounded-md border border-[hsl(var(--deck-border))] px-3 text-[12px] text-[hsl(var(--deck-ink))] hover:bg-[hsl(var(--deck-hairline))]/60",children:t("goal.action.cancel")}),e.jsxs("button",{type:"button",disabled:f==="delete",onClick:()=>void G(),className:"inline-flex gap-1.5 justify-center items-center px-3 h-8 text-[12px] font-medium text-white bg-rose-600 rounded-md hover:bg-rose-500 disabled:opacity-50",children:[f==="delete"&&e.jsx(B,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function me({label:t,children:s,disabled:r,destructive:a,onClick:i}){return e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:r,onClick:i,className:F("flex h-6 w-6 items-center justify-center rounded-md text-[hsl(var(--deck-ink-muted))] outline-none transition-colors focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent-glow))]/50 disabled:cursor-not-allowed disabled:opacity-35 [&_svg]:h-3.5 [&_svg]:w-3.5",a?"hover:bg-rose-500/10 hover:text-rose-500":"hover:bg-[hsl(var(--deck-hairline))]/60 hover:text-[hsl(var(--deck-ink))]"),children:s})}),e.jsx(pe,{side:"top",className:"text-[10px]",children:t})]})}function qs(){const t=_(),s=b(o=>o.currentSessionRef),r=b(o=>o.sessions),a=b(o=>o.messages),i=b(o=>ae(o.historySurfaceSelection)),n=x.useMemo(()=>{var g,v,d,j,f;const o=s?(g=gt(r,s))==null?void 0:g.pendingInteraction:void 0;if(o)return o.type;for(let N=a.length-1;N>=0;N-=1){const h=(v=a[N])==null?void 0:v.agentContent;if(((d=h==null?void 0:h.confirmation)==null?void 0:d.status)==="pending")return"permission";if(((j=h==null?void 0:h.question)==null?void 0:j.status)==="pending")return"question";if(((f=h==null?void 0:h.elicitation)==null?void 0:f.status)==="pending")return"elicitation"}return null},[s,a,r]);if(i||!n)return null;const l=()=>{const o=document.querySelector(`[data-pending-interaction="${n}"]`);o==null||o.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>o==null?void 0:o.focus(),250)},u=n==="question",m=n==="elicitation";return e.jsxs("div",{role:"alert",className:"mx-3 mb-2 flex flex-wrap items-center gap-2 rounded-lg border border-amber-300/80 bg-amber-50/95 px-3 py-2 font-mono text-amber-950 shadow-sm backdrop-blur dark:border-amber-800/80 dark:bg-amber-950/90 dark:text-amber-100 sm:mx-5",children:[e.jsx(Te,{className:"h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("div",{className:"text-[11.5px] font-semibold",children:t(u?"interaction.bar.questionTitle":m?"interaction.bar.elicitationTitle":"interaction.bar.permissionTitle")}),e.jsx("div",{className:"mt-0.5 text-[10px] leading-4 text-amber-800 dark:text-amber-300",children:t(u?"interaction.bar.questionHint":m?"interaction.bar.elicitationHint":"interaction.bar.permissionHint")})]}),e.jsxs("button",{type:"button",onClick:l,className:"inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-md border border-amber-400/80 bg-white/80 px-2.5 text-[10.5px] font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/70 dark:hover:bg-amber-900",children:[e.jsx(Me,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}function le(t){return Math.max(0,Math.ceil((t??0)/1e3))}function Gs(t,s=Date.now()){var a;const r=(a=t.snapshot)==null?void 0:a.nextActionAt;return r===void 0?void 0:le(r-s)}function ct(t,s=Date.now()){const r=t==null?void 0:t.snapshot;if(!r)return null;const a=Gs(t,s)??0,i=r.retry,n=r.admission,l=r.stall,u=r.fallback,m={seconds:a,attempt:(i==null?void 0:i.attempt)??0,maxRetries:(i==null?void 0:i.maxRetries)??0,budgetSeconds:le(i==null?void 0:i.recoveryRemainingMs),position:(n==null?void 0:n.queuePosition)??0,depth:n?Math.max(n.queueDepth,n.queuePosition):0,scope:(n==null?void 0:n.scope)??"",waitSeconds:le(n==null?void 0:n.waitMs),stallSeconds:le(l==null?void 0:l.durationMs),timeoutSeconds:le(l==null?void 0:l.timeoutMs),from:(u==null?void 0:u.from.model)??"",to:(u==null?void 0:u.to.model)??"",candidate:(u==null?void 0:u.candidate)??0,candidateCount:(u==null?void 0:u.candidateCount)??0};switch(r.activity){case"admission_wait":return{titleKey:"chat.providerRecovery.admission",detailKey:"chat.providerRecovery.admissionDetail",compactKey:"chat.providerRecovery.admissionCompact",params:m};case"retry_wait":return{titleKey:r.reason==="rate_limit"?"chat.providerRecovery.rateLimit":"chat.providerRecovery.retryWait",detailKey:"chat.providerRecovery.retryDetail",compactKey:"chat.providerRecovery.retryCompact",params:m};case"retry_attempt":return{titleKey:"chat.providerRecovery.retryAttempt",detailKey:"chat.providerRecovery.retryDetail",compactKey:"chat.providerRecovery.retryCompact",params:m};case"circuit_open":return{titleKey:"chat.providerRecovery.circuit",detailKey:"chat.providerRecovery.circuitDetail",compactKey:"chat.providerRecovery.circuitCompact",params:m};case"circuit_probe":return{titleKey:"chat.providerRecovery.probe",detailKey:"chat.providerRecovery.probeDetail",compactKey:"chat.providerRecovery.probeCompact",params:m};case"stream_stall":return{titleKey:l!=null&&l.outputStarted?"chat.providerRecovery.stallAfterOutput":"chat.providerRecovery.stall",detailKey:"chat.providerRecovery.stallDetail",compactKey:"chat.providerRecovery.stallCompact",params:m};case"fallback":return{titleKey:"chat.providerRecovery.fallback",detailKey:"chat.providerRecovery.fallbackDetail",compactKey:"chat.providerRecovery.fallbackCompact",params:m}}}function Ws({recovery:t,stopping:s,onStop:r}){var m;const a=_(),[i,n]=x.useState(Date.now()),l=(m=t==null?void 0:t.snapshot)==null?void 0:m.nextActionAt;x.useEffect(()=>{if(l===void 0)return;n(Date.now());const o=window.setInterval(()=>n(Date.now()),1e3);return()=>window.clearInterval(o)},[l]);const u=ct(t,i);return u?e.jsxs("section",{role:"status","aria-live":"polite","data-provider-recovery-banner":!0,className:"mx-4 mb-2 flex min-h-12 items-center gap-3 rounded-lg border border-amber-300/70 bg-amber-50/80 px-3 py-2 text-amber-950 shadow-sm dark:border-amber-800/60 dark:bg-amber-950/35 dark:text-amber-100 md:mx-6",children:[e.jsx(B,{className:"h-4 w-4 shrink-0 animate-spin","aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-xs font-semibold",children:a(u.titleKey,u.params)}),e.jsx("div",{className:"mt-0.5 truncate font-mono text-[10px] opacity-80",children:a(u.detailKey,u.params)})]}),e.jsxs("button",{type:"button","data-provider-recovery-stop":!0,onClick:r,disabled:s,className:"inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-md border border-amber-400/70 bg-white/70 px-2.5 text-xs font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 disabled:cursor-wait disabled:opacity-60 dark:border-amber-700 dark:bg-amber-950/50 dark:hover:bg-amber-900/50",children:[s?e.jsx(B,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}):e.jsx(kt,{className:"h-3 w-3 fill-current","aria-hidden":!0}),a(s?"chat.input.action.stopping":"chat.providerRecovery.stop")]})]}):null}const Js=x.lazy(()=>Xe(()=>import("./MarkdownRenderer-TWNqhwrr.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Ys(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Xs(){const t=_(),s=b(a=>a.sideConversation),r=b(a=>a.dismissSideConversation);return s?e.jsx("section",{"aria-label":t("chat.side.title"),"data-blade-side-conversation":!0,"data-status":s.status,className:"shrink-0 border-y border-[hsl(var(--deck-accent)/0.28)] bg-[hsl(var(--deck-accent-soft)/0.42)]",children:e.jsxs("div",{className:"px-4 py-3 md:px-6",children:[e.jsxs("header",{className:"flex min-h-7 items-start gap-2",children:[e.jsx(Gt,{"aria-hidden":!0,className:"mt-0.5 h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx("h2",{className:"font-mono text-[11px] font-semibold uppercase text-[hsl(var(--deck-accent))]",children:t("chat.side.title")}),s.durationMs!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[e.jsx(Ot,{"aria-hidden":!0,className:"h-3 w-3"}),Ys(s.durationMs)]})]}),e.jsx("p",{className:"mt-0.5 break-words font-mono text-[11px] leading-4 text-[hsl(var(--deck-ink-muted))]",children:s.question})]}),e.jsx("button",{type:"button",onClick:r,"aria-label":t("chat.side.dismiss"),title:t("chat.side.dismiss"),className:"flex h-7 w-7 shrink-0 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:e.jsx(tt,{"aria-hidden":!0,className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{"aria-live":"polite","aria-busy":s.status==="loading",className:"mt-2 max-h-[min(36vh,320px)] overflow-y-auto border-l-2 border-[hsl(var(--deck-accent)/0.42)] pl-3 pr-1",children:[s.status==="loading"&&e.jsxs("div",{role:"status",className:"flex min-h-9 items-center gap-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(B,{"aria-hidden":!0,className:"h-3.5 w-3.5 animate-spin text-[hsl(var(--deck-accent))]"}),t("chat.side.loading")]}),s.status==="error"&&e.jsxs("div",{role:"alert",className:"flex min-h-9 items-start gap-2 font-mono text-[11px] leading-5 text-red-700 dark:text-red-300",children:[e.jsx(Te,{"aria-hidden":!0,className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"break-words",children:s.error??t("chat.side.failed")})]}),s.status==="completed"&&s.response&&e.jsx(x.Suspense,{fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words font-mono text-[12px] leading-5 text-[hsl(var(--deck-ink))]",children:s.response}),children:e.jsx(Js,{content:s.response,className:"text-[12px] leading-5 [&_h1]:text-[14px] [&_h2]:text-[13px] [&_h3]:text-[12px]"})})]})]})}):null}function je(t){return Number.isFinite(t)?Math.max(0,t):0}function Zs(t){const s=je(t.totalInputTokens),r=je(t.cacheReadTokens),a=je(t.cacheWriteTokens),i=Math.min(r,s),n=Math.min(a,Math.max(0,s-i)),l=Math.max(0,s-i-n),u=s>0&&(r>0||a>0);return{totalInputTokens:s,cacheReadTokens:i,cacheWriteTokens:n,uncachedInputTokens:l,...u?{hitRate:i/s}:{}}}function er(t){return t===void 0||!Number.isFinite(t)?"—":`${Math.round(Math.max(0,Math.min(1,t))*100)}%`}const tr={running:"status.phase.running",compacting:"status.phase.compacting",recovering_context:"status.phase.recoveringContext",switching_model:"status.phase.switchingModel",waiting_permission:"status.phase.waitingPermission",error:"status.phase.error",idle:""},sr={model_changed:"status.cacheBreak.model",system_prompt_changed:"status.cacheBreak.system",tools_changed:"status.cacheBreak.tools",request_policy_changed:"status.cacheBreak.policy",ttl_expired:"status.cacheBreak.ttl",server_side:"status.cacheBreak.server"},ee=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),rr=t=>{const s=Math.max(0,Math.ceil(t/1e3)),r=Math.floor(s/60),a=s%60;return r>0?`${r}m ${a}s`:`${a}s`};function lt(){const t=_(),s=b(c=>c.tokenUsage),r=b(c=>c.isStreaming),a=b(c=>c.agentPhase),i=b(c=>c.providerRecovery),n=b(c=>c.turnActivity),l=b(c=>c.pendingResume),u=b(c=>c.actionStationarity),m=b(c=>c.turnRecovery),o=tr[a]??"",g=ct(i),v=(l==null?void 0:l.delayMs)!==void 0?` · retry in ${rr(l.delayMs)}`:"",d=(m==null?void 0:m.state)==="requires_attention"?t("status.recovery.review"):"",j=(m==null?void 0:m.state)==="requires_attention"?t(m.reason==="interrupted_tool_call"?"status.recovery.interruptedTool":"status.recovery.successfulTool"):"",f=d||(u?`${t(u.phase==="halted"?"status.phase.actionStationarityStopped":"status.phase.actionStationarityRecovering")} · ${u.toolName} · ${u.runLength}/${u.haltThreshold}`:g?t(g.compactKey,g.params):l?`Recovery attempt ${l.attempt}/${l.maxAttempts}${v}`:o?t(o):""),N=s.maxContextTokens>0?Math.round(s.totalTokens/s.maxContextTokens*100):0,h=Zs(s),T=er(h.hitRate),k=Math.min(N,100),p=N>95?"danger":N>80?"warn":"safe";return e.jsxs("div",{"data-chat-status-bar":!0,className:"flex items-center gap-2 border-t border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-canvas-veil))]/70 px-3 py-2 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] backdrop-blur-sm sm:gap-4 sm:px-5",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.context")}),e.jsxs("span",{className:"flex gap-1 items-baseline tabular-nums",children:[e.jsx("span",{className:F("text-[12px] font-medium",p==="safe"&&"text-[hsl(var(--deck-ink))]",p==="warn"&&"text-amber-600 dark:text-amber-400",p==="danger"&&"text-red-600 dark:text-red-400"),children:ee(s.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",ee(s.maxContextTokens)]})]}),s.isDefaultMaxTokens&&e.jsx(Ne,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsx(Qt,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(pe,{side:"top",className:"max-w-[220px]",children:e.jsx("p",{className:"text-xs",children:t("status.tokenLimitTooltip")})})]})}),e.jsxs("div",{className:"relative hidden h-2 w-32 overflow-hidden rounded-sm border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] sm:block","aria-hidden":"true",children:[e.jsx("div",{className:F("absolute inset-y-0 left-0 transition-[width] duration-300",p==="safe"&&"bg-[hsl(var(--deck-accent))]",p==="warn"&&"bg-amber-500",p==="danger"&&"bg-red-500"),style:{width:`${k}%`}}),e.jsx("div",{className:"flex absolute inset-0 pointer-events-none",children:[25,50,75].map(c=>e.jsx("span",{className:"absolute inset-y-0 w-px bg-[hsl(var(--deck-canvas-veil))]/60",style:{left:`${c}%`}},c))})]}),e.jsxs("span",{className:F("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",p==="warn"&&"text-amber-600 dark:text-amber-400",p==="danger"&&"text-red-600 dark:text-red-400"),children:[N,"%"]})]}),e.jsx(Ne,{children:e.jsxs(Se,{children:[e.jsx(Ce,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 cursor-help items-baseline gap-2 border-l border-[hsl(var(--deck-hairline))] pl-2 sm:pl-4","data-testid":"prompt-cache-hit-rate","aria-label":`${t("status.cache")} ${T}`,children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.cache")}),e.jsx("span",{className:F("tabular-nums",h.hitRate===void 0?"text-[hsl(var(--deck-ink-faint))]":"font-medium text-[hsl(var(--deck-accent))]"),children:T})]})}),e.jsx(pe,{side:"top",className:"max-w-[280px]",children:h.hitRate===void 0?e.jsx("p",{className:"text-xs",children:t("status.cacheUnavailable")}):e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsx("p",{children:t("status.cacheTooltip")}),e.jsx("p",{className:"font-mono tabular-nums",children:t("status.cacheDetails",{read:ee(h.cacheReadTokens),write:ee(h.cacheWriteTokens),uncached:ee(h.uncachedInputTokens)})}),s.cacheBreak&&e.jsx("p",{className:"text-[hsl(var(--deck-accent))]",children:t("status.cacheBreak",{reason:t(sr[s.cacheBreak.reason]??"status.cacheBreak.server"),previous:ee(s.cacheBreak.previousCacheReadTokens),current:ee(s.cacheBreak.cacheReadTokens)})})]})})]})}),e.jsx("div",{className:"flex-1"}),(d||r&&f&&(!(n!=null&&n.snapshot)||u))&&e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:F("shrink-0",d?"h-2 w-2 rounded-sm bg-amber-500":"deck-pulse-dot")}),e.jsxs("span",{className:F("truncate",d?"text-amber-600 dark:text-amber-400":"text-[hsl(var(--deck-accent))]"),children:[f,j?e.jsxs("span",{className:"hidden sm:inline",children:[" · ",j]}):null]})]})]})}function ar(){const{locale:t}=et(),s=yt(c=>c.agentTeamsEnabled),r=b(c=>c.teams),a=b(c=>c.currentSessionRef),i=b(c=>ae(c.historySurfaceSelection)),n=b(c=>c.loadTeams),[l,u]=x.useState({}),[m,o]=x.useState({}),[g,v]=x.useState({}),[d,j]=x.useState(null),[f,N]=x.useState(null),[h,T]=x.useState(null);if(x.useEffect(()=>{i||n(a??void 0)},[s,a,i,n]),i||!s||!a||r.length===0)return null;const k=async c=>{var D;if(O(b.getState()))return;const M=(D=g[c])==null?void 0:D.trim();if(!(!M||d)){j(c),T(null);try{await $e.sendMessage(a,c,m[c]??"*",M),v(R=>({...R,[c]:""})),await n(a)}catch(R){T(R instanceof Error?R.message:P(t,"actionFailed"))}finally{j(null)}}},p=async c=>{if(!O(b.getState())&&!f){N(c),T(null);try{await $e.delete(a,c),await n(a)}catch(M){T(M instanceof Error?M.message:P(t,"actionFailed"))}finally{N(null)}}};return e.jsxs("section",{"aria-label":P(t,"title"),"data-blade-team-panel":!0,className:"shrink-0 border-y border-emerald-300/50 bg-emerald-50/55 dark:border-emerald-800/55 dark:bg-emerald-950/20",children:[h&&e.jsx("div",{role:"alert",className:"border-b border-red-200 bg-red-50 px-4 py-2 font-mono text-[10px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300 md:px-6",children:h}),r.filter(c=>c.status!=="deleted").map(c=>{var R;const M=l[c.name]??c.status==="running",D=c.tasks.filter(w=>w.status==="completed").length;return e.jsxs("div",{className:"border-b border-emerald-200/40 last:border-0 dark:border-emerald-900/40",children:[e.jsxs("div",{className:"flex min-h-11 items-center gap-2 px-4 py-2 md:px-6",children:[e.jsx("button",{type:"button",onClick:()=>u(w=>({...w,[c.name]:!M})),"aria-label":M?P(t,"collapse"):P(t,"expand"),className:"flex h-7 w-7 items-center justify-center rounded-md text-emerald-700 hover:bg-emerald-100 dark:text-emerald-300 dark:hover:bg-emerald-900/50",children:M?e.jsx(de,{className:"h-4 w-4"}):e.jsx(ne,{className:"h-4 w-4"})}),e.jsx(Yt,{className:"h-4 w-4 shrink-0 text-emerald-700 dark:text-emerald-300"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[e.jsx("h2",{className:"truncate font-mono text-[11px] font-semibold uppercase text-emerald-800 dark:text-emerald-200",children:c.name}),e.jsxs("span",{className:"font-mono text-[9.5px] text-[hsl(var(--deck-ink-faint))]",children:[c.status," · ",c.members.length-1," ",P(t,"members")," · ",D,"/",c.tasks.length," ",P(t,"tasks")]})]}),c.description&&e.jsx("p",{className:"truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:c.description})]}),e.jsx("button",{type:"button",onClick:()=>void p(c.name),disabled:f===c.name,"aria-label":P(t,"delete"),title:P(t,"delete"),className:"flex h-7 w-7 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] hover:bg-red-50 hover:text-red-600 disabled:opacity-40 dark:hover:bg-red-950/40",children:e.jsx(re,{className:"h-3.5 w-3.5"})})]}),M&&e.jsxs("div",{className:"max-h-[min(40vh,360px)] overflow-y-auto border-t border-emerald-200/40 px-4 py-3 md:px-6 dark:border-emerald-900/40",children:[e.jsxs("div",{className:"grid gap-x-6 gap-y-2 lg:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1 font-mono text-[9.5px] font-semibold uppercase text-[hsl(var(--deck-ink-faint))]",children:P(t,"members")}),c.members.map(w=>e.jsxs("div",{className:"flex min-h-7 items-center gap-2 border-b border-[hsl(var(--deck-hairline)/0.55)] py-1 last:border-0",children:[e.jsx("span",{"aria-label":w.status,className:`h-1.5 w-1.5 shrink-0 rounded-full ${w.status==="running"?"bg-emerald-500":w.status==="completed"||w.status==="leader"?"bg-sky-500":w.status==="failed"?"bg-red-500":"bg-zinc-400"}`}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:w.name}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:w.subagentType}),w.worktreePath&&e.jsx(Qe,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]","aria-label":P(t,"worktree")})]},w.id))]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1 font-mono text-[9.5px] font-semibold uppercase text-[hsl(var(--deck-ink-faint))]",children:P(t,"tasks")}),c.tasks.length===0?e.jsx("p",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:P(t,"noTasks")}):c.tasks.map(w=>e.jsxs("div",{className:"flex min-h-7 items-center gap-2 border-b border-[hsl(var(--deck-hairline)/0.55)] py-1 last:border-0",children:[e.jsxs("span",{className:"w-5 shrink-0 font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:["#",w.id]}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:w.subject}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:w.status})]},w.id))]})]}),c.peerMessagingEnabled&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 border-t border-emerald-200/40 pt-3 dark:border-emerald-900/40",children:[e.jsxs("select",{"aria-label":P(t,"recipient"),value:m[c.name]??"*",onChange:w=>o(U=>({...U,[c.name]:w.target.value})),className:"h-8 max-w-32 rounded-md border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))] px-2 font-mono text-[10px]",children:[e.jsx("option",{value:"*",children:P(t,"broadcast")}),c.members.filter(w=>w.status!=="leader").map(w=>e.jsx("option",{value:w.name,children:w.name},w.id))]}),e.jsx("input",{value:g[c.name]??"",onChange:w=>v(U=>({...U,[c.name]:w.target.value})),onKeyDown:w=>{w.key==="Enter"&&k(c.name)},placeholder:P(t,"messagePlaceholder"),className:"h-8 min-w-0 flex-1 rounded-md border border-[hsl(var(--deck-hairline))] bg-[hsl(var(--deck-surface))] px-2 font-mono text-[10.5px] outline-none focus:border-emerald-500"}),e.jsx("button",{type:"button",onClick:()=>void k(c.name),disabled:!((R=g[c.name])!=null&&R.trim())||d===c.name,"aria-label":P(t,"send"),title:P(t,"send"),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-emerald-700 text-white hover:bg-emerald-800 disabled:opacity-40 dark:bg-emerald-600",children:e.jsx(ze,{className:"h-3.5 w-3.5"})})]})]})]},c.name)})]})}const nr={starting:"chat.turnActivity.starting",thinking:"chat.turnActivity.thinking",responding:"chat.turnActivity.responding",executing_tools:"chat.turnActivity.executingTools",compacting:"chat.turnActivity.compacting",continuing:"chat.turnActivity.continuing"};function ir(t){const s=Math.max(0,Math.floor(t/1e3));if(s<60)return`${s}s`;const r=Math.floor(s/60),a=s%60;return r<60?`${r}m ${a}s`:`${Math.floor(r/60)}h ${r%60}m ${a}s`}function or(t,s=Date.now()){const r=t==null?void 0:t.snapshot;if(!r)return null;const a=r.activeTools.length+r.activeToolOverflow,i=r.activeTools.slice(0,2).map(l=>l.progress!==void 0&&l.total!==void 0?`${l.name} ${l.progress}/${l.total}`:l.name),n=Math.max(0,r.activeTools.length-i.length+r.activeToolOverflow);return{phaseKey:nr[r.phase],phaseParams:{count:a},tools:i,hiddenTools:n,completedTools:r.toolCallsCompleted,startedTools:r.toolCallsStarted,turn:r.turn,maxTurns:r.maxTurns,elapsed:ir(s-r.startedAt)}}function cr({activity:t}){var u;const s=_(),[r,a]=x.useState(Date.now()),i=(u=t==null?void 0:t.snapshot)==null?void 0:u.startedAt;x.useEffect(()=>{if(i===void 0)return;a(Date.now());const m=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(m)},[i]);const n=or(t,r);if(!n)return null;const l=[...n.tools,n.hiddenTools>0?`+${n.hiddenTools}`:void 0,n.startedTools>0?s("chat.turnActivity.toolCount",{completed:n.completedTools,started:n.startedTools}):void 0,n.turn>0?n.maxTurns===null?s("chat.turnActivity.turn",{turn:n.turn}):s("chat.turnActivity.turnBounded",{turn:n.turn,maxTurns:n.maxTurns}):void 0].filter(m=>m!==void 0);return e.jsxs("section",{role:"status","aria-live":"polite","data-turn-activity-strip":!0,className:"mx-4 mb-2 flex min-h-10 items-center gap-3 rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]/80 px-3 py-2 text-[hsl(var(--deck-ink))] shadow-sm md:mx-6",children:[e.jsx(Kt,{className:"h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))] motion-safe:animate-pulse","aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-xs font-semibold",children:s(n.phaseKey,n.phaseParams)}),l.length>0&&e.jsx("div",{className:"mt-0.5 truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:l.join(" · ")})]}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))]",children:n.elapsed})]})}function lr(t){const s=[...t].reverse().find(i=>i.role==="user");if(!s)return null;if(typeof s.content=="string")return{content:s.content,attachments:[]};const r=s.content.filter(i=>i.type==="text").map(i=>i.text).join(`
63
- `),a=s.content.filter(i=>i.type==="image_url").map((i,n)=>{var u;const l=((u=i.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:u[1])??"application/octet-stream";return{id:`recovery-${s.id}-${n}`,name:`attachment-${n+1}`,mimeType:l,dataUrl:i.image_url.url}});return{content:r,attachments:a}}function dr({messages:t,isLoading:s,isStreaming:r,isStopping:a,errorMessage:i}){const n=_(),[l,u]=x.useState(!1),m=n(i?"status.phase.error":a?"chat.input.action.stopping":r?"status.phase.running":"preview.files.status.ready");return e.jsxs("details",{"data-preview-status-disclosure":!0,open:l,onToggle:o=>u(o.currentTarget.open),className:"group hidden",children:[e.jsxs("summary",{className:"flex h-9 cursor-pointer list-none items-center gap-2 px-3 font-mono text-[11px] text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[hsl(var(--deck-accent))]",children:[r&&e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:m}),e.jsx(ne,{className:"h-3.5 w-3.5 shrink-0 transition-transform group-open:rotate-90"})]}),l&&e.jsxs("div",{"data-preview-activity-details":!0,className:"flex h-[min(44vh,420px)] min-h-0 flex-col border-t border-[hsl(var(--deck-hairline))]",children:[i&&e.jsx("div",{role:"alert",className:"border-b border-red-200/60 bg-red-50/80 px-3 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300",children:i}),e.jsx(ot,{messages:t,isLoading:s}),e.jsx(lt,{})]})]})}function Cr(){var Fe;const t=_(),s=b(y=>y.messages),r=b(y=>y.currentSessionRef),a=b(y=>y.isStreaming),i=b(y=>y.isStopping),n=b(y=>y.providerRecovery),l=b(y=>y.turnActivity),u=b(y=>y.actionStationarity),m=b(y=>y.sessionEventConnectionState),o=b(y=>y.pendingSteeringCount),g=b(y=>y.pendingInputDelivery),v=b(y=>y.recoveredSteeringCount),d=b(y=>y.followUpQueue),j=b(y=>y.followUpQueueMutation),f=b(y=>y.mutateFollowUpQueue),N=b(y=>y.refreshFollowUpQueue),h=b(y=>!!y.historySurfaceSelection),T=b(y=>y.isLoading),k=b(y=>y.error),p=b(y=>y.errorContext),c=b(y=>y.sessions),M=b(y=>y.sendMessage),D=b(y=>y.abortSession),R=b(y=>y.retryTask),w=b(y=>y.retryingTaskKeys),U=Ee(y=>y.openSettings),G=b(y=>y.reconnectSessionEvents),S=b(y=>y.clearError),[C,$]=x.useState(null),I=r?c.find(y=>y.sessionId===r.sessionId&&y.projectPath===r.projectPath):void 0,z=!!k&&((p==null?void 0:p.kind)==="navigation"||!(p!=null&&p.sessionRef)||He(p.sessionRef,r)),H=(p==null?void 0:p.failureCode)??((Fe=I==null?void 0:I.taskFailure)==null?void 0:Fe.code),Y=((p==null?void 0:p.kind)==="execution"||p!=null&&p.failureCode)&&H?t(Mt(H)):k==="queue_full"?t("chat.error.queueFull"):k==="turn_unavailable"||k==="turn_active"?t("chat.error.turnChanged"):k,W=m==="connecting"||m==="reconnecting",Z=a&&m!=="connected",X=r?`session:${ce(r)}`:"session:temporary",A=x.useMemo(()=>lr(s),[s]),q=r?ce(r):"temporary-session",Q=!!(r&&(I!=null&&I.taskRetryAvailable)&&(!H||At(H)))&&((p==null?void 0:p.kind)==="execution"||(p==null?void 0:p.kind)==="task_action"),V=(p==null?void 0:p.kind)==="execution"&&(H==="authentication"||H==="permission"||H==="model_unavailable"),L=r?w.includes(ce(r)):!1;x.useEffect(()=>{$(null)},[q]);const E=async y=>O(b.getState())?!1:M({content:y.content,modelId:y.modelId,reasoningEffort:y.reasoningEffort,serviceTier:y.serviceTier,responseVerbosity:y.responseVerbosity,communicationStyle:y.communicationStyle,...y.outputSchema?{outputSchema:y.outputSchema}:{},attachments:y.attachments.map(ve=>({type:"image",content:ve.dataUrl,mimeType:ve.mimeType,name:ve.name}))}),K=()=>{if(!O(b.getState()))return D()},ie=async()=>{if(!O(b.getState())){if(V){S(),U("models");return}if(Q&&r){S(),await R(r).catch(()=>{});return}if((p==null?void 0:p.kind)==="execution"&&A){$({...A,revision:Date.now()}),S();return}S(),requestAnimationFrame(()=>Nt())}},De=Q?t(L?"chat.error.action.retryingTask":"chat.error.action.retryTask"):V?t("chat.error.action.checkModels"):(p==null?void 0:p.kind)==="execution"&&A?t("chat.error.action.editResend"):(p==null?void 0:p.kind)==="submission"?t("chat.error.action.returnDraft"):null;return e.jsxs("div",{"data-chat-view":!0,className:"flex h-full flex-col bg-[hsl(var(--deck-canvas))]",children:[e.jsxs("div",{"data-chat-history":!0,className:"contents",children:[z&&e.jsxs("div",{role:"alert","data-blade-session-error":!0,className:"flex min-h-11 flex-wrap items-center gap-2 border-b border-red-200/60 bg-red-50/80 px-4 py-2 font-mono text-[11px] text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300 sm:px-5",children:[e.jsx(Te,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"min-w-0 flex-1 break-words",children:[e.jsx("span",{className:"font-semibold",children:t((p==null?void 0:p.kind)==="submission"?"chat.error.title.submission":(p==null?void 0:p.kind)==="execution"?"chat.error.title.execution":(p==null?void 0:p.kind)==="navigation"?"chat.error.title.navigation":"chat.error.title.generic")})," ",Y]}),De&&e.jsxs("button",{type:"button",onClick:()=>void ie(),disabled:L,className:"inline-flex min-h-7 shrink-0 items-center gap-1.5 rounded-md border border-red-300/70 bg-white/65 px-2.5 font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-500 disabled:cursor-wait disabled:opacity-60 dark:border-red-800 dark:bg-red-950/45 dark:hover:bg-red-900/60",children:[Q?L?e.jsx(B,{className:"h-3 w-3 animate-spin"}):e.jsx(he,{className:"h-3 w-3"}):e.jsx(at,{className:"h-3 w-3"}),De]}),e.jsx("button",{type:"button",onClick:S,"aria-label":t("chat.error.dismiss"),className:"p-1 text-red-500 rounded transition-colors hover:bg-red-100/60 hover:text-red-700 dark:hover:bg-red-950/60 dark:hover:text-red-100",children:"✕"})]}),(W||m==="offline")&&e.jsxs("div",{role:m==="offline"?"alert":"status","aria-live":"polite",className:"flex min-h-10 flex-wrap items-center gap-2 border-b border-amber-300/60 bg-amber-50/80 px-4 py-2 font-mono text-[11px] text-amber-900 dark:border-amber-800/60 dark:bg-amber-950/35 dark:text-amber-200 sm:px-5",children:[W?e.jsx(B,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(jt,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(W?"chat.connection.reconnecting":"chat.connection.offline")}),m==="offline"&&e.jsxs("button",{type:"button",onClick:()=>{O(b.getState())||G().catch(()=>{})},className:"inline-flex min-h-7 items-center gap-1.5 rounded-md border border-amber-400/70 bg-white/60 px-2.5 font-medium transition-colors hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-700 dark:bg-amber-950/50 dark:hover:bg-amber-900/50",children:[e.jsx(Ze,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(Xt,{}),e.jsx(ot,{messages:s,isLoading:T},r?ce(r):"temporary-session"),e.jsx(ar,{}),e.jsx(Xs,{})]}),e.jsxs("div",{"data-chat-composer-dock":!0,className:"contents",children:[e.jsx(dr,{messages:s,isLoading:T,isStreaming:a,isStopping:i,errorMessage:z?Y:null},q),e.jsx(qs,{}),e.jsx(zs,{}),e.jsx(Vs,{queue:h?null:d,mutation:j,onMutate:f,onRefresh:N}),e.jsx(Ws,{recovery:h?null:n,stopping:i,onStop:K}),e.jsx(cr,{activity:h||n!=null&&n.snapshot||u||I!=null&&I.pendingInteraction?null:l}),e.jsx(wt,{draftKey:X,draft:C==null?void 0:C.content,draftAttachments:C==null?void 0:C.attachments,draftRevision:C==null?void 0:C.revision,onSend:E,onAbort:K,disabled:T||Z,isStreaming:a,isStopping:i,pendingSteeringCount:o,pendingInputDelivery:g,recoveredSteeringCount:v,workspacePath:r==null?void 0:r.projectPath},X),e.jsx("div",{"data-chat-primary-status":!0,className:"contents",children:e.jsx(lt,{})})]})]})}export{Cr as ChatView};