blade-code 0.10.205 → 0.11.1

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 (184) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-7ajvrtb3.js → chunk-06hkf59s.js} +1 -1
  3. package/dist/{chunk-p0wyhp5a.js → chunk-0b83mt1c.js} +2 -2
  4. package/dist/{chunk-qtwgm95z.js → chunk-0wcnkxe8.js} +3 -3
  5. package/dist/{chunk-b8ast0cp.js → chunk-1beqtjsw.js} +1 -1
  6. package/dist/chunk-1kxpnt9q.js +1 -0
  7. package/dist/chunk-25s0c8km.js +1726 -0
  8. package/dist/{chunk-ak5xvsxr.js → chunk-27bjk35b.js} +1 -1
  9. package/dist/{chunk-515yj7mt.js → chunk-2ftyzk83.js} +1 -1
  10. package/dist/chunk-2g3v9qpz.js +1 -0
  11. package/dist/{chunk-5zmp7p0n.js → chunk-2vrsfb8p.js} +59 -59
  12. package/dist/{chunk-17d4m89n.js → chunk-30p7aff1.js} +2 -2
  13. package/dist/{chunk-kehgewqh.js → chunk-3kszepm6.js} +1 -1
  14. package/dist/{chunk-ys8gysg8.js → chunk-3y2x6fb6.js} +1 -1
  15. package/dist/chunk-43gg1wdc.js +1 -0
  16. package/dist/{chunk-xbs91jd8.js → chunk-447ps2te.js} +2 -2
  17. package/dist/{chunk-0eajnhrj.js → chunk-4cdk4mds.js} +1 -1
  18. package/dist/{chunk-8pd1hp4r.js → chunk-5034apfz.js} +2 -2
  19. package/dist/{chunk-ynd1v33f.js → chunk-5bc4hwt9.js} +1 -1
  20. package/dist/chunk-72wn385d.js +1 -0
  21. package/dist/chunk-7eset766.js +25 -0
  22. package/dist/chunk-7vzz3rsx.js +332 -0
  23. package/dist/{chunk-xxbxc31z.js → chunk-80946c9a.js} +1 -1
  24. package/dist/chunk-8emp6ysb.js +1 -0
  25. package/dist/chunk-8evyh5t0.js +1 -0
  26. package/dist/chunk-8hdtssvs.js +1 -0
  27. package/dist/chunk-8n3jythp.js +733 -0
  28. package/dist/{chunk-zj1g4nbq.js → chunk-8sth12hd.js} +1 -1
  29. package/dist/{chunk-fdr4fcrf.js → chunk-9qxch6sy.js} +1 -1
  30. package/dist/chunk-9ydrwcpy.js +3 -0
  31. package/dist/chunk-9yn01a90.js +12 -0
  32. package/dist/chunk-a1tt14a2.js +2 -0
  33. package/dist/{chunk-egss0m1x.js → chunk-a731hdwa.js} +1 -1
  34. package/dist/{chunk-gn9er641.js → chunk-a74ynw4t.js} +1 -1
  35. package/dist/chunk-b36egepz.js +1 -0
  36. package/dist/chunk-dxq7462e.js +352 -0
  37. package/dist/{chunk-eg3ms291.js → chunk-f552hzcx.js} +1 -1
  38. package/dist/{chunk-g01mth5d.js → chunk-f6hc7t65.js} +2 -2
  39. package/dist/{chunk-qq5y7b2r.js → chunk-fqxzzsgr.js} +1 -1
  40. package/dist/{chunk-xyypxrad.js → chunk-g0hhqxpg.js} +1 -1
  41. package/dist/{chunk-4wx5sya5.js → chunk-gzbb747a.js} +1 -1
  42. package/dist/{chunk-w42j9p3t.js → chunk-h8w3ahnk.js} +1 -1
  43. package/dist/chunk-hmw99nm1.js +94 -0
  44. package/dist/chunk-hrtf7dba.js +2 -0
  45. package/dist/chunk-j7dx054r.js +1 -0
  46. package/dist/chunk-j9ppeg6v.js +1 -0
  47. package/dist/chunk-jemb0vwa.js +1 -0
  48. package/dist/{chunk-qdbbke8f.js → chunk-m30qwpe9.js} +1 -1
  49. package/dist/{chunk-kvp523gt.js → chunk-m70cnaeg.js} +1 -1
  50. package/dist/{chunk-rtwd35gd.js → chunk-m8te4s8f.js} +2 -2
  51. package/dist/chunk-ms0wve9g.js +14 -0
  52. package/dist/{chunk-wezr6wfq.js → chunk-n8qg68y2.js} +1 -1
  53. package/dist/chunk-pm5ssr7m.js +25 -0
  54. package/dist/chunk-r9m3b170.js +1 -0
  55. package/dist/chunk-rt3f4xjz.js +23 -0
  56. package/dist/{chunk-430b319j.js → chunk-s1cch8tt.js} +1 -1
  57. package/dist/chunk-sa9fxss4.js +2 -0
  58. package/dist/{chunk-xmymx75h.js → chunk-ta99scbr.js} +1 -1
  59. package/dist/chunk-tf1qz4q6.js +1 -0
  60. package/dist/{chunk-efjjkha8.js → chunk-tqt5c2f5.js} +2 -2
  61. package/dist/{chunk-9jz1q7bk.js → chunk-ts5xzefm.js} +2 -2
  62. package/dist/chunk-v17q4bsd.js +6 -0
  63. package/dist/{chunk-qp2qc4p2.js → chunk-v1k6nvth.js} +2 -2
  64. package/dist/{chunk-1cy4ab77.js → chunk-vbjgcn49.js} +1 -1
  65. package/dist/{chunk-kkzznz4w.js → chunk-wcps5gjm.js} +1 -1
  66. package/dist/{chunk-vz88tqtd.js → chunk-xcj23spc.js} +2 -2
  67. package/dist/chunk-xcy45yxx.js +8 -0
  68. package/dist/chunk-xseh3f4m.js +2 -0
  69. package/dist/chunk-xz7dddaj.js +4 -0
  70. package/dist/{chunk-c51wwnh2.js → chunk-xzva8y4e.js} +5 -6
  71. package/dist/chunk-y0wc0hef.js +10 -0
  72. package/dist/chunk-yrr9mdjn.js +44 -0
  73. package/dist/{chunk-f8kjdxz7.js → chunk-zjezws85.js} +2 -2
  74. package/dist/web/assets/ChatView-BA3kB_z1.js +17 -0
  75. package/dist/web/assets/CodeBlockHighlighter-B5kcdVCA.js +8 -0
  76. package/dist/web/assets/FilePreview-BQid6G2-.js +8 -0
  77. package/dist/web/assets/KanbanBoard-CTR7bMLa.js +1 -0
  78. package/dist/web/assets/MarkdownRenderer-d7DdyYdx.js +30 -0
  79. package/dist/web/assets/ScrollArea-D1tPWHKZ.js +1 -0
  80. package/dist/web/assets/SessionHistorySurface-Cv_jRoJr.js +1 -0
  81. package/dist/web/assets/SettingsModal-CFa2uCzI.js +5 -0
  82. package/dist/web/assets/Sidebar-DrRNJOgU.js +1 -0
  83. package/dist/web/assets/TaskSwitcher-C9AKJrl-.js +1 -0
  84. package/dist/web/assets/TerminalPanel-BxBGcuB9.js +1 -0
  85. package/dist/web/assets/archive-DNa9b1YE.js +1 -0
  86. package/dist/web/assets/arrow-left-BQh8jlfT.js +1 -0
  87. package/dist/web/assets/calendar-clock-CC7FeYTg.js +1 -0
  88. package/dist/web/assets/chevron-right-6ZTOJE0p.js +1 -0
  89. package/dist/web/assets/clock-3-P2q6i6vm.js +1 -0
  90. package/dist/web/assets/copy-C-KvzjCC.js +1 -0
  91. package/dist/web/assets/dist-DiQNoDMg.js +11 -0
  92. package/dist/web/assets/download-CJHn20x1.js +1 -0
  93. package/dist/web/assets/folder-DmyFehXD.js +1 -0
  94. package/dist/web/assets/index-BVEiHNFk.css +1 -0
  95. package/dist/web/assets/index-D-oma3Je.js +11 -0
  96. package/dist/web/assets/message-square-plus-CKu9bFq3.js +1 -0
  97. package/dist/web/assets/pause-D2FxNG-w.js +1 -0
  98. package/dist/web/assets/pencil-D6HI7KC8.js +1 -0
  99. package/dist/web/assets/play-4jKCDYR-.js +1 -0
  100. package/dist/web/assets/plus-C4p8E1Nk.js +1 -0
  101. package/dist/web/assets/preload-helper-BC9Zf9qO.js +1 -0
  102. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  103. package/dist/web/assets/session-events-CvFfHkFA.js +23 -0
  104. package/dist/web/assets/settings-fWlqCZ-U.js +1 -0
  105. package/dist/web/assets/team-qGS2kixH.js +1 -0
  106. package/dist/web/assets/teamService-DfIvlI2_.js +1 -0
  107. package/dist/web/assets/terminal-DZkEoiSb.js +1 -0
  108. package/dist/web/assets/triangle-alert-Detl9fRQ.js +1 -0
  109. package/dist/web/assets/vendor-radix-CHeA_3Pt.js +41 -0
  110. package/dist/web/assets/vendor-react-hNfZDUf2.js +9 -0
  111. package/dist/web/assets/vendor-xterm-CANZO_wP.js +16 -0
  112. package/dist/web/assets/vendor-xterm-CHOd7Rch.css +1 -0
  113. package/dist/web/index.html +6 -4
  114. package/package.json +11 -10
  115. package/dist/chunk-18swytk4.js +0 -25
  116. package/dist/chunk-3297ghav.js +0 -1
  117. package/dist/chunk-33ck9ryb.js +0 -1
  118. package/dist/chunk-4fa11h6f.js +0 -94
  119. package/dist/chunk-535s1mm8.js +0 -1
  120. package/dist/chunk-57939tb3.js +0 -8
  121. package/dist/chunk-6169xxb4.js +0 -2
  122. package/dist/chunk-6v0cdqkw.js +0 -1
  123. package/dist/chunk-8kwj6px8.js +0 -1
  124. package/dist/chunk-a8z11yd2.js +0 -3
  125. package/dist/chunk-aatfjx15.js +0 -2
  126. package/dist/chunk-b2ek44t5.js +0 -12
  127. package/dist/chunk-b9d0ex8n.js +0 -4
  128. package/dist/chunk-bwe49m6n.js +0 -1719
  129. package/dist/chunk-ccgtbzrz.js +0 -14
  130. package/dist/chunk-jgxfhk9k.js +0 -733
  131. package/dist/chunk-jhpwwwjt.js +0 -1
  132. package/dist/chunk-jjj86dej.js +0 -1
  133. package/dist/chunk-kejvty9z.js +0 -23
  134. package/dist/chunk-kf9gj2gn.js +0 -2
  135. package/dist/chunk-mhe1zppc.js +0 -1
  136. package/dist/chunk-pb1q26gw.js +0 -181
  137. package/dist/chunk-pc5f77qh.js +0 -1
  138. package/dist/chunk-pkx6kfy6.js +0 -1
  139. package/dist/chunk-qjptyj18.js +0 -1
  140. package/dist/chunk-shgxzmdw.js +0 -1
  141. package/dist/chunk-thytjs86.js +0 -44
  142. package/dist/chunk-tm3789m3.js +0 -2
  143. package/dist/chunk-tnmcrvk2.js +0 -25
  144. package/dist/chunk-wejthch2.js +0 -1
  145. package/dist/chunk-xv6ejk2z.js +0 -353
  146. package/dist/chunk-yvgef7rp.js +0 -10
  147. package/dist/chunk-zj48897e.js +0 -6
  148. package/dist/web/assets/ChatView-BF6HUrBw.js +0 -70
  149. package/dist/web/assets/CodeBlockHighlighter-C4CgCiRf.js +0 -8
  150. package/dist/web/assets/FilePreview-BS4PgFKb.js +0 -55
  151. package/dist/web/assets/KanbanBoard-DDXB-yq1.js +0 -16
  152. package/dist/web/assets/MarkdownRenderer-DS7RznBE.js +0 -30
  153. package/dist/web/assets/ScrollArea-BM9NzGZM.js +0 -1
  154. package/dist/web/assets/SessionHistorySurface-DnRySeLE.js +0 -6
  155. package/dist/web/assets/SettingsModal-D5YLUtIo.js +0 -20
  156. package/dist/web/assets/Sidebar-BZC6OkDJ.js +0 -31
  157. package/dist/web/assets/TaskSwitcher-WewOkw5m.js +0 -26
  158. package/dist/web/assets/TerminalPanel-C5SGdRNr.js +0 -6
  159. package/dist/web/assets/archive-DkczUU08.js +0 -6
  160. package/dist/web/assets/arrow-left-9pBiQwu7.js +0 -6
  161. package/dist/web/assets/calendar-clock-BFnUlxrU.js +0 -6
  162. package/dist/web/assets/chevron-right-yCVkAEcj.js +0 -6
  163. package/dist/web/assets/clock-3-CcoWoRQs.js +0 -6
  164. package/dist/web/assets/copy-HJF0oQBS.js +0 -6
  165. package/dist/web/assets/download-DSBCIqk3.js +0 -6
  166. package/dist/web/assets/external-link-zIgEO0KB.js +0 -11
  167. package/dist/web/assets/folder-BdRo64o3.js +0 -11
  168. package/dist/web/assets/index-B5mUEr6D.js +0 -11
  169. package/dist/web/assets/index-BVDkKudh.js +0 -211
  170. package/dist/web/assets/index-CaCifsSK.css +0 -1
  171. package/dist/web/assets/message-square-plus-3klTXO0S.js +0 -21
  172. package/dist/web/assets/pause-B9Q5JWvH.js +0 -6
  173. package/dist/web/assets/pencil-CbYIz1b1.js +0 -6
  174. package/dist/web/assets/play-CZMTj43e.js +0 -6
  175. package/dist/web/assets/plus-Cc7I8fhb.js +0 -6
  176. package/dist/web/assets/session-events-NEjosinC.js +0 -31
  177. package/dist/web/assets/settings-DSF3exX2.js +0 -6
  178. package/dist/web/assets/team-qfeJHL9s.js +0 -6
  179. package/dist/web/assets/teamService-Bs9qBKI8.js +0 -1
  180. package/dist/web/assets/terminal-DQLqe-Ed.js +0 -6
  181. package/dist/web/assets/vendor-radix-D6QrtXqd.js +0 -45
  182. package/dist/web/assets/vendor-react-DofNRwfy.js +0 -49
  183. package/dist/web/assets/vendor-xterm-9CEnUXvW.css +0 -32
  184. package/dist/web/assets/vendor-xterm-DuYZoU4T.js +0 -49
@@ -1,6 +0,0 @@
1
- import{p as gH,q as kH,r as CH,s as hH,t as OH,u as wH}from"./chunk-b9d0ex8n.js";import{B as RH,C as ZH,D as $H,E as qH,F as a,G as XH}from"./chunk-17d4m89n.js";import{H as NH,da as MH,fa as zH,ga as fH,ka as AH}from"./chunk-bwe49m6n.js";import"./chunk-g01mth5d.js";import"./chunk-tnmcrvk2.js";import{ab as QH}from"./chunk-kf9gj2gn.js";import{Nb as e,Zb as FH,ic as EH}from"./chunk-pb1q26gw.js";import"./chunk-fdr4fcrf.js";import{Td as GH,Xd as PH,Zd as d,ie as t}from"./chunk-4fa11h6f.js";import"./chunk-egss0m1x.js";import"./chunk-xv6ejk2z.js";import"./chunk-efjjkha8.js";import{sf as TH}from"./chunk-9jz1q7bk.js";import{uf as yH,vf as bH,wf as IH}from"./chunk-rtwd35gd.js";import{xf as SH}from"./chunk-8pd1hp4r.js";import"./chunk-p0wyhp5a.js";import{Xf as _H}from"./chunk-18swytk4.js";import"./chunk-5yyp6njq.js";import"./chunk-v508x7cg.js";import"./chunk-57939tb3.js";import"./chunk-ynd1v33f.js";import"./chunk-w42j9p3t.js";import"./chunk-zfxcef0z.js";import"./chunk-xyypxrad.js";import"./chunk-jgxfhk9k.js";import"./chunk-kehgewqh.js";import{ih as c,mh as BH}from"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-c51wwnh2.js";import"./chunk-ys8gysg8.js";import{Fh as xH}from"./chunk-thytjs86.js";import{Zi as r,_i as n}from"./chunk-tm3789m3.js";import{cj as C}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Gj as UH,Ij as H,Jj as YH,Lj as Y}from"./chunk-a8z11yd2.js";import"./chunk-qtwgm95z.js";import"./chunk-0eajnhrj.js";import"./chunk-6169xxb4.js";import"./chunk-f8kjdxz7.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import uJ from"yargs";import{hideBin as dJ}from"yargs/helpers";function i(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function aH(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=()=>{i(V,"drain",x),i(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 iH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await aH(V,Q)}class o{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new a("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new XH({maxPendingItems:Z.maxPendingItems??ZH,maxPendingBytes:Z.maxPendingBytes??$H,writeTimeoutMs:Z.writeTimeoutMs??qH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>iH(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 a("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))i(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var oH=L({type:H.Literal("content_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking_delta"),delta:H.String()}),rH=L({type:H.Literal("thinking"),content:H.String()}),nH=L({type:H.Literal("stream_end")}),tH=L({type:H.Literal("content"),content:H.String()}),eH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),s=Y(["readonly","write","execute"]),HJ=H.Object({kind:s,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),JJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s)}),KJ=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(HJ)}),VJ=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"])}),ZJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(VJ)}),$J=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())}),qJ=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())}),XJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),YJ=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())}),BJ=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())}),NJ=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())}),QJ=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())}),DJ=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()}),LJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),jJ=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()}),xJ=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())}),UJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),_J=L({type:H.Literal("task_update"),tasks:H.Array(NH)}),GJ=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}))}),PJ=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(BH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),execution_host_failure_category:H.Optional(Y(["timeout","admission","spawn","finalization","sandbox_start","terminal"])),execution_host_failure_count:H.Optional(H.Integer({minimum:1,maximum:3})),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})),root_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),current_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),parent_turn_id:H.Optional(H.String({minLength:1,maxLength:c}))}),FJ=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}))}),EJ=L({type:H.Literal("token_usage"),scope:H.Optional(H.Literal("auxiliary")),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())}),MJ=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"])),memory:H.Optional(QH)}),zJ=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"]))}),fJ=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}))}),AJ=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}))}),SJ=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()}),u=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),DH=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})]),TJ=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:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}))},{additionalProperties:!1}),yJ=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([TJ,H.Null()])},{additionalProperties:!1}),bJ=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}),IJ=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(bJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),RJ=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([IJ,H.Null()])},{additionalProperties:!1}),gJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}),kJ=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()}),CJ=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"]))}),hJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),OJ=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())}),wJ=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})}),mJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),cJ=L({type:H.Literal("error"),message:H.String()}),NK=YH(H.Union([oH,sH,rH,nH,tH,eH,JJ,KJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,MJ,fJ,AJ,zJ,SJ,yJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ,cJ]));function LH(V,Z){return{event_version:k,type:V,...Z}}function pJ(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 vJ(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 lJ=Y(["text","jsonl"]),aJ=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(xH)),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(lJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class mH{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 iJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function oJ(V){let Z=UH(aJ,V);if(!Z.success)throw Error(`Invalid headless options: ${iJ(Z.error)}`);return Z.data}function sJ(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 JK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
2
- `)}function rJ(V){return`[task] [${V.status}] ${V.subject}`}function nJ(){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 tJ(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 eJ(V){return V==="jsonl"?"jsonl":"text"}function WH(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 HK(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 jH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(LH(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,rJ(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,execution_host_failure_category:J.goal?.executionHostFailure?.category,execution_host_failure_count:J.goal?.executionHostFailure?.consecutiveCount,frontier_stall_category:J.goal?.frontierStall?.category,frontier_stall_count:J.goal?.frontierStall?.consecutiveCount,root_turn_id:J.goal?.turnLineage?.rootTurnId,current_turn_id:J.goal?.turnLineage?.currentTurnId,parent_turn_id:J.goal?.turnLineage?.parentTurnId});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",{...J.scope?{scope:J.scope}:{},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,memory:J.memory});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`:""}${J.memory?.outcome==="written"?`; saved ${J.memory.entries} project memories`:""}`)},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 JK(V,Z={stdout:process.stdout,stderr:process.stderr},Q){let q="text",J=new mH,K={targetLocked:!1},D,x,j,P=vJ(Q),T=!1,F=new o(Z,{signal:P.signal,onFailure:(N)=>{T=!0,P.abort(N)}}),p={stdout:{write:(N)=>F.write("stdout",N)},stderr:{write:(N)=>F.write("stderr",N)}},B=jH(p,q),v=async()=>{try{return await F.flush(),!T}catch{return!1}},E=async(N)=>{return x?.(),x=void 0,j?.(),j=void 0,await v()?N:1};try{let N=oJ(V);q=eJ(N.outputFormat);let y=await OH(N);B=jH(p,q,Boolean(y)),await gH();let HH=N.forkSession!==!0&&(N.continue===!0||typeof N.resume==="string"&&N.resume.length>0)?await CH({message:N.message,_:N._,stdin:Q?.stdin}):await kH({...N,stdin:Q?.stdin}),M=HH===void 0,_=M?{mode:"agent",content:""}:await hH(HH);if(_.mode==="output"){if(_.content)B.output(_.content,_.exitCode??0);return await E(_.exitCode??0)}if(!M&&_.content.length>r)throw Error(`User prompt exceeds the ${r}-character durable input limit`);if(!M&&Buffer.byteLength(_.content,"utf8")>n)throw Error(`User prompt exceeds the ${n}-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:JH,metadata:KH}=await wH({sessionId:N.sessionId,continue:N.continue,resume:N.resume,forkSession:N.forkSession,fallbackSessionPrefix:"headless"}),R=N.permissionMode??KH?.permissionMode??"yolo",VH=N.model&&N.model!=="inherit"?N.model:_H()?.id,U=N.taskIsolation?await RH.createSessionTask({sessionId:G,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,dispatch:{version:1,prompt:_.content,sourceProjectPath:C(),isolation:N.taskIsolation,permissionMode:R,...VH?{modelId:VH}:{},...y?{outputSchema:y}:{}}}):void 0,z=U?.metadata.projectPath??KH?.projectPath??C();if(j=e.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"],lH=["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&&!lH.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 t.setSessionPermissionMode(G,z,R);let cH=U?!1:await EH.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=e.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 uH={messages:cH?await t.loadSessionModelContext(G,z):[...JH],userId:"cli-user",sessionId:G,workspaceRoot:z,permissionMode:R,signal:P.signal,...U?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:nJ()};D=await MH.create({sessionId:G,workspaceRoot:z,modelId:N.model,permissionMode:R,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig,agents:N.agents?SH(N.agents):void 0,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{},...JH.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",l=D.getTurnRecoveryAssessment?.()??{state:"none"};if(M&&!g&&!w&&l.state==="requires_attention")return B.turnRecovery({kind:"turn_recovery",assessment:l}),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 $=l;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 v()}});return B.userShellCompleted($),await E($.record.status==="completed"?0:$.record.status==="aborted"?130:$.record.exitCode??1)}let dH=N.maxTurns??D.getConfig().maxTurns,pH=U?.taskWorktree?[...new Set([...N.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:N.disallowedTools,vH=await AH.createWithRuntime(D,{sessionId:G,systemPrompt:N.systemPrompt,appendSystemPrompt:N.appendSystemPrompt,maxTurns:N.maxTurns,modelId:N.model,permissionMode:R,toolWhitelist:N.allowedTools,toolBlacklist:pH,mcpConfig:N.mcpConfig,strictMcpConfig:N.strictMcpConfig}),m=await FH(vH.chatStream(_.content,uH,{stream:!0,signal:P.signal,maxTurns:N.maxTurns,builtinVerification:N.verificationAgent!==!1,outputSchema:y,pendingInputOnly:g,goalContinuationOnly:w,...dH===-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===d)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),A=zH(X.function.name,f),S=WH(X.function.name,f),I=HK(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===d)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===d)break;let f;try{let S=JSON.parse(X.function.arguments);f=WH(X.function.name,S)}catch{f=void 0}let A=PH(fH(X.function.name,$.result),GH);if(B.toolResult(X.function.name,A.summary,f,void 0,{success:$.result.success,errorType:$.result.error?.type,errorMessage:$.result.error?.message,background:pJ($.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 v()});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")p.stderr.write(`
6
- `);B.error(`Error: ${tJ(N)}`)}return await E(1)}finally{x?.(),j?.();try{await D?.dispose()}finally{F.close(),P.dispose()}}}async function OK(){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}=TH,j=uJ(dJ(process.argv)).scriptName("blade").strict(!1).options(x).middleware([bH,yH,IH]);return sJ(j),await j.parse(),!0}export{JK as runHeadless,OK as handleHeadlessMode,aJ as HeadlessOptionsSchema};
@@ -1,70 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownRenderer-DS7RznBE.js","assets/index-BVDkKudh.js","assets/vendor-react-DofNRwfy.js","assets/vendor-radix-D6QrtXqd.js","assets/session-events-NEjosinC.js","assets/index-CaCifsSK.css","assets/copy-HJF0oQBS.js"])))=>i.map(i=>d[i]);
2
- import{r as h,j as e,b as Nt}from"./vendor-react-DofNRwfy.js";import{c as ee,u as $,a as v,s as st,b as St,d as ue,H as He,P as Ct,G as at,L as K,S as $e,T as ie,C as je,D as rt,e as nt,f as Et,g as it,h as ot,i as ct,j as I,k as Tt,l as re,B as Mt,m as At,M as lt,n as Re,o as he,R as ve,F as Rt,_ as dt,p as Dt,q as Ft,r as It,t as ut,v as Lt,w as mt,x as Bt,X as ht,y as $t,A as Pe,z as Pt,E as _t,W as Ot,I as Ut,J as Kt}from"./index-BVDkKudh.js";import{a0 as _e,N as oe,$ as Q,a5 as ge,A as xt,a6 as Vt,a7 as Ht,V as zt,a8 as qt,Z as Qt,_ as Gt}from"./session-events-NEjosinC.js";import{A as Wt,E as Jt}from"./external-link-zIgEO0KB.js";import{S as Yt}from"./ScrollArea-BM9NzGZM.js";import{C as pt}from"./copy-HJF0oQBS.js";import{C as ce}from"./chevron-right-yCVkAEcj.js";import{M as Xt,A as Oe,a as Zt,C as es}from"./message-square-plus-3klTXO0S.js";import{f as ts,g as ss,h as as,i as ft}from"./vendor-radix-D6QrtXqd.js";import{P as rs}from"./pause-B9Q5JWvH.js";import{P as ns}from"./play-CZMTj43e.js";import{P as bt}from"./pencil-CbYIz1b1.js";import{C as is}from"./clock-3-CcoWoRQs.js";import{P as os}from"./plus-Cc7I8fhb.js";import{t as z,A as ze}from"./team-qfeJHL9s.js";import{teamService as qe}from"./teamService-Bs9qBKI8.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 cs=ee("CornerDownLeft",[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]]);/**
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 ls=ee("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"}]]);/**
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 ds=ee("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/**
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 us=ee("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"}]]);/**
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 ms=ee("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"}]]);/**
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 hs=ee("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"}]]);/**
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 De=ee("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"}]]);/**
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 xs=ee("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"}]]);/**
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 ps=ee("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"}]]);/**
48
- * @license lucide-react v0.300.0 - ISC
49
- *
50
- * This source code is licensed under the ISC license.
51
- * See the LICENSE file in the root directory of this source tree.
52
- */const fs=ee("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 Qe(t){return t.split("/").filter(Boolean).at(-1)||t}function bs(){const t=$(),s=v(j=>j.sessions),a=v(j=>j.currentSessionRef),r=v(j=>j.historySurfaceSelection),i=v(j=>j.taskDeliveryActions),n=v(j=>j.deliverTask),o=_e(j=>j.openFilePreview),[m,x]=h.useState(!1),l=s.find(j=>st({sessionId:j.sessionId,projectPath:j.projectPath},a));if(oe(r)||!(l!=null&&l.taskIsolation))return null;const b=l.taskDiffStat,g=l.taskIsolation==="worktree",u=St(l),k=i[ue(u)],p=l.taskDelivery,w=(p==null?void 0:p.status)==="conflicted",d=!!(b&&(b.changedFiles>0||b.commits>0)),N=!["queued","running"].includes(l.taskStatus),f=(p==null?void 0:p.status)==="applied"||(p==null?void 0:p.status)==="discarded",C=g&&d&&N&&!f,c=b?b.additions+b.deletions:0,M=c>0&&b?b.additions/c*100:0,R=j=>{Q(v.getState())||n(u,j).catch(()=>{})},D=()=>{Q(v.getState())||o({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(He,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate text-[hsl(var(--deck-ink))]",children:Qe(l.taskSourceProjectPath||l.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:[g?e.jsx(Ct,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-accent))]"}):e.jsx(He,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:g?"text-[hsl(var(--deck-accent))]":void 0,children:t(g?"artifact.env.isolated":"artifact.env.local")})]}),l.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:l.taskWorktreeBranch,children:[e.jsx(at,{className:"h-3 w-3 shrink-0 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"truncate",children:l.taskWorktreeBranch})]})]})]}),b&&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(ls,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{className:"tabular-nums",children:b.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:["+",b.additions]}),e.jsxs("span",{className:"tabular-nums text-red-600 dark:text-red-400",children:["-",b.deletions]}),b.commits>0&&e.jsx("span",{className:"hidden tabular-nums text-[hsl(var(--deck-ink-faint))] sm:inline",children:t("artifact.commits",{count:b.commits})}),d&&(p==null?void 0:p.status)!=="discarded"&&e.jsx("button",{type:"button",onClick:D,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")}),C&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!!k,onClick:()=>R("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:[k==="apply"?e.jsx(K,{className:"h-3 w-3 animate-spin"}):e.jsx($e,{className:"h-3 w-3"}),t(k==="apply"?"artifact.applying":w?"artifact.retryApply":"artifact.apply")]}),e.jsx("button",{type:"button",disabled:!!k,onClick:()=>x(!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:k==="discard"?e.jsx(K,{className:"h-3 w-3 animate-spin"}):e.jsx(ie,{className:"h-3 w-3"})})]}),(p==null?void 0:p.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(je,{className:"h-3 w-3"}),t("artifact.applied")]}),(p==null?void 0:p.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(ie,{className:"h-3 w-3"}),t("artifact.discarded")]})]}),(p==null?void 0:p.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(Wt,{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:p.message||t("artifact.conflict")}),e.jsx("span",{className:"block text-[hsl(var(--deck-ink-faint))]",children:t("artifact.conflictHint")})]})]})]}),e.jsx(rt,{open:m,onOpenChange:x,children:e.jsxs(nt,{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(Et,{children:[e.jsx(it,{children:t("artifact.discardDialog.title")}),e.jsx(ot,{className:"text-[hsl(var(--deck-ink-muted))]",children:t("artifact.discardDialog.description",{project:Qe(l.taskSourceProjectPath||l.projectPath),count:(b==null?void 0:b.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(ct,{className:"gap-2 sm:space-x-0",children:[e.jsx("button",{type:"button",onClick:()=>x(!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:()=>{x(!1),R("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(ie,{className:"h-3.5 w-3.5"}),t("artifact.discardDialog.confirm")]})]})]})})]})}function vs(t){var s,a;return!!((s=t.metadata)!=null&&s.codeReview||(a=t.metadata)!=null&&a.structuredOutput)}function Fe(t){const s=t.agentContent;return!!(t.role==="assistant"&&s&&!vs(t)&&s.tasks.length===0&&xt(s).length===0&&!s.confirmation&&!s.question&&!s.elicitation)}function gs(t,s){return s.map((a,r)=>({...a,id:`${t}:${r}:${a.id}`}))}function ks(t){return!Fe(t)||!t.agentContent?t:{...t,displaySourceMessageIds:[t.id],agentContent:{...t.agentContent,timeline:gs(t.id,ge(t.agentContent))}}}function ys(t,s){const a=t.map(i=>({...i})),r=new Map(a.map((i,n)=>[i.toolCallId,n]));for(const i of s){const n=r.get(i.toolCallId);n===void 0?(r.set(i.toolCallId,a.length),a.push({...i})):a[n]={...a[n],...i}}return a}function Se(t,s){return[t,s].filter(Boolean).join(`
53
-
54
- `)}function js(t,s){const a=t.agentContent,r=s.agentContent,i=new Set(a.toolCalls.map(o=>o.toolCallId)),n=ge(r).flatMap(o=>{if(o.type!=="tool_group")return[o];const m=o.toolCallIds.filter(x=>i.has(x)?!1:(i.add(x),!0));return m.length>0?[{...o,toolCallIds:m}]:[]});return{...t,...t.metadata||s.metadata?{metadata:{...t.metadata,...s.metadata}}:{},displaySourceMessageIds:[...t.displaySourceMessageIds??[t.id],...s.displaySourceMessageIds??[s.id]],agentContent:{...a,timeline:[...ge(a),...n],textBefore:Se(a.textBefore,r.textBefore),toolCalls:ys(a.toolCalls,r.toolCalls),textAfter:Se(a.textAfter,r.textAfter),thinkingContent:Se(a.thinkingContent,r.thinkingContent),tasks:[],subagent:null,subagents:[],confirmation:null,question:null,elicitation:null}}}function ws(t){const s=[];for(const a of t){const r=ks(a),i=s[s.length-1];i&&Fe(i)&&Fe(r)?s[s.length-1]=js(i,r):s.push(r)}return s}const Ns=new Set(["completed","stale","failed","aborted","interrupted"]),Ss={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"},Cs={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 ke(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Es(t){const s=ke(t),a=ke(s==null?void 0:s.codeLocation),r=s==null?void 0:s.priority,i=s==null?void 0:s.confidenceScore,n=a==null?void 0:a.lineStart,o=a==null?void 0:a.lineEnd;if(!(typeof(s==null?void 0:s.title)!="string"||typeof s.body!="string"||r!==0&&r!==1&&r!==2&&r!==3||typeof i!="number"||!Number.isFinite(i)||typeof(a==null?void 0:a.path)!="string"||!Number.isInteger(n)||!Number.isInteger(o)))return{title:s.title,body:s.body,priority:r,confidenceScore:i,codeLocation:{path:a.path,lineStart:n,lineEnd:o}}}function Ts(t){const s=ke(t),a=ke(s==null?void 0:s.target);if((s==null?void 0:s.phase)!=="completed"||typeof s.status!="string"||!Ns.has(s.status)||typeof(a==null?void 0:a.label)!="string"||a.kind!=="uncommitted"&&a.kind!=="base"&&a.kind!=="commit"||typeof s.overallExplanation!="string"||!Array.isArray(s.findings))return;const r=s.findings.map(Es);if(!r.some(i=>i===void 0))return{status:s.status,target:{kind:a.kind,label:a.label,...typeof a.reference=="string"?{reference:a.reference}:{}},overallExplanation:s.overallExplanation,findings:r,...typeof s.error=="string"?{error:s.error}:{}}}function Ms(t){const{path:s,lineStart:a,lineEnd:r}=t.codeLocation;return a===r?`${s}:L${a}`:`${s}:L${a}-${r}`}function As({report:t}){const s=$(),a=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"),": ",a]})]}),e.jsxs("span",{className:I("rounded-full border px-2.5 py-1 font-mono text-[10.5px] font-medium",Cs[t.status]),children:[s("chat.review.status"),": ",s(Ss[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((r,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:r.title}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:s("chat.review.confidence",{value:r.confidenceScore.toFixed(2)})})]}),e.jsx("code",{className:"mt-1 block text-[10.5px] text-[hsl(var(--deck-accent))]",children:Ms(r)}),e.jsx("p",{className:"mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:r.body})]},`${r.codeLocation.path}:${r.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 Rs({elicitation:t,messageId:s}){const a=$(),r=v(f=>f.currentSessionRef),i=v(f=>f.setElicitation),[n,o]=h.useState(()=>Fs(t.details.fields??[])),[m,x]=h.useState(()=>Is(t.details.fields??[])),[l,b]=h.useState(!1),[g,u]=h.useState(),k=t.details.fields??[],p=h.useMemo(()=>k.every(f=>{var c;if(!f.required)return!0;if(we(f))return!!((c=m[f.name])!=null&&c.trim()||f.defaultValue!==void 0);const C=n[f.name]??f.defaultValue;return Array.isArray(C)?C.length>0:C!==void 0}),[k,m,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:a(t.status==="cancelled"?"interaction.elicitation.cancelled":"interaction.elicitation.responded")});const w=async(f,C)=>{if(!Q(v.getState())&&!(!r||l)){b(!0),u(void 0);try{await re.respondToElicitation(r,t.toolCallId,{action:f,...C?{content:C}:{}}),i(s,{...t,status:"responded"})}catch(c){u(c instanceof Error?c.message:a("interaction.elicitation.failed"))}finally{b(!1)}}},d=async()=>{try{await w("accept",Ls(k,n,m))}catch(f){u(f instanceof Error?f.message:String(f))}},N=()=>{if(Q(v.getState()))return;const f=t.details.url;if(!f){u("MCP URL is unavailable");return}if(!window.open(f,"_blank","noopener,noreferrer")){u("The browser blocked the external window");return}w("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(Tt,{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:[a("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:a("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(ne,{onClick:N,disabled:l,primary:!0,label:a("interaction.elicitation.open"),icon:e.jsx(Jt,{className:"h-3.5 w-3.5"})}),e.jsx(ne,{onClick:()=>void w("decline"),disabled:l,label:a("interaction.elicitation.decline")}),e.jsx(ne,{onClick:()=>void w("cancel"),disabled:l,label:a("interaction.elicitation.cancel")})]})]}):e.jsxs("div",{className:"space-y-4",children:[k.map(f=>e.jsx(Ds,{field:f,value:n[f.name],rawValue:m[f.name]??"",onValueChange:C=>o(c=>({...c,[f.name]:C})),onRawChange:C=>x(c=>({...c,[f.name]:C}))},f.name)),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ne,{onClick:()=>void d(),disabled:l||!p,primary:!0,label:a("interaction.elicitation.submit"),icon:l?e.jsx(K,{className:"h-3.5 w-3.5 animate-spin"}):null}),e.jsx(ne,{onClick:()=>void w("decline"),disabled:l,label:a("interaction.elicitation.decline")}),e.jsx(ne,{onClick:()=>void w("cancel"),disabled:l,label:a("interaction.elicitation.cancel")})]})]}),g&&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:g})]})}function Ds({field:t,value:s,rawValue:a,onValueChange:r,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:Bs(t).map(n=>{const o=Array.isArray(s)?s.includes(n.value):s===n.typedValue;return e.jsx("button",{type:"button","aria-pressed":o,onClick:()=>{if(t.type==="multi-select"){const m=Array.isArray(s)?s:[];r(m.includes(n.value)?m.filter(x=>x!==n.value):[...m,n.value])}else r(n.typedValue)},className:I("rounded-md border px-3 py-2 font-mono text-[12px] transition-colors",o?"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:$s(t),value:a,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 ne({onClick:t,disabled:s,primary:a=!1,label:r,icon:i}){return e.jsxs("button",{type:"button",onClick:t,disabled:s,className:I("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",a?"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,r]})}function Fs(t){return Object.fromEntries(t.filter(s=>!we(s)&&s.defaultValue!==void 0).map(s=>[s.name,Array.isArray(s.defaultValue)?[...s.defaultValue]:s.defaultValue]))}function Is(t){return Object.fromEntries(t.filter(s=>we(s)&&s.defaultValue!==void 0).map(s=>[s.name,String(s.defaultValue)]))}function Ls(t,s,a){var i;const r={};for(const n of t){if(we(n)){const m=((i=a[n.name])==null?void 0:i.trim())??"";if(!m){if(n.defaultValue!==void 0)r[n.name]=n.defaultValue;else if(n.required)throw new Error(`${n.title} is required`);continue}if(n.type==="number"||n.type==="integer"){const x=Number(m);if(!Number.isFinite(x))throw new Error(`${n.title} must be a finite number`);if(n.type==="integer"&&!Number.isSafeInteger(x))throw new Error(`${n.title} must be a safe integer`);r[n.name]=x}else r[n.name]=m;continue}const o=s[n.name]??n.defaultValue;if(o===void 0){if(n.required)throw new Error(`${n.title} is required`);continue}if(Array.isArray(o)){if(n.minItems!==void 0&&o.length<n.minItems)throw new Error(`${n.title} requires at least ${n.minItems} choices`);if(n.maxItems!==void 0&&o.length>n.maxItems)throw new Error(`${n.title} allows at most ${n.maxItems} choices`)}r[n.name]=o}return r}function Bs(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 we(t){return t.type==="string"||t.type==="number"||t.type==="integer"}function $s(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 Ps(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 _s({report:t}){const s=$(),[a,r]=h.useState(!1),i=JSON.stringify(t.output,null,2),n=async()=>{try{await navigator.clipboard.writeText(i),r(!0),window.setTimeout(()=>r(!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(Mt,{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:a?e.jsx(je,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(pt,{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 Ue=h.createContext(null);function vt(t,s){const a=h.useContext(Ue),[r,i]=h.useState(()=>{var o;return((o=a==null?void 0:a.get(s))==null?void 0:o.has(t))??!1});return{expanded:r,toggle:()=>{const o=!r;if(a){const m=a.get(s)??new Set;o?m.add(t):m.delete(t),m.size>0?a.set(s,m):a.delete(s)}i(o)}}}const Os=h.lazy(()=>dt(()=>import("./MarkdownRenderer-DS7RznBE.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Ge({text:t,label:s}){const[a,r]=h.useState(!1);if(!t.trim())return null;const i=async()=>{try{await navigator.clipboard.writeText(t),r(!0),window.setTimeout(()=>r(!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:a?e.jsx(je,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}):e.jsx(pt,{className:"h-3.5 w-3.5"})})}function Us(){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(Re,{size:20,pulse:!1})})}function Ks(){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 We(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:We(t),images:[]};const s=t.filter(r=>r.type==="text").map(r=>r.text).join(`
55
- `),a=t.filter(r=>r.type==="image_url").map(r=>r.image_url.url);return{text:We(s),images:a}}function Ke(t){return typeof t=="string"?t:t.filter(s=>s.type==="text").map(s=>s.text).join(`
56
- `)}function Hs(t){const s=t.agentContent;return s?Vt(s):Ke(t.content)}function Je({content:t,syntaxHighlight:s=!0}){return e.jsx(h.Suspense,{fallback:e.jsx("pre",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono whitespace-pre-wrap",children:t}),children:e.jsx(Os,{content:t,syntaxHighlight:s})})}function Ve({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]"},a={running:"Running",success:"Success",error:"Error",pending:"Pending",info:"Info"};return e.jsx("span",{className:I("text-[11px] px-2 py-0.5 rounded-full font-mono",s[t]),children:a[t]})}function zs(t){if(!t)return"";if(typeof t=="string")try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}return JSON.stringify(t,null,2)}const Ye=500;function gt(t,s){if(t.length<=s)return t;let a=Math.max(0,s);return a>0&&/[\uD800-\uDBFF]/.test(t.charAt(a-1))&&(a-=1),t.slice(0,a)}function Xe(t,s){if(t.length<=s)return t;let a=Math.max(0,t.length-s);return/[\uDC00-\uDFFF]/.test(t.charAt(a))&&(a+=1),t.slice(a)}function Ce(t,s){if(t.length<=s)return t;if(s<=0)return"";const a=`
57
- ... (display clipped) ...
58
- `,r=s-a.length;if(r<=0)return Xe(t,s);const i=Math.floor(r/3);return`${gt(t,i)}${a}${Xe(t,r-i)}`}function qs(t){const s=t.split(`
59
- `),a=s.at(-1),r=a!=null&&a.startsWith("Output truncated")?a:void 0,i=r?s.slice(0,-1).join(`
60
- `):t,n=r?`
61
- ${r}`:"",o=Math.max(0,Ye-n.length),x=i.indexOf(`
62
- stderr:
63
- `);let l;if(x>=0&&i.includes(`
64
- stdout:
65
- `)){const b=i.slice(0,x),g=i.slice(x+1),u=Math.max(0,o-1),k=Math.floor(u/2);l=`${Ce(b,k)}
66
- ${Ce(g,u-k)}`}else l=Ce(i,o);return{body:gt(l,o),...r?{notice:r}:{},truncated:!!r||t.length>Ye}}function Qs({tool:t}){const{expanded:s,toggle:a}=vt("detail",t.toolCallId),r=zs(t.arguments),i=t.output?qs(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:a,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(he,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))] shrink-0"}):e.jsx(ce,{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(Ve,{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:[r&&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:r})]}),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:[`
67
- `,e.jsx("span",{"data-tool-truncation-notice":!0,children:i.notice})]})]})]})]})]})}function kt({toolCalls:t}){return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(s=>e.jsx(Qs,{tool:s},s.toolCallId))})}function Gs({toolCalls:t,toolCallIds:s}){const a=$(),{expanded:r,toggle:i}=vt("group",s[0]),n=h.useMemo(()=>new Map(t.map(g=>[g.toolCallId,g])),[t]),o=s.flatMap(g=>{const u=n.get(g);return u?[u]:[]});if(o.length===0)return null;const m=o.filter(g=>g.status==="running").length,x=o.filter(g=>g.status==="error").length,l=[...o].reverse().find(g=>g.status==="running"&&!!g.progressMessage),b=m>0?a(o.length===1?"chat.timeline.tools.runningOne":"chat.timeline.tools.running",{count:o.length}):x>0?a(o.length===1?"chat.timeline.tools.completedOneWithError":"chat.timeline.tools.completedWithErrors",{count:o.length,errors:x}):a(o.length===1?"chat.timeline.tools.completedOne":"chat.timeline.tools.completed",{count:o.length});return e.jsxs("div",{"data-agent-tool-group":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:i,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:[r?e.jsx(he,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(ce,{className:"h-3.5 w-3.5 shrink-0"}),m>0&&e.jsx(K,{className:"h-3 w-3 shrink-0 animate-spin text-[hsl(var(--deck-accent))]"}),e.jsx("span",{children:b}),(l==null?void 0:l.progressMessage)&&e.jsxs("span",{className:"min-w-0 truncate text-[10.5px] text-[hsl(var(--deck-ink-muted))]",children:[l.progressMessage,l.progress!==void 0&&l.progressTotal!==void 0&&` · ${Math.max(0,Math.min(100,Math.round(l.progress/l.progressTotal*100)))}%`]})]}),(l==null?void 0:l.progress)!==void 0&&l.progressTotal!==void 0&&e.jsx("div",{role:"progressbar","aria-label":`${l.toolName} progress`,"aria-valuemin":0,"aria-valuemax":l.progressTotal,"aria-valuenow":Math.min(l.progress,l.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,l.progress/l.progressTotal*100))}%`}})}),r&&e.jsx("div",{"data-agent-tool-group-details":!0,className:"pl-1 mt-2 space-y-2",children:e.jsx(kt,{toolCalls:o})})]})}function Ws({content:t}){const s=$(),[a,r]=h.useState(!1);return t?e.jsxs("div",{"data-agent-thinking":!0,className:"py-0.5",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>r(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:[a?e.jsx(he,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}):e.jsx(ce,{className:"h-4 w-4 text-[hsl(var(--deck-ink-faint))]"}),e.jsx("span",{children:s("chat.timeline.thinking")})]}),a&&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 Js({tasks:t}){if(t.length===0)return null;const s=t.filter(r=>r.status==="completed").length,a=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:a?"✓ All tasks done":`Tasks: ${s}/${t.length}`})})})}function Ys({toolCalls:t}){const s=_e(n=>n.openFilePreview),a=v(n=>oe(n.historySurfaceSelection)),r=h.useMemo(()=>{const n=new Map,o=["Write","SearchReplace","Edit","ApplyPatch"];for(const m of t){if(m.status!=="success")continue;const x=m.metadata;if(m.toolName==="ApplyPatch"&&Array.isArray(x==null?void 0:x.changes)){for(const b of x.changes)b&&typeof b=="object"&&"path"in b&&typeof b.path=="string"&&n.set(b.path,{path:b.path,toolName:m.toolName});continue}const l=x==null?void 0:x.file_path;l&&o.includes(m.toolName)&&n.set(l,{path:l,toolName:m.toolName})}return Array.from(n.values())},[t]);if(a||r.length===0)return null;const i=n=>{Q(v.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 (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(({path:n})=>{const o=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(Rt,{className:"w-3 h-3"}),o]},n)})})]})}function Xs({subagent:t}){var E,A,U,G;const s=$(),[a,r]=h.useState(null),[i,n]=h.useState(!1),[o,m]=h.useState(null),[x,l]=h.useState(!1),[b,g]=h.useState(""),[u,k]=h.useState(!1),[p,w]=h.useState(null),[d,N]=h.useState(null),[f,C]=h.useState(null),c=v(F=>F.currentSessionRef),M=v(F=>F.isStreaming),R=v(F=>F.isTemporarySession),D=v(F=>oe(F.historySurfaceSelection));if(!t)return null;const j=t.status==="running",P=a!==null?a:j,Z=t.toolCalls||o||[],T=t.output||t.thinking||Z.length>0||t.sessionId,L=d&&d.status!=="running"?d:f,O=(L==null?void 0:L.id)??t.sessionId,_=((E=L==null?void 0:L.restartRecovery)==null?void 0:E.outcome)==="failed",H=!j&&!M&&!R&&!D&&!_&&(d==null?void 0:d.status)!=="running"&&!!(O&&c);h.useEffect(()=>{if(D||!P||j||!t.sessionId||!(c!=null&&c.projectPath)||o!==null||t.toolCalls&&t.toolCalls.length>0)return;let F=!0;return n(!0),re.getMessages({sessionId:t.sessionId,projectPath:c.projectPath}).then(J=>{var q,V;if(!F)return;const Y=zt(J),W=new Map;for(const X of Y)if((V=(q=X.agentContent)==null?void 0:q.toolCalls)!=null&&V.length)for(const te of X.agentContent.toolCalls)W.has(te.toolCallId)||W.set(te.toolCallId,te);m(Array.from(W.values()))}).finally(()=>{F&&n(!1)}),()=>{F=!1}},[P,D,j,t.sessionId,t.toolCalls,o,c==null?void 0:c.projectPath]),h.useEffect(()=>{if(D||!t.sessionId||!c)return;let F=!0;const J=t.rootAgentId??t.sessionId,Y=t.resumeDepth??0;return re.listSubagents(c).then(W=>{if(!F)return;C(W.find(V=>V.id===t.sessionId)??null);const q=W.filter(V=>V.id!==t.sessionId&&V.rootAgentId===J&&V.resumeDepth>Y).sort((V,X)=>X.resumeDepth-V.resumeDepth||X.lastActiveAt-V.lastActiveAt)[0];q&&N(q)}).catch(()=>{}),()=>{F=!1}},[c==null?void 0:c.sessionId,c==null?void 0:c.projectPath,D,t.sessionId,t.rootAgentId,t.resumeDepth]),h.useEffect(()=>{if(D||!d||d.status!=="running"||!c)return;let F=!0;const J=async()=>{try{const q=(await re.listSubagents(c)).find(V=>V.id===d.id);F&&q&&N(q)}catch{}},Y=window.setInterval(()=>{J()},1e3);return()=>{F=!1,window.clearInterval(Y)}},[c,D,d==null?void 0:d.id,d==null?void 0:d.status]);const S=async()=>{if(!Q(v.getState())&&!(!c||!O||!b.trim()||u)){k(!0),w(null);try{const F=await re.resumeSubagent(c,O,b.trim());N(F.session),g(""),l(!1),r(!0)}catch(F){w(F instanceof Error?F.message:s("chat.subagent.resumeFailed"))}finally{k(!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:()=>r(!P),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:[j&&e.jsx(K,{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(Ve,{status:t.status==="completed"?"success":t.status==="failed"?"error":"running"}),t.type==="verification"&&t.verificationVerdict&&e.jsx("span",{"data-verification-verdict":t.verificationVerdict,className:I("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})})]}),T&&e.jsx(he,{className:I("h-3.5 w-3.5 text-[hsl(var(--deck-ink-muted))] transition-transform",P&&"rotate-180")})]}),!P&&!j&&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}),P&&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(K,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.loadingLogs")]}),!i&&Z.length>0&&e.jsx(Ue.Provider,{value:null,children:e.jsx(kt,{toolCalls:Z})}),d&&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:d.id,status:d.status,depth:d.resumeDepth??1})}),(((A=d.result)==null?void 0:A.message)||((U=d.result)==null?void 0:U.error))&&e.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[hsl(var(--deck-ink))]",children:d.result.message||d.result.error})]}),_&&((G=L==null?void 0:L.result)==null?void 0:G.error)&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:L.result.error}),H&&e.jsxs("div",{className:"space-y-2",children:[x?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:b,onChange:F=>g(F.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:()=>{l(!1),w(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 S(),disabled:!b.trim()||u,className:"flex items-center gap-1 rounded bg-[#7C3AED] px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50",children:[u&&e.jsx(K,{className:"w-3 h-3 animate-spin"}),s("chat.subagent.resumeAgent")]})]})]}):e.jsxs("button",{type:"button","aria-label":s("chat.subagent.resumeAria"),onClick:()=>l(!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(ve,{className:"w-3 h-3"}),s("chat.subagent.resume")]}),p&&e.jsx("div",{role:"alert",className:"text-[11px] text-red-600",children:p})]})]})]})}function Zs({confirmation:t,messageId:s}){const a=$(),[r,i]=h.useState(!1),[n,o]=h.useState(null),m=v(b=>b.currentSessionRef),x=v(b=>b.setConfirmation);if(!t)return null;const l=async(b,g)=>{if(!Q(v.getState())&&!(!m||r)){i(!0),o(null);try{await re.respondPermission(m,t.toolCallId,{approved:b,scope:g}),x(s,{...t,status:b?"approved":"denied"})}catch(u){o(u instanceof Error?u.message:a("interaction.permission.failed"))}finally{i(!1)}}};return t.status!=="pending"?null:e.jsxs("div",{"data-pending-interaction":"permission",tabIndex:-1,role:"alert",className:"p-4 space-y-3 rounded-lg border outline-none border-amber-300/70 bg-amber-50/70 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:a("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 l(!0,"once"),disabled:r,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:r?e.jsx(K,{className:"h-3.5 w-3.5 animate-spin"}):a("interaction.permission.once")}),t.allowRemember!==!1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void l(!0,"session"),disabled:r,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:a("interaction.permission.session")}),e.jsx("button",{type:"button",onClick:()=>void l(!0,"project"),disabled:r,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:a("interaction.permission.project")})]}),e.jsx("button",{type:"button",onClick:()=>void l(!1),disabled:r,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:a("interaction.permission.deny")})]})]})}function ea({question:t,messageId:s}){const a=$(),[r,i]=h.useState({}),[n,o]=h.useState({}),[m,x]=h.useState(!1),[l,b]=h.useState(null),g=v(d=>d.currentSessionRef),u=v(d=>d.setQuestion),k=h.useMemo(()=>t?t.questions.reduce((d,N)=>{var M;const f=(M=n[N.header])==null?void 0:M.trim(),C=r[N.header];if(N.multiSelect){const R=Array.isArray(C)?[...C]:[];return f&&R.push(f),R.length>0&&(d[N.header]=R),d}const c=f||(typeof C=="string"?C:"");return c&&(d[N.header]=c),d},{}):{},[r,n,t]),p=(t==null?void 0:t.questions.every(d=>d.header in k))??!1;if(!t)return null;const w=async()=>{if(!Q(v.getState())&&!(!g||m||!p)){x(!0),b(null);try{await re.respondToQuestion(g,t.toolCallId,k),u(s,{...t,status:"answered",answers:k})}catch(d){b(d instanceof Error?d.message:a("interaction.question.failed"))}finally{x(!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:a("interaction.question.answered")})}):e.jsxs("div",{"data-pending-interaction":"question",tabIndex:-1,role:"alert",className:"p-4 space-y-4 rounded-lg border outline-none border-amber-300/70 bg-amber-50/70 focus-visible:ring-2 focus-visible:ring-amber-500 dark:border-amber-800/70 dark:bg-amber-950/25",children:[t.questions.map((d,N)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[13px] text-[hsl(var(--deck-ink))] font-mono",children:d.question}),e.jsxs("div",{className:"space-y-1",children:[d.options.map((f,C)=>e.jsxs("button",{type:"button",onClick:()=>{if(d.multiSelect){const c=r[d.header]||[],M=c.includes(f.label)?c.filter(R=>R!==f.label):[...c,f.label];i({...r,[d.header]:M})}else i({...r,[d.header]:f.label}),o({...n,[d.header]:""})},className:I("w-full text-left px-3 py-2 rounded-md border text-[12px] font-mono transition-colors","border-[hsl(var(--deck-border))]",(d.multiSelect?(r[d.header]||[]).includes(f.label):r[d.header]===f.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:f.label}),e.jsx("div",{className:"text-[11px] text-[hsl(var(--deck-ink-faint))] mt-1",children:f.description})]},C)),e.jsx("input",{"aria-label":`${d.header} other response`,value:n[d.header]??"",onChange:f=>o({...n,[d.header]:f.target.value}),placeholder:a("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]"})]})]},N)),l&&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:l}),e.jsxs("button",{type:"button",onClick:()=>void w(),disabled:m||!p,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:[m&&e.jsx(K,{className:"h-3.5 w-3.5 animate-spin"}),a("interaction.question.submit")]})]})}function ta({message:t}){const s=t.agentContent,a=v(p=>{var w;return p.isStreaming&&!!(p.currentAssistantMessageId&&(((w=t.displaySourceMessageIds)==null?void 0:w.includes(p.currentAssistantMessageId))??p.currentAssistantMessageId===t.id))});if(!s){const p=Ke(t.content);return p?e.jsx(Je,{content:p}):null}const{toolCalls:r,tasks:i,confirmation:n,question:o,elicitation:m}=s,x=xt(s),l=Ht(ge(s));if(!(l.length>0||i.length>0||x.length>0||n||o||m)&&a)return e.jsxs("div",{className:"flex items-center gap-2 text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(K,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-[12px] font-mono",children:"Thinking..."})]});const u=r.length>0&&r.every(p=>p.status==="success"||p.status==="error")&&!a,k=!a;return e.jsxs("div",{className:"space-y-3",children:[l.map(p=>p.type==="thinking"?e.jsx("div",{"data-agent-timeline-block":"thinking",children:e.jsx(Ws,{content:p.content})},p.id):p.type==="text"?e.jsx("div",{"data-agent-timeline-block":"text",children:e.jsx(Je,{content:p.content,syntaxHighlight:k})},p.id):e.jsx("div",{"data-agent-timeline-block":"tool_group",children:e.jsx(Gs,{toolCalls:r,toolCallIds:p.toolCallIds})},p.id)),i.length>0&&e.jsx(Js,{tasks:i}),x.map(p=>e.jsx(Xs,{subagent:p},p.id)),n&&e.jsx(Zs,{confirmation:n,messageId:t.id}),o&&e.jsx(ea,{question:o,messageId:t.id}),m&&e.jsx(Rs,{elicitation:m,messageId:t.id}),u&&e.jsx(Ys,{toolCalls:r})]})}function sa({message:t,showAvatar:s=!0}){var x,l,b,g;const a=$(),r=t.role==="user";if(t.role==="system"){const u=Ke(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:u})})}if(r){const u=(x=t.metadata)!=null&&x.userShellCommand&&typeof t.metadata.userShellCommand=="object"?t.metadata.userShellCommand:(l=t.metadata)!=null&&l.userShellExecution&&typeof t.metadata.userShellExecution=="object"?t.metadata.userShellExecution:void 0;if(u){const d=typeof u.command=="string"?u.command:"",N=u.status==="running"?"running":u.status==="completed"?"success":"error",f=typeof u.output=="string"?u.output:[typeof u.stdout=="string"?u.stdout:"",typeof u.stderr=="string"&&u.stderr?`stderr:
68
- ${u.stderr}`:""].filter(Boolean).join(`
69
- `);return e.jsx("div",{"data-chat-message-id":t.id,"data-chat-role":"user","data-user-shell-command":!0,className:"flex justify-end p-4 w-full",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:"$"}),d]}),e.jsx(Ve,{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:f||"(no output)"}),typeof u.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 ",u.exitCode,typeof u.durationMs=="number"?` · ${(u.durationMs/1e3).toFixed(3)}s`:"",u.truncated===!0?" · truncated":""]})]})})}const{text:k,images:p}=Vs(t.content),w=At(t.metadata);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"user",className:"flex gap-2 justify-end items-start p-4 w-full group",children:[e.jsx("div",{className:"flex mt-1 opacity-0 transition-opacity shrink-0 group-hover:opacity-100 group-focus-within:opacity-100",children:e.jsx(Ge,{text:k,label:"Copy message"})}),e.jsxs("div",{className:"bg-[hsl(var(--deck-surface-2))] rounded-lg px-4 py-3 max-w-[85%]",children:[w.length>0&&e.jsxs("details",{"data-user-message-annotations":!0,className:"mb-2",children:[e.jsxs("summary",{className:"inline-flex min-h-7 cursor-pointer list-none items-center gap-1.5 rounded-md border border-[hsl(var(--deck-border-strong))] bg-[hsl(var(--deck-surface))] px-2.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[e.jsx(lt,{"aria-hidden":!0,className:"h-3.5 w-3.5"}),a(w.length===1?"chat.input.annotation.one":"chat.input.annotation.many",{count:w.length})]}),e.jsx("div",{className:"mt-2 space-y-2",children:w.map((d,N)=>e.jsxs("div",{className:"border-l-2 border-[hsl(var(--deck-accent)/0.45)] pl-2",children:[e.jsx("div",{className:"font-mono text-[9.5px] uppercase text-[hsl(var(--deck-ink-faint))]",children:a("chat.input.annotation.item",{index:N+1})}),e.jsx("blockquote",{className:"mt-0.5 whitespace-pre-wrap text-[11px] leading-4 text-[hsl(var(--deck-ink-muted))]",children:d.text}),d.comment&&e.jsx("p",{className:"mt-1 text-[11px] leading-4 text-[hsl(var(--deck-ink))]",children:d.comment})]},d.id))})]}),k&&e.jsx("p",{className:"text-[14px] text-[hsl(var(--deck-ink))] font-mono leading-relaxed whitespace-pre-wrap",children:k}),p.length>0&&e.jsx("div",{className:I("grid gap-2",p.length===1?"grid-cols-1 mt-0":"grid-cols-2 mt-3"),children:p.map((d,N)=>e.jsx("img",{src:d,alt:`attachment-${N+1}`,className:"object-cover w-full max-h-64 rounded-md"},`${d}-${N}`))})]}),e.jsx(Ks,{})]})}const n=Hs(t),o=Ts((b=t.metadata)==null?void 0:b.codeReview),m=Ps((g=t.metadata)==null?void 0:g.structuredOutput);return e.jsxs("div",{"data-chat-message-id":t.id,"data-chat-role":"assistant",className:I("flex gap-4 justify-start w-full group",s?"p-4":"px-4 pt-0 pb-3"),children:[s?e.jsx(Us,{}):e.jsx("div",{className:"w-8 shrink-0"}),e.jsxs("div",{className:"overflow-hidden flex-1 min-w-0",children:[o?e.jsx(As,{report:o}):m?e.jsx(_s,{report:m}):e.jsx(ta,{message:t}),!m&&n.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(Ge,{text:n,label:"Copy response"})})]})]})}const aa=h.memo(sa),pe=8,Ze=10;function ra(t){return t instanceof HTMLElement&&!!t.closest('input, textarea, select, [contenteditable="true"], [role="textbox"]')}function na(){const t=window.visualViewport;return{left:(t==null?void 0:t.offsetLeft)??0,top:(t==null?void 0:t.offsetTop)??0,width:(t==null?void 0:t.width)??window.innerWidth,height:(t==null?void 0:t.height)??window.innerHeight}}function ia(t,s,a){const r=na(),i=r.left+pe,n=r.left+r.width-s-pe,o=t.left+t.width/2-s/2,m=Math.max(i,Math.min(Math.max(i,n),o)),x=t.bottom+Ze,l=t.top-a-Ze,b=r.top+r.height-a-pe,g=x<=b?x:Math.max(r.top+pe,Math.min(b,l));return{left:m,top:g}}function oa({rootRef:t,draftKey:s,canAskSideConversation:a,onOpenSideConversation:r}){const i=$(),n=h.useRef(null),o=h.useRef(null),m=h.useRef(!1),x=h.useRef("actions"),[l,b]=h.useState(null),[g,u]=h.useState("actions"),[k,p]=h.useState(""),[w,d]=h.useState(null),N=h.useCallback(T=>{m.current=!1,x.current=T,u(T),p("")},[]),f=h.useCallback(()=>{var T;m.current=!1,x.current="actions",u("actions"),p(""),b(null),d(null),(T=window.getSelection())==null||T.removeAllRanges()},[]),C=h.useCallback(T=>{var H,S;if(!l||l.tooLarge)return;const L=((S=(H=globalThis.crypto)==null?void 0:H.randomUUID)==null?void 0:S.call(H))??`selection-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,O=T==null?void 0:T.trim();Dt(s,{id:L,text:l.text,sourceMessageId:l.messageId,sourceRole:l.role,...O?{comment:O}:{}})&&f()},[f,s,l]),c=h.useCallback(()=>{!l||l.tooLarge||!a||r(l.text)&&f()},[a,f,r,l]),M=h.useCallback(()=>{if(x.current!=="actions")return;const T=t.current;if(!T)return;const L=Ft(T,window.getSelection());b(L),d(null)},[t]);if(h.useEffect(()=>{var S;let T=0;const L=()=>{window.cancelAnimationFrame(T),T=window.requestAnimationFrame(M)},O=E=>{var A;(A=n.current)!=null&&A.contains(E.target)||l&&(m.current=!1,x.current="actions",u("actions"),p(""),b(null))},_=E=>{var A;(A=n.current)!=null&&A.contains(E.target)||f()},H=E=>{if(!(!l||m.current||E.isComposing||E.keyCode===229)){if(E.key==="Escape"){E.preventDefault(),f();return}if(!(x.current!=="actions"||ra(E.target))){if((E.metaKey||E.ctrlKey)&&E.key.toLowerCase()==="j"){E.preventDefault(),N("comment");return}E.key==="Enter"&&(E.preventDefault(),C())}}};return document.addEventListener("selectionchange",L),document.addEventListener("pointerup",L),document.addEventListener("pointerdown",O),document.addEventListener("keydown",H),document.addEventListener("scroll",_,!0),window.addEventListener("resize",f),(S=window.visualViewport)==null||S.addEventListener("resize",f),()=>{var E;window.cancelAnimationFrame(T),document.removeEventListener("selectionchange",L),document.removeEventListener("pointerup",L),document.removeEventListener("pointerdown",O),document.removeEventListener("keydown",H),document.removeEventListener("scroll",_,!0),window.removeEventListener("resize",f),(E=window.visualViewport)==null||E.removeEventListener("resize",f)}},[C,M,f,l,N]),h.useLayoutEffect(()=>{if(!l||!n.current)return;const T=n.current.getBoundingClientRect();d(ia(l.rect,T.width,T.height))},[g,l]),h.useEffect(()=>{g!=="actions"&&requestAnimationFrame(()=>{var T;return(T=o.current)==null?void 0:T.focus()})},[g]),!l||typeof document>"u")return null;const D=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/u.test(navigator.userAgent)?"⌘ J":"Ctrl J",j=l.tooLarge?i("chat.selection.tooLarge"):a?void 0:i("chat.selection.sideUnavailable"),P={left:(w==null?void 0:w.left)??0,top:(w==null?void 0:w.top)??0,visibility:w?"visible":"hidden"},Z=T=>{if(!(m.current||T.nativeEvent.isComposing||T.keyCode===229)){if((T.metaKey||T.ctrlKey)&&T.key.toLocaleLowerCase()==="a"){T.preventDefault(),T.stopPropagation(),T.currentTarget.select();return}if(T.key==="Escape"){T.preventDefault(),f();return}T.key!=="Enter"||T.shiftKey||(T.preventDefault(),C(k))}};return Nt.createPortal(e.jsx("div",{ref:n,"data-chat-selection-overlay":!0,style:P,className:"fixed z-50 max-w-[calc(100vw-1rem)]",onPointerDown:T=>T.stopPropagation(),onPointerUp:T=>T.stopPropagation(),children:g==="actions"?e.jsxs("div",{role:"toolbar","aria-label":i("chat.selection.toolbar"),className:"grid min-w-[250px] overflow-hidden rounded-lg border border-[hsl(var(--deck-border-strong))] bg-[hsl(var(--deck-surface))]/98 text-[hsl(var(--deck-ink))] shadow-xl backdrop-blur-md divide-y divide-[hsl(var(--deck-border))] sm:flex sm:min-w-0 sm:divide-x sm:divide-y-0",onPointerDown:T=>T.preventDefault(),children:[e.jsxs("button",{type:"button","aria-keyshortcuts":"Meta+J Control+J",disabled:l.tooLarge,onClick:()=>N("comment"),className:"flex min-h-11 items-center gap-2 whitespace-nowrap px-3 text-left text-[12px] transition-colors hover:bg-[hsl(var(--deck-surface-2))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[hsl(var(--deck-accent))] disabled:cursor-not-allowed disabled:opacity-45",children:[e.jsx(lt,{"aria-hidden":!0,className:"h-4 w-4 shrink-0"}),e.jsx("span",{children:i("chat.selection.comment")}),e.jsx("kbd",{className:"ml-auto font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:D})]}),e.jsxs("button",{type:"button","aria-keyshortcuts":"Enter",disabled:l.tooLarge,onClick:()=>C(),className:"flex min-h-11 items-center gap-2 whitespace-nowrap px-3 text-left text-[12px] transition-colors hover:bg-[hsl(var(--deck-surface-2))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[hsl(var(--deck-accent))] disabled:cursor-not-allowed disabled:opacity-45",children:[e.jsx(Xt,{"aria-hidden":!0,className:"h-4 w-4 shrink-0"}),e.jsx("span",{children:i("chat.selection.add")}),e.jsx("kbd",{className:"ml-auto font-mono text-[11px] text-[hsl(var(--deck-ink-faint))]",children:"↵"})]}),e.jsxs("button",{type:"button",disabled:!!j,title:j,onClick:c,className:"flex min-h-11 items-center gap-2 whitespace-nowrap px-3 text-left text-[12px] transition-colors hover:bg-[hsl(var(--deck-surface-2))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[hsl(var(--deck-accent))] disabled:cursor-not-allowed disabled:opacity-45",children:[e.jsx(De,{"aria-hidden":!0,className:"h-4 w-4 shrink-0"}),e.jsx("span",{children:i("chat.selection.askSide")})]})]}):e.jsxs("form",{role:"dialog","aria-label":i("chat.selection.commentDialog"),className:"w-[min(360px,calc(100vw-1rem))] rounded-lg border border-[hsl(var(--deck-border-strong))] bg-[hsl(var(--deck-surface))] p-2 shadow-xl",onSubmit:T=>{T.preventDefault(),C(k)},children:[e.jsx("div",{className:"mb-2 line-clamp-2 border-l-2 border-[hsl(var(--deck-accent)/0.55)] pl-2 font-mono text-[10.5px] leading-4 text-[hsl(var(--deck-ink-muted))]",children:l.text}),e.jsx("textarea",{ref:o,name:"selected-conversation-comment",maxLength:qt,rows:3,value:k,onChange:T=>p(T.target.value),onCompositionStart:()=>{m.current=!0},onCompositionEnd:()=>{m.current=!1},onBlur:()=>{m.current=!1},onKeyDown:Z,"aria-label":i("chat.selection.commentInput"),placeholder:i("chat.selection.commentPlaceholder"),className:"block max-h-32 min-h-[72px] w-full resize-none rounded-md border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-canvas))] px-2.5 py-2 text-[12px] leading-5 text-[hsl(var(--deck-ink))] placeholder:text-[hsl(var(--deck-ink-faint))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]"}),e.jsxs("div",{className:"mt-2 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:f,className:"h-8 rounded-md px-2.5 text-[11px] text-[hsl(var(--deck-ink-muted))] transition-colors hover:bg-[hsl(var(--deck-surface-2))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:i("chat.selection.cancel")}),e.jsxs("button",{type:"submit",className:"inline-flex h-8 items-center gap-1.5 rounded-md bg-[hsl(var(--deck-accent))] px-3 text-[11px] font-medium text-white transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--deck-accent))] focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-45",children:[i("chat.selection.add"),e.jsx(cs,{"aria-hidden":!0,className:"h-3 w-3"})]})]})]})}),document.body)}function ca(t,s,a){return Math.max(0,t+(a-s))}function la(t,s,a){return Math.min(s,Math.max(0,t)+Math.max(0,a))}function da(t,s,a,r){const i=new Map(t.filter(o=>!!o.id).map(o=>[o.id,o])),n=new Set(a);for(const o of s){if(!o.id)continue;const m=i.get(o.id);m!==o&&(!m||!r||r(m)!==r(o))&&n.add(o.id)}return n}function et(t,s){return t?t.querySelector(`[data-chat-message-id="${CSS.escape(s)}"]`):null}function ua({turns:t,viewportRef:s,containerRef:a,onRevealTurn:r}){const i=$(),[n,o]=h.useState(null),[m,x]=h.useState(!1),l=h.useRef(null),b=h.useCallback(()=>{var d;const u=s.current,k=a.current;if(!u||!k||t.length===0)return;const p=u.getBoundingClientRect().top;let w=((d=t[0])==null?void 0:d.id)??null;for(const N of t){const f=et(k,N.id);if(f)if(f.getBoundingClientRect().top-p<=24)w=N.id;else break}o(w)},[t,s,a]);h.useEffect(()=>{const u=s.current;if(!u)return;const k=()=>{l.current===null&&(l.current=window.requestAnimationFrame(()=>{l.current=null,b()}))};return b(),u.addEventListener("scroll",k,{passive:!0}),()=>{u.removeEventListener("scroll",k),l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null)}},[b,s]);const g=h.useCallback(u=>{const k=()=>{const w=et(a.current,u.id);w&&(w.scrollIntoView({behavior:"smooth",block:"start"}),o(u.id))};r(u.index)?k():window.requestAnimationFrame(()=>window.requestAnimationFrame(k))},[a,r]);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:()=>x(!0),onMouseLeave:()=>x(!1),onFocusCapture:()=>x(!0),onBlurCapture:u=>{u.currentTarget.contains(u.relatedTarget)||x(!1)},children:e.jsxs("div",{className:"relative flex items-center justify-end",children:[e.jsx("ul",{className:I("flex flex-col items-center gap-2 py-2 transition-opacity",m?"opacity-0":"opacity-100"),"aria-hidden":m,children:t.map(u=>e.jsx("li",{children:e.jsx("span",{className:I("block rounded-full transition-all",u.id===n?"h-2 w-2 bg-[hsl(var(--deck-accent))]":"h-1.5 w-1.5 bg-[hsl(var(--deck-ink-faint))]/40")})},u.id))}),e.jsx("div",{className:I("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",m?"pointer-events-auto translate-x-0 opacity-100":"pointer-events-none translate-x-2 opacity-0"),children:t.map((u,k)=>e.jsxs("button",{type:"button",onClick:()=>g(u),className:I("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors",u.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:I("mt-1 h-1.5 w-1.5 shrink-0 rounded-full",u.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:k+1})}),e.jsx("span",{className:"line-clamp-2 text-[12px] leading-4",children:u.preview})]})]},u.id))})]})})}const tt=80;function ma(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(s=>s.type==="text").map(s=>s.text).join(" "):""}function ha(t){const s=ma(t).replace(/\s+/g," ").trim();return s?s.length>tt?`${s.slice(0,tt-1)}…`:s:""}function xa(t){const s=[];for(let a=0;a<t.length;a+=1){const r=t[a];if(r.role!=="user"||!r.id)continue;const i=ha(r.content);i&&s.push({id:r.id,index:a,preview:i})}return s}const Ee=120,Te=80,pa=96;function de(t){return(t==null?void 0:t.querySelector("[data-radix-scroll-area-viewport]"))??null}function fa(t){return JSON.stringify([t.role,t.content,t.metadata,t.agentContent])}function ba({messages:t,isLoading:s,selectionDraftKey:a,canAskSideConversation:r=!1,onOpenSideConversation:i}){const n=$(),o=h.useMemo(()=>ws(t),[t]),m=h.useRef(new Map);h.useEffect(()=>{if(s)return;const S=new Set(t.flatMap(E=>{var A;return((A=E.agentContent)==null?void 0:A.toolCalls.map(U=>U.toolCallId))??[]}));for(const E of m.current.keys())S.has(E)||m.current.delete(E)},[t,s]);const x=h.useRef(null),l=h.useRef(null),b=h.useRef(!0),g=h.useRef(!1),u=h.useRef(o),k=h.useRef(o),p=h.useRef(new Set),w=h.useRef(o.length),d=h.useRef(null),[N,f]=h.useState(Ee),[C,c]=h.useState(!1),[M,R]=h.useState(0),D=o.length>0;u.current=o,h.useEffect(()=>{const S=de(x.current);if(!S||g.current&&!b.current)return;const E=window.requestAnimationFrame(()=>{S.scrollTop=S.scrollHeight,g.current=!0,b.current=!0,p.current=new Set,R(0),c(!1)});return()=>window.cancelAnimationFrame(E)},[o]),h.useEffect(()=>{const S=de(x.current);if(!S)return;l.current=S;const E=()=>{if(!g.current)return;const U=S.scrollHeight-S.scrollTop-S.clientHeight<=pa,G=b.current;b.current=U,c(!U),U?(p.current=new Set,R(0)):G&&(k.current=u.current,p.current=new Set,R(0))};return E(),S.addEventListener("scroll",E,{passive:!0}),()=>S.removeEventListener("scroll",E)},[D,s]),h.useEffect(()=>{const S=k.current;if(k.current=o,b.current){p.current.size>0&&(p.current=new Set,R(0));return}const E=da(S,o,p.current,fa);p.current=E,R(E.size)},[o]),h.useEffect(()=>{const S=w.current;w.current=o.length,f(E=>E>=S&&o.length>S?o.length:Math.min(Math.max(E,Ee),o.length||Ee))},[o.length]);const j=Math.max(o.length-N,0),P=j,Z=h.useMemo(()=>o.slice(P),[o,P]),T=h.useMemo(()=>xa(o),[o]);if(h.useLayoutEffect(()=>{var A;const S=d.current;if(!S)return;const E=de(x.current);if(d.current=null,!!E){if((A=S.element)!=null&&A.isConnected){const U=S.element.getBoundingClientRect().top-S.viewportTop;E.scrollTop+=U;return}E.scrollTop=ca(S.scrollTop,S.scrollHeight,E.scrollHeight)}},[N]),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(Re,{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(It,{className:"w-3 h-3"}),n("chat.list.loading.eyebrow")]}),e.jsx("h2",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:n("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:n("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,E)=>e.jsxs("div",{className:I("flex gap-3",E%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:`${E*120}ms`}})]},S))})]})});if(o.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(Re,{size:44}),e.jsxs("div",{children:[e.jsx("div",{className:"deck-eyebrow text-[hsl(var(--deck-accent))]",children:n("chat.list.empty.eyebrow")}),e.jsx("div",{className:"mt-2 text-[15px] font-medium text-[hsl(var(--deck-ink))]",children:n("chat.list.empty.title")}),e.jsx("div",{className:"mt-1 max-w-xs text-[12px] text-[hsl(var(--deck-ink-muted))]",children:n("chat.list.empty.hint")})]})]})});const L=()=>{const S=de(x.current);S&&(S.scrollTop=S.scrollHeight,b.current=!0,g.current=!0,p.current=new Set,R(0),c(!1))},O=()=>{var E;const S=de(x.current);if(S){const A=((E=x.current)==null?void 0:E.querySelector("[data-chat-message-id]"))??null;d.current={element:A,viewportTop:(A==null?void 0:A.getBoundingClientRect().top)??0,scrollHeight:S.scrollHeight,scrollTop:S.scrollTop}}f(A=>la(A,o.length,Te))},_=S=>S>=P?!0:(f(o.length),!1),H=M===1?n("chat.list.unreadMessage"):n("chat.list.unreadMessages",{count:M});return e.jsxs("div",{ref:x,className:"relative flex-1 min-h-0",children:[e.jsx(Yt,{className:"h-full",children:e.jsxs("div",{className:"flex flex-col px-4 pb-4 w-full md:px-6",children:[j>0&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx("button",{type:"button",onClick:O,"aria-label":n("chat.list.showEarlierWithRemaining",{count:Math.min(j,Te),remaining:j}),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:n("chat.list.showEarlier",{count:Math.min(j,Te)})})}),Z.map((S,E)=>{const A=P+E,U=A>0?o[A-1]:null,G=!U||U.role!==S.role||U.role==="user";return e.jsx(Ue.Provider,{value:m.current,children:e.jsx(aa,{message:S,showAvatar:G})},S.id||`msg-${A}`)})]})}),e.jsx(ua,{turns:T,viewportRef:l,containerRef:x,onRevealTurn:_}),a&&i&&e.jsx(oa,{rootRef:x,draftKey:a,canAskSideConversation:r,onOpenSideConversation:i}),C&&e.jsxs("button",{type:"button",onClick:L,"aria-live":"polite","aria-label":M>0?H:n("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(Oe,{className:"h-3.5 w-3.5 text-[hsl(var(--deck-accent))]"}),M>0?H:n("chat.list.jumpLatest")]})]})}const yt=h.memo(ba);function va({queue:t,mutation:s,onMutate:a,onRefresh:r}){const i=$(),[n,o]=h.useState(!1),m=h.useRef(null),x=h.useRef(null),l=h.useRef(null);h.useLayoutEffect(()=>{var p,w,d;if(s.pending||!m.current)return;const u=m.current;m.current=null,(d=Array.from(((p=x.current)==null?void 0:p.querySelectorAll("[data-follow-up-focus-id]"))??[]).find(N=>N.dataset.followUpFocusId===u)??((w=x.current)==null?void 0:w.querySelector("button")))==null||d.focus()},[s.pending,t==null?void 0:t.version]);const b=h.useCallback(async u=>{m.current=u.messageId,await a(u)},[a]),g=h.useCallback((u,k)=>{b({type:"move",messageId:u,toPosition:k})},[b]);return!t||t.pending===0&&!s.errorMessage?null:e.jsxs("section",{ref:x,"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:()=>o(u=>!u),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(ms,{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(ce,{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}),r&&e.jsx("button",{type:"button","aria-label":i("chat.followUpQueue.refresh"),onClick:()=>void r(),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(ut,{className:"h-3.5 w-3.5","aria-hidden":!0})})]}),e.jsx("ol",{className:"space-y-1.5",children:t.items.map((u,k)=>{const p=t.items[k-1],w=t.items[k+1],d=u.mutable&&(p==null?void 0:p.mutable)===!0,N=u.mutable&&(w==null?void 0:w.mutable)===!0,f=s.pending;return e.jsxs("li",{"data-follow-up-id":u.id,"data-follow-up-state":u.state,"data-follow-up-focus-id":u.id,tabIndex:-1,draggable:u.mutable&&!s.pending,onDragStart:()=>{l.current=u.mutable?u.id:null},onDragOver:C=>{const c=l.current,M=t.items.find(R=>R.id===c);M!=null&&M.mutable&&u.mutable&&C.preventDefault()},onDrop:C=>{C.preventDefault();const c=l.current;l.current=null;const M=t.items.find(j=>j.id===c);if(!(M!=null&&M.mutable)||!u.mutable||M.id===u.id)return;const R=Math.min(M.position,u.position),D=Math.max(M.position,u.position);t.items.slice(R,D+1).some(j=>!j.mutable)||g(M.id,u.position)},onDragEnd:()=>{l.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:k+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-xs text-[hsl(var(--deck-ink))]",children:u.kind==="internal"?i("chat.followUpQueue.internal"):u.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.${u.delivery}`)}),!u.mutable&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(hs,{className:"h-2.5 w-2.5","aria-hidden":!0}),i("chat.followUpQueue.locked")]}),u.attachmentCount>0&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Lt,{className:"h-2.5 w-2.5","aria-hidden":!0}),u.attachmentCount]})]})]}),f&&s.messageId===u.id?e.jsx(K,{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:u.id}),disabled:f||!d,onClick:()=>g(u.id,k-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(Zt,{className:"h-3.5 w-3.5","aria-hidden":!0})}),e.jsx("button",{type:"button","aria-label":i("chat.followUpQueue.moveDown",{id:u.id}),disabled:f||!N,onClick:()=>g(u.id,k+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(Oe,{className:"h-3.5 w-3.5","aria-hidden":!0})}),e.jsx("button",{type:"button","aria-label":i("chat.followUpQueue.remove",{id:u.id}),disabled:f||!u.mutable,onClick:()=>void b({type:"remove",messageId:u.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(ie,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})]},u.id)})})]})]})}const Ie=ts,Le=ss,Be=as,ye=h.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(ft,{ref:r,sideOffset:s,className:I("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),...a}));ye.displayName=ft.displayName;const ga={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 fe(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function ka(t){if(t<60)return`${t}s`;const s=Math.floor(t/60),a=t%60;return a===0?`${s}m`:`${s}m ${a}s`}function ya(){var T,L,O,_,H,S,E,A,U,G,F,J,Y,W,q,V,X,te,le,xe;const t=$(),{locale:s}=mt(),a=v(B=>B.goal),r=v(B=>B.pauseGoal),i=v(B=>B.resumeGoal),n=v(B=>B.editGoal),o=v(B=>B.clearGoal),m=v(B=>oe(B.historySurfaceSelection)),[x,l]=h.useState(!1),[b,g]=h.useState(!1),[u,k]=h.useState(""),[p,w]=h.useState(null),[d,N]=h.useState(!1);if(h.useEffect(()=>{l(!1),g(!1),k((a==null?void 0:a.objective)??""),N(!1)},[a==null?void 0:a.goalId]),m||!a)return null;const f=ga[a.status],C=["active","verifying","paused","blocked"].includes(a.status),c=a.status==="active"||a.status==="verifying",M=a.status==="paused"||a.status==="blocked",R=p!==null,D=async(B,se)=>{if(!Q(v.getState())){w(B);try{await se()}finally{w(null)}}},j=()=>{k(a.objective),g(!0),l(!0)},P=async B=>{B.preventDefault();const se=u.trim();if(!se||se===a.objective){g(!1);return}await D("edit",()=>n(se)),g(!1)},Z=async()=>{await D("delete",o),N(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(Ie,{delayDuration:250,children:e.jsxs("section",{"aria-label":t("goal.aria.section"),className:"mx-3 mb-1 shrink-0","data-blade-goal-status":a.status,"data-blade-goal-recovery":(T=a.prematureStop)==null?void 0:T.consecutiveCount,"data-blade-goal-recovery-pattern":(L=a.prematureStop)==null?void 0:L.pattern,"data-blade-goal-verification-stall":(O=a.verificationStall)==null?void 0:O.consecutiveCount,"data-blade-goal-frontier-task-list":(_=a.executionFrontier)==null?void 0:_.taskListId,"data-blade-goal-frontier-total":(H=a.executionFrontier)==null?void 0:H.total,"data-blade-goal-frontier-completed":(S=a.executionFrontier)==null?void 0:S.completed,"data-blade-goal-frontier-in-progress":(E=a.executionFrontier)==null?void 0:E.inProgress,"data-blade-goal-frontier-pending":(A=a.executionFrontier)==null?void 0:A.pending,"data-blade-goal-frontier-blocked":(U=a.executionFrontier)==null?void 0:U.blocked,"data-blade-goal-frontier-next-task":(F=(G=a.executionFrontier)==null?void 0:G.nextTask)==null?void 0:F.id,"data-blade-goal-frontier-digest":(J=a.executionFrontier)==null?void 0:J.digestSha256.slice(0,16),"data-blade-goal-frontier-stall":(Y=a.frontierStall)==null?void 0:Y.category,"data-blade-goal-frontier-stall-count":(W=a.frontierStall)==null?void 0:W.consecutiveCount,"data-blade-goal-execution-host-failure":(q=a.executionHostFailure)==null?void 0:q.category,"data-blade-goal-execution-host-failure-count":(V=a.executionHostFailure)==null?void 0:V.consecutiveCount,"data-blade-goal-root-turn":(X=a.turnLineage)==null?void 0:X.rootTurnId,"data-blade-goal-current-turn":(te=a.turnLineage)==null?void 0:te.currentTurnId,"data-blade-goal-parent-turn":(le=a.turnLineage)==null?void 0:le.parentTurnId,children:[e.jsxs("div",{className:I("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",x&&"rounded-b-none border-b-0"),children:[a.status==="complete"?e.jsx(Bt,{className:"h-3.5 w-3.5 shrink-0 text-emerald-500"}):e.jsx(xs,{className:I("h-3.5 w-3.5 shrink-0",f.accent)}),e.jsx("span",{className:I("h-1.5 w-1.5 shrink-0 rounded-full",f.dot)}),e.jsx("span",{className:I("shrink-0 text-[10px] font-medium leading-none",f.accent),children:a.status==="verifying"?s==="zh"?"验证中":"Verifying":t(f.labelKey)}),e.jsx("span",{className:"h-3 w-px shrink-0 bg-[hsl(var(--deck-hairline))]"}),e.jsx("button",{type:"button","aria-label":t(x?"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:()=>l(B=>!B),"aria-expanded":x,title:a.objective,children:a.objective}),a.tokensUsed>0&&e.jsxs("span",{className:"hidden shrink-0 text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))] sm:inline",children:[fe(a.tokensUsed),a.tokenBudget!==void 0&&`/${fe(a.tokenBudget)}`]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[c&&e.jsx(be,{label:t("goal.action.pause"),disabled:R,onClick:()=>void D("pause",r),children:p==="pause"?e.jsx(K,{className:"animate-spin"}):e.jsx(rs,{})}),M&&e.jsx(be,{label:t("goal.action.resume"),disabled:R,onClick:()=>void D("resume",i),children:p==="resume"?e.jsx(K,{className:"animate-spin"}):e.jsx(ns,{})}),e.jsx(be,{label:t(C?"goal.action.edit":"goal.action.expand"),disabled:!C&&!x,onClick:C?j:()=>l(B=>!B),children:C?e.jsx(bt,{}):e.jsx(es,{})}),e.jsx(be,{label:t("goal.action.delete"),disabled:R,destructive:!0,onClick:()=>N(!0),children:e.jsx(ie,{})})]})]}),x&&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:b?e.jsxs("form",{onSubmit:P,children:[e.jsx("textarea",{id:"goal-objective",value:u,onChange:B=>k(B.target.value),onKeyDown:B=>{B.key==="Escape"&&g(!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:()=>g(!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(ht,{className:"h-3 w-3"}),t("goal.action.cancel")]}),e.jsxs("button",{type:"submit",disabled:!u.trim()||p==="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:[p==="edit"?e.jsx(K,{className:"h-3 w-3 animate-spin"}):e.jsx(je,{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:a.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(ds,{className:"h-3 w-3"}),fe(a.tokensUsed),a.tokenBudget!==void 0&&` / ${fe(a.tokenBudget)}`," ",t("goal.metrics.tokens")]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ps,{className:"h-3 w-3"}),ka(a.timeUsedSeconds)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ve,{className:"h-3 w-3"}),a.continuationCount===1?t("goal.metrics.continuationOne",{n:a.continuationCount}):t("goal.metrics.continuationMany",{n:a.continuationCount})]})]}),a.turnLineage&&e.jsxs("div",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-md border border-[hsl(var(--deck-border))]/50 bg-[hsl(var(--deck-canvas))]/45 px-2.5 py-2 font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx("span",{children:t("goal.lineage.origin")}),e.jsx("span",{className:"truncate",children:a.turnLineage.rootTurnId??"?"}),e.jsx("span",{children:t("goal.lineage.current")}),e.jsx("span",{className:"truncate",children:a.turnLineage.currentTurnId}),e.jsx("span",{children:t("goal.lineage.parent")}),e.jsx("span",{className:"truncate",children:a.turnLineage.parentTurnId??"?"})]}),a.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(ve,{className:"h-3 w-3"}),s==="zh"?"恢复提示":"Recovery nudge"," ",a.prematureStop.consecutiveCount," ·"," ",a.prematureStop.pattern.replaceAll("_"," ")]}),a.executionHostFailure&&e.jsxs("div",{className:"mt-2 rounded-md border border-amber-200/50 bg-amber-50/60 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-400/15 dark:bg-amber-400/[0.05] dark:text-amber-100",children:[e.jsx("p",{className:"font-medium",children:t("goal.executionHostFailure.title")}),e.jsxs("p",{className:"mt-1 font-mono opacity-80",children:[t(`goal.executionHostFailure.category.${a.executionHostFailure.category}`)," ","· ",a.executionHostFailure.consecutiveCount,"/3"]})]}),a.completionVerification&&e.jsxs("div",{"data-goal-verification":a.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:["#",a.completionVerification.attempt," ·"," ",a.completionVerification.status.toUpperCase()," ·"," ",((xe=a.completionVerification.verifierSessionId)==null?void 0:xe.slice(0,12))??"-",a.verificationStall?s==="zh"?` · 重复 ${a.verificationStall.consecutiveCount}/3`:` · repeat ${a.verificationStall.consecutiveCount}/3`:""]}),a.completionVerification.summary&&e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap opacity-80",children:a.completionVerification.summary}),a.completionVerification.evidenceSha256&&e.jsxs("p",{className:"mt-1 font-mono text-[10px] opacity-60",children:["sha256:",a.completionVerification.evidenceSha256.slice(0,12)]})]}),a.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:a.statusReason})]})})]})}),e.jsx(rt,{open:d,onOpenChange:N,children:e.jsxs(nt,{className:"max-w-[400px] border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))]",children:[e.jsx(it,{children:t("goal.dialog.title")}),e.jsx(ot,{children:t("goal.dialog.description")}),e.jsxs(ct,{className:"mt-2",children:[e.jsx("button",{type:"button",onClick:()=>N(!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:p==="delete",onClick:()=>void Z(),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:[p==="delete"&&e.jsx(K,{className:"w-3.5 h-3.5 animate-spin"}),t("goal.action.delete")]})]})]})})]})}function be({label:t,children:s,disabled:a,destructive:r,onClick:i}){return e.jsxs(Le,{children:[e.jsx(Be,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":t,disabled:a,onClick:i,className:I("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",r?"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(ye,{side:"top",className:"text-[10px]",children:t})]})}function ja(){const t=$(),s=v(l=>l.currentSessionRef),a=v(l=>l.sessions),r=v(l=>l.messages),i=v(l=>oe(l.historySurfaceSelection)),n=h.useMemo(()=>{var b,g,u,k,p;const l=s?(b=$t(a,s))==null?void 0:b.pendingInteraction:void 0;if(l)return l.type;for(let w=r.length-1;w>=0;w-=1){const d=(g=r[w])==null?void 0:g.agentContent;if(((u=d==null?void 0:d.confirmation)==null?void 0:u.status)==="pending")return"permission";if(((k=d==null?void 0:d.question)==null?void 0:k.status)==="pending")return"question";if(((p=d==null?void 0:d.elicitation)==null?void 0:p.status)==="pending")return"elicitation"}return null},[s,r,a]);if(i||!n)return null;const o=()=>{const l=document.querySelector(`[data-pending-interaction="${n}"]`);l==null||l.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>l==null?void 0:l.focus(),250)},m=n==="question",x=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(Pe,{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(m?"interaction.bar.questionTitle":x?"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(m?"interaction.bar.questionHint":x?"interaction.bar.elicitationHint":"interaction.bar.permissionHint")})]}),e.jsxs("button",{type:"button",onClick:o,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(Oe,{className:"h-3 w-3"}),t("interaction.bar.review")]})]})}function me(t){return Math.max(0,Math.ceil((t??0)/1e3))}function wa(t,s=Date.now()){var r;const a=(r=t.snapshot)==null?void 0:r.nextActionAt;return a===void 0?void 0:me(a-s)}function jt(t,s=Date.now()){const a=t==null?void 0:t.snapshot;if(!a)return null;const r=wa(t,s)??0,i=a.retry,n=a.admission,o=a.stall,m=a.fallback,x={seconds:r,attempt:(i==null?void 0:i.attempt)??0,maxRetries:(i==null?void 0:i.maxRetries)??0,budgetSeconds:me(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:me(n==null?void 0:n.waitMs),stallSeconds:me(o==null?void 0:o.durationMs),timeoutSeconds:me(o==null?void 0:o.timeoutMs),from:(m==null?void 0:m.from.model)??"",to:(m==null?void 0:m.to.model)??"",candidate:(m==null?void 0:m.candidate)??0,candidateCount:(m==null?void 0:m.candidateCount)??0};switch(a.activity){case"admission_wait":return{titleKey:"chat.providerRecovery.admission",detailKey:"chat.providerRecovery.admissionDetail",compactKey:"chat.providerRecovery.admissionCompact",params:x};case"retry_wait":return{titleKey:a.reason==="rate_limit"?"chat.providerRecovery.rateLimit":"chat.providerRecovery.retryWait",detailKey:"chat.providerRecovery.retryDetail",compactKey:"chat.providerRecovery.retryCompact",params:x};case"retry_attempt":return{titleKey:"chat.providerRecovery.retryAttempt",detailKey:"chat.providerRecovery.retryDetail",compactKey:"chat.providerRecovery.retryCompact",params:x};case"circuit_open":return{titleKey:a.reason==="rate_limit"?"chat.providerRecovery.rateLimitCircuit":"chat.providerRecovery.circuit",detailKey:"chat.providerRecovery.circuitDetail",compactKey:a.reason==="rate_limit"?"chat.providerRecovery.rateLimitCircuitCompact":"chat.providerRecovery.circuitCompact",params:x};case"circuit_probe":return{titleKey:"chat.providerRecovery.probe",detailKey:"chat.providerRecovery.probeDetail",compactKey:"chat.providerRecovery.probeCompact",params:x};case"stream_stall":return{titleKey:o!=null&&o.outputStarted?"chat.providerRecovery.stallAfterOutput":"chat.providerRecovery.stall",detailKey:"chat.providerRecovery.stallDetail",compactKey:"chat.providerRecovery.stallCompact",params:x};case"fallback":return{titleKey:"chat.providerRecovery.fallback",detailKey:"chat.providerRecovery.fallbackDetail",compactKey:"chat.providerRecovery.fallbackCompact",params:x}}}function Na({recovery:t,stopping:s,onStop:a}){var x;const r=$(),[i,n]=h.useState(Date.now()),o=(x=t==null?void 0:t.snapshot)==null?void 0:x.nextActionAt;h.useEffect(()=>{if(o===void 0)return;n(Date.now());const l=window.setInterval(()=>n(Date.now()),1e3);return()=>window.clearInterval(l)},[o]);const m=jt(t,i);return m?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(K,{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:r(m.titleKey,m.params)}),e.jsx("div",{className:"mt-0.5 truncate font-mono text-[10px] opacity-80",children:r(m.detailKey,m.params)})]}),e.jsxs("button",{type:"button","data-provider-recovery-stop":!0,onClick:a,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(K,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}):e.jsx(Pt,{className:"h-3 w-3 fill-current","aria-hidden":!0}),r(s?"chat.input.action.stopping":"chat.providerRecovery.stop")]})]}):null}const Sa=h.lazy(()=>dt(()=>import("./MarkdownRenderer-DS7RznBE.js").then(t=>t.M),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.MarkdownRenderer})));function Ca(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Ea(t,s){return t?[{id:"legacy-user",role:"user",content:t},...s?[{id:"legacy-assistant",role:"assistant",content:s}]:[]]:[]}function Me(t){return t?JSON.stringify([t.sessionRef.projectPath,t.sessionRef.sessionId,t.requestId]):null}function Ta(){const t=$(),s=v(d=>d.sideConversation),a=v(d=>d.askSideConversation),r=v(d=>d.openSideConversation),i=v(d=>d.dismissSideConversation),n=Me(s),[o,m]=h.useState({owner:n,text:""}),x=o.owner===n?o.text:"";o.owner!==n&&m({owner:n,text:""});const l=d=>m({owner:n,text:d}),b=h.useRef(null),g=h.useRef(!1),u=h.useRef(null),k=h.useMemo(()=>(s==null?void 0:s.messages)??Ea((s==null?void 0:s.question)??"",s==null?void 0:s.response),[s==null?void 0:s.messages,s==null?void 0:s.question,s==null?void 0:s.response]);if(h.useEffect(()=>{if(g.current=!1,!s||s.status==="loading")return;const d=document.activeElement;if(s.status!=="idle"&&d instanceof HTMLElement&&d!==b.current&&d.matches('input, textarea, select, [contenteditable="true"]'))return;const N=requestAnimationFrame(()=>{var f;document.activeElement===d&&((f=b.current)==null||f.focus())});return()=>cancelAnimationFrame(N)},[s==null?void 0:s.sessionRef,s==null?void 0:s.selectedText,s==null?void 0:s.status]),h.useEffect(()=>{var d,N;(N=(d=u.current)==null?void 0:d.scrollIntoView)==null||N.call(d,{block:"nearest"})},[k.length,s==null?void 0:s.status]),!s)return null;const p=()=>{const d=x.trim();if(!d||s.status==="loading")return;l("");const N=a(d),f=Me(v.getState().sideConversation);N.then(C=>{!C&&f!==null&&Me(v.getState().sideConversation)===f&&m({owner:f,text:d})})},w=d=>{if(!(g.current||d.nativeEvent.isComposing||d.keyCode===229)){if((d.metaKey||d.ctrlKey)&&d.key.toLocaleLowerCase()==="a"){d.preventDefault(),d.stopPropagation(),d.currentTarget.select();return}if(d.key==="Escape"){d.preventDefault(),i();return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),p())}};return e.jsxs("aside",{"aria-label":t("chat.side.title"),"data-blade-side-conversation":!0,"data-status":s.status,className:"absolute inset-0 z-30 flex min-h-0 flex-col bg-[hsl(var(--deck-canvas))] md:relative md:inset-auto md:w-[min(420px,42vw)] md:shrink-0 md:border-l md:border-[hsl(var(--deck-hairline))]",children:[e.jsxs("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-[hsl(var(--deck-hairline))] px-3",children:[e.jsx(De,{"aria-hidden":!0,className:"h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))]"}),e.jsx("h2",{className:"min-w-0 flex-1 truncate text-[13px] font-medium text-[hsl(var(--deck-ink))]",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(is,{"aria-hidden":!0,className:"h-3 w-3"}),Ca(s.durationMs)]}),e.jsx("button",{type:"button",onClick:()=>{l(""),r()},"aria-label":t("chat.side.new"),title:t("chat.side.new"),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface-2))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:e.jsx(os,{"aria-hidden":!0,className:"h-4 w-4"})}),e.jsx("button",{type:"button",onClick:i,"aria-label":t("chat.side.dismiss"),title:t("chat.side.dismiss"),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-[hsl(var(--deck-ink-faint))] transition-colors hover:bg-[hsl(var(--deck-surface-2))] hover:text-[hsl(var(--deck-ink))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:e.jsx(ht,{"aria-hidden":!0,className:"h-4 w-4"})})]}),e.jsxs("div",{"aria-live":"polite","aria-busy":s.status==="loading",className:"min-h-0 flex-1 space-y-4 overflow-y-auto px-4 py-4",children:[s.selectedText&&e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"inline-flex min-h-8 cursor-pointer list-none items-center gap-1.5 rounded-md border border-[hsl(var(--deck-border-strong))] bg-[hsl(var(--deck-surface))] px-2.5 font-mono text-[10.5px] text-[hsl(var(--deck-ink-muted))] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[hsl(var(--deck-accent))]",children:[e.jsx(De,{"aria-hidden":!0,className:"h-3.5 w-3.5"}),t("chat.side.selectedText")]}),e.jsx("blockquote",{className:"mt-2 whitespace-pre-wrap border-l-2 border-[hsl(var(--deck-accent)/0.45)] pl-3 font-mono text-[11px] leading-5 text-[hsl(var(--deck-ink-muted))]",children:s.selectedText})]}),k.map(d=>d.role==="user"?e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[88%] rounded-lg bg-[hsl(var(--deck-surface-2))] px-3 py-2 text-[12px] leading-5 text-[hsl(var(--deck-ink))]",children:d.content})},d.id):e.jsx("div",{className:"min-w-0",children:e.jsx(h.Suspense,{fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words text-[12px] leading-5 text-[hsl(var(--deck-ink))]",children:d.content}),children:e.jsx(Sa,{content:d.content,className:"text-[12px] leading-5 [&_h1]:text-[14px] [&_h2]:text-[13px] [&_h3]:text-[12px]"})})},d.id)),s.status==="loading"&&e.jsxs("div",{role:"status",className:"flex min-h-9 items-center gap-2 text-[11px] text-[hsl(var(--deck-ink-muted))]",children:[e.jsx(K,{"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 text-[11px] leading-5 text-red-700 dark:text-red-300",children:[e.jsx(Pe,{"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")})]}),e.jsx("div",{ref:u})]}),e.jsx("div",{className:"shrink-0 border-t border-[hsl(var(--deck-hairline))] p-3",children:e.jsxs("div",{className:"rounded-lg border border-[hsl(var(--deck-border))] bg-[hsl(var(--deck-surface))] focus-within:border-[hsl(var(--deck-border-strong))] focus-within:ring-1 focus-within:ring-[hsl(var(--deck-border-strong))]",children:[e.jsx("textarea",{ref:b,name:"side-conversation-composer",value:x,onChange:d=>l(d.target.value),onCompositionStart:()=>{g.current=!0},onCompositionEnd:()=>{g.current=!1},onBlur:()=>{g.current=!1},onKeyDown:w,rows:3,disabled:s.status==="loading","aria-label":t("chat.side.input"),placeholder:t("chat.side.placeholder"),className:"block max-h-40 min-h-[88px] w-full resize-none bg-transparent px-3 py-2.5 text-[13px] leading-5 text-[hsl(var(--deck-ink))] placeholder:text-[hsl(var(--deck-ink-faint))] focus:outline-none disabled:cursor-wait disabled:opacity-60"}),e.jsx("div",{className:"flex items-center justify-end px-2 pb-2",children:e.jsx("button",{type:"button",onClick:p,disabled:!x.trim()||s.status==="loading","aria-label":t("chat.side.send"),title:t("chat.side.send"),className:"flex h-8 w-8 items-center justify-center rounded-md bg-[hsl(var(--deck-ink))] text-[hsl(var(--deck-canvas))] transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--deck-accent))] focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-35",children:e.jsx($e,{"aria-hidden":!0,className:"h-3.5 w-3.5"})})})]})})]})}function Ae(t){return Number.isFinite(t)?Math.max(0,t):0}function Ma(t){const s=Ae(t.totalInputTokens),a=Ae(t.cacheReadTokens),r=Ae(t.cacheWriteTokens),i=Math.min(a,s),n=Math.min(r,Math.max(0,s-i)),o=Math.max(0,s-i-n),m=s>0&&(a>0||r>0);return{totalInputTokens:s,cacheReadTokens:i,cacheWriteTokens:n,uncachedInputTokens:o,...m?{hitRate:i/s}:{}}}function Aa(t){return t===void 0||!Number.isFinite(t)?"—":`${Math.round(Math.max(0,Math.min(1,t))*100)}%`}const Ra={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:""},Da={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"},ae=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString(),Fa=t=>{const s=Math.max(0,Math.ceil(t/1e3)),a=Math.floor(s/60),r=s%60;return a>0?`${a}m ${r}s`:`${r}s`};function wt(){const t=$(),s=v(c=>c.tokenUsage),a=v(c=>c.isStreaming),r=v(c=>c.agentPhase),i=v(c=>c.providerRecovery),n=v(c=>c.turnActivity),o=v(c=>c.pendingResume),m=v(c=>c.actionStationarity),x=v(c=>c.turnRecovery),l=Ra[r]??"",b=jt(i),g=(o==null?void 0:o.delayMs)!==void 0?` · retry in ${Fa(o.delayMs)}`:"",u=(x==null?void 0:x.state)==="requires_attention"?t("status.recovery.review"):"",k=(x==null?void 0:x.state)==="requires_attention"?t(x.reason==="interrupted_tool_call"?"status.recovery.interruptedTool":"status.recovery.successfulTool"):"",p=u||(m?`${t(m.phase==="halted"?"status.phase.actionStationarityStopped":"status.phase.actionStationarityRecovering")} · ${m.toolName} · ${m.runLength}/${m.haltThreshold}`:b?t(b.compactKey,b.params):o?`Recovery attempt ${o.attempt}/${o.maxAttempts}${g}`:l?t(l):""),w=s.maxContextTokens>0?Math.round(s.totalTokens/s.maxContextTokens*100):0,d=Ma(s),N=Aa(d.hitRate),f=Math.min(w,100),C=w>95?"danger":w>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:I("text-[12px] font-medium",C==="safe"&&"text-[hsl(var(--deck-ink))]",C==="warn"&&"text-amber-600 dark:text-amber-400",C==="danger"&&"text-red-600 dark:text-red-400"),children:ae(s.totalTokens)}),e.jsxs("span",{className:"text-[hsl(var(--deck-ink-faint))]",children:["/ ",ae(s.maxContextTokens)]})]}),s.isDefaultMaxTokens&&e.jsx(Ie,{children:e.jsxs(Le,{children:[e.jsx(Be,{asChild:!0,children:e.jsx(us,{className:"h-3 w-3 cursor-help text-[hsl(var(--deck-ink-faint))]"})}),e.jsx(ye,{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:I("absolute inset-y-0 left-0 transition-[width] duration-300",C==="safe"&&"bg-[hsl(var(--deck-accent))]",C==="warn"&&"bg-amber-500",C==="danger"&&"bg-red-500"),style:{width:`${f}%`}}),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:I("w-10 text-right tabular-nums text-[hsl(var(--deck-ink-faint))]",C==="warn"&&"text-amber-600 dark:text-amber-400",C==="danger"&&"text-red-600 dark:text-red-400"),children:[w,"%"]})]}),e.jsx(Ie,{children:e.jsxs(Le,{children:[e.jsx(Be,{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")} ${N}`,children:[e.jsx("span",{className:"deck-eyebrow text-[hsl(var(--deck-ink-faint))]",children:t("status.cache")}),e.jsx("span",{className:I("tabular-nums",d.hitRate===void 0?"text-[hsl(var(--deck-ink-faint))]":"font-medium text-[hsl(var(--deck-accent))]"),children:N})]})}),e.jsx(ye,{side:"top",className:"max-w-[280px]",children:d.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:ae(d.cacheReadTokens),write:ae(d.cacheWriteTokens),uncached:ae(d.uncachedInputTokens)})}),s.cacheBreak&&e.jsx("p",{className:"text-[hsl(var(--deck-accent))]",children:t("status.cacheBreak",{reason:t(Da[s.cacheBreak.reason]??"status.cacheBreak.server"),previous:ae(s.cacheBreak.previousCacheReadTokens),current:ae(s.cacheBreak.cacheReadTokens)})})]})})]})}),e.jsx("div",{className:"flex-1"}),(u||a&&p&&(!(n!=null&&n.snapshot)||m))&&e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:I("shrink-0",u?"h-2 w-2 rounded-sm bg-amber-500":"deck-pulse-dot")}),e.jsxs("span",{className:I("truncate",u?"text-amber-600 dark:text-amber-400":"text-[hsl(var(--deck-accent))]"),children:[p,k?e.jsxs("span",{className:"hidden sm:inline",children:[" · ",k]}):null]})]})]})}function Ia(){const{locale:t}=mt(),s=_t(c=>c.agentTeamsEnabled),a=v(c=>c.teams),r=v(c=>c.currentSessionRef),i=v(c=>oe(c.historySurfaceSelection)),n=v(c=>c.loadTeams),[o,m]=h.useState({}),[x,l]=h.useState({}),[b,g]=h.useState({}),[u,k]=h.useState(null),[p,w]=h.useState(null),[d,N]=h.useState(null);if(h.useEffect(()=>{i||n(r??void 0)},[s,r,i,n]),i||!s||!r||a.length===0)return null;const f=async c=>{var R;if(Q(v.getState()))return;const M=(R=b[c])==null?void 0:R.trim();if(!(!M||u)){k(c),N(null);try{await qe.sendMessage(r,c,x[c]??"*",M),g(D=>({...D,[c]:""})),await n(r)}catch(D){N(D instanceof Error?D.message:z(t,"actionFailed"))}finally{k(null)}}},C=async c=>{if(!Q(v.getState())&&!p){w(c),N(null);try{await qe.delete(r,c),await n(r)}catch(M){N(M instanceof Error?M.message:z(t,"actionFailed"))}finally{w(null)}}};return e.jsxs("section",{"aria-label":z(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:[d&&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:d}),a.filter(c=>c.status!=="deleted").map(c=>{var D;const M=o[c.name]??c.status==="running",R=c.tasks.filter(j=>j.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:()=>m(j=>({...j,[c.name]:!M})),"aria-label":M?z(t,"collapse"):z(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(he,{className:"h-4 w-4"}):e.jsx(ce,{className:"h-4 w-4"})}),e.jsx(fs,{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," ",z(t,"members")," · ",R,"/",c.tasks.length," ",z(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 C(c.name),disabled:p===c.name,"aria-label":z(t,"delete"),title:z(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(ie,{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:z(t,"members")}),c.members.map(j=>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":j.status,className:`h-1.5 w-1.5 shrink-0 rounded-full ${j.status==="running"?"bg-emerald-500":j.status==="completed"||j.status==="leader"?"bg-sky-500":j.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:j.name}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:j.subagentType}),j.worktreePath&&e.jsx(at,{className:"h-3 w-3 text-[hsl(var(--deck-ink-faint))]","aria-label":z(t,"worktree")})]},j.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:z(t,"tasks")}),c.tasks.length===0?e.jsx("p",{className:"font-mono text-[10px] text-[hsl(var(--deck-ink-faint))]",children:z(t,"noTasks")}):c.tasks.map(j=>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:["#",j.id]}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-[hsl(var(--deck-ink))]",children:j.subject}),e.jsx("span",{className:"font-mono text-[9px] text-[hsl(var(--deck-ink-faint))]",children:j.status})]},j.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":z(t,"recipient"),value:x[c.name]??"*",onChange:j=>l(P=>({...P,[c.name]:j.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:z(t,"broadcast")}),c.members.filter(j=>j.status!=="leader").map(j=>e.jsx("option",{value:j.name,children:j.name},j.id))]}),e.jsx("input",{value:b[c.name]??"",onChange:j=>g(P=>({...P,[c.name]:j.target.value})),onKeyDown:j=>{j.key==="Enter"&&f(c.name)},placeholder:z(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 f(c.name),disabled:!((D=b[c.name])!=null&&D.trim())||u===c.name,"aria-label":z(t,"send"),title:z(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($e,{className:"h-3.5 w-3.5"})})]})]})]},c.name)})]})}const La={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 Ba(t){const s=Math.max(0,Math.floor(t/1e3));if(s<60)return`${s}s`;const a=Math.floor(s/60),r=s%60;return a<60?`${a}m ${r}s`:`${Math.floor(a/60)}h ${a%60}m ${r}s`}function $a(t,s=Date.now()){const a=t==null?void 0:t.snapshot;if(!a)return null;const r=a.activeTools.length+a.activeToolOverflow,i=a.activeTools.slice(0,2).map(o=>o.progress!==void 0&&o.total!==void 0?`${o.name} ${o.progress}/${o.total}`:o.name),n=Math.max(0,a.activeTools.length-i.length+a.activeToolOverflow);return{phaseKey:La[a.phase],phaseParams:{count:r},tools:i,hiddenTools:n,completedTools:a.toolCallsCompleted,startedTools:a.toolCallsStarted,turn:a.turn,maxTurns:a.maxTurns,elapsed:Ba(s-a.startedAt)}}function Pa({activity:t,memory:s=null}){var x;const a=$(),[r,i]=h.useState(Date.now()),n=(x=t==null?void 0:t.snapshot)==null?void 0:x.startedAt;h.useEffect(()=>{if(n===void 0)return;i(Date.now());const l=window.setInterval(()=>i(Date.now()),1e3);return()=>window.clearInterval(l)},[n]);const o=$a(t,r);if(!o)return(s==null?void 0:s.outcome)!=="written"?null:e.jsxs("section",{role:"status","aria-live":"polite","data-memory-consolidation-notice":!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(ze,{className:"h-4 w-4 shrink-0 text-[hsl(var(--deck-accent))]","aria-hidden":!0}),e.jsx("span",{className:"text-xs font-semibold",children:a("chat.memoryConsolidation.saved",{count:s.entries})})]});const m=[(s==null?void 0:s.outcome)==="written"?a("chat.memoryConsolidation.saved",{count:s.entries}):void 0,...o.tools,o.hiddenTools>0?`+${o.hiddenTools}`:void 0,o.startedTools>0?a("chat.turnActivity.toolCount",{completed:o.completedTools,started:o.startedTools}):void 0,o.turn>0?o.maxTurns===null?a("chat.turnActivity.turn",{turn:o.turn}):a("chat.turnActivity.turnBounded",{turn:o.turn,maxTurns:o.maxTurns}):void 0].filter(l=>l!==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(ze,{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:a(o.phaseKey,o.phaseParams)}),m.length>0&&e.jsx("div",{className:"mt-0.5 truncate font-mono text-[10px] text-[hsl(var(--deck-ink-muted))]",children:m.join(" · ")})]}),e.jsx("span",{className:"shrink-0 font-mono text-[10px] tabular-nums text-[hsl(var(--deck-ink-muted))]",children:o.elapsed})]})}function _a(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 a=s.content.filter(i=>i.type==="text").map(i=>i.text).join(`
70
- `),r=s.content.filter(i=>i.type==="image_url").map((i,n)=>{var m;const o=((m=i.image_url.url.match(/^data:([^;,]+)[;,]/))==null?void 0:m[1])??"application/octet-stream";return{id:`recovery-${s.id}-${n}`,name:`attachment-${n+1}`,mimeType:o,dataUrl:i.image_url.url}});return{content:a,attachments:r}}function Oa({messages:t,isLoading:s,isStreaming:a,isStopping:r,errorMessage:i}){const n=$(),[o,m]=h.useState(!1),x=n(i?"status.phase.error":r?"chat.input.action.stopping":a?"status.phase.running":"preview.files.status.ready");return e.jsxs("details",{"data-preview-status-disclosure":!0,open:o,onToggle:l=>m(l.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:[a&&e.jsx("span",{className:"deck-pulse-dot"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:x}),e.jsx(ce,{className:"h-3.5 w-3.5 shrink-0 transition-transform group-open:rotate-90"})]}),o&&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(yt,{messages:t,isLoading:s}),e.jsx(wt,{})]})]})}function ar(){var se;const t=$(),s=v(y=>y.messages),a=v(y=>y.currentSessionRef),r=v(y=>y.isStreaming),i=v(y=>y.isStopping),n=v(y=>y.providerRecovery),o=v(y=>y.turnActivity),m=v(y=>y.memoryConsolidation),x=v(y=>y.actionStationarity),l=v(y=>y.sessionEventConnectionState),b=v(y=>y.pendingSteeringCount),g=v(y=>y.pendingInputDelivery),u=v(y=>y.recoveredSteeringCount),k=v(y=>y.followUpQueue),p=v(y=>y.followUpQueueMutation),w=v(y=>y.mutateFollowUpQueue),d=v(y=>y.refreshFollowUpQueue),N=v(y=>!!y.historySurfaceSelection),f=v(y=>y.isLoading),C=v(y=>y.error),c=v(y=>y.errorContext),M=v(y=>y.sessions),R=v(y=>y.sendMessage),D=v(y=>y.openSideConversation),j=v(y=>y.abortSession),P=v(y=>y.retryTask),Z=v(y=>y.retryingTaskKeys),T=_e(y=>y.openSettings),L=v(y=>y.reconnectSessionEvents),O=v(y=>y.clearError),[_,H]=h.useState(null),S=a?M.find(y=>y.sessionId===a.sessionId&&y.projectPath===a.projectPath):void 0,E=!!C&&((c==null?void 0:c.kind)==="navigation"||!(c!=null&&c.sessionRef)||st(c.sessionRef,a)),A=(c==null?void 0:c.failureCode)??((se=S==null?void 0:S.taskFailure)==null?void 0:se.code),U=((c==null?void 0:c.kind)==="execution"||c!=null&&c.failureCode)&&A?t(Qt(A)):C==="queue_full"?t("chat.error.queueFull"):C==="turn_unavailable"||C==="turn_active"?t("chat.error.turnChanged"):C,G=l==="connecting"||l==="reconnecting",F=r&&l!=="connected",J=a?`session:${ue(a)}`:"session:temporary",Y=h.useMemo(()=>_a(s),[s]),W=a?ue(a):"temporary-session",q=!!(a&&(S!=null&&S.taskRetryAvailable)&&(!A||Gt(A)))&&((c==null?void 0:c.kind)==="execution"||(c==null?void 0:c.kind)==="task_action"),V=(c==null?void 0:c.kind)==="execution"&&(A==="authentication"||A==="permission"||A==="model_unavailable"),X=a?Z.includes(ue(a)):!1;h.useEffect(()=>{H(null)},[W]);const te=async y=>Q(v.getState())?!1:R({content:y.content,modelId:y.modelId,reasoningEffort:y.reasoningEffort,serviceTier:y.serviceTier,responseVerbosity:y.responseVerbosity,communicationStyle:y.communicationStyle,...y.annotations?{annotations:y.annotations}:{},...y.outputSchema?{outputSchema:y.outputSchema}:{},attachments:y.attachments.map(Ne=>({type:"image",content:Ne.dataUrl,mimeType:Ne.mimeType,name:Ne.name}))}),le=()=>{if(!Q(v.getState()))return j()},xe=async()=>{if(!Q(v.getState())){if(V){O(),T("models");return}if(q&&a){O(),await P(a).catch(()=>{});return}if((c==null?void 0:c.kind)==="execution"&&Y){H({...Y,revision:Date.now()}),O();return}O(),requestAnimationFrame(()=>Kt())}},B=q?t(X?"chat.error.action.retryingTask":"chat.error.action.retryTask"):V?t("chat.error.action.checkModels"):(c==null?void 0:c.kind)==="execution"&&Y?t("chat.error.action.editResend"):(c==null?void 0:c.kind)==="submission"?t("chat.error.action.returnDraft"):null;return e.jsxs("div",{"data-chat-view":!0,className:"relative flex h-full min-h-0 overflow-hidden bg-[hsl(var(--deck-canvas))]",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsxs("div",{"data-chat-history":!0,className:"contents",children:[E&&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(Pe,{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((c==null?void 0:c.kind)==="submission"?"chat.error.title.submission":(c==null?void 0:c.kind)==="execution"?"chat.error.title.execution":(c==null?void 0:c.kind)==="navigation"?"chat.error.title.navigation":"chat.error.title.generic")})," ",U]}),B&&e.jsxs("button",{type:"button",onClick:()=>void xe(),disabled:X,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?X?e.jsx(K,{className:"h-3 w-3 animate-spin"}):e.jsx(ve,{className:"h-3 w-3"}):e.jsx(bt,{className:"h-3 w-3"}),B]}),e.jsx("button",{type:"button",onClick:O,"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:"✕"})]}),(G||l==="offline")&&e.jsxs("div",{role:l==="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:[G?e.jsx(K,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):e.jsx(Ot,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 flex-1",children:t(G?"chat.connection.reconnecting":"chat.connection.offline")}),l==="offline"&&e.jsxs("button",{type:"button",onClick:()=>{Q(v.getState())||L().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(ut,{className:"h-3 w-3"}),t("chat.connection.retry")]})]}),e.jsx(bs,{}),e.jsx(yt,{messages:s,isLoading:f,selectionDraftKey:N?void 0:J,canAskSideConversation:!!(a&&!N),onOpenSideConversation:D},a?ue(a):"temporary-session"),e.jsx(Ia,{})]}),e.jsxs("div",{"data-chat-composer-dock":!0,className:"contents",children:[e.jsx(Oa,{messages:s,isLoading:f,isStreaming:r,isStopping:i,errorMessage:E?U:null},W),e.jsx(ja,{}),e.jsx(ya,{}),e.jsx(va,{queue:N?null:k,mutation:p,onMutate:w,onRefresh:d}),e.jsx(Na,{recovery:N?null:n,stopping:i,onStop:le}),e.jsx(Pa,{activity:N||n!=null&&n.snapshot||x||S!=null&&S.pendingInteraction?null:o,memory:N?null:m}),e.jsx(Ut,{draftKey:J,draft:_==null?void 0:_.content,draftAttachments:_==null?void 0:_.attachments,draftRevision:_==null?void 0:_.revision,onSend:te,onAbort:le,disabled:f||F,isStreaming:r,isStopping:i,pendingSteeringCount:b,pendingInputDelivery:g,recoveredSteeringCount:u,workspacePath:a==null?void 0:a.projectPath},J),e.jsx("div",{"data-chat-primary-status":!0,className:"contents",children:e.jsx(wt,{})})]})]}),e.jsx(Ta,{})]})}export{ar as ChatView};