@artooi/ag-ui-web-component 0.37.0 → 0.38.0

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 (195) hide show
  1. package/CHANGELOG.md +75 -1
  2. package/dist/ag-ui-web-component.bundle.js +81 -81
  3. package/dist/ag-ui-web-component.bundle.js.map +4 -4
  4. package/dist/core/activity_registration.d.ts +19 -0
  5. package/dist/core/activity_registration.d.ts.map +1 -0
  6. package/dist/core/activity_renderer.d.ts +20 -0
  7. package/dist/core/activity_renderer.d.ts.map +1 -0
  8. package/dist/core/ag_ui_chat.d.ts +6 -126
  9. package/dist/core/ag_ui_chat.d.ts.map +1 -1
  10. package/dist/core/events/attachments_detail.d.ts +9 -0
  11. package/dist/core/events/attachments_detail.d.ts.map +1 -0
  12. package/dist/core/events/custom_agent_detail.d.ts +8 -0
  13. package/dist/core/events/custom_agent_detail.d.ts.map +1 -0
  14. package/dist/core/events/feedback_detail.d.ts +7 -0
  15. package/dist/core/events/feedback_detail.d.ts.map +1 -0
  16. package/dist/core/events/invalidate_detail.d.ts +16 -0
  17. package/dist/core/events/invalidate_detail.d.ts.map +1 -0
  18. package/dist/core/events/run_finished_detail.d.ts +22 -0
  19. package/dist/core/events/run_finished_detail.d.ts.map +1 -0
  20. package/dist/core/events/state_detail.d.ts +5 -0
  21. package/dist/core/events/state_detail.d.ts.map +1 -0
  22. package/dist/core/events/submit_detail.d.ts +8 -0
  23. package/dist/core/events/submit_detail.d.ts.map +1 -0
  24. package/dist/core/events/toggle_detail.d.ts +5 -0
  25. package/dist/core/events/toggle_detail.d.ts.map +1 -0
  26. package/dist/core/events/tool_run.d.ts +11 -0
  27. package/dist/core/events/tool_run.d.ts.map +1 -0
  28. package/dist/core/events/unread_detail.d.ts +5 -0
  29. package/dist/core/events/unread_detail.d.ts.map +1 -0
  30. package/dist/core/message_role.d.ts +4 -0
  31. package/dist/core/message_role.d.ts.map +1 -0
  32. package/dist/core/tool_outcome.d.ts +1 -1
  33. package/dist/core/tool_outcome.d.ts.map +1 -1
  34. package/dist/index.d.ts +30 -17
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +8579 -8573
  37. package/dist/index.js.map +4 -4
  38. package/dist/ui/charts/chart_block.d.ts.map +1 -0
  39. package/dist/ui/charts/chart_spec_from.d.ts.map +1 -0
  40. package/dist/ui/{chart_tool.d.ts → charts/chart_tool.d.ts} +1 -1
  41. package/dist/ui/charts/chart_tool.d.ts.map +1 -0
  42. package/dist/ui/{attachment_tray.d.ts → composer/attachment_tray.d.ts} +3 -3
  43. package/dist/ui/composer/attachment_tray.d.ts.map +1 -0
  44. package/dist/ui/{skills_menu.d.ts → composer/skills_menu.d.ts} +1 -1
  45. package/dist/ui/composer/skills_menu.d.ts.map +1 -0
  46. package/dist/ui/{voice_input.d.ts → composer/voice_input.d.ts} +2 -2
  47. package/dist/ui/composer/voice_input.d.ts.map +1 -0
  48. package/dist/ui/{attach_copy_buttons.d.ts → excerpts/attach_copy_buttons.d.ts} +1 -1
  49. package/dist/ui/excerpts/attach_copy_buttons.d.ts.map +1 -0
  50. package/dist/ui/excerpts/copy_payload.d.ts.map +1 -0
  51. package/dist/ui/excerpts/page_quote_offer.d.ts.map +1 -0
  52. package/dist/ui/excerpts/quote_selection.d.ts.map +1 -0
  53. package/dist/ui/{checkpoint_menu.d.ts → history/checkpoint_menu.d.ts} +2 -2
  54. package/dist/ui/history/checkpoint_menu.d.ts.map +1 -0
  55. package/dist/ui/{relative_time.d.ts → history/relative_time.d.ts} +1 -1
  56. package/dist/ui/history/relative_time.d.ts.map +1 -0
  57. package/dist/ui/{thread_drawer.d.ts → history/thread_drawer.d.ts} +2 -2
  58. package/dist/ui/history/thread_drawer.d.ts.map +1 -0
  59. package/dist/ui/{approval_card.d.ts → interrupts/approval_card.d.ts} +1 -1
  60. package/dist/ui/interrupts/approval_card.d.ts.map +1 -0
  61. package/dist/ui/{confirmation_card.d.ts → interrupts/confirmation_card.d.ts} +1 -1
  62. package/dist/ui/interrupts/confirmation_card.d.ts.map +1 -0
  63. package/dist/ui/{question_card.d.ts → interrupts/question_card.d.ts} +1 -1
  64. package/dist/ui/interrupts/question_card.d.ts.map +1 -0
  65. package/dist/ui/placement/clamp_launcher.d.ts.map +1 -0
  66. package/dist/ui/placement/clamp_panel.d.ts.map +1 -0
  67. package/dist/ui/placement/launcher_drag.d.ts.map +1 -0
  68. package/dist/ui/placement/launcher_placement.d.ts.map +1 -0
  69. package/dist/ui/placement/panel_drag.d.ts.map +1 -0
  70. package/dist/ui/placement/place_widget.d.ts.map +1 -0
  71. package/dist/ui/placement/resize_handle.d.ts.map +1 -0
  72. package/dist/ui/progress/prettify_tool_name.d.ts.map +1 -0
  73. package/dist/ui/progress/run_notice.d.ts.map +1 -0
  74. package/dist/ui/{subagent_panel.d.ts → progress/subagent_panel.d.ts} +2 -2
  75. package/dist/ui/progress/subagent_panel.d.ts.map +1 -0
  76. package/dist/ui/progress/subagent_update.d.ts.map +1 -0
  77. package/dist/ui/{thoughts_block.d.ts → progress/thoughts_block.d.ts} +1 -1
  78. package/dist/ui/progress/thoughts_block.d.ts.map +1 -0
  79. package/dist/ui/{tool_call_card.d.ts → progress/tool_call_card.d.ts} +2 -2
  80. package/dist/ui/progress/tool_call_card.d.ts.map +1 -0
  81. package/dist/ui/{attachment_chips.d.ts → transcript/attachment_chips.d.ts} +1 -1
  82. package/dist/ui/transcript/attachment_chips.d.ts.map +1 -0
  83. package/dist/ui/{message_actions.d.ts → transcript/message_actions.d.ts} +1 -1
  84. package/dist/ui/transcript/message_actions.d.ts.map +1 -0
  85. package/dist/ui/transcript/render_markdown.d.ts.map +1 -0
  86. package/dist/ui/transcript/reveal_words.d.ts.map +1 -0
  87. package/dist/ui/transcript/stick_to_bottom.d.ts.map +1 -0
  88. package/dist/ui/{suggestion_chips.d.ts → transcript/suggestion_chips.d.ts} +1 -1
  89. package/dist/ui/transcript/suggestion_chips.d.ts.map +1 -0
  90. package/package.json +5 -5
  91. package/src/core/activity_registration.ts +19 -0
  92. package/src/core/activity_renderer.ts +19 -0
  93. package/src/core/ag_ui_chat.ts +84 -178
  94. package/src/core/events/attachments_detail.ts +9 -0
  95. package/src/core/events/custom_agent_detail.ts +7 -0
  96. package/src/core/events/feedback_detail.ts +6 -0
  97. package/src/core/events/invalidate_detail.ts +15 -0
  98. package/src/core/events/run_finished_detail.ts +22 -0
  99. package/src/core/events/state_detail.ts +4 -0
  100. package/src/core/events/submit_detail.ts +8 -0
  101. package/src/core/events/toggle_detail.ts +4 -0
  102. package/src/core/events/tool_run.ts +10 -0
  103. package/src/core/events/unread_detail.ts +4 -0
  104. package/src/core/message_role.ts +4 -0
  105. package/src/core/tool_outcome.ts +1 -1
  106. package/src/index.ts +52 -54
  107. package/src/ui/{chart_tool.ts → charts/chart_tool.ts} +1 -1
  108. package/src/ui/{attachment_tray.ts → composer/attachment_tray.ts} +5 -5
  109. package/src/ui/{skills_menu.ts → composer/skills_menu.ts} +1 -1
  110. package/src/ui/{voice_input.ts → composer/voice_input.ts} +3 -3
  111. package/src/ui/{attach_copy_buttons.ts → excerpts/attach_copy_buttons.ts} +1 -1
  112. package/src/ui/{checkpoint_menu.ts → history/checkpoint_menu.ts} +2 -2
  113. package/src/ui/{relative_time.ts → history/relative_time.ts} +1 -1
  114. package/src/ui/{thread_drawer.ts → history/thread_drawer.ts} +2 -2
  115. package/src/ui/{approval_card.ts → interrupts/approval_card.ts} +1 -1
  116. package/src/ui/{confirmation_card.ts → interrupts/confirmation_card.ts} +1 -1
  117. package/src/ui/{question_card.ts → interrupts/question_card.ts} +1 -1
  118. package/src/ui/{clamp_launcher.ts → placement/clamp_launcher.ts} +1 -1
  119. package/src/ui/{clamp_panel.ts → placement/clamp_panel.ts} +1 -1
  120. package/src/ui/{launcher_placement.ts → placement/launcher_placement.ts} +1 -1
  121. package/src/ui/{subagent_panel.ts → progress/subagent_panel.ts} +2 -2
  122. package/src/ui/{subagent_update.ts → progress/subagent_update.ts} +1 -1
  123. package/src/ui/{thoughts_block.ts → progress/thoughts_block.ts} +1 -1
  124. package/src/ui/{tool_call_card.ts → progress/tool_call_card.ts} +2 -2
  125. package/src/ui/{attachment_chips.ts → transcript/attachment_chips.ts} +2 -2
  126. package/src/ui/{message_actions.ts → transcript/message_actions.ts} +2 -2
  127. package/src/ui/{suggestion_chips.ts → transcript/suggestion_chips.ts} +1 -1
  128. package/src/version.ts +1 -1
  129. package/dist/ui/approval_card.d.ts.map +0 -1
  130. package/dist/ui/attach_copy_buttons.d.ts.map +0 -1
  131. package/dist/ui/attachment_chips.d.ts.map +0 -1
  132. package/dist/ui/attachment_tray.d.ts.map +0 -1
  133. package/dist/ui/chart_block.d.ts.map +0 -1
  134. package/dist/ui/chart_spec_from.d.ts.map +0 -1
  135. package/dist/ui/chart_tool.d.ts.map +0 -1
  136. package/dist/ui/checkpoint_menu.d.ts.map +0 -1
  137. package/dist/ui/clamp_launcher.d.ts.map +0 -1
  138. package/dist/ui/clamp_panel.d.ts.map +0 -1
  139. package/dist/ui/confirmation_card.d.ts.map +0 -1
  140. package/dist/ui/copy_payload.d.ts.map +0 -1
  141. package/dist/ui/launcher_drag.d.ts.map +0 -1
  142. package/dist/ui/launcher_placement.d.ts.map +0 -1
  143. package/dist/ui/message_actions.d.ts.map +0 -1
  144. package/dist/ui/page_quote_offer.d.ts.map +0 -1
  145. package/dist/ui/panel_drag.d.ts.map +0 -1
  146. package/dist/ui/place_widget.d.ts.map +0 -1
  147. package/dist/ui/prettify_tool_name.d.ts.map +0 -1
  148. package/dist/ui/question_card.d.ts.map +0 -1
  149. package/dist/ui/quote_selection.d.ts.map +0 -1
  150. package/dist/ui/relative_time.d.ts.map +0 -1
  151. package/dist/ui/render_markdown.d.ts.map +0 -1
  152. package/dist/ui/resize_handle.d.ts.map +0 -1
  153. package/dist/ui/reveal_words.d.ts.map +0 -1
  154. package/dist/ui/run_notice.d.ts.map +0 -1
  155. package/dist/ui/skills_menu.d.ts.map +0 -1
  156. package/dist/ui/stick_to_bottom.d.ts.map +0 -1
  157. package/dist/ui/subagent_panel.d.ts.map +0 -1
  158. package/dist/ui/subagent_update.d.ts.map +0 -1
  159. package/dist/ui/suggestion_chips.d.ts.map +0 -1
  160. package/dist/ui/thoughts_block.d.ts.map +0 -1
  161. package/dist/ui/thread_drawer.d.ts.map +0 -1
  162. package/dist/ui/tool_call_card.d.ts.map +0 -1
  163. package/dist/ui/voice_input.d.ts.map +0 -1
  164. /package/dist/ui/{chart_block.d.ts → charts/chart_block.d.ts} +0 -0
  165. /package/dist/ui/{chart_spec_from.d.ts → charts/chart_spec_from.d.ts} +0 -0
  166. /package/dist/ui/{copy_payload.d.ts → excerpts/copy_payload.d.ts} +0 -0
  167. /package/dist/ui/{page_quote_offer.d.ts → excerpts/page_quote_offer.d.ts} +0 -0
  168. /package/dist/ui/{quote_selection.d.ts → excerpts/quote_selection.d.ts} +0 -0
  169. /package/dist/ui/{clamp_launcher.d.ts → placement/clamp_launcher.d.ts} +0 -0
  170. /package/dist/ui/{clamp_panel.d.ts → placement/clamp_panel.d.ts} +0 -0
  171. /package/dist/ui/{launcher_drag.d.ts → placement/launcher_drag.d.ts} +0 -0
  172. /package/dist/ui/{launcher_placement.d.ts → placement/launcher_placement.d.ts} +0 -0
  173. /package/dist/ui/{panel_drag.d.ts → placement/panel_drag.d.ts} +0 -0
  174. /package/dist/ui/{place_widget.d.ts → placement/place_widget.d.ts} +0 -0
  175. /package/dist/ui/{resize_handle.d.ts → placement/resize_handle.d.ts} +0 -0
  176. /package/dist/ui/{prettify_tool_name.d.ts → progress/prettify_tool_name.d.ts} +0 -0
  177. /package/dist/ui/{run_notice.d.ts → progress/run_notice.d.ts} +0 -0
  178. /package/dist/ui/{subagent_update.d.ts → progress/subagent_update.d.ts} +0 -0
  179. /package/dist/ui/{render_markdown.d.ts → transcript/render_markdown.d.ts} +0 -0
  180. /package/dist/ui/{reveal_words.d.ts → transcript/reveal_words.d.ts} +0 -0
  181. /package/dist/ui/{stick_to_bottom.d.ts → transcript/stick_to_bottom.d.ts} +0 -0
  182. /package/src/ui/{chart_block.ts → charts/chart_block.ts} +0 -0
  183. /package/src/ui/{chart_spec_from.ts → charts/chart_spec_from.ts} +0 -0
  184. /package/src/ui/{copy_payload.ts → excerpts/copy_payload.ts} +0 -0
  185. /package/src/ui/{page_quote_offer.ts → excerpts/page_quote_offer.ts} +0 -0
  186. /package/src/ui/{quote_selection.ts → excerpts/quote_selection.ts} +0 -0
  187. /package/src/ui/{launcher_drag.ts → placement/launcher_drag.ts} +0 -0
  188. /package/src/ui/{panel_drag.ts → placement/panel_drag.ts} +0 -0
  189. /package/src/ui/{place_widget.ts → placement/place_widget.ts} +0 -0
  190. /package/src/ui/{resize_handle.ts → placement/resize_handle.ts} +0 -0
  191. /package/src/ui/{prettify_tool_name.ts → progress/prettify_tool_name.ts} +0 -0
  192. /package/src/ui/{run_notice.ts → progress/run_notice.ts} +0 -0
  193. /package/src/ui/{render_markdown.ts → transcript/render_markdown.ts} +0 -0
  194. /package/src/ui/{reveal_words.ts → transcript/reveal_words.ts} +0 -0
  195. /package/src/ui/{stick_to_bottom.ts → transcript/stick_to_bottom.ts} +0 -0
@@ -8,36 +8,35 @@ Patch operations: ${JSON.stringify(h,null,2)}
8
8
  Error: ${x}`)}}return u()}case b.MESSAGES_SNAPSHOT:{let p=await ne(r,s,a,(h,g,x)=>h.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(p),p.stopPropagation!==!0){let{messages:h}=m,g=h.map(v=>{if(v.subagentRunId!==null)return v;let A={...v};return delete A.subagentRunId,A}),x=new Map(g.map(v=>[v.id,v])),T=g.some(v=>v.role==="activity"),S=g.some(v=>v.role==="reasoning"),L=v=>v.role==="activity"&&!T||v.role==="reasoning"&&!S;s=s.filter(v=>L(v)||x.has(v.id)).map(v=>L(v)?v:x.get(v.id));let z=new Set(s.map(v=>v.id));for(let v of g)z.has(v.id)||s.push(v);c({messages:s})}return u()}case b.ACTIVITY_SNAPSHOT:{let p=m,h=s.findIndex(L=>L.id===p.messageId),g=h>=0?s[h]:void 0,x=g?.role==="activity"?g:void 0,T=p.replace??!0,S=await ne(r,s,a,(L,z,v)=>L.onActivitySnapshotEvent?.({event:p,messages:z,state:v,agent:n,input:t,activityMessage:x,existingMessage:g}));if(c(S),S.stopPropagation!==!0){let L={id:p.messageId,role:"activity",activityType:p.activityType,content:J(p.content),...p.subagentRunId!=null&&{subagentRunId:p.subagentRunId}},z,v;h===-1?(s.push(L),z=L,v=L):x?(T&&(s[h]={...x,activityType:p.activityType,content:J(p.content),subagentRunId:p.subagentRunId},p.subagentRunId??delete s[h].subagentRunId),v=s[h]):T&&(s[h]=L,z=L,v=L),Fe(v,p),c({messages:s}),z&&await Promise.all(r.map(A=>A.onNewMessage?.({message:z,messages:s,state:a,agent:n,input:t})))}return u()}case b.ACTIVITY_DELTA:{let p=m,h=s.findIndex(S=>S.id===p.messageId);if(h===-1)return u();let g=s[h];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${p.messageId}' is not an activity message`),u();let x=g,T=await ne(r,s,a,(S,L,z)=>S.onActivityDeltaEvent?.({event:p,messages:L,state:z,agent:n,input:t,activityMessage:x}));if(c(T),T.stopPropagation!==!0)try{Fe(x,p)&&c({messages:s});let S=J(x.content??{}),L=Oo.applyPatch(S,p.patch??[],!0,!1).newDocument;s[h]={...x,content:J(L),activityType:p.activityType},c({messages:s})}catch(S){let L=S instanceof Error?S.message:String(S);console.warn(`Failed to apply activity patch for '${p.messageId}': ${L}`)}return u()}case b.RAW:return c(await ne(r,s,a,(p,h,g)=>p.onRawEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.CUSTOM:return c(await ne(r,s,a,(p,h,g)=>p.onCustomEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.RUN_STARTED:{let p=await ne(r,s,a,(h,g,x)=>h.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(p),p.stopPropagation!==!0){let h=m;if(h.input?.messages){for(let g of h.input.messages){let x=g;if(g.subagentRunId===null){let T={...g};delete T.subagentRunId,x=T}s.find(T=>T.id===x.id)||s.push(x)}c({messages:s})}}return u()}case b.RUN_FINISHED:{let p=m,h=p.outcome?.type==="interrupt"?{event:p,outcome:"interrupt",interrupts:p.outcome.interrupts}:{event:p,outcome:"success",result:p.result},g=await ne(r,s,a,(x,T,S)=>x.onRunFinishedEvent?.({...h,messages:T,state:S,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=h.outcome==="interrupt"?h.interrupts.map(x=>{if(x.subagentRunId!==null)return x;let T={...x};return delete T.subagentRunId,T}):[]),u()}case b.RUN_ERROR:return c(await ne(r,s,a,(p,h,g)=>p.onRunErrorEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.STEP_STARTED:return c(await ne(r,s,a,(p,h,g)=>p.onStepStartedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.STEP_FINISHED:return c(await ne(r,s,a,(p,h,g)=>p.onStepFinishedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be transformed before being applied");case b.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be transformed before being applied");case b.THINKING_START:return u();case b.THINKING_END:return u();case b.THINKING_TEXT_MESSAGE_START:return u();case b.THINKING_TEXT_MESSAGE_CONTENT:return u();case b.THINKING_TEXT_MESSAGE_END:return u();case b.REASONING_START:return c(await ne(r,s,a,(p,h,g)=>p.onReasoningStartEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.REASONING_MESSAGE_START:{let p=await ne(r,s,a,(h,g,x)=>h.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(p),p.stopPropagation!==!0){let{messageId:h,subagentRunId:g}=m,x=s.find(L=>L.id===h),T=x;if(!T){let L={id:h,role:"reasoning",content:"",...g!=null&&{subagentRunId:g}};s.push(L),T=L}let S=Fe(T,m);(!x||S)&&c({messages:s})}return u()}case b.REASONING_MESSAGE_CONTENT:{let{messageId:p,delta:h}=m,g=s.find(T=>T.id===p);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${p}'`),u();let x=await ne(r,s,a,(T,S,L)=>T.onReasoningMessageContentEvent?.({event:m,messages:S,state:L,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,Fe(g,m),c({messages:s})),u()}case b.REASONING_MESSAGE_END:{let{messageId:p}=m,h=s.find(x=>x.id===p);if(!h)return console.warn(`REASONING_MESSAGE_END: No message found with ID '${p}'`),u();let g=await ne(r,s,a,(x,T,S)=>x.onReasoningMessageEndEvent?.({event:m,messages:T,state:S,agent:n,input:t,reasoningMessageBuffer:typeof h.content=="string"?h.content:""}));return c(g),g.stopPropagation!==!0&&Fe(h,m)&&c({messages:s}),await Promise.all(r.map(x=>{x.onNewMessage?.({message:h,messages:s,state:a,agent:n,input:t})})),u()}case b.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case b.REASONING_END:return c(await ne(r,s,a,(p,h,g)=>p.onReasoningEndEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.REASONING_ENCRYPTED_VALUE:{let{subtype:p,entityId:h,encryptedValue:g}=m,x=await ne(r,s,a,(T,S,L)=>T.onReasoningEncryptedValueEvent?.({event:m,messages:S,state:L,agent:n,input:t}));if(c(x),x.stopPropagation!==!0){let T=!1;if(p==="tool-call"){for(let S of s)if(S.role==="assistant"&&S.toolCalls){let L=S.toolCalls.find(z=>z.id===h);if(L){L.encryptedValue=g,T=!0;break}}}else{let S=s.find(L=>L.id===h);S?.role!=="activity"&&S&&(S.encryptedValue=g,T=!0)}T&&(l.messages=s)}return u()}case b.SUBAGENT_STARTED:return c(await ne(r,s,a,(p,h,g)=>p.onSubagentStartedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.SUBAGENT_FINISHED:return c(await ne(r,s,a,(p,h,g)=>p.onSubagentFinishedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u();case b.SUBAGENT_ERROR:return c(await ne(r,s,a,(p,h,g)=>p.onSubagentErrorEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),u()}return m.type,u()}),xa(),r.length>0?_a({}):m=>m)},Fa=t=>e=>{let n=Ar(t),r=new Set,o=new Set,i=new Set,s={message:new Map,toolCall:new Map,activity:new Map,reasoning:new Map},a=!1,l=!1,c=!1,u=new Map,m=v=>{let A=u.get(v);return A||(A=new Map,u.set(v,A)),A},w=()=>{for(let v of u.values())if(v.size>0)return!0;return!1},p=new Map,h=new Set,g=!1,x=!1,T=!1,S=()=>{r.clear(),o.clear(),i.clear(),s.message.clear(),s.toolCall.clear(),s.activity.clear(),s.reasoning.clear(),u.clear(),p.clear(),h.clear(),g=!1,x=!1,a=!1,l=!1,T=!0},L=(v,A)=>{let E=v??[];if(Array.isArray(E))for(let R of E){if(!R||typeof R.id!="string")continue;if(R.subagentRunId===null)return new j(`Cannot send a message (id '${R.id}') with 'subagentRunId: null'. The field is optional \u2014 omit it entirely.`);let B=R.role==="reasoning"?s.reasoning:R.role==="activity"?s.activity:s.message;(A||!B.has(R.id))&&B.set(R.id,{subagentRunId:R.subagentRunId});for(let le of R.toolCalls??[])le&&typeof le.id=="string"&&(A||!s.toolCall.has(le.id))&&s.toolCall.set(le.id,{subagentRunId:R.subagentRunId??void 0})}},z=(v,A,E,R,B)=>{if(A!==void 0&&E&&E.subagentRunId!==A)return new j(`Cannot send '${v}': subagentRunId '${A}' does not match the ${R} '${B}' opener's subagent '${E.subagentRunId??"(the parent agent)"}'.`)};return e.pipe(Ue(v=>{let A=v.type;if(n?.event("VERIFY","Event:",v,{type:v.type}),l&&A!==b.RUN_STARTED)return G(()=>new j(`Cannot send event type '${A}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(a&&A!==b.RUN_ERROR&&A!==b.RUN_STARTED)return G(()=>new j(`Cannot send event type '${A}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(c){if(A===b.RUN_STARTED){if(T&&!a&&!l)return G(()=>new j("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));(a||l)&&S()}}else if(c=!0,A!==b.RUN_STARTED&&A!==b.RUN_ERROR)return G(()=>new j("First event must be 'RUN_STARTED'"));if(v.subagentRunId===null)return G(()=>new j(`Cannot send '${A}' with 'subagentRunId: null'. The field is optional \u2014 omit it entirely.`));if(A===b.SUBAGENT_STARTED||A===b.SUBAGENT_FINISHED||A===b.SUBAGENT_ERROR){let E=A===b.SUBAGENT_STARTED?["description","parentSubagentRunId","parentToolCallId","parentMessageId"]:A===b.SUBAGENT_FINISHED?["outcome"]:["code"];for(let B of E)if(v[B]===null)return G(()=>new j(`Cannot send '${A}' with '${B}: null'. The field is optional \u2014 omit it entirely.`));let R=v.outcome;if(R!=null&&R.type!=="success"&&R.type!=="suspended")return G(()=>new j(`Cannot send '${A}' with outcome type '${String(R.type)}'. The outcome is either { type: "success" } or { type: "suspended" }.`));if(R&&R.interruptIds===null)return G(()=>new j(`Cannot send '${A}' with 'outcome.interruptIds: null'. The field is optional \u2014 omit it entirely.`));if(R&&Array.isArray(R.interruptIds)&&R.interruptIds.some(B=>typeof B!="string"))return G(()=>new j(`Cannot send '${A}' with a non-string entry in 'outcome.interruptIds'. Interrupt ids are strings.`))}if(A===b.RUN_FINISHED){let E=v.outcome;if(E?.type==="interrupt"&&Array.isArray(E.interrupts)){for(let R of E.interrupts)if(R&&R.subagentRunId===null)return G(()=>new j(`Cannot send 'RUN_FINISHED' with an interrupt (id '${R.id}') carrying 'subagentRunId: null'. The field is optional \u2014 omit it entirely.`))}}switch(A){case b.TEXT_MESSAGE_START:{let E=v.messageId;if(r.has(E))return G(()=>new j(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${E}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`));let R=s.message.get(E);if(R){let B=z(A,v.subagentRunId,R,"message",E);if(B)return G(()=>B)}return r.add(E),R||s.message.set(E,{subagentRunId:v.subagentRunId}),te(v)}case b.TEXT_MESSAGE_CONTENT:{let E=v.messageId;if(!r.has(E))return G(()=>new j(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${E}'. Start a text message with 'TEXT_MESSAGE_START' first.`));let R=z(A,v.subagentRunId,s.message.get(E),"message",E);return R?G(()=>R):te(v)}case b.TEXT_MESSAGE_END:{let E=v.messageId;if(!r.has(E))return G(()=>new j(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${E}'. A 'TEXT_MESSAGE_START' event must be sent first.`));let R=z(A,v.subagentRunId,s.message.get(E),"message",E);return R?G(()=>R):(r.delete(E),te(v))}case b.TOOL_CALL_START:{let E=v.toolCallId;if(o.has(E))return G(()=>new j(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${E}' is already in progress. Complete it with 'TOOL_CALL_END' first.`));let R=v.parentMessageId,B=v.subagentRunId,le;if(R!==void 0){let je=s.message.get(R);if(je){if(B!==void 0&&B!==je.subagentRunId)return G(()=>new j(`Cannot send 'TOOL_CALL_START': subagentRunId '${B}' does not match its parent message '${R}' owner '${je.subagentRunId??"(the parent agent)"}'. A tool call belongs to the message that carries it.`));le=je}}let we=s.toolCall.get(E);if(we){let je=z(A,B,we,"tool call",E);if(je)return G(()=>je);if(B===void 0&&le&&le.subagentRunId!==we.subagentRunId)return G(()=>new j(`Cannot send 'TOOL_CALL_START': tool call '${E}' is owned by '${we.subagentRunId??"(the parent agent)"}' but its parent message '${R}' is owned by '${le.subagentRunId??"(the parent agent)"}'. A tool call belongs to the message that carries it.`))}return o.add(E),we||s.toolCall.set(E,B===void 0?le??{subagentRunId:void 0}:{subagentRunId:B}),te(v)}case b.TOOL_CALL_ARGS:{let E=v.toolCallId;if(!o.has(E))return G(()=>new j(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${E}'. Start a tool call with 'TOOL_CALL_START' first.`));let R=z(A,v.subagentRunId,s.toolCall.get(E),"tool call",E);return R?G(()=>R):te(v)}case b.TOOL_CALL_END:{let E=v.toolCallId;if(!o.has(E))return G(()=>new j(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${E}'. A 'TOOL_CALL_START' event must be sent first.`));let R=z(A,v.subagentRunId,s.toolCall.get(E),"tool call",E);return R?G(()=>R):(o.delete(E),te(v))}case b.STEP_STARTED:{let E=v.stepName,R=v.subagentRunId;return m(R).has(E)?G(()=>new j(`Step "${E}" is already active for 'STEP_STARTED'${R===void 0?"":` in subagent '${R}'`}`)):(m(R).set(E,!0),te(v))}case b.STEP_FINISHED:{let E=v.stepName,R=v.subagentRunId;if(!m(R).has(E)){let B,le=!1;for(let[we,je]of u)if(we!==R&&je.has(E)){B=we,le=!0;break}return G(le?()=>new j(`Cannot send 'STEP_FINISHED' for step "${E}" attributed to ${R===void 0?"the parent agent":`subagent '${R}'`}: that step is open under ${B===void 0?"the parent agent":`subagent '${B}'`}. A step must be finished by whoever started it.`):()=>new j(`Cannot send 'STEP_FINISHED' for step "${E}" that was not started`))}return m(R).delete(E),te(v)}case b.ACTIVITY_SNAPSHOT:{let E=v.messageId;return(!s.activity.has(E)||v.replace!==!1)&&s.activity.set(E,{subagentRunId:v.subagentRunId}),te(v)}case b.TOOL_CALL_RESULT:{let E=v.messageId;return typeof E=="string"&&s.message.set(E,{subagentRunId:v.subagentRunId}),te(v)}case b.REASONING_START:case b.REASONING_MESSAGE_START:{let E=v.messageId,R=s.reasoning.get(E);if(R){let B=z(A,v.subagentRunId,R,"reasoning message",E);if(B)return G(()=>B)}return i.add(E),R||s.reasoning.set(E,{subagentRunId:v.subagentRunId}),te(v)}case b.REASONING_MESSAGE_CONTENT:case b.REASONING_MESSAGE_END:case b.REASONING_END:{let E=v.messageId,R=z(A,v.subagentRunId,s.reasoning.get(E),"reasoning message",E);return R?G(()=>R):(A===b.REASONING_END&&i.delete(E),te(v))}case b.REASONING_ENCRYPTED_VALUE:{let E=v.entityId,R=v.subtype,B=R==="tool-call"?s.toolCall.get(E):R==="message"?s.message.get(E)??s.reasoning.get(E):s.reasoning.get(E),le=R==="tool-call"?"tool call":R==="message"?"message":"reasoning message",we=z(A,v.subagentRunId,B,le,E);return we?G(()=>we):te(v)}case b.ACTIVITY_DELTA:{let E=v.messageId,R=z(A,v.subagentRunId,s.activity.get(E),"activity",E);return R?G(()=>R):te(v)}case b.SUBAGENT_STARTED:{if(typeof v.subagentRunId!="string")return G(()=>new j("Cannot send 'SUBAGENT_STARTED' without a 'subagentRunId'."));if(typeof v.name!="string")return G(()=>new j("Cannot send 'SUBAGENT_STARTED' without a 'name'."));let E=v.subagentRunId,R=v.parentSubagentRunId;return p.has(E)?G(()=>new j(`Cannot send 'SUBAGENT_STARTED': subagent '${E}' is already active. Finish it with 'SUBAGENT_FINISHED' first.`)):h.has(E)?G(()=>new j(`Cannot send 'SUBAGENT_STARTED': subagent '${E}' has already finished in this run. Subagent IDs are per-invocation and cannot be reused.`)):R!==void 0&&!p.has(R)&&!h.has(R)?G(()=>new j(`Cannot send 'SUBAGENT_STARTED': parentSubagentRunId '${R}' has not been started in this run.`)):(p.set(E,!0),te(v))}case b.SUBAGENT_FINISHED:case b.SUBAGENT_ERROR:{if(typeof v.subagentRunId!="string")return G(()=>new j(`Cannot send '${A}' without a 'subagentRunId'.`));if(A===b.SUBAGENT_ERROR&&typeof v.message!="string")return G(()=>new j("Cannot send 'SUBAGENT_ERROR' without a 'message'."));let E=v.subagentRunId;return p.has(E)?(p.delete(E),h.add(E),te(v)):G(()=>new j(`Cannot send '${A}': no active subagent found with ID '${E}'. A 'SUBAGENT_STARTED' event must be sent first.`))}case b.MESSAGES_SNAPSHOT:{let E=L(v.messages,!0);if(E)return G(()=>E)}return te(v);case b.RUN_STARTED:T=!0;{let E=L((v.input??{}).messages,!1);if(E)return G(()=>E)}return te(v);case b.RUN_FINISHED:if(w()){let E=[];for(let[B,le]of u)for(let we of le.keys())E.push(B===void 0?we:`${we} (subagent '${B}')`);let R=E.join(", ");return G(()=>new j(`Cannot send 'RUN_FINISHED' while steps are still active: ${R}`))}if(r.size>0){let E=Array.from(r.keys()).join(", ");return G(()=>new j(`Cannot send 'RUN_FINISHED' while text messages are still active: ${E}`))}if(o.size>0){let E=Array.from(o.keys()).join(", ");return G(()=>new j(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${E}`))}if(p.size>0){let E=Array.from(p.keys()).join(", ");return G(()=>new j(`Cannot send 'RUN_FINISHED' while subagents are still active: ${E}`))}return a=!0,te(v);case b.RUN_ERROR:return l=!0,te(v);case b.CUSTOM:return te(v);case b.THINKING_TEXT_MESSAGE_START:return g?x?G(()=>new j("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(x=!0,te(v)):G(()=>new j("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case b.THINKING_TEXT_MESSAGE_CONTENT:return x?te(v):G(()=>new j("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case b.THINKING_TEXT_MESSAGE_END:return x?(x=!1,te(v)):G(()=>new j("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case b.THINKING_START:return g?G(()=>new j("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(g=!0,te(v));case b.THINKING_END:return g?(g=!1,te(v)):G(()=>new j("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return te(v)}}))},fn=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),Fb=t=>ti(()=>un(t())).pipe(Ta(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return un(e.text()).pipe(Ue(i=>{let s=i;if(o.includes("application/json"))try{s=JSON.parse(i)}catch{}let a=Error(`HTTP ${e.status}: ${typeof s=="string"?s:JSON.stringify(s)}`);return a.status=e.status,a.payload=s,G(()=>a)}))}let n={type:fn.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new ce(o=>(o.next(n),(async()=>{try{for(;;){let{done:i,value:s}=await r.read();if(i)break;let a={type:fn.DATA,data:s};o.next(a)}o.complete()}catch(i){o.error(i)}})(),()=>{r.cancel().catch(i=>{if(i?.name!=="AbortError")throw i})})):G(()=>Error("Failed to getReader() from response"))})),$b=(t,e)=>{let n=Ar(e),r=new ft,o=new TextDecoder("utf-8",{fatal:!1}),i="";t.subscribe({next:a=>{if(a.type!==fn.HEADERS&&a.type===fn.DATA&&a.data){let l=o.decode(a.data,{stream:!0});i+=l;let c=i.split(/\n\n/);i=c.pop()||"";for(let u of c)s(u)}},error:a=>r.error(a),complete:()=>{i&&(i+=o.decode(),s(i)),r.complete()}});function s(a){let l=a.split(`
9
9
  `),c=[];for(let u of l)u.startsWith("data:")&&c.push(u.slice(5).replace(/^ /,""));if(c.length>0)try{let u=c.join(`
10
10
  `),m=JSON.parse(u);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(u){r.error(u)}}return r.asObservable()},Bb=t=>{let e=new ft,n=new Uint8Array;t.subscribe({next:o=>{if(o.type!==fn.HEADERS&&o.type===fn.DATA&&o.data){let i=new Uint8Array(n.length+o.data.length);i.set(n,0),i.set(o.data,n.length),n=i,r()}},error:o=>e.error(o),complete:()=>{if(n.length>0)try{r()}catch{console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function r(){for(;n.length>=4;){let o=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<o)break;try{let i=n.slice(4,o),s=Gu(i);e.next(s),n=n.slice(o)}catch(i){let s=i instanceof Error?i.message:String(i);e.error(Error(`Failed to decode protocol buffer message: ${s}`));return}}}return e.asObservable()},Vb=(t,e)=>{let n=Ar(e),r=new ft,o=new zo,i=!1;return t.subscribe({next:s=>{if(o.next(s),s.type===fn.HEADERS&&!i){i=!0;let a=s.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Ua?"protobuf":"sse"}),a===Ua?Bb(o).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):$b(o,n).subscribe({next:l=>{try{let c=To.parse(l);n?.event("HTTP","Event validated:",c,{type:c.type,valid:!0}),r.next(c)}catch(c){n?.event("HTTP","Event invalid:",{json:l,error:String(c)}),r.error(c)}},error:l=>{if(l?.name==="AbortError"){r.next({type:b.RUN_ERROR,message:l.message||"Request aborted",code:"abort",rawEvent:l}),r.complete();return}return r.error(l)},complete:()=>r.complete()})}else i||r.error(Error("No headers event received before data events"))},error:s=>{o.error(s),r.error(s)},complete:()=>{o.complete()}}),r.asObservable()},se=d.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),jb=d.enum(["LangGraphInterruptEvent","PredictState","Exit"]),qb=d.object({type:d.literal(se.enum.TextMessageStart),messageId:d.string(),parentMessageId:d.string().optional(),role:d.string().optional()}),Wb=d.object({type:d.literal(se.enum.TextMessageContent),messageId:d.string(),content:d.string()}),Xb=d.object({type:d.literal(se.enum.TextMessageEnd),messageId:d.string()}),Yb=d.object({type:d.literal(se.enum.ActionExecutionStart),actionExecutionId:d.string(),actionName:d.string(),parentMessageId:d.string().optional()}),Kb=d.object({type:d.literal(se.enum.ActionExecutionArgs),actionExecutionId:d.string(),args:d.string()}),Zb=d.object({type:d.literal(se.enum.ActionExecutionEnd),actionExecutionId:d.string()}),Qb=d.object({type:d.literal(se.enum.ActionExecutionResult),actionName:d.string(),actionExecutionId:d.string(),result:d.string()}),Jb=d.object({type:d.literal(se.enum.AgentStateMessage),threadId:d.string(),agentName:d.string(),nodeName:d.string(),runId:d.string(),active:d.boolean(),role:d.string(),state:d.string(),running:d.boolean()}),ev=d.object({type:d.literal(se.enum.MetaEvent),name:jb,value:d.any()}),tv=d.object({type:d.literal(se.enum.RunError),message:d.string(),code:d.string().optional()});d.discriminatedUnion("type",[qb,Wb,Xb,Yb,Kb,Zb,Qb,Jb,ev,tv]),d.object({id:d.string(),role:d.string(),content:d.string(),parentMessageId:d.string().optional()}),d.object({id:d.string(),name:d.string(),arguments:d.any(),parentMessageId:d.string().optional()}),d.object({id:d.string(),result:d.any(),actionExecutionId:d.string(),actionName:d.string()});var nv=t=>{if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.filter(n=>n.type==="text").map(n=>n.text).filter(n=>n.length>0);if(e.length!==0)return e.join(`
11
- `)},rv=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,u=[],m={},w=p=>{typeof p=="object"&&p&&("messages"in p&&delete p.messages,o=p)};return r.pipe(Ue(p=>{switch(p.type){case b.TEXT_MESSAGE_START:{let h=p;return[{type:se.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case b.TEXT_MESSAGE_CONTENT:{let h=p;return[{type:se.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case b.TEXT_MESSAGE_END:{let h=p;return[{type:se.enum.TextMessageEnd,messageId:h.messageId}]}case b.TOOL_CALL_START:{let h=p;return u.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),s=!0,m[h.toolCallId]=h.toolCallName,[{type:se.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case b.TOOL_CALL_ARGS:{let h=p,g=u.find(T=>T.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let x=!1;if(c){let T=c.find(S=>S.tool==g.function.name);if(T)try{let S=JSON.parse(ii(g.function.arguments));T.tool_argument&&T.tool_argument in S?(w({...o,[T.state_key]:S[T.tool_argument]}),x=!0):T.tool_argument||(w({...o,[T.state_key]:S}),x=!0)}catch{}}return[{type:se.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},...x?[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]:[]]}case b.TOOL_CALL_END:{let h=p;return[{type:se.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case b.TOOL_CALL_RESULT:{let h=p;return[{type:se.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case b.RAW:return[];case b.CUSTOM:{let h=p;switch(h.name){case"Exit":i=!1;break;case"PredictState":c=h.value;break}return[{type:se.enum.MetaEvent,name:h.name,value:h.value}]}case b.STATE_SNAPSHOT:return w(p.snapshot),[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}];case b.STATE_DELTA:{let h=p,g=Oo.applyPatch(o,h.delta,!0,!1);return g?(w(g.newDocument),[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]):[]}case b.MESSAGES_SNAPSHOT:return l=p.messages,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case b.RUN_STARTED:return[];case b.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:ov(l)}:{}}),active:!1}];case b.RUN_ERROR:{let h=p;return[{type:se.enum.RunError,message:h.message,code:h.code}]}case b.STEP_STARTED:return a=p.stepName,u=[],c=null,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!0}];case b.STEP_FINISHED:return u=[],c=null,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function ov(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=nv(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let i={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(i)}}else if(n.role==="tool"){let r="unknown";for(let i of t)if(i.role==="assistant"&&i.toolCalls?.length){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var iv=t=>t.kind==="tool"?t.fields.toolCallId:t.fields.messageId,sv=t=>t==="tool"?"toolCallId":"messageId",Qn=(t,e)=>e.metadata===void 0?t:{...t,metadata:e.metadata},Bi=t=>e=>{let n=Ar(t),r=new Map,o=l=>{let c=r.get(l);if(!c)return[];switch(r.delete(l),c.kind){case"text":{let u={type:b.TEXT_MESSAGE_END,messageId:c.fields.messageId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","TEXT_MESSAGE_END",u,{messageId:u.messageId}),[u]}case"tool":{let u={type:b.TOOL_CALL_END,toolCallId:c.fields.toolCallId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","TOOL_CALL_END",u,{toolCallId:u.toolCallId}),[u]}case"reasoning":{let u={type:b.REASONING_MESSAGE_END,messageId:c.fields.messageId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","REASONING_MESSAGE_END",u,{messageId:u.messageId}),[u]}}},i=()=>[...r.keys()].flatMap(l=>o(l)),s=(l,c)=>{for(let[u,m]of r)if(m.kind===l&&iv(m)===c)return{owner:u}},a=(l,c,u,m,w)=>{if(c!==void 0){let h=s(l,c);if(h){if(u!==void 0&&u!==h.owner)throw Error(`Cannot continue ${w} '${c}': chunk subagentRunId '${u}' does not match the open stream's subagent '${h.owner??"(the parent agent)"}'.`);return h.owner}return u}if(u!==void 0)return u;if(r.get(void 0)?.kind===l)return;let p=[...r.entries()].filter(([,h])=>h.kind===l);if(p.length===1)return p[0][0];if(p.length>1)throw Error(`Ambiguous ${m}: it carries neither a ${sv(l)} nor a subagentRunId, but ${p.length} lanes have an open ${w}. Attribute the chunk to the subagent it belongs to.`)};return e.pipe(Ue(l=>{switch(l.type){case b.TEXT_MESSAGE_START:case b.TEXT_MESSAGE_CONTENT:case b.TEXT_MESSAGE_END:case b.TOOL_CALL_START:case b.TOOL_CALL_ARGS:case b.TOOL_CALL_END:case b.TOOL_CALL_RESULT:case b.STATE_SNAPSHOT:case b.STATE_DELTA:case b.CUSTOM:case b.STEP_STARTED:case b.STEP_FINISHED:case b.THINKING_START:case b.THINKING_END:case b.THINKING_TEXT_MESSAGE_START:case b.THINKING_TEXT_MESSAGE_CONTENT:case b.THINKING_TEXT_MESSAGE_END:case b.REASONING_START:case b.REASONING_MESSAGE_START:case b.REASONING_MESSAGE_CONTENT:case b.REASONING_MESSAGE_END:case b.REASONING_END:return[...o(l.subagentRunId??void 0),l];case b.RUN_STARTED:case b.RUN_FINISHED:case b.RUN_ERROR:case b.MESSAGES_SNAPSHOT:return[...i(),l];case b.RAW:case b.ACTIVITY_SNAPSHOT:case b.ACTIVITY_DELTA:case b.REASONING_ENCRYPTED_VALUE:case b.SUBAGENT_STARTED:return[l];case b.SUBAGENT_FINISHED:case b.SUBAGENT_ERROR:{let c=l.subagentRunId;return c==null?[l]:[...o(c),l]}case b.TEXT_MESSAGE_CHUNK:{let c=l,u=a("text",c.messageId,c.subagentRunId??void 0,"TEXT_MESSAGE_CHUNK","text message"),m=r.get(u),w=[],p;if(m?.kind==="text"&&(c.messageId===void 0||c.messageId===m.fields.messageId))p=m.fields;else{if(w.push(...o(u)),c.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");p={messageId:c.messageId,name:c.name,subagentRunId:c.subagentRunId},r.set(u,{kind:"text",fields:p});let h=Qn({type:b.TEXT_MESSAGE_START,messageId:c.messageId,role:c.role||"assistant",...c.name!==void 0&&{name:c.name},...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","TEXT_MESSAGE_START",h,{messageId:c.messageId})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.TEXT_MESSAGE_CONTENT,messageId:p.messageId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",g,{messageId:p.messageId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.TEXT_MESSAGE_CONTENT,messageId:p.messageId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}case b.TOOL_CALL_CHUNK:{let c=l,u=a("tool",c.toolCallId,c.subagentRunId??void 0,"TOOL_CALL_CHUNK","tool call"),m=r.get(u),w=[],p;if(m?.kind==="tool"&&(c.toolCallId===void 0||c.toolCallId===m.fields.toolCallId))p=m.fields;else{if(w.push(...o(u)),c.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(c.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");p={toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId,subagentRunId:c.subagentRunId},r.set(u,{kind:"tool",fields:p});let h=Qn({type:b.TOOL_CALL_START,toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId,...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","TOOL_CALL_START",h,{toolCallId:c.toolCallId,toolCallName:c.toolCallName})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.TOOL_CALL_ARGS,toolCallId:p.toolCallId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","TOOL_CALL_ARGS",g,{toolCallId:p.toolCallId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.TOOL_CALL_ARGS,toolCallId:p.toolCallId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}case b.REASONING_MESSAGE_CHUNK:{let c=l,u=a("reasoning",c.messageId,c.subagentRunId??void 0,"REASONING_MESSAGE_CHUNK","reasoning message"),m=r.get(u),w=[],p;if(m?.kind==="reasoning"&&(c.messageId===void 0||c.messageId===m.fields.messageId))p=m.fields;else{if(w.push(...o(u)),c.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");p={messageId:c.messageId,subagentRunId:c.subagentRunId},r.set(u,{kind:"reasoning",fields:p});let h=Qn({type:b.REASONING_MESSAGE_START,messageId:c.messageId,role:"reasoning",...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","REASONING_MESSAGE_START",h,{messageId:c.messageId})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.REASONING_MESSAGE_CONTENT,messageId:p.messageId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",g,{messageId:p.messageId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.REASONING_MESSAGE_CONTENT,messageId:p.messageId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}}return l.type,[]}),hn(()=>{i()}))};function av(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function eh(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),o=[...n].filter(s=>!r.has(s));if(o.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${o.join(", ")}`);let i=[...r].filter(s=>!n.has(s));if(i.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${i.join(", ")}`);return t.map(s=>{let a=e[s.id],l={interruptId:s.id,status:a.status};return a.status==="resolved"&&a.payload!==void 0&&(l.payload=a.payload),a.metadata!==void 0&&(l.metadata=a.metadata),l})}var kr=class{runNext(t,e){return e.run(t).pipe(Bi(!1))}runNextWithState(t,e){let n=J(t.messages||[]),r=J(t.state||{}),o=new zo;return Ju(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(ni(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:J(n),state:J(r)})))}},lv=class extends kr{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function cv(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var dv=class extends kr{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(cv)};return this.runNext(o,e)}},Vu="THINKING_START",ju="THINKING_END",qu="THINKING_TEXT_MESSAGE_START",Wu="THINKING_TEXT_MESSAGE_CONTENT",Xu="THINKING_TEXT_MESSAGE_END",uv=class extends kr{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(Lt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Vu:{this.currentReasoningId=Ie();let{title:e,...n}=t;return this.warnAboutTransformation(Vu,b.REASONING_START),{...n,type:b.REASONING_START,messageId:this.currentReasoningId}}case qu:return this.currentMessageId=Ie(),this.warnAboutTransformation(qu,b.REASONING_MESSAGE_START),{...t,type:b.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Wu:{let{delta:e,...n}=t;return this.warnAboutTransformation(Wu,b.REASONING_MESSAGE_CONTENT),{...n,type:b.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Ie(),delta:e}}case Xu:{let e=this.currentMessageId??Ie();return this.warnAboutTransformation(Xu,b.REASONING_MESSAGE_END),{...t,type:b.REASONING_MESSAGE_END,messageId:e}}case ju:{let e=this.currentReasoningId??Ie();return this.warnAboutTransformation(ju,b.REASONING_END),{...t,type:b.REASONING_END,messageId:e}}default:return t}}};function hv(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function pv(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function fv(t){let e=hv(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function mv(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>pv(r)?fv(r):r);return{...t,content:n}}var gv=class extends kr{run(t,e){let n={...t,messages:t.messages.map(mv)};return this.runNext(n,e)}},Yu="SUBAGENT_STARTED",Ku="SUBAGENT_FINISHED",Zu="SUBAGENT_ERROR";function Vi(t){if(t&&typeof t=="object"&&"subagentRunId"in t){let{subagentRunId:e,...n}=t;return n}return t}function Qu(t){return t.map(e=>Vi(e))}var bv=class extends kr{warnDroppedLifecycleEvent(t){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is dropping ${t} because the target agent predates subagent support. To remove this warning, upgrade your AG-UI integration package. To suppress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){let n={...t,messages:(t.messages??[]).map(r=>Vi(r))};return this.runNext(n,e).pipe(oi(r=>{let o=r.type;(o===Yu||o===Ku||o===Zu)&&this.warnDroppedLifecycleEvent(o)}),Ea(r=>{let o=r.type;return o!==Yu&&o!==Ku&&o!==Zu}),Lt(r=>{let o=Vi(r);if(o.type===b.MESSAGES_SNAPSHOT){let i=o;if(Array.isArray(i.messages))return{...i,messages:Qu(i.messages)}}if(o.type===b.RUN_FINISHED){let i=o;if(i.outcome&&Array.isArray(i.outcome.interrupts))return{...i,outcome:{...i.outcome,interrupts:i.outcome.interrupts.map(s=>Vi(s))}}}if(o.type===b.RUN_STARTED){let i=o;if(i.input&&Array.isArray(i.input.messages))return{...i,input:{...i.input,messages:Qu(i.input.messages)}}}return o}))}},vv="0.0.59",yv=class{get maxVersion(){return vv}get debug(){return this._debug}set debug(t){this._debug=$i(t),this._debugLogger=za(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?za($i(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:i}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??Rt(),this.messages=J(r??[]),this.state=J(o??{}),this._debug=$i(i),this._debugLogger=za(this._debug),Zn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new dv),Zn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new uv),Zn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new gv),Zn(this.maxVersion,"0.0.57")<=0&&this.middlewares.unshift(new bv)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new lv(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Rt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new ft;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ei(Go(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:u=>c.run(u,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),Bi(this.debugLogger),Fa(this.debugLogger),l=>l.pipe(ri(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),_r(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,i))),hn(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=J(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new la}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Rt();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new ft;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ei(Go(()=>ti(()=>this.connect(n)),Bi(this.debugLogger),Fa(this.debugLogger),l=>l.pipe(ri(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),_r(l=>(this.isRunning=!1,l instanceof la?Fo:this.onError(n,l,i))),hn(()=>{this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=J(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Ju(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(oi(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=J(this.messages);for(let r of e)r.subagentRunId===null&&delete r.subagentRunId;let n=e.filter(r=>r.role!=="activity");return{threadId:this.threadId,runId:t?.runId||Rt(),tools:J(t?.tools??[]),context:J(t?.context??[]),forwardedProps:J(t?.forwardedProps??{}),state:J(this.state),messages:n,...t?.resume===void 0?{}:{resume:J(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(i=>i.interruptId)),o=this.pendingInterrupts.map(i=>i.id).filter(i=>!r.has(i));if(o.length>0)throw new j(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let i of this.pendingInterrupts)if(av(i))throw new j(`Interrupt ${i.id} expired at ${i.expiresAt}`)}let n=await ne(e,this.messages,this.state,(r,o,i)=>r.onRunInitialized?.({messages:o,state:i,agent:this,input:t}));if(n.messages!==void 0||n.state!==void 0){if(n.messages){this.messages=n.messages;for(let r of n.messages)r.subagentRunId===null&&delete r.subagentRunId;t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})}n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}}onError(t,e,n){return un(ne(n,this.messages,this.state,(r,o,i)=>r.onRunFailed?.({error:e,messages:o,state:i,agent:this,input:t}))).pipe(Lt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let i=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||i==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await ne(e,this.messages,this.state,(r,o,i)=>r.onRunFinalized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=J(this.messages),t.state=J(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=J(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=J(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=J(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??Rt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Bi(this.debugLogger),Fa(this.debugLogger),rv(this.threadId,e.runId,this.agentId),n=>n.pipe(Lt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}};function wv(t){if(!Array.isArray(t.messages))return t;let e=!1,n=t.messages.map(r=>{if(r.subagentRunId===null){e=!0;let o={...r};return delete o.subagentRunId,o}return r});return e?{...t,messages:n}:t}var th=class extends yv{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(wv(t)),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=J(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return Vb(Fb(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=J(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var xv=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function nh(t,e){let n=[];return{text:t.replace(xv,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function Ev(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&(e.prompt===void 0||typeof e.prompt=="string")}function Va(t){return Array.isArray(t)?t.filter(Ev):[]}var ji=["top-left","top-right","bottom-left","bottom-right"];function rh(t){return ji.includes(t)}function ja(t){return[{name:"read_chat_surface",description:"Describe the chat panel you are speaking from: its placement, whether it is collapsed, whether it can be moved, and the box it occupies. Read this before moving or minimising yourself, since a full-screen panel has nowhere to move to. Read-only.",parameters:{type:"object",properties:{},required:[],[xe]:"Read the chat's own position"},handler:()=>t.describeSurface()},{name:"move_chat",description:"Move your own panel to a corner, to uncover something the user needs to see. `corner` is top-left, top-right, bottom-left or bottom-right. Answers `moved: false` with a reason when the placement owns its position or the panel fills the screen; check `read_chat_surface` first, and prefer minimise_chat when there is nowhere to move to.",parameters:{type:"object",properties:{corner:{type:"string",enum:[...ji]}},required:["corner"],[xe]:"Move the chat out of the way"},handler:e=>{let n=String(e.corner??""),r=t.describeSurface();return rh(n)?r.movable?{moved:t.moveTo(n,{announce:!0}),corner:n}:{moved:!1,reason:r.fullBleed?"the panel fills the screen, so there is nowhere to move it to":r.draggable===!1?"this page has turned off moving the panel":`the "${r.placement??""}" placement owns the panel's position`,suggestion:r.collapsible?"minimise_chat":null}:{moved:!1,reason:`"${n}" is not a corner; use one of ${ji.join(", ")}`}}},{name:"minimise_chat",description:"Collapse your own panel to its launcher, so the user can see the whole page. The launcher stays visible and reopens it. Answers `minimised: false` when the placement has no collapsed state, which is the case for a full-page chat.",parameters:{type:"object",properties:{},required:[],[xe]:"Minimise the chat"},handler:()=>t.describeSurface().collapsible?(t.setCollapsed(!0,{announce:!0}),{minimised:!0}):{minimised:!1,reason:"this placement has no collapsed state, so there is no launcher to return to"}},{name:"restore_chat",description:"Open your own panel again after minimising it.",parameters:{type:"object",properties:{},required:[],[xe]:"Restore the chat"},handler:()=>(t.setCollapsed(!1),{restored:!0})}]}var Ir=class{#t=new Map;register(e){this.#t.set(e.name,e)}has(e){return this.#t.has(e)}get(e){let n=this.#t.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#t.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function qa(t){return t[hr]===!0}function qi(t){return t[pr]===!0}var _v="#4f46e5";function Jn(t,e,n){let r=window.getComputedStyle(t).getPropertyValue(e).trim();return r===""?n:r}var Tv=4;function Wa(t,e={}){let n=document.createElement("div");n.setAttribute("data-ag-ui-highlight",""),n.setAttribute("aria-hidden","true"),n.style.cssText=["position: fixed","inset: 0","pointer-events: none",`z-index: ${Jn(t,"--ag-ui-highlight-z-index",String(Yc))}`].join(";");let r=document.createElement("div"),o=document.createElement("div");n.className="ag-ui-highlight",r.className="ag-ui-highlight-scrim",o.className="ag-ui-highlight-ring",e.scrim===!0&&n.append(r),n.append(o);let i=e.ringWidth??Number.parseFloat(Jn(t,"--ag-ui-highlight-ring-width","3")),s=e.flowMs??Number.parseFloat(Jn(t,"--ag-ui-highlight-flow-ms","2400")),a=()=>{let u=t.getBoundingClientRect(),m=e.padding??Tv,w=e.radius??Number.parseFloat(getComputedStyle(t).borderRadius),p=u.left-m,h=u.top-m,g=u.width+m*2,x=u.height+m*2;e.scrim===!0&&(r.style.cssText=["position: absolute","inset: 0",`background: ${Jn(t,"--ag-ui-highlight-scrim","rgba(15, 15, 25, 0.45)")}`,`clip-path: path(evenodd, '${kv(p,h,g,x,w+m)}')`].join(";")),o.style.cssText=["position: absolute",`left: ${p}px`,`top: ${h}px`,`width: ${g}px`,`height: ${x}px`,`border-radius: ${w+m}px`,`border: ${i}px solid transparent`,"box-sizing: border-box",Av(t,e)].join(";")};a();let l=null;e.gradient===!0&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches&&(l=o.animate([{backgroundPosition:"100% 0"},{backgroundPosition:"-100% 0"}],{duration:s,iterations:Number.POSITIVE_INFINITY,easing:"linear"}));let c={capture:!0,passive:!0};return window.addEventListener("scroll",a,c),window.addEventListener("resize",a,c),document.body.appendChild(n),()=>{window.removeEventListener("scroll",a,c),window.removeEventListener("resize",a,c),l?.cancel(),n.remove()}}function Sv(t){return t===void 0?null:CSS.supports("color",t)?t:null}function Av(t,e){let n=Sv(e.color)??Jn(t,"--ag-ui-accent",_v);if(e.gradient!==!0)return`border-color: ${n}`;let r=Jn(t,"--ag-ui-highlight-gradient",`linear-gradient(115deg, transparent 20%, ${n} 50%, transparent 80%)`),o="linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)";return[`background-image: ${r}`,"background-origin: border-box","background-size: 300% 100%",`-webkit-mask: ${o}`,`mask: ${o}`,"-webkit-mask-composite: xor","mask-composite: exclude","background-position: 50% 0"].join(";")}function kv(t,e,n,r,o){let i=Math.max(0,Math.min(o,n/2,r/2)),s=t+n,a=e+r,l=`M 0 0 H ${window.innerWidth} V ${window.innerHeight} H 0 Z`,c=[`M ${t+i} ${e}`,`H ${s-i}`,`A ${i} ${i} 0 0 1 ${s} ${e+i}`,`V ${a-i}`,`A ${i} ${i} 0 0 1 ${s-i} ${a}`,`H ${t+i}`,`A ${i} ${i} 0 0 1 ${t} ${a-i}`,`V ${e+i}`,`A ${i} ${i} 0 0 1 ${t+i} ${e}`,"Z"].join(" ");return`${l} ${c}`}function Wi(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Iv=Wi(HTMLInputElement.prototype,"value"),Rv=Wi(HTMLTextAreaElement.prototype,"value"),Cv=Wi(HTMLSelectElement.prototype,"value"),Nv=Wi(HTMLInputElement.prototype,"checked");function mn(t,e){t instanceof HTMLTextAreaElement?Rv.call(t,e):t instanceof HTMLSelectElement?Cv.call(t,e):Iv.call(t,e)}function Rr(t,e){Nv.call(t,e)}var Xa="#4f46e5",Ov="rgba(79, 70, 229, 0.4)",Mv="--ag-ui-accent";function er(t){return new Promise(e=>{setTimeout(e,t)})}function Xi(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ya(t){return t<=0||Xi()?Promise.resolve():er(t)}function Yi(t,e){let n=window.getComputedStyle(t).getPropertyValue(Mv).trim();return n===""?e:n}function oh(t){return`0 0 0 3px ${Yi(t,Ov)}`}async function Ka(t,e,n={}){let r=n.charDelayMs??35;mn(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)mn(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await er(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Za(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${Yi(t,Xa)}`,t.style.outlineOffset="2px",await er(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}var Lv=600,Pv=100;function _t(t,e={}){let n=Xi();return t.scrollIntoView({block:"center",inline:"nearest",behavior:n?"auto":"smooth"}),n?Promise.resolve():new Promise(r=>{let o,i=()=>{clearTimeout(o),document.removeEventListener("scroll",s,!0),document.removeEventListener("scrollend",i,!0),r()},s=()=>{document.removeEventListener("scroll",s,!0),clearTimeout(o),o=setTimeout(i,e.settleMs??Lv)};o=setTimeout(i,Pv),document.addEventListener("scroll",s,!0),document.addEventListener("scrollend",i,!0)})}var Dv=1200,Uv=1/3;async function ih(t,e,n){(e.focus??n)&&t.focus({preventScroll:!0});let r=e.flashMs??Dv;if(r<=0)return;if(e.scrim===!0||e.gradient===!0){let c=Wa(t,{scrim:e.scrim===!0,gradient:e.gradient===!0,...e.color===void 0?{}:{color:e.color},...e.ringPadding===void 0?{}:{padding:e.ringPadding}});await er(r),c();return}let o=t.style.outline,i=t.style.outlineOffset,s=t.style.transition,a=e.color??Yi(t,Xa);t.style.outline=`3px solid ${a}`,t.style.outlineOffset="2px";let l=Xi()?0:Math.round(r*Uv);await er(r-l),l>0&&(t.style.transition=`outline-color ${l}ms ease-out`,t.style.outline="3px solid transparent",await er(l)),t.style.outline=o,t.style.outlineOffset=i,t.style.transition=s}function Hv(t,e={}){return ih(t,e,!1)}function Qa(t,e={}){return ih(t,e,!0)}async function Ja(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,i=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=oh(t),await Ya(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function Gv(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function el(t,e,n={}){let r=Gv(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,i=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${Yi(t,Xa)}`,t.style.outlineOffset="2px",await Ya(o),mn(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=i,t.style.outlineOffset=s}async function tl(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=oh(t),await Ya(r),Rr(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var Nr={SCROLL:"scroll",DRAG:"drag",CHAT:"chat"};function nl(t,e){let n=[];return t.has(Nr.SCROLL)&&n.push(zv(e)),t.has(Nr.DRAG)&&n.push(Fv(e)),n}function zv(t){return{name:"scroll_to",description:"Scroll a target into view. `target` is `top`, `bottom`, or a CSS selector / page-map element id. Read-only: it changes nothing on the page.",parameters:{type:"object",properties:{target:{type:"string"}},required:["target"],[xe]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let o=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:o,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return _t(r),{scrolled:!0,target:n}}}}function Fv(t){return{name:"drag_and_drop",description:"Drag the `from` element onto the `to` element (CSS selectors or page-map element ids), firing the page's native drag-and-drop. Use for reordering sortable lists. The page decides what the drop commits.",parameters:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"],[xe]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),o=t(n);if(o===null)throw new Error(`no element matching "${n}"`);let i=t(r);if(i===null)throw new Error(`no element matching "${r}"`);return $v(o,i),{dragged:!0,from:n,to:r}}}}function $v(t,e){let n=new DataTransfer;Cr(t,"dragstart",n),Cr(e,"dragenter",n),Cr(e,"dragover",n),Cr(e,"drop",n),Cr(t,"dragend",n)}function Cr(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function rl(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Ki(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[xe]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[hr]:!0,[xe]:`Update ${t.name}`},handler:r=>n(r)}),e}var Bv=Ki;function ol(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,i=r.summary,s=r.description;typeof o=="string"&&typeof i=="string"&&(e[o]=typeof s=="string"?{name:o,summary:i,description:s}:{name:o,summary:i})}return e}var sh=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Vv(t){return[...t.matchAll(sh)].map(e=>e[0].slice(1))}function jv(t,e,n){let r={...n};return{path:e.replace(sh,(i,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function qv(t,e){let n=new URLSearchParams;for(let[o,i]of Object.entries(e))n.set(o,String(i));let r=n.toString();return r===""?t:`${t}?${r}`}function il(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[xe]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Vv(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[pr]:!0,[xe]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(u=>u.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=jv(o.id,o.path,i),l=qv(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}var ae={title:"Assistant",chatHistory:"Chat history",closeHistory:"Close history",searchConversations:"Search conversations",queued:"Waiting to send",removeQueued:'Do not send "{text}"',noMatches:"No conversations match that.",chatMoved:"Moved this panel out of the way",chatMinimised:"Minimised this panel",undo:"Undo",newChat:"New chat",collapse:"Collapse",expand:"Expand",expandUnread:"Expand \u2014 {count} unread",toggleTheme:"Toggle theme",copyCode:"Copy",copied:"Copied",copyFailed:"Copy failed",checkpoints:"Continue a run",noCheckpoints:"Nothing to continue yet.",resumeRun:"Resume",forkRun:"Fork",forkedRun:"branched",conversation:"Conversation",jumpToLatest:"Jump to latest",announceResponding:"Assistant is responding",announceAnswerReady:"Assistant answered",announceAwaitingDecision:"{count} action is waiting for your approval",announceStopped:"Response stopped",announceFailed:"The response failed",thinking:"Assistant is thinking\u2026",thoughts:"Thoughts",stopped:"\u23F9 Stopped",connectionLost:"Connection lost",noResult:"No result returned.",declinedAction:"User declined the action.",navigating:"Navigating\u2026",historyReplaced:"The server replaced this conversation's history. Reload to see the updated transcript.",chartUndrawable:"A chart could not be drawn from the data sent, so it was removed.",historyCompacted:"Earlier turns condensed to fit the context window ({count} removed)",usingSkill:"Using skill {name}",runInterrupted:"The previous response didn\u2019t finish \u2014 the page changed before it arrived.",pageMoved:"The page changed since you last looked at it. Call read_page to see the current page, then retry.",attachmentsStillUploading:"{n} file still uploading \u2014 it was not sent with this message and is still attached.",notConnected:"This chat isn\u2019t connected to an agent, so the message wasn\u2019t sent.",continueNeedsTurn:"Type the next turn in the composer first, then pick a run to continue.",skillNeeds:"\u201C{title}\u201D needs {fields} \u2014 fill it in below, then send.",message:"Message",inputPlaceholder:"Ask anything\u2026",send:"Send",stop:"Stop",attachFiles:"Attach files",recordVoice:"Record voice",stopRecording:"Stop recording",transcribing:"Transcribing\u2026",transcriptionFailed:"Transcription failed",recordingLimit:"Stopped at the {n}-minute limit \u2014 transcribing what was recorded.",toolRunning:"running\u2026",toolDeferred:"waiting for you",toolDone:"\u2713 done",toolError:"\u26A0 error",toolDeclined:"\u2298 declined",resizePanel:"Resize the chat panel",decisionApproved:"approved by you",decisionDeclined:"declined by you",argumentsLabel:"Arguments",resultLabel:"Result",errorLabel:"Error",declinedLabel:"Declined",details:"Details",subAgentWorking:"Working\u2026",subAgentDelegatedTo:"Delegated to {agent}",subAgentFinished:"{agent} finished",subAgentFailed:"The sub-agent failed",subAgentSteps:"Steps the sub-agent took",approvalEditArgs:"Edit the arguments before approving",approvalArgsInvalid:"That is not valid JSON, so nothing was sent.",approvalArgsNotAnObject:"Arguments have to be a JSON object.",suggestions:"Suggested follow-ups",messageActions:"Message actions",quoteSelection:"Quote",copyMessage:"Copy message",retryMessage:"Try again",feedbackUp:"Good answer",feedbackDown:"Poor answer",confirmAction:"Confirm action",confirmAlways:"Always allow",confirmRun:"Run \u201C{tool}\u201D?",confirm:"Confirm",cancel:"Cancel",approveAction:"Approve action",approvalPrompt:"Approve this action?",approve:"Approve",deny:"Deny",askUserAction:"Question",otherOption:"Other\u2026",answerPlaceholder:"Type your answer\u2026",submit:"Submit",chats:"Chats",noConversations:"No conversations yet.",rename:"Rename",renameConversation:"Rename conversation",delete:"Delete",deleteConversation:"Delete conversation",deletePrompt:"Delete?",tooLarge:"Too large (max {size})",fileTypeNotAllowed:"File type not allowed",uploadFailed:"upload failed",retry:"Retry",retryUpload:"Retry upload",remove:"Remove",removeAttachment:"Remove attachment",justNow:"just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago",weeksAgo:"{n}w ago"};function sl(t){let e={...ae};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function ah(t,e){let n=document.createElement("button");return n.type="button",n.className=`approval-btn approval-btn--${t}`,n.setAttribute("part",`approval-button approval-${t}`),n.textContent=e,n}function al(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="approval",i.setAttribute("part","approval"),e.toolName!==void 0&&i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.approveAction);let s=document.createElement("div");s.className="approval-body",s.setAttribute("part","approval-body"),s.textContent=e.message??r.approvalPrompt;let a=Wv(e,n,r),l=document.createElement("div");l.className="approval-actions",l.setAttribute("part","approval-actions");let c=ah("deny",r.deny),u=ah("approve",r.approve),m=!1,w=p=>{m||(m=!0,c.disabled=!0,u.disabled=!0,i.setAttribute("data-resolved",p?"approved":"denied"),o(p))};if(c.addEventListener("click",()=>w(!1)),u.addEventListener("click",()=>{a!==null&&!a.commit()||w(!0)}),n.signal?.addEventListener("abort",()=>w(!1),{once:!0}),l.append(c,u),i.append(s,...a===null?[]:[a.root],l),t.appendChild(i),n.signal?.aborted===!0){w(!1);return}u.focus()})}function Wv(t,e,n){let{onEdit:r}=e;if(r===void 0||t.args===void 0)return null;let o=JSON.stringify(t.args,null,2),i=document.createElement("div");i.className="approval-edit",i.setAttribute("part","approval-edit");let s=document.createElement("textarea");s.className="approval-args",s.setAttribute("part","approval-args"),s.setAttribute("aria-label",n.approvalEditArgs),s.rows=Math.min(10,o.split(`
12
- `).length),s.value=o;let a=document.createElement("div");return a.className="approval-error",a.setAttribute("part","approval-error"),a.setAttribute("role","alert"),a.hidden=!0,i.append(s,a),{root:i,commit:()=>{if(s.value===o)return!0;let l;try{l=JSON.parse(s.value)}catch{return a.textContent=n.approvalArgsInvalid,a.hidden=!1,s.focus(),!1}return typeof l!="object"||l===null||Array.isArray(l)?(a.textContent=n.approvalArgsNotAnObject,a.hidden=!1,s.focus(),!1):(a.hidden=!0,r(l),!0)}}}function ll(t,e){for(let n of Array.from(t.querySelectorAll("pre"))){let r=n.querySelector("code");r===null||n.querySelector(".code-copy")!==null||(n.classList.add("has-copy"),n.append(Xv(r,e)))}}function Xv(t,e){let n=t.textContent,r=document.createElement("button");return r.type="button",r.className="code-copy",r.setAttribute("part","code-copy"),r.textContent=e.copyCode,r.title=e.copyCode,r.setAttribute("aria-label",e.copyCode),r.addEventListener("click",()=>{Yv(n).then(o=>{Kv(r,o?e.copied:e.copyFailed,e)})}),r}async function Yv(t){let e=navigator.clipboard;if(e===void 0)return!1;try{return await e.writeText(t),!0}catch{return!1}}function Kv(t,e,n){t.textContent=e,t.dataset.state=e===n.copied?"copied":"failed",setTimeout(()=>{t.textContent=n.copyCode,delete t.dataset.state},1500)}function cl(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(Zv(n));return e}function Zv(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready",e.setAttribute("part","attachment-chip");let n=document.createElement("span");n.className="attachment-chip-icon",n.setAttribute("part","attachment-chip-icon"),n.innerHTML=dl(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.setAttribute("part","attachment-chip-name"),r.textContent=t.name,r.title=t.name;let o=document.createElement("span");return o.className="attachment-chip-size",o.setAttribute("part","attachment-chip-size"),o.textContent=Zi(t.size),e.append(n,r,o),e}function dl(t){return t.startsWith("image/")?jc:t==="application/pdf"?qc:t.startsWith("text/")?Wc:Vc}function Zi(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${e[r]}`}var Qi=class{element;#t;#n;#e=[];constructor(e){this.#t=e,this.#n=e.strings??ae,this.element=document.createElement("div"),this.element.className="attachment-tray",this.element.setAttribute("part","attachment-tray"),this.element.hidden=!0}add(e){let n={localId:Ie(),file:e,status:Ge.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#e.push(n);let r=this.#s(e);if(r!==null){n.status=Ge.ERROR,n.error=r,this.#o(),this.#t.onChange?.();return}this.#o(),this.#t.onChange?.(),this.#r(n)}readyRefs(){let e=[];for(let n of this.#e)n.ref!==null&&e.push(n.ref);return e}hasPending(){return this.#e.some(e=>e.status===Ge.UPLOADING)}pendingCount(){return this.#e.filter(e=>e.status===Ge.UPLOADING).length}isEmpty(){return this.#e.length===0}clearReady(){this.#e=this.#e.filter(e=>e.status===Ge.UPLOADING),this.#o()}clear(){for(let e of this.#e)e.controller?.abort();this.#e=[],this.#o()}dispose(){for(let e of this.#e)e.controller?.abort()}#s(e){return this.#t.maxBytes>0&&e.size>this.#t.maxBytes?this.#n.tooLarge.replace("{size}",Zi(this.#t.maxBytes)):Qv(this.#t.accept,e)?null:this.#n.fileTypeNotAllowed}#r(e){let n=this.#s(e.file);if(n!==null){e.status=Ge.ERROR,e.error=n,this.#o(),this.#t.onChange?.();return}e.status=Ge.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#o(),this.#t.upload(e.file,o=>{e.progress=o,this.#o()},r.signal).then(o=>{e.status=Ge.READY,e.ref=o}).catch(o=>{e.status=Ge.ERROR,e.error=o instanceof Error?o.message:this.#n.uploadFailed}).finally(()=>{e.controller=null,this.#o(),this.#t.onChange?.()})}#i(e){e.controller?.abort(),this.#e=this.#e.filter(n=>n!==e),this.#o(),this.#t.onChange?.()}#o(){this.element.replaceChildren(),this.element.hidden=this.#e.length===0;for(let e of this.#e)this.element.appendChild(this.#u(e))}#u(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`,n.setAttribute("part","attachment-chip");let r=document.createElement("span");r.className="attachment-chip-icon",r.setAttribute("part","attachment-chip-icon"),r.innerHTML=dl(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.setAttribute("part","attachment-chip-name"),o.textContent=e.file.name,o.title=e.file.name;let i=document.createElement("span");if(i.className="attachment-chip-size",i.setAttribute("part","attachment-chip-size"),i.textContent=e.status===Ge.ERROR?e.error:Zi(e.file.size),n.append(r,o,i),e.status===Ge.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar",a.setAttribute("part","attachment-chip-bar");let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.setAttribute("part","attachment-chip-bar-fill"),l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Ge.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.setAttribute("part","attachment-chip-retry"),a.title=this.#n.retry,a.setAttribute("aria-label",this.#n.retryUpload),a.textContent="\u21BB",a.addEventListener("click",()=>this.#r(e)),n.appendChild(a)}let s=document.createElement("button");return s.type="button",s.className="attachment-chip-remove",s.setAttribute("part","attachment-chip-remove"),s.title=this.#n.remove,s.setAttribute("aria-label",this.#n.removeAttachment),s.textContent="\u2715",s.addEventListener("click",()=>this.#i(e)),n.appendChild(s),n}};function Qv(t,e){let n=t.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(i=>i.startsWith(".")?o.endsWith(i):i.endsWith("/*")?r.startsWith(i.slice(0,-1)):r===i)}var Jv="http://www.w3.org/2000/svg",$e={top:20,right:12,bottom:30,left:44},ey=480,ty=220,ny=220/480,ry=160,oy=320,lh=8,iy=5.6,ch=["var(--ag-ui-chart-1, #4f7cff)","var(--ag-ui-chart-2, #21b573)","var(--ag-ui-chart-3, #e0803c)","var(--ag-ui-chart-4, #b563d8)","var(--ag-ui-chart-5, #d84f6e)","var(--ag-ui-chart-6, #3ba7c4)"];function gn(t){return ch[t%ch.length]}function dh(t){let e=Math.max(ty,t),n=Math.min(oy,Math.max(ry,Math.round(e*ny)));return{width:e,height:n,plotW:e-$e.left-$e.right,plotH:n-$e.top-$e.bottom}}function mt(t,e){let n=document.createElementNS(Jv,t);for(let[r,o]of Object.entries(e))n.setAttribute(r,String(o));return n}function uh(t,e){let n=mt("text",{"font-size":10,fill:"currentColor","fill-opacity":.65,...e});return n.textContent=t,n}function sy(t){let e=[];return t.labels.forEach((n,r)=>{let o=0;for(let i of t.series)o+=i.points[r]??0,e.push(o)}),e}function ay(t){let e=t.kind==="stacked"?sy(t):t.series.flatMap(o=>[...o.points]),n=Math.max(0,...e),r=Math.min(0,...e);return n===r?{min:r,max:n+1}:{min:r,max:n}}function bn(t,e,n,r){return $e.top+r.plotH-(t-e)/(n-e)*r.plotH}function ul(t,e,n){let r=n.plotW/e;return $e.left+r*t+r/2}function ly(t,e){let n=e.plotW/t.length,r=Math.max(...t.map(o=>o.length))*iy;return Math.max(1,Math.ceil(r/n))}function cy(t,e,n,r,o){for(let s of[r,o]){let a=bn(s,r,o,n);t.appendChild(mt("line",{x1:$e.left,y1:a,x2:n.width-$e.right,y2:a,stroke:"currentColor","stroke-opacity":s===r?.35:.12})),t.appendChild(uh(String(Math.round(s)),{x:$e.left-6,y:a+4,"text-anchor":"end"}))}let i=ly(e.labels,n);e.labels.forEach((s,a)=>{a%i===0&&t.appendChild(uh(s,{x:ul(a,e.labels.length,n),y:n.height-$e.bottom+16,"text-anchor":"middle"}))})}function dy(t,e,n,r,o){let i=n.plotW/e.labels.length,s=i*.7/e.series.length,a=bn(r,r,o,n);e.series.forEach((l,c)=>{l.points.forEach((u,m)=>{let w=bn(u,r,o,n);t.appendChild(mt("rect",{x:$e.left+i*m+i*.15+s*c,y:w,width:s,height:Math.max(1,a-w),fill:gn(c),rx:2}))})})}function uy(t,e,n,r,o){let i=n.plotW/e.labels.length,s=i*.7,a=e.labels.map(()=>0);e.series.forEach((l,c)=>{l.points.forEach((u,m)=>{let w=a[m]??0,p=w+u;a[m]=p;let h=bn(p,r,o,n);t.appendChild(mt("rect",{x:$e.left+i*m+i*.15,y:h,width:s,height:Math.max(1,bn(w,r,o,n)-h),fill:gn(c)}))})})}function hy(t,e,n,r,o){e.series.forEach((i,s)=>{let a=i.points.map((l,c)=>`${ul(c,e.labels.length,n)},${bn(l,r,o,n)}`).join(" ");t.appendChild(mt("polyline",{points:a,fill:"none",stroke:gn(s),"stroke-width":2,"stroke-linejoin":"round"}))})}function py(t,e,n,r,o){e.series.forEach((i,s)=>{i.points.forEach((a,l)=>{t.appendChild(mt("circle",{cx:ul(l,e.labels.length,n),cy:bn(a,r,o,n),r:4,fill:gn(s),"fill-opacity":.85}))})})}function fy(t,e,n){let r=e.reduce((l,c)=>l+c,0),o=n.width/2,i=$e.top+n.plotH/2,s=Math.min(n.plotW,n.plotH)/2;if(r===0){t.appendChild(mt("circle",{cx:o,cy:i,r:s,fill:"none",stroke:"currentColor","stroke-opacity":.3}));return}let a=-Math.PI/2;e.forEach((l,c)=>{let u=l/r*Math.PI*2,m=a+u;if(u>=Math.PI*2)t.appendChild(mt("circle",{cx:o,cy:i,r:s,fill:gn(c)}));else{let w=o+s*Math.cos(a),p=i+s*Math.sin(a),h=o+s*Math.cos(m),g=i+s*Math.sin(m),x=u>Math.PI?1:0;t.appendChild(mt("path",{d:`M ${o} ${i} L ${w} ${p} A ${s} ${s} 0 ${x} 1 ${h} ${g} Z`,fill:gn(c)}))}a=m})}function hh(t,e){let n=mt("svg",{viewBox:`0 0 ${e.width} ${e.height}`,width:"100%",role:"img"});if(n.setAttribute("aria-label",t.title??`${t.kind} chart`),t.kind==="pie"){let i=t.series[0];return fy(n,i.points.map(s=>Math.max(0,s)),e),n}let{min:r,max:o}=ay(t);return cy(n,t,e,r,o),t.kind==="bar"?dy(n,t,e,r,o):t.kind==="stacked"?uy(n,t,e,r,o):t.kind==="line"?hy(n,t,e,r,o):py(n,t,e,r,o),n}function my(t){if(t.length<2)return null;let e=document.createElement("div");return e.className="chart-legend",e.setAttribute("part","chart-legend"),t.forEach((n,r)=>{let o=document.createElement("span");o.className="chart-legend-item";let i=document.createElement("span");i.className="chart-legend-swatch",i.style.background=gn(r),o.append(i,document.createTextNode(n)),e.appendChild(o)}),e}function gy(t,e){new ResizeObserver(()=>{e(Math.round(t.clientWidth/lh)*lh)}).observe(t)}function Or(t){if(t.labels.length===0||t.series.length===0)return null;let e=document.createElement("div");if(e.className="chart-block",e.setAttribute("part","chart-block"),t.title!==void 0&&t.title!==""){let i=document.createElement("div");i.className="chart-title",i.setAttribute("part","chart-title"),i.textContent=t.title,e.appendChild(i)}let n=ey,r=hh(t,dh(n));e.appendChild(r);let o=my(t.kind==="pie"?t.labels:t.series.map(i=>i.label));return o!==null&&e.appendChild(o),gy(e,i=>{if(i===n)return;n=i;let s=hh(t,dh(n));r.replaceWith(s),r=s}),e}var by=["bar","line","pie","scatter","stacked"];function vy(t){return by.includes(t)?t:"bar"}function yy(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="number"||!Number.isFinite(n)||Math.abs(n)>1e15)return null;e.push(n)}return e}function wy(t){if(!Array.isArray(t))return null;for(let e=0;e<t.length;e+=1)if(typeof t[e]!="string")return null;return t}function tr(t){if(typeof t!="object"||t===null)return null;let e=t,n=wy(e.labels);if(n===null||!Array.isArray(e.series))return null;let r=[];for(let s of e.series){if(typeof s!="object"||s===null)return null;let a=s,l=yy(a.points);if(l===null||l.length!==n.length)return null;r.push({label:typeof a.label=="string"?a.label:"",points:l})}if(r.length===0||r.length*n.length>2e4||n.length>2e3)return null;let o=vy(e.kind),i=e.title;return typeof i=="string"?{kind:o,title:i,labels:n,series:r}:{kind:o,labels:n,series:r}}var Ji="render_chart";function xy(t){let e=tr(t);return e===null?null:Or(e)}function Ey(t){let e=tr(t);return e!==null&&e.labels.length>0&&e.series.length>0}var _y="chart not rendered: expected labels (strings) and series, each with one finite number per label";function ph(){return{name:Ji,description:"Show a chart in the conversation. Supply the data and the page draws it. Every series must have exactly one point per label.",parameters:{type:"object",properties:{kind:{type:"string",enum:["bar","line","pie","scatter","stacked"]},title:{type:"string"},labels:{type:"array",items:{type:"string"}},series:{type:"array",items:{type:"object",properties:{label:{type:"string"},points:{type:"array",items:{type:"number"}}},required:["points"]}}},required:["labels","series"],"x-summary":"Draw a chart"},handler:t=>Ey(t)?"chart rendered":_y,render:xy}}function Mr(t,e=Date.now(),n=ae){if(!Number.isFinite(t))return n.justNow;let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let o=Math.round(r/60);if(o<60)return n.minutesAgo.replace("{n}",String(o));let i=Math.round(o/60);if(i<24)return n.hoursAgo.replace("{n}",String(i));let s=Math.round(i/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}function fh(t){return t.preview!==void 0&&t.preview!==null&&t.preview!==""?t.preview:null}function mh(t){return t.replace(/\s+/g," ").trim()}var Lr=class{element;#t;#n;#e;#s=null;#r=null;#i;#o=[];constructor(e,n=ae){this.#t=e,this.#i=n,this.element=document.createElement("div"),this.element.className="checkpoints",this.element.setAttribute("part","checkpoints"),this.element.setAttribute("role","dialog"),this.element.setAttribute("aria-label",n.checkpoints),this.element.tabIndex=-1,this.element.hidden=!0;let r=document.createElement("div");r.className="checkpoints-header",r.setAttribute("part","checkpoints-header"),this.#e=document.createElement("span"),this.#e.className="checkpoints-title",this.#e.setAttribute("part","checkpoints-title"),this.#e.textContent=n.checkpoints,r.append(this.#e),this.#n=document.createElement("div"),this.#n.className="checkpoints-list",this.#n.setAttribute("part","checkpoints-list"),this.element.append(r,this.#n),this.element.addEventListener("keydown",o=>this.#c(o))}setRuns(e){this.#o=e,this.#d()}setRelativeTimeFormatter(e){this.#r=e}#u(e){return this.#r!==null?this.#r(e):Mr(e,Date.now(),this.#i)}setStrings(e){this.#i=e,this.element.setAttribute("aria-label",e.checkpoints),this.#e.textContent=e.checkpoints,this.#d()}open(){this.open_||(this.#s=this.#h(),this.element.hidden=!1,(this.#l()[0]??this.element).focus())}close(){this.open_&&(this.element.hidden=!0,this.#s?.focus(),this.#s=null)}#h(){return this.element.getRootNode().activeElement}#l(){return Array.from(this.element.querySelectorAll("button, [tabindex]")).filter(e=>!e.hidden)}#c(e){if(e.key==="Escape"){e.stopPropagation(),this.close();return}if(e.key!=="Tab")return;let n=this.#l(),r=n[0],o=n[n.length-1],i=this.#h();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}get open_(){return!this.element.hidden}#d(){if(this.#n.replaceChildren(),this.#o.length===0){let n=document.createElement("div");n.className="checkpoints-empty",n.setAttribute("part","checkpoints-empty"),n.textContent=this.#i.noCheckpoints,this.#n.append(n);return}let e=this.#p();for(let n of this.#o)this.#n.append(this.#y(n,e))}#p(){let e=new Set,n=new Set;for(let r of this.#o){let o=fh(r);if(o===null)continue;let i=mh(o);e.has(i)&&n.add(i),e.add(i)}return n}#y(e,n){let r=document.createElement("div");r.className="checkpoint-row",r.setAttribute("part","checkpoint-row");let o=fh(e),i=e.started_at===null?null:this.#u(Date.parse(e.started_at)),s=document.createElement("span");if(s.className="checkpoint-label",s.setAttribute("part","checkpoint-label"),s.textContent=o??i??e.run_id,r.append(s),o!==null&&i!==null){let l=document.createElement("span");l.className="checkpoint-time",l.setAttribute("part","checkpoint-time"),l.textContent=i,r.append(l)}if((o===null?i!==null:n.has(mh(o)))&&e.run_id!==""){let l=document.createElement("span");l.className="checkpoint-id",l.setAttribute("part","checkpoint-id"),l.textContent=e.run_id.slice(0,8),l.title=e.run_id,r.append(l)}if(e.parent_run_id!==null){let l=document.createElement("span");l.className="checkpoint-branch",l.setAttribute("part","checkpoint-branch"),l.textContent=this.#i.forkedRun,l.title=e.parent_run_id,r.append(l)}return r.append(this.#m(e.run_id,"resume",this.#i.resumeRun),this.#m(e.run_id,"fork",this.#i.forkRun)),r}#m(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`checkpoint-action checkpoint-${n}`,o.setAttribute("part",`checkpoint-action checkpoint-${n}`),o.textContent=r,o.addEventListener("click",()=>{this.close(),this.#t(e,n)}),o}};function Dt(t,e,n=Je){let r=Math.min(n,Math.max(0,(e.width-t.width)/2)),o=Math.min(n,Math.max(0,(e.height-t.height)/2));return{left:Math.max(e.left+r,Math.min(t.left,e.left+e.width-t.width-r)),top:Math.max(e.top+o,Math.min(t.top,e.top+e.height-t.height-o))}}function Pr(t,e,n=Bt){let r=t.right-t.left,o=t.bottom-t.top,i=Math.max(e.left+n,Math.min(t.left,e.left+e.width-n-r)),s=Math.max(e.top+n,Math.min(t.top,e.top+e.height-n-o));return{left:i,top:s,right:i+r,bottom:s+o}}function hl(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.setAttribute("part",`confirm-button confirm-${t}`),n.textContent=e,n}function pl(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="confirm",i.setAttribute("part","confirm"),i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.confirmAction);let s=document.createElement("div");s.className="confirm-body",s.setAttribute("part","confirm-body"),s.textContent=e.message??r.confirmRun.replace("{tool}",e.toolName);let a=document.createElement("pre");a.className="confirm-args",a.setAttribute("part","confirm-args"),a.textContent=JSON.stringify(e.args,null,2),a.hidden=Object.keys(e.args).length===0;let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=hl("cancel",r.cancel),u=n.onAlwaysAllow===void 0?null:hl("always",r.confirmAlways.replace("{tool}",e.toolName)),m=hl("confirm",r.confirm),w=!1,p=h=>{w||(w=!0,i.remove(),o(h))};if(c.addEventListener("click",()=>p(!1)),m.addEventListener("click",()=>p(!0)),u?.addEventListener("click",()=>{n.onAlwaysAllow?.(),p(!0)}),n.signal?.addEventListener("abort",()=>p(!1),{once:!0}),l.append(c,...u===null?[]:[u],m),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){p(!1);return}m.focus()})}var Ty=new Set(["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","DD","DIV","DL","DT","FIGCAPTION","FIGURE","FOOTER","H1","H2","H3","H4","H5","H6","HEADER","HR","MAIN","NAV","OL","P","SECTION","UL"]);function es(t){let e=t.cloneNode(!0);for(let n of Array.from(e.querySelectorAll("button")))n.remove();return{text:ky(gh(e)),html:e.innerHTML}}function gh(t){if(t.nodeType===Node.TEXT_NODE)return t.nodeValue.replace(/\s+/g," ");if(t.nodeType!==Node.ELEMENT_NODE)return"";let e=t,n=e.tagName;if(n==="BR")return`
11
+ `)},rv=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,u=[],m={},w=p=>{typeof p=="object"&&p&&("messages"in p&&delete p.messages,o=p)};return r.pipe(Ue(p=>{switch(p.type){case b.TEXT_MESSAGE_START:{let h=p;return[{type:se.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case b.TEXT_MESSAGE_CONTENT:{let h=p;return[{type:se.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case b.TEXT_MESSAGE_END:{let h=p;return[{type:se.enum.TextMessageEnd,messageId:h.messageId}]}case b.TOOL_CALL_START:{let h=p;return u.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),s=!0,m[h.toolCallId]=h.toolCallName,[{type:se.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case b.TOOL_CALL_ARGS:{let h=p,g=u.find(T=>T.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let x=!1;if(c){let T=c.find(S=>S.tool==g.function.name);if(T)try{let S=JSON.parse(ii(g.function.arguments));T.tool_argument&&T.tool_argument in S?(w({...o,[T.state_key]:S[T.tool_argument]}),x=!0):T.tool_argument||(w({...o,[T.state_key]:S}),x=!0)}catch{}}return[{type:se.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},...x?[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]:[]]}case b.TOOL_CALL_END:{let h=p;return[{type:se.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case b.TOOL_CALL_RESULT:{let h=p;return[{type:se.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case b.RAW:return[];case b.CUSTOM:{let h=p;switch(h.name){case"Exit":i=!1;break;case"PredictState":c=h.value;break}return[{type:se.enum.MetaEvent,name:h.name,value:h.value}]}case b.STATE_SNAPSHOT:return w(p.snapshot),[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}];case b.STATE_DELTA:{let h=p,g=Oo.applyPatch(o,h.delta,!0,!1);return g?(w(g.newDocument),[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]):[]}case b.MESSAGES_SNAPSHOT:return l=p.messages,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case b.RUN_STARTED:return[];case b.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:ov(l)}:{}}),active:!1}];case b.RUN_ERROR:{let h=p;return[{type:se.enum.RunError,message:h.message,code:h.code}]}case b.STEP_STARTED:return a=p.stepName,u=[],c=null,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!0}];case b.STEP_FINISHED:return u=[],c=null,[{type:se.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function ov(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=nv(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let i={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(i)}}else if(n.role==="tool"){let r="unknown";for(let i of t)if(i.role==="assistant"&&i.toolCalls?.length){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var iv=t=>t.kind==="tool"?t.fields.toolCallId:t.fields.messageId,sv=t=>t==="tool"?"toolCallId":"messageId",Qn=(t,e)=>e.metadata===void 0?t:{...t,metadata:e.metadata},Bi=t=>e=>{let n=Ar(t),r=new Map,o=l=>{let c=r.get(l);if(!c)return[];switch(r.delete(l),c.kind){case"text":{let u={type:b.TEXT_MESSAGE_END,messageId:c.fields.messageId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","TEXT_MESSAGE_END",u,{messageId:u.messageId}),[u]}case"tool":{let u={type:b.TOOL_CALL_END,toolCallId:c.fields.toolCallId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","TOOL_CALL_END",u,{toolCallId:u.toolCallId}),[u]}case"reasoning":{let u={type:b.REASONING_MESSAGE_END,messageId:c.fields.messageId,...c.fields.subagentRunId!=null&&{subagentRunId:c.fields.subagentRunId}};return n?.event("TRANSFORM","REASONING_MESSAGE_END",u,{messageId:u.messageId}),[u]}}},i=()=>[...r.keys()].flatMap(l=>o(l)),s=(l,c)=>{for(let[u,m]of r)if(m.kind===l&&iv(m)===c)return{owner:u}},a=(l,c,u,m,w)=>{if(c!==void 0){let h=s(l,c);if(h){if(u!==void 0&&u!==h.owner)throw Error(`Cannot continue ${w} '${c}': chunk subagentRunId '${u}' does not match the open stream's subagent '${h.owner??"(the parent agent)"}'.`);return h.owner}return u}if(u!==void 0)return u;if(r.get(void 0)?.kind===l)return;let p=[...r.entries()].filter(([,h])=>h.kind===l);if(p.length===1)return p[0][0];if(p.length>1)throw Error(`Ambiguous ${m}: it carries neither a ${sv(l)} nor a subagentRunId, but ${p.length} lanes have an open ${w}. Attribute the chunk to the subagent it belongs to.`)};return e.pipe(Ue(l=>{switch(l.type){case b.TEXT_MESSAGE_START:case b.TEXT_MESSAGE_CONTENT:case b.TEXT_MESSAGE_END:case b.TOOL_CALL_START:case b.TOOL_CALL_ARGS:case b.TOOL_CALL_END:case b.TOOL_CALL_RESULT:case b.STATE_SNAPSHOT:case b.STATE_DELTA:case b.CUSTOM:case b.STEP_STARTED:case b.STEP_FINISHED:case b.THINKING_START:case b.THINKING_END:case b.THINKING_TEXT_MESSAGE_START:case b.THINKING_TEXT_MESSAGE_CONTENT:case b.THINKING_TEXT_MESSAGE_END:case b.REASONING_START:case b.REASONING_MESSAGE_START:case b.REASONING_MESSAGE_CONTENT:case b.REASONING_MESSAGE_END:case b.REASONING_END:return[...o(l.subagentRunId??void 0),l];case b.RUN_STARTED:case b.RUN_FINISHED:case b.RUN_ERROR:case b.MESSAGES_SNAPSHOT:return[...i(),l];case b.RAW:case b.ACTIVITY_SNAPSHOT:case b.ACTIVITY_DELTA:case b.REASONING_ENCRYPTED_VALUE:case b.SUBAGENT_STARTED:return[l];case b.SUBAGENT_FINISHED:case b.SUBAGENT_ERROR:{let c=l.subagentRunId;return c==null?[l]:[...o(c),l]}case b.TEXT_MESSAGE_CHUNK:{let c=l,u=a("text",c.messageId,c.subagentRunId??void 0,"TEXT_MESSAGE_CHUNK","text message"),m=r.get(u),w=[],p;if(m?.kind==="text"&&(c.messageId===void 0||c.messageId===m.fields.messageId))p=m.fields;else{if(w.push(...o(u)),c.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");p={messageId:c.messageId,name:c.name,subagentRunId:c.subagentRunId},r.set(u,{kind:"text",fields:p});let h=Qn({type:b.TEXT_MESSAGE_START,messageId:c.messageId,role:c.role||"assistant",...c.name!==void 0&&{name:c.name},...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","TEXT_MESSAGE_START",h,{messageId:c.messageId})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.TEXT_MESSAGE_CONTENT,messageId:p.messageId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",g,{messageId:p.messageId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.TEXT_MESSAGE_CONTENT,messageId:p.messageId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}case b.TOOL_CALL_CHUNK:{let c=l,u=a("tool",c.toolCallId,c.subagentRunId??void 0,"TOOL_CALL_CHUNK","tool call"),m=r.get(u),w=[],p;if(m?.kind==="tool"&&(c.toolCallId===void 0||c.toolCallId===m.fields.toolCallId))p=m.fields;else{if(w.push(...o(u)),c.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(c.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");p={toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId,subagentRunId:c.subagentRunId},r.set(u,{kind:"tool",fields:p});let h=Qn({type:b.TOOL_CALL_START,toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId,...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","TOOL_CALL_START",h,{toolCallId:c.toolCallId,toolCallName:c.toolCallName})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.TOOL_CALL_ARGS,toolCallId:p.toolCallId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","TOOL_CALL_ARGS",g,{toolCallId:p.toolCallId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.TOOL_CALL_ARGS,toolCallId:p.toolCallId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}case b.REASONING_MESSAGE_CHUNK:{let c=l,u=a("reasoning",c.messageId,c.subagentRunId??void 0,"REASONING_MESSAGE_CHUNK","reasoning message"),m=r.get(u),w=[],p;if(m?.kind==="reasoning"&&(c.messageId===void 0||c.messageId===m.fields.messageId))p=m.fields;else{if(w.push(...o(u)),c.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");p={messageId:c.messageId,subagentRunId:c.subagentRunId},r.set(u,{kind:"reasoning",fields:p});let h=Qn({type:b.REASONING_MESSAGE_START,messageId:c.messageId,role:"reasoning",...c.subagentRunId!=null&&{subagentRunId:c.subagentRunId}},c);w.push(h),n?.event("TRANSFORM","REASONING_MESSAGE_START",h,{messageId:c.messageId})}if(c.delta!==void 0){let h=c.subagentRunId??p.subagentRunId,g=Qn({type:b.REASONING_MESSAGE_CONTENT,messageId:p.messageId,delta:c.delta,...h!=null&&{subagentRunId:h}},c);w.push(g),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",g,{messageId:p.messageId})}if(w.length===0&&c.metadata!==void 0){let h=c.subagentRunId??p.subagentRunId;w.push({type:b.REASONING_MESSAGE_CONTENT,messageId:p.messageId,delta:"",metadata:c.metadata,...h!=null&&{subagentRunId:h}})}return w}}return l.type,[]}),hn(()=>{i()}))};function av(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function eh(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),o=[...n].filter(s=>!r.has(s));if(o.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${o.join(", ")}`);let i=[...r].filter(s=>!n.has(s));if(i.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${i.join(", ")}`);return t.map(s=>{let a=e[s.id],l={interruptId:s.id,status:a.status};return a.status==="resolved"&&a.payload!==void 0&&(l.payload=a.payload),a.metadata!==void 0&&(l.metadata=a.metadata),l})}var kr=class{runNext(t,e){return e.run(t).pipe(Bi(!1))}runNextWithState(t,e){let n=J(t.messages||[]),r=J(t.state||{}),o=new zo;return Ju(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(ni(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:J(n),state:J(r)})))}},lv=class extends kr{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function cv(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var dv=class extends kr{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(cv)};return this.runNext(o,e)}},Vu="THINKING_START",ju="THINKING_END",qu="THINKING_TEXT_MESSAGE_START",Wu="THINKING_TEXT_MESSAGE_CONTENT",Xu="THINKING_TEXT_MESSAGE_END",uv=class extends kr{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(Lt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Vu:{this.currentReasoningId=Ie();let{title:e,...n}=t;return this.warnAboutTransformation(Vu,b.REASONING_START),{...n,type:b.REASONING_START,messageId:this.currentReasoningId}}case qu:return this.currentMessageId=Ie(),this.warnAboutTransformation(qu,b.REASONING_MESSAGE_START),{...t,type:b.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Wu:{let{delta:e,...n}=t;return this.warnAboutTransformation(Wu,b.REASONING_MESSAGE_CONTENT),{...n,type:b.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Ie(),delta:e}}case Xu:{let e=this.currentMessageId??Ie();return this.warnAboutTransformation(Xu,b.REASONING_MESSAGE_END),{...t,type:b.REASONING_MESSAGE_END,messageId:e}}case ju:{let e=this.currentReasoningId??Ie();return this.warnAboutTransformation(ju,b.REASONING_END),{...t,type:b.REASONING_END,messageId:e}}default:return t}}};function hv(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function pv(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function fv(t){let e=hv(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function mv(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>pv(r)?fv(r):r);return{...t,content:n}}var gv=class extends kr{run(t,e){let n={...t,messages:t.messages.map(mv)};return this.runNext(n,e)}},Yu="SUBAGENT_STARTED",Ku="SUBAGENT_FINISHED",Zu="SUBAGENT_ERROR";function Vi(t){if(t&&typeof t=="object"&&"subagentRunId"in t){let{subagentRunId:e,...n}=t;return n}return t}function Qu(t){return t.map(e=>Vi(e))}var bv=class extends kr{warnDroppedLifecycleEvent(t){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is dropping ${t} because the target agent predates subagent support. To remove this warning, upgrade your AG-UI integration package. To suppress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){let n={...t,messages:(t.messages??[]).map(r=>Vi(r))};return this.runNext(n,e).pipe(oi(r=>{let o=r.type;(o===Yu||o===Ku||o===Zu)&&this.warnDroppedLifecycleEvent(o)}),Ea(r=>{let o=r.type;return o!==Yu&&o!==Ku&&o!==Zu}),Lt(r=>{let o=Vi(r);if(o.type===b.MESSAGES_SNAPSHOT){let i=o;if(Array.isArray(i.messages))return{...i,messages:Qu(i.messages)}}if(o.type===b.RUN_FINISHED){let i=o;if(i.outcome&&Array.isArray(i.outcome.interrupts))return{...i,outcome:{...i.outcome,interrupts:i.outcome.interrupts.map(s=>Vi(s))}}}if(o.type===b.RUN_STARTED){let i=o;if(i.input&&Array.isArray(i.input.messages))return{...i,input:{...i.input,messages:Qu(i.input.messages)}}}return o}))}},vv="0.0.59",yv=class{get maxVersion(){return vv}get debug(){return this._debug}set debug(t){this._debug=$i(t),this._debugLogger=za(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?za($i(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:i}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??Rt(),this.messages=J(r??[]),this.state=J(o??{}),this._debug=$i(i),this._debugLogger=za(this._debug),Zn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new dv),Zn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new uv),Zn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new gv),Zn(this.maxVersion,"0.0.57")<=0&&this.middlewares.unshift(new bv)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new lv(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Rt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new ft;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ei(Go(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:u=>c.run(u,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),Bi(this.debugLogger),Fa(this.debugLogger),l=>l.pipe(ri(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),_r(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,i))),hn(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=J(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new la}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??Rt();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new ft;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ei(Go(()=>ti(()=>this.connect(n)),Bi(this.debugLogger),Fa(this.debugLogger),l=>l.pipe(ri(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),_r(l=>(this.isRunning=!1,l instanceof la?Fo:this.onError(n,l,i))),hn(()=>{this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=J(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Ju(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(oi(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=J(this.messages);for(let r of e)r.subagentRunId===null&&delete r.subagentRunId;let n=e.filter(r=>r.role!=="activity");return{threadId:this.threadId,runId:t?.runId||Rt(),tools:J(t?.tools??[]),context:J(t?.context??[]),forwardedProps:J(t?.forwardedProps??{}),state:J(this.state),messages:n,...t?.resume===void 0?{}:{resume:J(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(i=>i.interruptId)),o=this.pendingInterrupts.map(i=>i.id).filter(i=>!r.has(i));if(o.length>0)throw new j(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let i of this.pendingInterrupts)if(av(i))throw new j(`Interrupt ${i.id} expired at ${i.expiresAt}`)}let n=await ne(e,this.messages,this.state,(r,o,i)=>r.onRunInitialized?.({messages:o,state:i,agent:this,input:t}));if(n.messages!==void 0||n.state!==void 0){if(n.messages){this.messages=n.messages;for(let r of n.messages)r.subagentRunId===null&&delete r.subagentRunId;t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})}n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}}onError(t,e,n){return un(ne(n,this.messages,this.state,(r,o,i)=>r.onRunFailed?.({error:e,messages:o,state:i,agent:this,input:t}))).pipe(Lt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let i=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||i==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await ne(e,this.messages,this.state,(r,o,i)=>r.onRunFinalized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=J(this.messages),t.state=J(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=J(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=J(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=J(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??Rt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Bi(this.debugLogger),Fa(this.debugLogger),rv(this.threadId,e.runId,this.agentId),n=>n.pipe(Lt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}};function wv(t){if(!Array.isArray(t.messages))return t;let e=!1,n=t.messages.map(r=>{if(r.subagentRunId===null){e=!0;let o={...r};return delete o.subagentRunId,o}return r});return e?{...t,messages:n}:t}var th=class extends yv{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(wv(t)),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=J(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return Vb(Fb(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=J(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var xv=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function nh(t,e){let n=[];return{text:t.replace(xv,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function Ev(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&(e.prompt===void 0||typeof e.prompt=="string")}function Va(t){return Array.isArray(t)?t.filter(Ev):[]}var ji=["top-left","top-right","bottom-left","bottom-right"];function rh(t){return ji.includes(t)}function ja(t){return[{name:"read_chat_surface",description:"Describe the chat panel you are speaking from: its placement, whether it is collapsed, whether it can be moved, and the box it occupies. Read this before moving or minimising yourself, since a full-screen panel has nowhere to move to. Read-only.",parameters:{type:"object",properties:{},required:[],[xe]:"Read the chat's own position"},handler:()=>t.describeSurface()},{name:"move_chat",description:"Move your own panel to a corner, to uncover something the user needs to see. `corner` is top-left, top-right, bottom-left or bottom-right. Answers `moved: false` with a reason when the placement owns its position or the panel fills the screen; check `read_chat_surface` first, and prefer minimise_chat when there is nowhere to move to.",parameters:{type:"object",properties:{corner:{type:"string",enum:[...ji]}},required:["corner"],[xe]:"Move the chat out of the way"},handler:e=>{let n=String(e.corner??""),r=t.describeSurface();return rh(n)?r.movable?{moved:t.moveTo(n,{announce:!0}),corner:n}:{moved:!1,reason:r.fullBleed?"the panel fills the screen, so there is nowhere to move it to":r.draggable===!1?"this page has turned off moving the panel":`the "${r.placement??""}" placement owns the panel's position`,suggestion:r.collapsible?"minimise_chat":null}:{moved:!1,reason:`"${n}" is not a corner; use one of ${ji.join(", ")}`}}},{name:"minimise_chat",description:"Collapse your own panel to its launcher, so the user can see the whole page. The launcher stays visible and reopens it. Answers `minimised: false` when the placement has no collapsed state, which is the case for a full-page chat.",parameters:{type:"object",properties:{},required:[],[xe]:"Minimise the chat"},handler:()=>t.describeSurface().collapsible?(t.setCollapsed(!0,{announce:!0}),{minimised:!0}):{minimised:!1,reason:"this placement has no collapsed state, so there is no launcher to return to"}},{name:"restore_chat",description:"Open your own panel again after minimising it.",parameters:{type:"object",properties:{},required:[],[xe]:"Restore the chat"},handler:()=>(t.setCollapsed(!1),{restored:!0})}]}var Ir=class{#t=new Map;register(e){this.#t.set(e.name,e)}has(e){return this.#t.has(e)}get(e){let n=this.#t.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#t.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function qa(t){return t[hr]===!0}function qi(t){return t[pr]===!0}var _v="#4f46e5";function Jn(t,e,n){let r=window.getComputedStyle(t).getPropertyValue(e).trim();return r===""?n:r}var Tv=4;function Wa(t,e={}){let n=document.createElement("div");n.setAttribute("data-ag-ui-highlight",""),n.setAttribute("aria-hidden","true"),n.style.cssText=["position: fixed","inset: 0","pointer-events: none",`z-index: ${Jn(t,"--ag-ui-highlight-z-index",String(Yc))}`].join(";");let r=document.createElement("div"),o=document.createElement("div");n.className="ag-ui-highlight",r.className="ag-ui-highlight-scrim",o.className="ag-ui-highlight-ring",e.scrim===!0&&n.append(r),n.append(o);let i=e.ringWidth??Number.parseFloat(Jn(t,"--ag-ui-highlight-ring-width","3")),s=e.flowMs??Number.parseFloat(Jn(t,"--ag-ui-highlight-flow-ms","2400")),a=()=>{let u=t.getBoundingClientRect(),m=e.padding??Tv,w=e.radius??Number.parseFloat(getComputedStyle(t).borderRadius),p=u.left-m,h=u.top-m,g=u.width+m*2,x=u.height+m*2;e.scrim===!0&&(r.style.cssText=["position: absolute","inset: 0",`background: ${Jn(t,"--ag-ui-highlight-scrim","rgba(15, 15, 25, 0.45)")}`,`clip-path: path(evenodd, '${kv(p,h,g,x,w+m)}')`].join(";")),o.style.cssText=["position: absolute",`left: ${p}px`,`top: ${h}px`,`width: ${g}px`,`height: ${x}px`,`border-radius: ${w+m}px`,`border: ${i}px solid transparent`,"box-sizing: border-box",Av(t,e)].join(";")};a();let l=null;e.gradient===!0&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches&&(l=o.animate([{backgroundPosition:"100% 0"},{backgroundPosition:"-100% 0"}],{duration:s,iterations:Number.POSITIVE_INFINITY,easing:"linear"}));let c={capture:!0,passive:!0};return window.addEventListener("scroll",a,c),window.addEventListener("resize",a,c),document.body.appendChild(n),()=>{window.removeEventListener("scroll",a,c),window.removeEventListener("resize",a,c),l?.cancel(),n.remove()}}function Sv(t){return t===void 0?null:CSS.supports("color",t)?t:null}function Av(t,e){let n=Sv(e.color)??Jn(t,"--ag-ui-accent",_v);if(e.gradient!==!0)return`border-color: ${n}`;let r=Jn(t,"--ag-ui-highlight-gradient",`linear-gradient(115deg, transparent 20%, ${n} 50%, transparent 80%)`),o="linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)";return[`background-image: ${r}`,"background-origin: border-box","background-size: 300% 100%",`-webkit-mask: ${o}`,`mask: ${o}`,"-webkit-mask-composite: xor","mask-composite: exclude","background-position: 50% 0"].join(";")}function kv(t,e,n,r,o){let i=Math.max(0,Math.min(o,n/2,r/2)),s=t+n,a=e+r,l=`M 0 0 H ${window.innerWidth} V ${window.innerHeight} H 0 Z`,c=[`M ${t+i} ${e}`,`H ${s-i}`,`A ${i} ${i} 0 0 1 ${s} ${e+i}`,`V ${a-i}`,`A ${i} ${i} 0 0 1 ${s-i} ${a}`,`H ${t+i}`,`A ${i} ${i} 0 0 1 ${t} ${a-i}`,`V ${e+i}`,`A ${i} ${i} 0 0 1 ${t+i} ${e}`,"Z"].join(" ");return`${l} ${c}`}function Wi(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Iv=Wi(HTMLInputElement.prototype,"value"),Rv=Wi(HTMLTextAreaElement.prototype,"value"),Cv=Wi(HTMLSelectElement.prototype,"value"),Nv=Wi(HTMLInputElement.prototype,"checked");function mn(t,e){t instanceof HTMLTextAreaElement?Rv.call(t,e):t instanceof HTMLSelectElement?Cv.call(t,e):Iv.call(t,e)}function Rr(t,e){Nv.call(t,e)}var Xa="#4f46e5",Ov="rgba(79, 70, 229, 0.4)",Mv="--ag-ui-accent";function er(t){return new Promise(e=>{setTimeout(e,t)})}function Xi(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ya(t){return t<=0||Xi()?Promise.resolve():er(t)}function Yi(t,e){let n=window.getComputedStyle(t).getPropertyValue(Mv).trim();return n===""?e:n}function oh(t){return`0 0 0 3px ${Yi(t,Ov)}`}async function Ka(t,e,n={}){let r=n.charDelayMs??35;mn(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)mn(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await er(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Za(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${Yi(t,Xa)}`,t.style.outlineOffset="2px",await er(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}var Lv=600,Pv=100;function _t(t,e={}){let n=Xi();return t.scrollIntoView({block:"center",inline:"nearest",behavior:n?"auto":"smooth"}),n?Promise.resolve():new Promise(r=>{let o,i=()=>{clearTimeout(o),document.removeEventListener("scroll",s,!0),document.removeEventListener("scrollend",i,!0),r()},s=()=>{document.removeEventListener("scroll",s,!0),clearTimeout(o),o=setTimeout(i,e.settleMs??Lv)};o=setTimeout(i,Pv),document.addEventListener("scroll",s,!0),document.addEventListener("scrollend",i,!0)})}var Dv=1200,Uv=1/3;async function ih(t,e,n){(e.focus??n)&&t.focus({preventScroll:!0});let r=e.flashMs??Dv;if(r<=0)return;if(e.scrim===!0||e.gradient===!0){let c=Wa(t,{scrim:e.scrim===!0,gradient:e.gradient===!0,...e.color===void 0?{}:{color:e.color},...e.ringPadding===void 0?{}:{padding:e.ringPadding}});await er(r),c();return}let o=t.style.outline,i=t.style.outlineOffset,s=t.style.transition,a=e.color??Yi(t,Xa);t.style.outline=`3px solid ${a}`,t.style.outlineOffset="2px";let l=Xi()?0:Math.round(r*Uv);await er(r-l),l>0&&(t.style.transition=`outline-color ${l}ms ease-out`,t.style.outline="3px solid transparent",await er(l)),t.style.outline=o,t.style.outlineOffset=i,t.style.transition=s}function Hv(t,e={}){return ih(t,e,!1)}function Qa(t,e={}){return ih(t,e,!0)}async function Ja(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,i=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=oh(t),await Ya(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function Gv(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function el(t,e,n={}){let r=Gv(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,i=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${Yi(t,Xa)}`,t.style.outlineOffset="2px",await Ya(o),mn(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=i,t.style.outlineOffset=s}async function tl(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=oh(t),await Ya(r),Rr(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var Nr={SCROLL:"scroll",DRAG:"drag",CHAT:"chat"};function nl(t,e){let n=[];return t.has(Nr.SCROLL)&&n.push(zv(e)),t.has(Nr.DRAG)&&n.push(Fv(e)),n}function zv(t){return{name:"scroll_to",description:"Scroll a target into view. `target` is `top`, `bottom`, or a CSS selector / page-map element id. Read-only: it changes nothing on the page.",parameters:{type:"object",properties:{target:{type:"string"}},required:["target"],[xe]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let o=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:o,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return _t(r),{scrolled:!0,target:n}}}}function Fv(t){return{name:"drag_and_drop",description:"Drag the `from` element onto the `to` element (CSS selectors or page-map element ids), firing the page's native drag-and-drop. Use for reordering sortable lists. The page decides what the drop commits.",parameters:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"],[xe]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),o=t(n);if(o===null)throw new Error(`no element matching "${n}"`);let i=t(r);if(i===null)throw new Error(`no element matching "${r}"`);return $v(o,i),{dragged:!0,from:n,to:r}}}}function $v(t,e){let n=new DataTransfer;Cr(t,"dragstart",n),Cr(e,"dragenter",n),Cr(e,"dragover",n),Cr(e,"drop",n),Cr(t,"dragend",n)}function Cr(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function rl(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Ki(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[xe]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[hr]:!0,[xe]:`Update ${t.name}`},handler:r=>n(r)}),e}var Bv=Ki;function ol(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,i=r.summary,s=r.description;typeof o=="string"&&typeof i=="string"&&(e[o]=typeof s=="string"?{name:o,summary:i,description:s}:{name:o,summary:i})}return e}var sh=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Vv(t){return[...t.matchAll(sh)].map(e=>e[0].slice(1))}function jv(t,e,n){let r={...n};return{path:e.replace(sh,(i,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function qv(t,e){let n=new URLSearchParams;for(let[o,i]of Object.entries(e))n.set(o,String(i));let r=n.toString();return r===""?t:`${t}?${r}`}function il(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[xe]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Vv(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[pr]:!0,[xe]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(u=>u.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=jv(o.id,o.path,i),l=qv(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}var Wv="http://www.w3.org/2000/svg",$e={top:20,right:12,bottom:30,left:44},Xv=480,Yv=220,Kv=220/480,Zv=160,Qv=320,ah=8,Jv=5.6,lh=["var(--ag-ui-chart-1, #4f7cff)","var(--ag-ui-chart-2, #21b573)","var(--ag-ui-chart-3, #e0803c)","var(--ag-ui-chart-4, #b563d8)","var(--ag-ui-chart-5, #d84f6e)","var(--ag-ui-chart-6, #3ba7c4)"];function gn(t){return lh[t%lh.length]}function ch(t){let e=Math.max(Yv,t),n=Math.min(Qv,Math.max(Zv,Math.round(e*Kv)));return{width:e,height:n,plotW:e-$e.left-$e.right,plotH:n-$e.top-$e.bottom}}function mt(t,e){let n=document.createElementNS(Wv,t);for(let[r,o]of Object.entries(e))n.setAttribute(r,String(o));return n}function dh(t,e){let n=mt("text",{"font-size":10,fill:"currentColor","fill-opacity":.65,...e});return n.textContent=t,n}function ey(t){let e=[];return t.labels.forEach((n,r)=>{let o=0;for(let i of t.series)o+=i.points[r]??0,e.push(o)}),e}function ty(t){let e=t.kind==="stacked"?ey(t):t.series.flatMap(o=>[...o.points]),n=Math.max(0,...e),r=Math.min(0,...e);return n===r?{min:r,max:n+1}:{min:r,max:n}}function bn(t,e,n,r){return $e.top+r.plotH-(t-e)/(n-e)*r.plotH}function sl(t,e,n){let r=n.plotW/e;return $e.left+r*t+r/2}function ny(t,e){let n=e.plotW/t.length,r=Math.max(...t.map(o=>o.length))*Jv;return Math.max(1,Math.ceil(r/n))}function ry(t,e,n,r,o){for(let s of[r,o]){let a=bn(s,r,o,n);t.appendChild(mt("line",{x1:$e.left,y1:a,x2:n.width-$e.right,y2:a,stroke:"currentColor","stroke-opacity":s===r?.35:.12})),t.appendChild(dh(String(Math.round(s)),{x:$e.left-6,y:a+4,"text-anchor":"end"}))}let i=ny(e.labels,n);e.labels.forEach((s,a)=>{a%i===0&&t.appendChild(dh(s,{x:sl(a,e.labels.length,n),y:n.height-$e.bottom+16,"text-anchor":"middle"}))})}function oy(t,e,n,r,o){let i=n.plotW/e.labels.length,s=i*.7/e.series.length,a=bn(r,r,o,n);e.series.forEach((l,c)=>{l.points.forEach((u,m)=>{let w=bn(u,r,o,n);t.appendChild(mt("rect",{x:$e.left+i*m+i*.15+s*c,y:w,width:s,height:Math.max(1,a-w),fill:gn(c),rx:2}))})})}function iy(t,e,n,r,o){let i=n.plotW/e.labels.length,s=i*.7,a=e.labels.map(()=>0);e.series.forEach((l,c)=>{l.points.forEach((u,m)=>{let w=a[m]??0,p=w+u;a[m]=p;let h=bn(p,r,o,n);t.appendChild(mt("rect",{x:$e.left+i*m+i*.15,y:h,width:s,height:Math.max(1,bn(w,r,o,n)-h),fill:gn(c)}))})})}function sy(t,e,n,r,o){e.series.forEach((i,s)=>{let a=i.points.map((l,c)=>`${sl(c,e.labels.length,n)},${bn(l,r,o,n)}`).join(" ");t.appendChild(mt("polyline",{points:a,fill:"none",stroke:gn(s),"stroke-width":2,"stroke-linejoin":"round"}))})}function ay(t,e,n,r,o){e.series.forEach((i,s)=>{i.points.forEach((a,l)=>{t.appendChild(mt("circle",{cx:sl(l,e.labels.length,n),cy:bn(a,r,o,n),r:4,fill:gn(s),"fill-opacity":.85}))})})}function ly(t,e,n){let r=e.reduce((l,c)=>l+c,0),o=n.width/2,i=$e.top+n.plotH/2,s=Math.min(n.plotW,n.plotH)/2;if(r===0){t.appendChild(mt("circle",{cx:o,cy:i,r:s,fill:"none",stroke:"currentColor","stroke-opacity":.3}));return}let a=-Math.PI/2;e.forEach((l,c)=>{let u=l/r*Math.PI*2,m=a+u;if(u>=Math.PI*2)t.appendChild(mt("circle",{cx:o,cy:i,r:s,fill:gn(c)}));else{let w=o+s*Math.cos(a),p=i+s*Math.sin(a),h=o+s*Math.cos(m),g=i+s*Math.sin(m),x=u>Math.PI?1:0;t.appendChild(mt("path",{d:`M ${o} ${i} L ${w} ${p} A ${s} ${s} 0 ${x} 1 ${h} ${g} Z`,fill:gn(c)}))}a=m})}function uh(t,e){let n=mt("svg",{viewBox:`0 0 ${e.width} ${e.height}`,width:"100%",role:"img"});if(n.setAttribute("aria-label",t.title??`${t.kind} chart`),t.kind==="pie"){let i=t.series[0];return ly(n,i.points.map(s=>Math.max(0,s)),e),n}let{min:r,max:o}=ty(t);return ry(n,t,e,r,o),t.kind==="bar"?oy(n,t,e,r,o):t.kind==="stacked"?iy(n,t,e,r,o):t.kind==="line"?sy(n,t,e,r,o):ay(n,t,e,r,o),n}function cy(t){if(t.length<2)return null;let e=document.createElement("div");return e.className="chart-legend",e.setAttribute("part","chart-legend"),t.forEach((n,r)=>{let o=document.createElement("span");o.className="chart-legend-item";let i=document.createElement("span");i.className="chart-legend-swatch",i.style.background=gn(r),o.append(i,document.createTextNode(n)),e.appendChild(o)}),e}function dy(t,e){new ResizeObserver(()=>{e(Math.round(t.clientWidth/ah)*ah)}).observe(t)}function Or(t){if(t.labels.length===0||t.series.length===0)return null;let e=document.createElement("div");if(e.className="chart-block",e.setAttribute("part","chart-block"),t.title!==void 0&&t.title!==""){let i=document.createElement("div");i.className="chart-title",i.setAttribute("part","chart-title"),i.textContent=t.title,e.appendChild(i)}let n=Xv,r=uh(t,ch(n));e.appendChild(r);let o=cy(t.kind==="pie"?t.labels:t.series.map(i=>i.label));return o!==null&&e.appendChild(o),dy(e,i=>{if(i===n)return;n=i;let s=uh(t,ch(n));r.replaceWith(s),r=s}),e}var uy=["bar","line","pie","scatter","stacked"];function hy(t){return uy.includes(t)?t:"bar"}function py(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="number"||!Number.isFinite(n)||Math.abs(n)>1e15)return null;e.push(n)}return e}function fy(t){if(!Array.isArray(t))return null;for(let e=0;e<t.length;e+=1)if(typeof t[e]!="string")return null;return t}function tr(t){if(typeof t!="object"||t===null)return null;let e=t,n=fy(e.labels);if(n===null||!Array.isArray(e.series))return null;let r=[];for(let s of e.series){if(typeof s!="object"||s===null)return null;let a=s,l=py(a.points);if(l===null||l.length!==n.length)return null;r.push({label:typeof a.label=="string"?a.label:"",points:l})}if(r.length===0||r.length*n.length>2e4||n.length>2e3)return null;let o=hy(e.kind),i=e.title;return typeof i=="string"?{kind:o,title:i,labels:n,series:r}:{kind:o,labels:n,series:r}}var Zi="render_chart";function my(t){let e=tr(t);return e===null?null:Or(e)}function gy(t){let e=tr(t);return e!==null&&e.labels.length>0&&e.series.length>0}var by="chart not rendered: expected labels (strings) and series, each with one finite number per label";function hh(){return{name:Zi,description:"Show a chart in the conversation. Supply the data and the page draws it. Every series must have exactly one point per label.",parameters:{type:"object",properties:{kind:{type:"string",enum:["bar","line","pie","scatter","stacked"]},title:{type:"string"},labels:{type:"array",items:{type:"string"}},series:{type:"array",items:{type:"object",properties:{label:{type:"string"},points:{type:"array",items:{type:"number"}}},required:["points"]}}},required:["labels","series"],"x-summary":"Draw a chart"},handler:t=>gy(t)?"chart rendered":by,render:my}}function al(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(vy(n));return e}function vy(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready",e.setAttribute("part","attachment-chip");let n=document.createElement("span");n.className="attachment-chip-icon",n.setAttribute("part","attachment-chip-icon"),n.innerHTML=ll(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.setAttribute("part","attachment-chip-name"),r.textContent=t.name,r.title=t.name;let o=document.createElement("span");return o.className="attachment-chip-size",o.setAttribute("part","attachment-chip-size"),o.textContent=Qi(t.size),e.append(n,r,o),e}function ll(t){return t.startsWith("image/")?jc:t==="application/pdf"?qc:t.startsWith("text/")?Wc:Vc}function Qi(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${e[r]}`}var ae={title:"Assistant",chatHistory:"Chat history",closeHistory:"Close history",searchConversations:"Search conversations",queued:"Waiting to send",removeQueued:'Do not send "{text}"',noMatches:"No conversations match that.",chatMoved:"Moved this panel out of the way",chatMinimised:"Minimised this panel",undo:"Undo",newChat:"New chat",collapse:"Collapse",expand:"Expand",expandUnread:"Expand \u2014 {count} unread",toggleTheme:"Toggle theme",copyCode:"Copy",copied:"Copied",copyFailed:"Copy failed",checkpoints:"Continue a run",noCheckpoints:"Nothing to continue yet.",resumeRun:"Resume",forkRun:"Fork",forkedRun:"branched",conversation:"Conversation",jumpToLatest:"Jump to latest",announceResponding:"Assistant is responding",announceAnswerReady:"Assistant answered",announceAwaitingDecision:"{count} action is waiting for your approval",announceStopped:"Response stopped",announceFailed:"The response failed",thinking:"Assistant is thinking\u2026",thoughts:"Thoughts",stopped:"\u23F9 Stopped",connectionLost:"Connection lost",noResult:"No result returned.",declinedAction:"User declined the action.",navigating:"Navigating\u2026",historyReplaced:"The server replaced this conversation's history. Reload to see the updated transcript.",chartUndrawable:"A chart could not be drawn from the data sent, so it was removed.",historyCompacted:"Earlier turns condensed to fit the context window ({count} removed)",usingSkill:"Using skill {name}",runInterrupted:"The previous response didn\u2019t finish \u2014 the page changed before it arrived.",pageMoved:"The page changed since you last looked at it. Call read_page to see the current page, then retry.",attachmentsStillUploading:"{n} file still uploading \u2014 it was not sent with this message and is still attached.",notConnected:"This chat isn\u2019t connected to an agent, so the message wasn\u2019t sent.",continueNeedsTurn:"Type the next turn in the composer first, then pick a run to continue.",skillNeeds:"\u201C{title}\u201D needs {fields} \u2014 fill it in below, then send.",message:"Message",inputPlaceholder:"Ask anything\u2026",send:"Send",stop:"Stop",attachFiles:"Attach files",recordVoice:"Record voice",stopRecording:"Stop recording",transcribing:"Transcribing\u2026",transcriptionFailed:"Transcription failed",recordingLimit:"Stopped at the {n}-minute limit \u2014 transcribing what was recorded.",toolRunning:"running\u2026",toolDeferred:"waiting for you",toolDone:"\u2713 done",toolError:"\u26A0 error",toolDeclined:"\u2298 declined",resizePanel:"Resize the chat panel",decisionApproved:"approved by you",decisionDeclined:"declined by you",argumentsLabel:"Arguments",resultLabel:"Result",errorLabel:"Error",declinedLabel:"Declined",details:"Details",subAgentWorking:"Working\u2026",subAgentDelegatedTo:"Delegated to {agent}",subAgentFinished:"{agent} finished",subAgentFailed:"The sub-agent failed",subAgentSteps:"Steps the sub-agent took",approvalEditArgs:"Edit the arguments before approving",approvalArgsInvalid:"That is not valid JSON, so nothing was sent.",approvalArgsNotAnObject:"Arguments have to be a JSON object.",suggestions:"Suggested follow-ups",messageActions:"Message actions",quoteSelection:"Quote",copyMessage:"Copy message",retryMessage:"Try again",feedbackUp:"Good answer",feedbackDown:"Poor answer",confirmAction:"Confirm action",confirmAlways:"Always allow",confirmRun:"Run \u201C{tool}\u201D?",confirm:"Confirm",cancel:"Cancel",approveAction:"Approve action",approvalPrompt:"Approve this action?",approve:"Approve",deny:"Deny",askUserAction:"Question",otherOption:"Other\u2026",answerPlaceholder:"Type your answer\u2026",submit:"Submit",chats:"Chats",noConversations:"No conversations yet.",rename:"Rename",renameConversation:"Rename conversation",delete:"Delete",deleteConversation:"Delete conversation",deletePrompt:"Delete?",tooLarge:"Too large (max {size})",fileTypeNotAllowed:"File type not allowed",uploadFailed:"upload failed",retry:"Retry",retryUpload:"Retry upload",remove:"Remove",removeAttachment:"Remove attachment",justNow:"just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago",weeksAgo:"{n}w ago"};function cl(t){let e={...ae};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}var Ji=class{element;#t;#n;#e=[];constructor(e){this.#t=e,this.#n=e.strings??ae,this.element=document.createElement("div"),this.element.className="attachment-tray",this.element.setAttribute("part","attachment-tray"),this.element.hidden=!0}add(e){let n={localId:Ie(),file:e,status:Ge.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#e.push(n);let r=this.#s(e);if(r!==null){n.status=Ge.ERROR,n.error=r,this.#o(),this.#t.onChange?.();return}this.#o(),this.#t.onChange?.(),this.#r(n)}readyRefs(){let e=[];for(let n of this.#e)n.ref!==null&&e.push(n.ref);return e}hasPending(){return this.#e.some(e=>e.status===Ge.UPLOADING)}pendingCount(){return this.#e.filter(e=>e.status===Ge.UPLOADING).length}isEmpty(){return this.#e.length===0}clearReady(){this.#e=this.#e.filter(e=>e.status===Ge.UPLOADING),this.#o()}clear(){for(let e of this.#e)e.controller?.abort();this.#e=[],this.#o()}dispose(){for(let e of this.#e)e.controller?.abort()}#s(e){return this.#t.maxBytes>0&&e.size>this.#t.maxBytes?this.#n.tooLarge.replace("{size}",Qi(this.#t.maxBytes)):yy(this.#t.accept,e)?null:this.#n.fileTypeNotAllowed}#r(e){let n=this.#s(e.file);if(n!==null){e.status=Ge.ERROR,e.error=n,this.#o(),this.#t.onChange?.();return}e.status=Ge.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#o(),this.#t.upload(e.file,o=>{e.progress=o,this.#o()},r.signal).then(o=>{e.status=Ge.READY,e.ref=o}).catch(o=>{e.status=Ge.ERROR,e.error=o instanceof Error?o.message:this.#n.uploadFailed}).finally(()=>{e.controller=null,this.#o(),this.#t.onChange?.()})}#i(e){e.controller?.abort(),this.#e=this.#e.filter(n=>n!==e),this.#o(),this.#t.onChange?.()}#o(){this.element.replaceChildren(),this.element.hidden=this.#e.length===0;for(let e of this.#e)this.element.appendChild(this.#u(e))}#u(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`,n.setAttribute("part","attachment-chip");let r=document.createElement("span");r.className="attachment-chip-icon",r.setAttribute("part","attachment-chip-icon"),r.innerHTML=ll(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.setAttribute("part","attachment-chip-name"),o.textContent=e.file.name,o.title=e.file.name;let i=document.createElement("span");if(i.className="attachment-chip-size",i.setAttribute("part","attachment-chip-size"),i.textContent=e.status===Ge.ERROR?e.error:Qi(e.file.size),n.append(r,o,i),e.status===Ge.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar",a.setAttribute("part","attachment-chip-bar");let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.setAttribute("part","attachment-chip-bar-fill"),l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Ge.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.setAttribute("part","attachment-chip-retry"),a.title=this.#n.retry,a.setAttribute("aria-label",this.#n.retryUpload),a.textContent="\u21BB",a.addEventListener("click",()=>this.#r(e)),n.appendChild(a)}let s=document.createElement("button");return s.type="button",s.className="attachment-chip-remove",s.setAttribute("part","attachment-chip-remove"),s.title=this.#n.remove,s.setAttribute("aria-label",this.#n.removeAttachment),s.textContent="\u2715",s.addEventListener("click",()=>this.#i(e)),n.appendChild(s),n}};function yy(t,e){let n=t.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(i=>i.startsWith(".")?o.endsWith(i):i.endsWith("/*")?r.startsWith(i.slice(0,-1)):r===i)}var es=class{chips;palette;#t;#n=[];#e=!1;#s=!1;#r=[];#i=0;constructor(e){this.#t=e,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.setAttribute("part","skill-chips"),this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("part","skill-palette"),this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(e){this.#n=e,this.#l()}enableChips(e){this.#e=e,this.#l()}enableSlash(e){this.#s=e}isOpen(){return!this.palette.hidden}onInput(e){this.#s&&e.startsWith("/")?this.#o(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#u(1),!0):e.key==="ArrowUp"?(this.#u(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#r.slice(this.#i,this.#i+1).forEach(n=>{this.#h(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#o(e){let n=e.trim().toLowerCase(),r=this.#n.filter(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#r=r,this.#i=0,this.#c(),this.palette.hidden=!1}#u(e){let n=this.#r.length;this.#i=(this.#i+e+n)%n,this.#c()}#h(e){this.close(),this.#t(e)}#l(){this.chips.replaceChildren();let e=this.#e?this.#n.filter(n=>n.chip===!0):[];this.chips.hidden=e.length===0;for(let n of e){let r=document.createElement("button");r.type="button",r.className="skill-chip",r.setAttribute("part","skill-chip"),r.textContent=n.title,r.title=`/${n.name}`,r.addEventListener("click",()=>this.#h(n)),this.chips.appendChild(r)}}#c(){this.palette.replaceChildren(),this.#r.forEach((e,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("part","skill-item"),r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#i?"true":"false");let o=document.createElement("span");o.className="skill-item-title",o.setAttribute("part","skill-item-title");let i=document.createElement("code");if(i.className="skill-item-token",i.setAttribute("part","skill-item-token"),i.textContent=`/${e.name}`,o.append(i,document.createTextNode(` ${e.title}`)),r.appendChild(o),e.description!==void 0){let s=document.createElement("span");s.className="skill-item-desc",s.setAttribute("part","skill-item-desc"),s.textContent=e.description,r.appendChild(s)}r.addEventListener("click",()=>this.#h(e)),this.palette.appendChild(r)})}};var ph=12e4,ts=class{element;#t;#n;#e;#s="idle";#r=null;#i=null;#o=[];#u=null;#h=!1;#l=!1;constructor(e){this.#t=e.transcribe,this.#n=e.onText,this.#e=e.strings??ae,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button");let n=document.createElement("slot");n.name="icon-voice",n.innerHTML=Dc,this.element.append(n),this.#T("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#d();return}this.#s!=="transcribing"&&await this.#c()}async#c(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#N(this.#e.transcriptionFailed);return}this.#i=e,this.#o=[],this.#h=!1;let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#o.push(r.data)}),n.addEventListener("stop",()=>{this.#y(n.mimeType)}),this.#r=n,n.start(),this.#u=setTimeout(()=>{this.#h=!0,this.#d()},ph),this.#T("recording")}#d(){this.#p(),this.#r?.stop()}#p(){this.#u!==null&&(clearTimeout(this.#u),this.#u=null)}dispose(){this.#l=!0,this.#p(),this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#m()}async#y(e){if(this.#l)return;this.#m(),this.#T("transcribing");let n=new Blob(this.#o,{type:e||"audio/webm"});try{let r=await this.#t(n);this.#T("idle"),this.#h&&(this.element.title=this.#e.recordingLimit.replace("{n}",String(ph/6e4))),r!==""&&this.#n(r)}catch(r){this.#N(r instanceof Error?r.message:this.#e.transcriptionFailed)}finally{this.#r=null}}#m(){for(let e of this.#i?.getTracks()??[])e.stop();this.#i=null}#N(e){this.#m(),this.#r=null,this.#T("idle"),this.element.title=e}#T(e){this.#s=e,this.element.dataset.state=e;let n=this.#x(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#x(e){return e==="recording"?this.#e.stopRecording:e==="transcribing"?this.#e.transcribing:this.#e.recordVoice}};function dl(t,e){for(let n of Array.from(t.querySelectorAll("pre"))){let r=n.querySelector("code");r===null||n.querySelector(".code-copy")!==null||(n.classList.add("has-copy"),n.append(wy(r,e)))}}function wy(t,e){let n=t.textContent,r=document.createElement("button");return r.type="button",r.className="code-copy",r.setAttribute("part","code-copy"),r.textContent=e.copyCode,r.title=e.copyCode,r.setAttribute("aria-label",e.copyCode),r.addEventListener("click",()=>{xy(n).then(o=>{Ey(r,o?e.copied:e.copyFailed,e)})}),r}async function xy(t){let e=navigator.clipboard;if(e===void 0)return!1;try{return await e.writeText(t),!0}catch{return!1}}function Ey(t,e,n){t.textContent=e,t.dataset.state=e===n.copied?"copied":"failed",setTimeout(()=>{t.textContent=n.copyCode,delete t.dataset.state},1500)}var _y=new Set(["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","DD","DIV","DL","DT","FIGCAPTION","FIGURE","FOOTER","H1","H2","H3","H4","H5","H6","HEADER","HR","MAIN","NAV","OL","P","SECTION","UL"]);function ns(t){let e=t.cloneNode(!0);for(let n of Array.from(e.querySelectorAll("button")))n.remove();return{text:Ay(fh(e)),html:e.innerHTML}}function fh(t){if(t.nodeType===Node.TEXT_NODE)return t.nodeValue.replace(/\s+/g," ");if(t.nodeType!==Node.ELEMENT_NODE)return"";let e=t,n=e.tagName;if(n==="BR")return`
13
12
  `;if(n==="PRE")return`
14
13
 
15
- ${vh(e)}
14
+ ${gh(e)}
16
15
 
17
16
  `;if(n==="TABLE")return`
18
17
 
19
- ${Ay(e)}
18
+ ${Sy(e)}
20
19
 
21
20
  `;if(n==="UL"||n==="OL")return`
22
21
 
23
- ${Sy(e,n==="OL")}
22
+ ${Ty(e,n==="OL")}
24
23
 
25
- `;let r=bh(e);return Ty.has(n)?`
24
+ `;let r=mh(e);return _y.has(n)?`
26
25
 
27
26
  ${r}
28
27
 
29
- `:r}function bh(t){let e="";for(let n of Array.from(t.childNodes))e+=gh(n);return e}function Sy(t,e){return Array.from(t.children).map((n,r)=>`${e?`${r+1}. `:"- "}${bh(n).trim()}`).join(`
30
- `)}function Ay(t){return Array.from(t.querySelectorAll("tr")).map(e=>Array.from(e.children).map(n=>vh(n).replace(/\s+/g," ").trim()).join(" ")).join(`
31
- `)}function vh(t){return t.textContent}function ky(t){return t.replace(/[^\S\n]+\n/g,`
28
+ `:r}function mh(t){let e="";for(let n of Array.from(t.childNodes))e+=fh(n);return e}function Ty(t,e){return Array.from(t.children).map((n,r)=>`${e?`${r+1}. `:"- "}${mh(n).trim()}`).join(`
29
+ `)}function Sy(t){return Array.from(t.querySelectorAll("tr")).map(e=>Array.from(e.children).map(n=>gh(n).replace(/\s+/g," ").trim()).join(" ")).join(`
30
+ `)}function gh(t){return t.textContent}function Ay(t){return t.replace(/[^\S\n]+\n/g,`
32
31
  `).replace(/\n{3,}/g,`
33
32
 
34
- `).trim()}var Iy=4,Ry=16,Cy=64;function yh(t,e){let n=!1;t.addEventListener("click",i=>{!n||i.detail===0||(n=!1,i.stopPropagation(),i.preventDefault())},!0),t.addEventListener("pointerdown",i=>{if(n=!1,!e.enabled())return;let s=e.rect(),a=i.clientX,l=i.clientY,c=!1,u=w=>{let p=w.clientX-a,h=w.clientY-l;if(!c&&Math.hypot(p,h)<Iy)return;c=!0,t.setAttribute("data-dragging","true");let g=Dt({...s,left:s.left+p,top:s.top+h},e.viewport());e.apply(g.left,g.top)},m=w=>{if(window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),!c)return;t.removeAttribute("data-dragging"),n=!0;let p=Dt({...s,left:s.left+(w.clientX-a),top:s.top+(w.clientY-l)},e.viewport());e.commit(p.left,p.top)};window.addEventListener("pointermove",u),window.addEventListener("pointerup",m),window.addEventListener("pointercancel",m)});let r=null,o=()=>{if(r===null)return;let{left:i,top:s}=r;r=null,e.commit(i,s)};t.addEventListener("keydown",i=>{if(!e.enabled())return;let s=i.shiftKey?Cy:Ry,a=e.rect(),l=null;if(i.key==="ArrowLeft"?l={left:a.left-s,top:a.top}:i.key==="ArrowRight"?l={left:a.left+s,top:a.top}:i.key==="ArrowUp"?l={left:a.left,top:a.top-s}:i.key==="ArrowDown"&&(l={left:a.left,top:a.top+s}),l===null)return;i.preventDefault();let c=Dt({...a,...l},e.viewport());e.apply(c.left,c.top),r=c}),t.addEventListener("keyup",o),t.addEventListener("blur",o)}function Dr(t,e,n,r){return{hostInset:wh({top:n.y==="top"?t.top:null,right:n.x==="right"?r.width-t.right:null,bottom:n.y==="bottom"?r.height-t.bottom:null,left:n.x==="left"?t.left:null}),launcherInset:wh({top:n.y==="top"?e.top-t.top:null,right:n.x==="right"?t.right-(e.left+e.width):null,bottom:n.y==="bottom"?t.bottom-(e.top+e.height):null,left:n.x==="left"?e.left-t.left:null})}}function wh(t){let e=n=>n===null?"auto":`${Math.round(n)}px`;return`${e(t.top)} ${e(t.right)} ${e(t.bottom)} ${e(t.left)}`}function fl(t,e,n,r,o=Je){let i=n.left+n.width-t.left,s=t.left+t.width-n.left,a=n.top+n.height-t.top,l=t.top+t.height-n.top,c={x:i>=s?"left":"right",y:a>=l?"top":"bottom"},u=c.x==="left"?t.left:t.left+t.width-e.width,m=c.y==="top"?t.top:t.top+t.height-e.height,w=Pr({left:u,top:m,right:u+e.width,bottom:m+e.height},n,o);return{corner:c,...Dr(w,t,c,r)}}var Ny=1500;function gl(t,e){if(Eh(t)!==null)return;let n=ts(t,e.strings),r=e.text;r!==void 0&&n.appendChild(Oy(e.strings,r,e.html)),e.onFeedback!==void 0&&n.append(xh("up",e.strings.feedbackUp,e.onFeedback),xh("down",e.strings.feedbackDown,e.onFeedback))}function ts(t,e){let n=Eh(t);if(n!==null)return n;let r=document.createElement("div");return r.className="message-actions",r.setAttribute("part","message-actions"),r.setAttribute("role","group"),r.setAttribute("aria-label",e.messageActions),t.after(r),r}function Eh(t){let e=t.nextElementSibling;return e?.classList.contains("message-actions")===!0?e:null}function ns(t,e,n){let r=document.createElement("button");r.type="button",r.className=`message-action message-action--${t}`,r.setAttribute("part",`message-action message-action-${t}`),ml(r,e);let o=document.createElement("span");return o.className="message-action-icon",o.setAttribute("part",`message-action-icon message-action-icon-${t}`),o.setAttribute("aria-hidden","true"),o.innerHTML=n,r.appendChild(o),r}function ml(t,e){t.title=e,t.setAttribute("aria-label",e),t.dataset.tooltip=e}function Oy(t,e,n){let r=ns("copy",t.copyMessage,zc);return r.addEventListener("click",()=>{My(e(),n?.()).then(o=>{Ly(r,o?t.copied:t.copyFailed,t.copyMessage)})}),r}async function My(t,e){let n=navigator.clipboard;if(n===void 0)return!1;if(e!==void 0&&typeof ClipboardItem=="function")try{return await n.write([new ClipboardItem({"text/plain":new Blob([t],{type:"text/plain"}),"text/html":new Blob([e],{type:"text/html"})})]),!0}catch{}try{return await n.writeText(t),!0}catch{return!1}}function xh(t,e,n){let r=ns(t==="up"?"up":"down",e,t==="up"?$c:Bc);return r.addEventListener("click",()=>{let o=r.getAttribute("aria-pressed")==="true";r.setAttribute("aria-pressed",o?"false":"true"),n(t)}),r.setAttribute("aria-pressed","false"),r}function Ly(t,e,n){ml(t,e),t.classList.add("message-action--confirmed"),setTimeout(()=>{ml(t,n),t.classList.remove("message-action--confirmed")},Ny)}var Py=500;function Ur(t,e=[],n){for(let r of qy(e)){if(!t.contains(r.startContainer)||!t.contains(r.endContainer))continue;let o=document.createRange();o.setStart(r.startContainer,r.startOffset),o.setEnd(r.endContainer,r.endOffset);let i=Gy(o).trim();if(i!=="")return{text:i,rect:jy(o,n)}}return null}function bl(t){let e=Dy(t);return e.length===0?"":`${Hy(e.join(`
33
+ `).trim()}var ky=500;function Mr(t,e=[],n){for(let r of Hy(e)){if(!t.contains(r.startContainer)||!t.contains(r.endContainer))continue;let o=document.createRange();o.setStart(r.startContainer,r.startOffset),o.setEnd(r.endContainer,r.endOffset);let i=Ny(o).trim();if(i!=="")return{text:i,rect:Uy(o,n)}}return null}function ul(t){let e=Iy(t);return e.length===0?"":`${Cy(e.join(`
35
34
  `)).split(`
36
35
  `).map(o=>`> ${o}`.trimEnd()).join(`
37
36
  `)}
38
37
 
39
- `}function Dy(t){let e=t.split(/\r\n?|\n/).map(i=>i.trimEnd()),n=e.filter(i=>i!=="").map(Uy),r=n.length===0?0:Math.min(...n),o=[];for(let i of e){let s=i.slice(r);s===""&&(o.length===0||o[o.length-1]==="")||o.push(s)}for(;o[o.length-1]==="";)o.pop();return o}function Uy(t){return t.length-t.trimStart().length}function Hy(t){return t.length>500?`${t.slice(0,500).trimEnd()}...`:t}function Gy(t){let e="";for(let n of By(t)){let r=n.parentElement;if(!Vy(r))continue;let o=n===t.startContainer?t.startOffset:0,i=n===t.endContainer?t.endOffset:n.data.length;e+=zy(n.data.slice(o,i),r)}return e}function zy(t,e){return Fy.has($y(e))?t:t.replace(/[^\S\n]*\n[^\S\n]*/g,`
40
- `).replace(/[^\S\n]+/g," ")}var Fy=new Set(["pre","pre-wrap","break-spaces"]);function $y(t){return window.getComputedStyle(t).whiteSpace}function By(t){let e=t.commonAncestorContainer;if(e.nodeType===Node.TEXT_NODE)return[e];let n=[],r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let o=r.nextNode();o!==null;o=r.nextNode())t.intersectsNode(o)&&n.push(o);return n}function Vy(t){return typeof t.checkVisibility!="function"?!0:t.checkVisibility({contentVisibilityAuto:!0,opacityProperty:!0,visibilityProperty:!0})}function jy(t,e){let n=[...t.getClientRects()];if(n.length===0)return t.getBoundingClientRect();if(e===void 0)return n[0];let r=n[0],o=_h(r,e);for(let i of n.slice(1)){let s=_h(i,e);s<o&&(o=s,r=i)}return r}function _h(t,e){let n=Math.max(t.left-e.x,0,e.x-t.right),r=Math.max(t.top-e.y,0,e.y-t.bottom);return Math.hypot(n,r)}function qy(t){let e=window.getSelection();if(e===null)return[];let n=[...Wy(e,t)];return e.rangeCount>0&&n.push(e.getRangeAt(0)),n}function Wy(t,e){let n=t.getComposedRanges;if(n===void 0)return[];try{return n.call(t,{shadowRoots:e})}catch{return n.call(t,...e)}}var vl=6,Xy=`
38
+ `}function Iy(t){let e=t.split(/\r\n?|\n/).map(i=>i.trimEnd()),n=e.filter(i=>i!=="").map(Ry),r=n.length===0?0:Math.min(...n),o=[];for(let i of e){let s=i.slice(r);s===""&&(o.length===0||o[o.length-1]==="")||o.push(s)}for(;o[o.length-1]==="";)o.pop();return o}function Ry(t){return t.length-t.trimStart().length}function Cy(t){return t.length>500?`${t.slice(0,500).trimEnd()}...`:t}function Ny(t){let e="";for(let n of Py(t)){let r=n.parentElement;if(!Dy(r))continue;let o=n===t.startContainer?t.startOffset:0,i=n===t.endContainer?t.endOffset:n.data.length;e+=Oy(n.data.slice(o,i),r)}return e}function Oy(t,e){return My.has(Ly(e))?t:t.replace(/[^\S\n]*\n[^\S\n]*/g,`
39
+ `).replace(/[^\S\n]+/g," ")}var My=new Set(["pre","pre-wrap","break-spaces"]);function Ly(t){return window.getComputedStyle(t).whiteSpace}function Py(t){let e=t.commonAncestorContainer;if(e.nodeType===Node.TEXT_NODE)return[e];let n=[],r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let o=r.nextNode();o!==null;o=r.nextNode())t.intersectsNode(o)&&n.push(o);return n}function Dy(t){return typeof t.checkVisibility!="function"?!0:t.checkVisibility({contentVisibilityAuto:!0,opacityProperty:!0,visibilityProperty:!0})}function Uy(t,e){let n=[...t.getClientRects()];if(n.length===0)return t.getBoundingClientRect();if(e===void 0)return n[0];let r=n[0],o=bh(r,e);for(let i of n.slice(1)){let s=bh(i,e);s<o&&(o=s,r=i)}return r}function bh(t,e){let n=Math.max(t.left-e.x,0,e.x-t.right),r=Math.max(t.top-e.y,0,e.y-t.bottom);return Math.hypot(n,r)}function Hy(t){let e=window.getSelection();if(e===null)return[];let n=[...Gy(e,t)];return e.rangeCount>0&&n.push(e.getRangeAt(0)),n}function Gy(t,e){let n=t.getComposedRanges;if(n===void 0)return[];try{return n.call(t,{shadowRoots:e})}catch{return n.call(t,...e)}}var hl=6,zy=`
41
40
  .ag-ui-quote-offer {
42
41
  position: fixed;
43
42
  z-index: 2147483000;
@@ -59,73 +58,8 @@ ${r}
59
58
  .ag-ui-quote-offer[data-below="true"] {
60
59
  transform: translate(-50%, 0);
61
60
  }
62
- `;function yl(t){let{within:e,exclude:n,onQuote:r}=t,o=new CSSStyleSheet;o.replaceSync(Xy),document.adoptedStyleSheets=[...document.adoptedStyleSheets,o];let i=document.createElement("button");i.type="button",i.className="ag-ui-quote-offer",i.textContent=t.label,i.hidden=!0,document.body.append(i);let s="",a=()=>{i.hidden=!0,s=""},l=u=>{if(u.composedPath().includes(n)){a();return}if(Yy()){a();return}let m=u instanceof MouseEvent?{x:u.clientX,y:u.clientY}:void 0,w=Ur(e,[],m);if(w===null){a();return}s=w.text,Ky(i,w.rect)},c=u=>{i.contains(u.target)||a()};return e.addEventListener("mouseup",l),e.addEventListener("keyup",l),e.addEventListener("mousedown",c),document.addEventListener("scroll",a,!0),window.addEventListener("resize",a),i.addEventListener("mousedown",u=>{u.preventDefault()}),i.addEventListener("click",()=>{let u=s;window.getSelection()?.removeAllRanges(),a(),r(u)}),{element:i,detach(){e.removeEventListener("mouseup",l),e.removeEventListener("keyup",l),e.removeEventListener("mousedown",c),document.removeEventListener("scroll",a,!0),window.removeEventListener("resize",a),i.remove(),document.adoptedStyleSheets=document.adoptedStyleSheets.filter(u=>u!==o)}}}function Yy(){let t=document.activeElement;return t===null?!1:t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable===!0}function Ky(t,e){t.hidden=!1;let n=e.top<vl+t.offsetHeight;t.dataset.below=String(n),t.style.top=`${n?e.bottom+vl:e.top-vl}px`;let r=t.offsetWidth/2,o=e.left+e.width/2,i=document.documentElement.clientWidth;t.style.left=`${Math.min(Math.max(o,r),i-r)}px`}var Zy="button, a[href], input, select, textarea, [contenteditable]";function Th(t,e){t.addEventListener("pointerdown",n=>{if(n.button!==0||!e.enabled()||Qy(n,t))return;let r=e.rect(),o=n.clientX,i=n.clientY,s=!1,a=(u,m)=>{let w=u-o,p=m-i;return{left:r.left+w,top:r.top+p,right:r.right+w,bottom:r.bottom+p}},l=u=>{!s&&Math.hypot(u.clientX-o,u.clientY-i)<4||(s=!0,t.setAttribute("data-dragging","true"),e.apply(a(u.clientX,u.clientY),r))},c=u=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),s&&(t.removeAttribute("data-dragging"),e.commit(a(u.clientX,u.clientY),r))};n.preventDefault(),window.addEventListener("pointermove",l),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c)})}function Qy(t,e){let n=t.composedPath();return n.slice(0,n.indexOf(e)).some(r=>r instanceof Element&&r.matches(Zy))}function wl(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function Jy(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function xl(t,e,n={}){let r=n.strings??ae,o=e.options??[],i=o.length>0,s=!i||e.allowCustom===!0;return new Promise(a=>{let l=document.createElement("div");l.className="question",l.setAttribute("part","question"),l.setAttribute("role","group"),l.setAttribute("aria-label",r.askUserAction);let c=document.createElement("div");c.className="question-body",c.setAttribute("part","question-body"),c.textContent=e.question;let u=document.createElement("div");u.className="question-options",u.setAttribute("part","question-options");let m=`q-${o.length}-${e.question.length}`,w=[];for(let v of o){let A=document.createElement("label");A.className="question-choice",A.setAttribute("part","question-choice");let E=document.createElement("input");E.type="radio",E.name=m,E.value=v,E.setAttribute("part","question-radio");let R=document.createElement("span");R.setAttribute("part","question-choice-text"),R.textContent=v,A.append(E,R),u.appendChild(A),w.push(E)}let p=null,h=null;if(s){if(h=Jy(r.answerPlaceholder),i){let v=document.createElement("label");v.className="question-choice",v.setAttribute("part","question-choice"),p=document.createElement("input"),p.type="radio",p.name=m,p.value="",p.setAttribute("part","question-radio");let A=document.createElement("span");A.setAttribute("part","question-choice-text"),A.textContent=r.otherOption,v.append(p,A),u.appendChild(v),h.disabled=!0}u.appendChild(h)}let g=document.createElement("div");g.className="question-actions",g.setAttribute("part","question-actions");let x=document.createElement("button");x.type="button",x.className="question-btn",x.setAttribute("part","question-button"),x.textContent=r.submit,g.appendChild(x);let T=!1,S=()=>{let v=w.find(A=>A.checked);if(v!==void 0)return v.value;if(h!==null&&(p===null||p.checked)){let A=h.value.trim();return A===""?null:A}return null},L=()=>{h!==null&&p!==null&&(h.disabled=!p.checked),x.disabled=S()===null},z=v=>{if(!T){T=!0,x.disabled=!0;for(let A of w)A.disabled=!0;p!==null&&(p.disabled=!0),h!==null&&(h.disabled=!0),l.setAttribute("data-resolved",v===""?"cancelled":"answered"),a(v)}};for(let v of[...w,...p!==null?[p]:[]])v.addEventListener("change",L);if(h?.addEventListener("input",L),h?.addEventListener("keydown",v=>{if(v.key==="Enter"){v.preventDefault();let A=S();A!==null&&z(A)}}),x.addEventListener("click",()=>{let v=S();v!==null&&z(v)}),n.signal?.addEventListener("abort",()=>z(""),{once:!0}),l.append(c,u,g),t.appendChild(l),n.signal?.aborted===!0){z("");return}L(),(i?w[0]:h)?.focus()})}function Sh(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function ew(t){if(Array.isArray(t))return t}function tw(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,i,s,a=[],l=!0,c=!1;try{if(i=(n=n.call(t)).next,e!==0)for(;!(l=(r=i.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(u){c=!0,o=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw o}}return a}}function nw(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
63
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function rw(t,e){return ew(t)||tw(t,e)||ow(t,e)||nw()}function ow(t,e){if(t){if(typeof t=="string")return Sh(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Sh(t,e):void 0}}var zh=Object.entries,Ah=Object.setPrototypeOf,iw=Object.isFrozen,sw=Object.getPrototypeOf,aw=Object.getOwnPropertyDescriptor,ye=Object.freeze,_e=Object.seal,nr=Object.create,Fh=typeof Reflect<"u"&&Reflect,Il=Fh.apply,Rl=Fh.construct;ye||(ye=function(e){return e});_e||(_e=function(e){return e});Il||(Il=function(e,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];return e.apply(n,o)});Rl||(Rl=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new e(...r)});var yn=ve(Array.prototype.forEach),lw=ve(Array.prototype.lastIndexOf),kh=ve(Array.prototype.pop),Hr=ve(Array.prototype.push),cw=ve(Array.prototype.splice),rr=Array.isArray,Fr=ve(String.prototype.toLowerCase),El=ve(String.prototype.toString),Ih=ve(String.prototype.match),Gr=ve(String.prototype.replace),Rh=ve(String.prototype.indexOf),dw=ve(String.prototype.trim),uw=ve(Number.prototype.toString),hw=ve(Boolean.prototype.toString),Ch=typeof BigInt>"u"?null:ve(BigInt.prototype.toString),Nh=typeof Symbol>"u"?null:ve(Symbol.prototype.toString),He=ve(Object.prototype.hasOwnProperty),zr=ve(Object.prototype.toString),Ce=ve(RegExp.prototype.test),vn=pw(TypeError);function ve(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Il(t,e,r)}}function pw(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Rl(t,n)}}function ee(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Fr;if(Ah&&Ah(t,null),!rr(e))return t;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let i=n(o);i!==o&&(iw(e)||(e[r]=i),o=i)}t[o]=!0}return t}function fw(t){for(let e=0;e<t.length;e++)He(t,e)||(t[e]=null);return t}function Ve(t){let e=nr(null);for(let r of zh(t)){var n=rw(r,2);let o=n[0],i=n[1];He(t,o)&&(rr(i)?e[o]=fw(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=Ve(i):e[o]=i)}return e}function mw(t){switch(typeof t){case"string":return t;case"number":return uw(t);case"boolean":return hw(t);case"bigint":return Ch?Ch(t):"0";case"symbol":return Nh?Nh(t):"Symbol()";case"undefined":return zr(t);case"function":case"object":{if(t===null)return zr(t);let e=t,n=rt(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:zr(r)}return zr(t)}default:return zr(t)}}function rt(t,e){for(;t!==null;){let r=aw(t,e);if(r){if(r.get)return ve(r.get);if(typeof r.value=="function")return ve(r.value)}t=sw(t)}function n(){return null}return n}function gw(t){try{return Ce(t,""),!0}catch{return!1}}var Oh=ye(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),_l=ye(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Tl=ye(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),bw=ye(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Sl=ye(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),vw=ye(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Mh=ye(["#text"]),Lh=ye(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Al=ye(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Ph=ye(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),rs=ye(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),yw=_e(/{{[\w\W]*|^[\w\W]*}}/g),ww=_e(/<%[\w\W]*|^[\w\W]*%>/g),xw=_e(/\${[\w\W]*/g),Ew=_e(/^data-[\-\w.\u00B7-\uFFFF]+$/),_w=_e(/^aria-[\-\w]+$/),Dh=_e(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Tw=_e(/^(?:\w+script|data):/i),Sw=_e(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Aw=_e(/^html$/i),kw=_e(/^[a-z][.\w]*(-[.\w]+)+$/i),Uh=_e(/<[/\w!]/g),Hh=_e(/<[/\w]/g),Iw=_e(/<\/no(script|embed|frames)/i),Rw=_e(/\/>/i),Be={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},$h=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],Cw=ye(ee({},$h)),Nw=(function(){let t={};return yn($h,e=>{t[e]=_e(new RegExp("</"+e+"(?=[\\t\\n\\f\\r />])","i"))}),ye(t)})(),Ow=function(){return typeof window>"u"?null:window},Mw=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Gh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Ut=function(e,n,r,o){return He(e,n)&&rr(e[n])?ee(o.base?Ve(o.base):{},e[n],o.transform):r},kl=function(e,n,r){let o=He(e,n)?e[n]:void 0;return o&&typeof o=="object"?Ve(o):r()};function Bh(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ow(),e=I=>Bh(I);if(e.version="3.4.14",e.removed=[],!t||!t.document||t.document.nodeType!==Be.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,o=r.currentScript;t.DocumentFragment;let i=t.HTMLTemplateElement,s=t.Node,a=t.Element,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let u=t.DOMParser,m=t.trustedTypes,w=a.prototype,p=rt(w,"cloneNode"),h=rt(w,"remove"),g=rt(w,"nextSibling"),x=rt(w,"childNodes"),T=rt(w,"parentNode"),S=rt(w,"shadowRoot"),L=rt(w,"attributes"),z=s&&s.prototype?rt(s.prototype,"nodeType"):null,v=s&&s.prototype?rt(s.prototype,"nodeName"):null,A=s&&s.prototype?rt(s.prototype,"ownerDocument"):null,E=function(f){return z?z(f):f.nodeType},R=function(f){return v?v(f):f.nodeName};if(typeof i=="function"){let I=n.createElement("template");I.content&&I.content.ownerDocument&&(n=I.content.ownerDocument)}let B,le="",we,je=!1,lr=0,tc=function(){if(lr>0)throw vn('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},_n=function(f){tc(),lr++;try{return B.createHTML(f)}finally{lr--}},Op=function(f){tc(),lr++;try{return B.createScriptURL(f)}finally{lr--}},Mp=function(){return je||(we=Mw(m,o),je=!0),we},Jr=n,Ts=Jr.implementation,nc=Jr.createNodeIterator,Lp=Jr.createDocumentFragment,Pp=Jr.getElementsByTagName,Dp=r.importNode,de=Gh();e.isSupported=typeof zh=="function"&&typeof T=="function"&&Ts&&Ts.createHTMLDocument!==void 0;let Up=yw,Hp=ww,Gp=xw,zp=Ew,Fp=_w,$p=Tw,rc=Sw,Bp=kw,oc=Dh,ue=null,Ss=ee({},[...Oh,..._l,...Tl,...Sl,...Mh]),he=null,As=ee({},[...Lh,...Al,...Ph,...rs]),st=Object.seal(nr(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),cr=null,ic=null,St=Object.seal(nr(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),sc=!0,ks=!0,ac=!1,lc=!0,At=!1,Gt=!0,zt=!1,Is=!1,eo=null,to=null,Rs=!1,Tn=!1,no=!1,ro=!1,cc=!0,dc=!1,uc="user-content-",Cs=!0,Ns=!1,Sn={},An=null,hc=ee({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),pc=null,fc=ee({},["audio","video","img","source","image","track"]),mc=null,gc=ee({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),oo="http://www.w3.org/1998/Math/MathML",io="http://www.w3.org/2000/svg",at="http://www.w3.org/1999/xhtml",kn=at,Os=!1,Ms=null,Vp=ee({},[oo,io,at],El),bc=ye(["mi","mo","mn","ms","mtext"]),Ls=ee({},bc),vc=ye(["annotation-xml"]),Ps=ee({},vc),jp=ee({},["title","style","font","a","script"]),dr=null,qp=["application/xhtml+xml","text/html"],Wp="text/html",ge=null,In=null,Xp=n.createElement("form"),yc=function(f){return f instanceof RegExp||f instanceof Function},Ds=function(){let f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(In&&In===f)return;(!f||typeof f!="object")&&(f={}),f=Ve(f),dr=qp.indexOf(f.PARSER_MEDIA_TYPE)===-1?Wp:f.PARSER_MEDIA_TYPE,ge=dr==="application/xhtml+xml"?El:Fr,ue=Ut(f,"ALLOWED_TAGS",Ss,{transform:ge}),he=Ut(f,"ALLOWED_ATTR",As,{transform:ge}),Ms=Ut(f,"ALLOWED_NAMESPACES",Vp,{transform:El}),mc=Ut(f,"ADD_URI_SAFE_ATTR",gc,{transform:ge,base:gc}),pc=Ut(f,"ADD_DATA_URI_TAGS",fc,{transform:ge,base:fc}),An=Ut(f,"FORBID_CONTENTS",hc,{transform:ge}),cr=Ut(f,"FORBID_TAGS",Ve({}),{transform:ge}),ic=Ut(f,"FORBID_ATTR",Ve({}),{transform:ge}),Sn=He(f,"USE_PROFILES")?f.USE_PROFILES&&typeof f.USE_PROFILES=="object"?Ve(f.USE_PROFILES):f.USE_PROFILES:!1,sc=f.ALLOW_ARIA_ATTR!==!1,ks=f.ALLOW_DATA_ATTR!==!1,ac=f.ALLOW_UNKNOWN_PROTOCOLS||!1,lc=f.ALLOW_SELF_CLOSE_IN_ATTR!==!1,At=f.SAFE_FOR_TEMPLATES||!1,Gt=f.SAFE_FOR_XML!==!1,zt=f.WHOLE_DOCUMENT||!1,Tn=f.RETURN_DOM||!1,no=f.RETURN_DOM_FRAGMENT||!1,ro=f.RETURN_TRUSTED_TYPE||!1,Rs=f.FORCE_BODY||!1,cc=f.SANITIZE_DOM!==!1,dc=f.SANITIZE_NAMED_PROPS||!1,Cs=f.KEEP_CONTENT!==!1,Ns=f.IN_PLACE||!1,oc=gw(f.ALLOWED_URI_REGEXP)?f.ALLOWED_URI_REGEXP:Dh,kn=typeof f.NAMESPACE=="string"?f.NAMESPACE:at,Ls=kl(f,"MATHML_TEXT_INTEGRATION_POINTS",()=>ee({},bc)),Ps=kl(f,"HTML_INTEGRATION_POINTS",()=>ee({},vc));let y=kl(f,"CUSTOM_ELEMENT_HANDLING",()=>nr(null));if(st=nr(null),He(y,"tagNameCheck")&&yc(y.tagNameCheck)&&(st.tagNameCheck=y.tagNameCheck),He(y,"attributeNameCheck")&&yc(y.attributeNameCheck)&&(st.attributeNameCheck=y.attributeNameCheck),He(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(st.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),_e(st),At&&(ks=!1),no&&(Tn=!0),Sn&&(ue=ee({},Mh),he=nr(null),Sn.html===!0&&(ee(ue,Oh),ee(he,Lh)),Sn.svg===!0&&(ee(ue,_l),ee(he,Al),ee(he,rs)),Sn.svgFilters===!0&&(ee(ue,Tl),ee(he,Al),ee(he,rs)),Sn.mathMl===!0&&(ee(ue,Sl),ee(he,Ph),ee(he,rs))),St.tagCheck=null,St.attributeCheck=null,He(f,"ADD_TAGS")&&(typeof f.ADD_TAGS=="function"?St.tagCheck=f.ADD_TAGS:rr(f.ADD_TAGS)&&(ue===Ss&&(ue=Ve(ue)),ee(ue,f.ADD_TAGS,ge))),He(f,"ADD_ATTR")&&(typeof f.ADD_ATTR=="function"?St.attributeCheck=f.ADD_ATTR:rr(f.ADD_ATTR)&&(he===As&&(he=Ve(he)),ee(he,f.ADD_ATTR,ge))),He(f,"ADD_FORBID_CONTENTS")&&rr(f.ADD_FORBID_CONTENTS)&&(An===hc&&(An=Ve(An)),ee(An,f.ADD_FORBID_CONTENTS,ge)),Cs&&(ue["#text"]=!0),zt&&ee(ue,["html","head","body"]),ue.table&&(ee(ue,["tbody"]),delete cr.tbody),f.TRUSTED_TYPES_POLICY){if(typeof f.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof f.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let _=B;B=f.TRUSTED_TYPES_POLICY;try{le=_n("")}catch(O){throw B=_,O}}else f.TRUSTED_TYPES_POLICY===null?(B=void 0,le=""):(B===void 0&&(B=Mp()),B&&typeof le=="string"&&(le=_n("")));ye&&ye(f),In=f},wc=ee({},[..._l,...Tl,...bw]),xc=ee({},[...Sl,...vw]),Yp=function(f,y,_){return y.namespaceURI===at?f==="svg":y.namespaceURI===oo?f==="svg"&&(_==="annotation-xml"||Ls[_]):!!wc[f]},Kp=function(f,y,_){return y.namespaceURI===at?f==="math":y.namespaceURI===io?f==="math"&&Ps[_]:!!xc[f]},Zp=function(f,y,_){return y.namespaceURI===io&&!Ps[_]||y.namespaceURI===oo&&!Ls[_]?!1:!xc[f]&&(jp[f]||!wc[f])},Qp=function(f){let y=T(f);(!y||!y.tagName)&&(y={namespaceURI:kn,tagName:"template"});let _=Fr(f.tagName),O=Fr(y.tagName);return Ms[f.namespaceURI]?f.namespaceURI===io?Yp(_,y,O):f.namespaceURI===oo?Kp(_,y,O):f.namespaceURI===at?Zp(_,y,O):!!(dr==="application/xhtml+xml"&&Ms[f.namespaceURI]):!1},kt=function(f){Hr(e.removed,{element:f});try{T(f).removeChild(f)}catch{if(h(f),!T(f))throw vn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ec=function(f,y,_){try{f.removeAttributeNode(y)}catch{try{f.removeAttribute(_)}catch{}}},so=function(f){ao(f);let y=x(f);if(y){let O=[];yn(y,H=>{Hr(O,H)}),yn(O,H=>{try{h(H)}catch{}})}let _=L(f);if(_)for(let O=_.length-1;O>=0;--O){let H=_[O],V=H&&H.name;typeof V=="string"&&Ec(f,H,V)}},Ft=function(f,y,_){if(!_)try{_=y.getAttributeNode(f)}catch{_=null}Hr(e.removed,{attribute:_||null,from:y});try{_?y.removeAttributeNode(_):y.removeAttribute(f)}catch{try{y.removeAttribute(f)}catch{}}if(f==="is")if(Tn||no)try{kt(y)}catch{}else try{y.setAttribute(f,"")}catch{}},Jp=function(f){let y=L(f);if(y)for(let _=y.length-1;_>=0;--_){let O=y[_],H=O&&O.name;typeof H!="string"||he[ge(H)]||Ec(f,O,H)}},ao=function(f){let y=[f];for(;y.length>0;){let _=y.pop();E(_)===Be.element&&Jp(_);let H=x(_);if(H)for(let V=H.length-1;V>=0;--V)y.push(H[V])}},_c=function(f,y){return Gt?f==="patchsrc"?!0:f==="for"&&y!=="label"&&y!=="output":!1},ef=function(f){if(!Gt)return;let y=[f];for(;y.length>0;){let _=y.pop(),O=E(_);if(O===Be.processingInstruction||O===Be.comment&&Ce(Hh,_.data)){try{h(_)}catch{}continue}if(O===Be.element){let V=_,ie=ge(R(_));try{V.hasAttribute&&V.hasAttribute("patchsrc")&&V.removeAttribute("patchsrc"),V.hasAttribute&&V.hasAttribute("for")&&_c("for",ie)&&V.removeAttribute("for")}catch{}}let H=x(_);if(H)for(let V=H.length-1;V>=0;--V)y.push(H[V])}},Tc=function(f){let y=null,_=null;if(Rs)f="<remove></remove>"+f;else{let V=Ih(f,/^[\r\n\t ]+/);_=V&&V[0]}dr==="application/xhtml+xml"&&kn===at&&(f='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+f+"</body></html>");let O=B?_n(f):f;if(kn===at)try{y=new u().parseFromString(O,dr)}catch{}if(!y||!y.documentElement){y=Ts.createDocument(kn,"template",null);try{y.documentElement.innerHTML=Os?le:O}catch{}}let H=y.body||y.documentElement;return f&&_&&H.insertBefore(n.createTextNode(_),H.childNodes[0]||null),kn===at?Pp.call(y,zt?"html":"body")[0]:zt?y.documentElement:H},Sc=function(f){let y=A?A(f):f.ownerDocument;return nc.call(y||f,f,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},lo=function(f){return f=Gr(f,Up," "),f=Gr(f,Hp," "),f=Gr(f,Gp," "),f},Us=function(f){var y;f.normalize();let _=A?A(f):f.ownerDocument,O=nc.call(_||f,f,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),H=O.nextNode();for(;H;)H.data=lo(H.data),H=O.nextNode();let V=(y=f.querySelectorAll)===null||y===void 0?void 0:y.call(f,"template");V&&yn(V,ie=>{Rn(ie.content)&&Us(ie.content)})},co=function(f){let y=v?v(f):null;return typeof y!="string"||ge(y)!=="form"?!1:typeof f.nodeName!="string"||typeof f.textContent!="string"||typeof f.removeChild!="function"||f.attributes!==L(f)||typeof f.removeAttribute!="function"||typeof f.setAttribute!="function"||typeof f.namespaceURI!="string"||typeof f.insertBefore!="function"||typeof f.hasChildNodes!="function"||f.nodeType!==z(f)||f.childNodes!==x(f)},Rn=function(f){if(!z||typeof f!="object"||f===null)return!1;try{return z(f)===Be.documentFragment}catch{return!1}},ur=function(f){if(!z||typeof f!="object"||f===null)return!1;try{return typeof z(f)=="number"}catch{return!1}};function lt(I,f,y){I.length!==0&&yn(I,_=>{_.call(e,f,y,In)})}let tf=function(f,y){return!!(Gt&&f.hasChildNodes()&&!ur(f.firstElementChild)&&Ce(Uh,f.textContent)&&Ce(Uh,f.innerHTML)||Gt&&f.namespaceURI===at&&Cw[y]&&(ur(f.firstElementChild)||typeof f.textContent=="string"&&Ce(Nw[y],f.textContent))||f.nodeType===Be.processingInstruction||Gt&&f.nodeType===Be.comment&&Ce(Hh,f.data))},uo=function(f,y){if(f instanceof RegExp)return Ce(f,y);if(f instanceof Function){for(var _=arguments.length,O=new Array(_>2?_-2:0),H=2;H<_;H++)O[H-2]=arguments[H];return!!f(y,...O)}return!1},nf=function(f,y,_){if(!cr[y]&&Cc(y)&&uo(st.tagNameCheck,y))return!1;if(Cs&&!An[y]){let O=T(f),H=x(f);if(H&&O){let V=H.length;for(let ie=V-1;ie>=0;--ie){let pe=f===_?p(H[ie],!0):H[ie];O.insertBefore(pe,g(f))}}}return kt(f),!0},Ac=function(f,y,_,O){return f.length===0?y:y===_||y===O?Ve(y):y},kc=function(f,y){return f===y||T(f)!==null?!1:(Ns&&ao(f),!0)},Ic=function(f,y){if(lt(de.beforeSanitizeElements,f,null),kc(f,y))return!0;if(co(f))return kt(f),!0;let _=ge(R(f));if(ue=Ac(de.uponSanitizeElement,ue,Ss,eo),lt(de.uponSanitizeElement,f,{tagName:_,allowedTags:ue}),kc(f,y))return!0;if(tf(f,_))return kt(f),!0;if(cr[_]||!(St.tagCheck instanceof Function&&St.tagCheck(_))&&!ue[_]){let H=nf(f,_,y);return H===!1&&lt(de.afterSanitizeElements,f,null),H}if(E(f)===Be.element&&!Qp(f)||(_==="noscript"||_==="noembed"||_==="noframes")&&Ce(Iw,f.innerHTML))return kt(f),!0;if(At&&f.nodeType===Be.text){let H=lo(f.textContent);f.textContent!==H&&(Hr(e.removed,{element:f.cloneNode()}),f.textContent=H)}return lt(de.afterSanitizeElements,f,null),!1},Rc=function(f,y,_){if(ic[y]||_c(y,f)||cc&&(y==="id"||y==="name")&&(_ in n||_ in Xp))return!1;let O=he[y]||St.attributeCheck instanceof Function&&St.attributeCheck(y,f);return ks&&Ce(zp,y)||sc&&Ce(Fp,y)?!0:O?mc[y]||Ce(oc,Gr(_,rc,""))||(y==="src"||y==="xlink:href"||y==="href")&&f!=="script"&&Rh(_,"data:")===0&&pc[f]||ac&&!Ce($p,Gr(_,rc,""))?!0:!_:Cc(f)&&uo(st.tagNameCheck,f)&&uo(st.attributeNameCheck,y,f)||y==="is"&&st.allowCustomizedBuiltInElements&&uo(st.tagNameCheck,_)},rf=ee({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Cc=function(f){return!rf[Fr(f)]&&Ce(Bp,f)},of=function(f,y,_,O){if(B&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!_)switch(m.getAttributeType(f,y)){case"TrustedHTML":return _n(O);case"TrustedScriptURL":return Op(O)}return O},sf=function(f,y,_,O){try{_?f.setAttributeNS(_,y,O):f.setAttribute(y,O),co(f)?kt(f):kh(e.removed)}catch{Ft(y,f)}},Nc=function(f){lt(de.beforeSanitizeAttributes,f,null);let y=f.attributes;if(!y||co(f))return;he=Ac(de.uponSanitizeAttribute,he,As,to);let _={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:he,forceKeepAttr:void 0},O=y.length,H=ge(f.nodeName);for(;O--;){let V=y[O],ie=V.name,pe=V.namespaceURI,Me=V.value,Le=ge(ie),Gs=Me,Oe=ie==="value"?Gs:dw(Gs);if(_.attrName=Le,_.attrValue=Oe,_.keepAttr=!0,_.forceKeepAttr=void 0,lt(de.uponSanitizeAttribute,f,_),Oe=_.attrValue,dc&&(Le==="id"||Le==="name")&&Rh(Oe,uc)!==0&&(Ft(ie,f,V),Oe=uc+Oe),Gt&&Ce(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Oe)){Ft(ie,f,V);continue}if(Le==="attributename"&&Ih(Oe,"href")){Ft(ie,f,V);continue}if(!_.forceKeepAttr){if(!_.keepAttr){Ft(ie,f,V);continue}if(!lc&&Ce(Rw,Oe)){Ft(ie,f,V);continue}if(At&&(Oe=lo(Oe)),!Rc(H,Le,Oe)){Ft(ie,f,V);continue}Oe=of(H,Le,pe,Oe),Oe!==Gs&&sf(f,ie,pe,Oe)}}lt(de.afterSanitizeAttributes,f,null)},ho=function(f){let y=null,_=Sc(f);for(lt(de.beforeSanitizeShadowDOM,f,null);y=_.nextNode();)if(lt(de.uponSanitizeShadowNode,y,null),Ic(y,f),Nc(y),Rn(y.content)&&ho(y.content),E(y)===Be.element){let O=S(y);Rn(O)&&(Hs(O),ho(O))}lt(de.afterSanitizeShadowDOM,f,null)},Hs=function(f){let y=[{node:f,shadow:null}];for(;y.length>0;){let _=y.pop();if(_.shadow){ho(_.shadow);continue}let O=_.node,V=E(O)===Be.element,ie=x(O);if(ie)for(let pe=ie.length-1;pe>=0;--pe)y.push({node:ie[pe],shadow:null});if(V){let pe=v?v(O):null;if(typeof pe=="string"&&ge(pe)==="template"){let Me=O.content;Rn(Me)&&y.push({node:Me,shadow:null})}}if(V){let pe=S(O);Rn(pe)&&y.push({node:null,shadow:pe},{node:pe,shadow:null})}}};return e.sanitize=function(I){let f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,_=null,O=null,H=null;if(Os=!I,Os&&(I="<!-->"),typeof I!="string"&&!ur(I)&&(I=mw(I),typeof I!="string"))throw vn("dirty is not a string, aborting");if(!e.isSupported)return I;Is?(ue=eo,he=to):Ds(f),(de.uponSanitizeElement.length>0||de.uponSanitizeAttribute.length>0)&&(ue=Ve(ue)),de.uponSanitizeAttribute.length>0&&(he=Ve(he)),e.removed=[];let V=Ns&&typeof I!="string"&&ur(I);if(V){ef(I);let Me=R(I);if(typeof Me=="string"){let Le=ge(Me);if(!ue[Le]||cr[Le])throw so(I),vn("root node is forbidden and cannot be sanitized in-place")}if(co(I))throw so(I),vn("root node is clobbered and cannot be sanitized in-place");try{Hs(I)}catch(Le){throw so(I),Le}}else if(ur(I))y=Tc("<!---->"),_=y.ownerDocument.importNode(I,!0),_.nodeType===Be.element&&_.nodeName==="BODY"||_.nodeName==="HTML"?y=_:y.appendChild(_),Hs(_);else{if(!Tn&&!At&&!zt&&I.indexOf("<")===-1)return B&&ro?_n(I):I;if(y=Tc(I),!y)return Tn?null:ro?le:""}y&&Rs&&kt(y.firstChild);let ie=V?I:y;try{let Me=Sc(ie);for(;O=Me.nextNode();)Ic(O,ie),Nc(O),Rn(O.content)&&ho(O.content)}catch(Me){throw V&&(so(I),yn(e.removed,Le=>{Le.element&&ao(Le.element)})),Me}if(V)return yn(e.removed,Me=>{Me.element&&ao(Me.element)}),At&&Us(I),I;if(Tn){if(At&&Us(y),no)for(H=Lp.call(y.ownerDocument);y.firstChild;)H.appendChild(y.firstChild);else H=y;return(he.shadowroot||he.shadowrootmode)&&(H=Dp.call(r,H,!0)),H}let pe=zt?y.outerHTML:y.innerHTML;return zt&&ue["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&Ce(Aw,y.ownerDocument.doctype.name)&&(pe="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
64
- `+pe),At&&(pe=lo(pe)),B&&ro?_n(pe):pe},e.setConfig=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ds(I),Is=!0,eo=ue,to=he},e.clearConfig=function(){In=null,Is=!1,eo=null,to=null,B=we,le=""},e.isValidAttribute=function(I,f,y){In||Ds({});let _=ge(I),O=ge(f);return Rc(_,O,y)},e.addHook=function(I,f){typeof f=="function"&&He(de,I)&&Hr(de[I],f)},e.removeHook=function(I,f){if(He(de,I)){if(f!==void 0){let y=lw(de[I],f);return y===-1?void 0:cw(de[I],y,1)[0]}return kh(de[I])}},e.removeHooks=function(I){He(de,I)&&(de[I]=[])},e.removeAllHooks=function(){de=Gh()},e}var Vh=Bh();function Ml(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var En=Ml();function Qh(t){En=t}var wn={exec:()=>null};function or(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),o=e[r];return o||(o=t(r),e[r]=o),o}}function Z(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(o,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(Ne.caret,"$1"),n=n.replace(o,s),r},getRegex:()=>new RegExp(n,e)};return r}var Lw=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Ne={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:or(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:or(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:or(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:or(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:or(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:or(t=>new RegExp(`^ {0,${t}}>`))},Pw=/^(?:[ \t]*(?:\n|$))+/,Dw=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Uw=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Vr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Hw=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ll=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Jh=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ep=Z(Jh).replace(/bull/g,Ll).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Gw=Z(Jh).replace(/bull/g,Ll).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Pl=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,zw=/^[^\n]+/,Dl=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Fw=Z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Dl).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),$w=Z(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Ll).getRegex(),ls="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Ul=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Bw=Z("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ul).replace("tag",ls).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),tp=t=>Z(Pl).replace("hr",Vr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",t).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ls).getRegex(),Vw=tp(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),jw=tp(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),qw=Z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",jw).getRegex(),Hl={blockquote:qw,code:Dw,def:Fw,fences:Uw,heading:Hw,hr:Vr,html:Bw,lheading:ep,list:$w,newline:Pw,paragraph:Vw,table:wn,text:zw},jh=Z("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Vr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ls).getRegex(),Ww={...Hl,lheading:Gw,table:jh,paragraph:Z(Pl).replace("hr",Vr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",jh).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ls).getRegex()},Xw={...Hl,html:Z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ul).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:wn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Z(Pl).replace("hr",Vr).replace("heading",` *#{1,6} *[^
65
- ]`).replace("lheading",ep).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Yw=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Kw=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,np=/^( {2,}|\\)\n(?!\s*$)/,Zw=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Tt=/[\p{P}\p{S}]/u,ir=/[\s\p{P}\p{S}]/u,jr=/[^\s\p{P}\p{S}]/u,Qw=Z(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ir).getRegex(),Jw=/[\p{Pi}\p{Ps}"']/u,rp=/(?!~)[\p{P}\p{S}]/u,ex=/(?!~)[\s\p{P}\p{S}]/u,tx=/(?:[^\s\p{P}\p{S}]|~)/u,nx=Z(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Lw?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),op=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,rx=Z(op,"u").replace(/punct/g,Tt).getRegex(),ox=Z(op,"u").replace(/punct/g,rp).getRegex(),ix=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,sx=Z(ix,"u").replace(/openQuote/g,Jw).replace(/punct/g,Tt).getRegex(),ip="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",ax=Z(ip,"gu").replace(/notPunctSpace/g,jr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),lx=Z(ip,"gu").replace(/notPunctSpace/g,tx).replace(/punctSpace/g,ex).replace(/punct/g,rp).getRegex(),cx="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",dx=Z(cx,"gu").replace(/notPunctSpace/g,jr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),ux=Z("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,jr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),hx="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",px=Z(hx,"gu").replace(/notPunctSpace/g,jr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),fx=Z(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Tt).getRegex(),mx="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",gx=Z(mx,"gu").replace(/notPunctSpace/g,jr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),bx=Z(/\\(punct)/,"gu").replace(/punct/g,Tt).getRegex(),vx=Z(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),yx=Z(Ul).replace("(?:-->|$)","-->").getRegex(),wx=Z("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",yx).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),is=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,xx=Z(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",is).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),sp=Z(/^!?\[(label)\]\[(ref)\]/).replace("label",is).replace("ref",Dl).getRegex(),ap=Z(/^!?\[(ref)\](?:\[\])?/).replace("ref",Dl).getRegex(),Ex=Z("reflink|nolink(?!\\()","g").replace("reflink",sp).replace("nolink",ap).getRegex(),qh=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Gl={_backpedal:wn,anyPunctuation:bx,autolink:vx,blockSkip:nx,br:np,code:Kw,del:wn,delLDelim:wn,delRDelim:wn,emStrongLDelim:rx,emStrongRDelimAst:ax,emStrongRDelimUnd:ux,escape:Yw,link:xx,nolink:ap,punctuation:Qw,reflink:sp,reflinkSearch:Ex,tag:wx,text:Zw,url:wn},_x={...Gl,emStrongLDelim:sx,emStrongRDelimAst:dx,emStrongRDelimUnd:px,link:Z(/^!?\[(label)\]\((.*?)\)/).replace("label",is).getRegex(),reflink:Z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",is).getRegex()},Cl={...Gl,emStrongRDelimAst:lx,emStrongLDelim:ox,delLDelim:fx,delRDelim:gx,url:Z(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",qh).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Z(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",qh).getRegex()},Tx={...Cl,br:Z(np).replace("{2,}","*").getRegex(),text:Z(Cl.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},os={normal:Hl,gfm:Ww,pedantic:Xw},$r={normal:Gl,gfm:Cl,breaks:Tx,pedantic:_x},Sx={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Wh=t=>Sx[t];function gt(t,e){if(e){if(Ne.escapeTest.test(t))return t.replace(Ne.escapeReplace,Wh)}else if(Ne.escapeTestNoEncode.test(t))return t.replace(Ne.escapeReplaceNoEncode,Wh);return t}function Xh(t){try{t=encodeURI(t).replace(Ne.percentDecode,"%")}catch{return null}return t}function Yh(t,e){let n=t.replace(Ne.findPipe,(i,s,a)=>{let l=!1,c=s;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Ne.splitPipe),o=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(Ne.slashPipe,"|");return r}function Ht(t,e,n){let r=t.length;if(r===0)return"";let o=0;for(;o<r;){let i=t.charAt(r-o-1);if(i===e&&!n)o++;else if(i!==e&&n)o++;else break}return t.slice(0,r-o)}function Kh(t){let e=t.split(`
66
- `),n=e.length-1;for(;n>=0&&Ne.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
67
- `)}function Ax(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function kx(t,e=0){let n=e,r="";for(let o of t)if(o===" "){let i=4-n%4;r+=" ".repeat(i),n+=i}else r+=o,n++;return r}function Zh(t,e,n,r,o){let i=e.href,s=e.title||null,a=t[1].replace(o.other.outputLinkReplace,"$1"),l=t[0].charAt(0)==="!";r.state.inLink=!0;let c=r.state.linkEmitted,u=r.state.inRawBlock;r.state.linkEmitted=!1;let m=r.inlineTokens(a),w=r.state.linkEmitted;if(r.state.linkEmitted=c,r.state.inLink=!1,!l){if(w){r.state.inRawBlock=u;return}r.state.linkEmitted=!0}return{type:l?"image":"link",raw:n,href:i,title:s,text:a,tokens:m}}function Ix(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let o=r[1];return e.split(`
68
- `).map(i=>{let s=i.match(n.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=o.length?i.slice(o.length):i}).join(`
69
- `)}var ss=class{options;rules;lexer;constructor(t){this.options=t||En}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=this.options.pedantic?e[0]:Kh(e[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=Ix(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=Ht(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:Ht(e[0],`
70
- `),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:Ht(e[0],`
71
- `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=Ht(e[0],`
72
- `).split(`
73
- `),r="",o="",i=[];for(;n.length>0;){let s=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),s=!0;else if(!s)a.push(n[l]);else break;n=n.slice(l);let c=a.join(`
74
- `),u=c.replace(this.rules.other.blockquoteSetextReplace,`
75
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
76
- ${c}`:c,o=o?`${o}
77
- ${u}`:u;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,i,!0),this.lexer.state.top=m,n.length===0)break;let w=i.at(-1);if(w?.type==="code")break;if(w?.type==="blockquote"){let p=w,h=n.join(`
78
- `),g=p.raw+`
79
- `+h.replace(this.rules.other.blockquoteSetextReplace2,""),x=this.blockquote(g);i[i.length-1]=x,r=`${r}
80
- ${h}`,o=o.substring(0,o.length-p.text.length)+x.text;break}else if(w?.type==="list"){let p=w,h=p.raw+`
81
- `+n.join(`
82
- `),g=this.list(h);i[i.length-1]=g,r=r.substring(0,r.length-w.raw.length)+g.raw,o=o.substring(0,o.length-p.raw.length)+g.raw,n=h.substring(i.at(-1).raw.length).split(`
83
- `);continue}}return{type:"blockquote",raw:r,tokens:i,text:o}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,o={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let i=this.rules.other.listItemRegex(n),s=!1;for(;t;){let l=!1,c="",u="";if(!(e=i.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=kx(e[2].split(`
84
- `,1)[0],e[1].length),w=t.split(`
85
- `,1)[0],p=!m.trim(),h=0;if(this.options.pedantic?(h=2,u=m.trimStart()):p?h=e[1].length+1:(h=m.search(this.rules.other.nonSpaceChar),h=h>4?1:h,u=m.slice(h),h+=e[1].length),p&&this.rules.other.blankLine.test(w)&&(c+=w+`
86
- `,t=t.substring(w.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(h),x=this.rules.other.hrRegex(h),T=this.rules.other.fencesBeginRegex(h),S=this.rules.other.headingBeginRegex(h),L=this.rules.other.htmlBeginRegex(h),z=this.rules.other.blockquoteBeginRegex(h);for(;t;){let v=t.split(`
87
- `,1)[0],A;if(w=v,this.options.pedantic?(w=w.replace(this.rules.other.listReplaceNesting," "),A=w):A=w.replace(this.rules.other.tabCharGlobal," "),T.test(w)||S.test(w)||L.test(w)||z.test(w)||g.test(w)||x.test(w))break;if(A.search(this.rules.other.nonSpaceChar)>=h||!w.trim())u+=`
88
- `+A.slice(h);else{if(p||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||T.test(m)||S.test(m)||x.test(m))break;u+=`
89
- `+w}p=!w.trim(),c+=v+`
90
- `,t=t.substring(v.length+1),m=A.slice(h)}}o.loose||(s?o.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),o.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=c}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let l of o.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!o.loose){let c=l.tokens.filter(m=>m.type==="space"),u=c.length>0&&c.some(m=>this.rules.other.anyLine.test(m.raw));o.loose=u}for(let l of o.items){let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let m={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=m.checked,o.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=m.raw+l.tokens[0].raw,l.tokens[0].text=m.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(m)):l.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):l.tokens.unshift(m)}}else l.task&&(l.task=!1)}if(o.loose)for(let l of o.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=Kh(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:Ht(e[0],`
91
- `),href:r,title:o}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=Yh(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
92
- `):[],i={type:"table",raw:Ht(e[0],`
93
- `),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?i.align.push("right"):this.rules.other.tableAlignCenter.test(s)?i.align.push("center"):this.rules.other.tableAlignLeft.test(s)?i.align.push("left"):i.align.push(null);for(let s=0;s<n.length;s++)i.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:i.align[s]});for(let s of o)i.rows.push(Yh(s,i.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:i.align[l]})));return i}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:Ht(e[0],`
94
- `),depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
95
- `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Ht(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=Ax(e[2],"()");if(i===-2)return;if(i>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],o="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],o=i[3])}else o=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Zh(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[r.toLowerCase()];if(!o){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Zh(n,o,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=0,c=r[0][0],u=n===c,m=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,e=e.slice(-1*t.length+o);(r=m.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(s=[...i].length,r[3]||r[4]){a+=s;continue}else if(r[5]||r[6]){if(o%3&&!((o+s)%3)){l+=s;continue}if(u)break}if(a-=s,a>0)continue;s=Math.min(s,s+a+l);let w=[...r[0]][0].length,p=t.slice(0,o+r.index+w+s);if(Math.min(o,s)%2){let g=p.slice(1,-1);return{type:"em",raw:p,text:g,tokens:this.lexer.inlineTokens(g)}}let h=p.slice(2,-2);return{type:"strong",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),o=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&o&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+o);(r=l.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(s=[...i].length,s!==o))continue;if(r[3]||r[4]){a+=s;continue}if(a-=s,a>0)continue;s=Math.min(s,s+a);let c=[...r[0]][0].length,u=t.slice(0,o+r.index+c+s),m=u.slice(o,-o);return{type:"del",raw:u,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let o;do o=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(o!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},ot=class Nl{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||En,this.options.tokenizer=this.options.tokenizer||new ss,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let n={other:Ne,block:os.normal,inline:$r.normal};this.options.pedantic?(n.block=os.pedantic,n.inline=$r.pedantic):this.options.gfm&&(n.block=os.gfm,this.options.breaks?n.inline=$r.breaks:n.inline=$r.gfm),this.tokenizer.rules=n}static get rules(){return{block:os,inline:$r}}static lex(e,n){return new Nl(n).lex(e)}static lexInline(e,n){return new Nl(n).inlineTokens(e)}lex(e){e=e.replace(Ne.carriageReturn,`
96
- `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Ne.tabCharGlobal," ").replace(Ne.spaceLine,""));let o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(a=>(i=a.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let a=n.at(-1);i.raw.length===1&&a!==void 0?a.raw+=`
97
- `:n.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
98
- `)?"":`
99
- `)+i.raw,a.text+=`
100
- `+i.text,this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
101
- `)?"":`
102
- `)+i.raw,a.text+=`
103
- `+i.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},n.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),n.push(i);continue}let s=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),c;this.options.extensions.startBlock.forEach(u=>{c=u.call({lexer:this},l),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(s=e.substring(0,a+1))}if(this.state.top&&(i=this.tokenizer.paragraph(s))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
104
- `)?"":`
105
- `)+i.raw,a.text+=`
106
- `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i),r=s.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
107
- `)?"":`
108
- `)+i.raw,a.text+=`
109
- `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}linkInText(e){if(!e.includes("["))return!1;let n=this.tokenizer.rules.inline.link;for(let r of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(n.test(r[0])&&e.charAt(r.index-1)!=="!")return!0;for(let r of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let o=r[0],i=o.lastIndexOf("[");if(!(o.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,o.slice(i+1,-1)))&&!(i>1&&this.linkInText(o.slice(1,i-1))))return!0}return!1}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e;if(this.tokens.links&&e.includes("[")){let a=this.tokenizer.rules.inline.reflinkSearch,l=c=>{let u=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(u+1,-1)))return c;if(u>1&&c.charAt(0)!=="!"){let m=c.slice(1,u-1);if(this.linkInText(m))return"["+m.replace(a,l)+"]["+"a".repeat(c.length-u-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};r=r.replace(a,l)}r=r.replace(this.tokenizer.rules.inline.anyPunctuation,a=>"+".repeat(a.length)),r=r.replace(this.tokenizer.rules.inline.blockSkip,(a,l,c)=>{let u=c?c.length:0;return a.slice(0,u)+"["+"a".repeat(a.length-u-2)+"]"}),r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,i="",s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}o||(i=""),o=!1;let a;if(this.options.extensions?.inline?.some(c=>(a=c.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let c=n.at(-1);a.type==="text"&&c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,r,i)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,r,i)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let l=e;if(this.options.extensions?.startInline){let c=1/0,u=e.slice(1),m;this.options.extensions.startInline.forEach(w=>{m=w.call({lexer:this},u),typeof m=="number"&&m>=0&&(c=Math.min(c,m))}),c<1/0&&c>=0&&(l=e.substring(0,c+1))}if(a=this.tokenizer.inlineText(l)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(i=a.raw.slice(-1)),o=!0;let c=n.at(-1);c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):n.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}infiniteLoopError(e){let n="Infinite loop on byte: "+e;if(this.options.silent)console.error(n);else throw new Error(n)}},as=class{options;parser;constructor(t){this.options=t||En}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(Ne.notSpaceStart)?.[0],o=t.replace(Ne.endingNewline,"")+`
110
- `;return r?'<pre><code class="language-'+gt(r)+'">'+(n?o:gt(o,!0))+`</code></pre>
111
- `:"<pre><code>"+(n?o:gt(o,!0))+`</code></pre>
112
- `}blockquote({tokens:t}){return`<blockquote>
113
- ${this.parser.parse(t)}</blockquote>
114
- `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
115
- `}hr(t){return`<hr>
116
- `}list(t){let e=t.ordered,n=t.start,r="";for(let s=0;s<t.items.length;s++){let a=t.items[s];r+=this.listitem(a)}let o=e?"ol":"ul",i=e&&n!==1?' start="'+n+'"':"";return"<"+o+i+`>
117
- `+r+"</"+o+`>
118
- `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
119
- `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
120
- `}table(t){let e="",n="";for(let o=0;o<t.header.length;o++)n+=this.tablecell(t.header[o]);e+=this.tablerow({text:n});let r="";for(let o=0;o<t.rows.length;o++){let i=t.rows[o];n="";for(let s=0;s<i.length;s++)n+=this.tablecell(i[s]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
121
- <thead>
122
- `+e+`</thead>
123
- `+r+`</table>
124
- `}tablerow({text:t}){return`<tr>
125
- ${t}</tr>
126
- `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
127
- `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${gt(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),o=Xh(t);if(o===null)return r;t=o;let i='<a href="'+t+'"';return e&&(i+=' title="'+gt(e)+'"'),i+=">"+r+"</a>",i}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=Xh(t);if(o===null)return gt(n);t=o;let i=`<img src="${t}" alt="${gt(n)}"`;return e&&(i+=` title="${gt(e)}"`),i+=">",i}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:gt(t.text)}},zl=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},it=class Ol{options;renderer;textRenderer;constructor(e){this.options=e||En,this.options.renderer=this.options.renderer||new as,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new zl}static parse(e,n){return new Ol(n).parse(e)}static parseInline(e,n){return new Ol(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let s=o,a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(s.type)){n+=a||"";continue}}let i=o;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let s='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<e.length;o++){let i=e[o];if(this.options.extensions?.renderers?.[i.type]){let a=this.options.extensions.renderers[i.type].call({parser:this},i);if(a!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(i.type)){r+=a||"";continue}}let s=i;switch(s.type){case"escape":{r+=n.text(s);break}case"html":{r+=n.html(s);break}case"link":{r+=n.link(s);break}case"image":{r+=n.image(s);break}case"checkbox":{r+=n.checkbox(s);break}case"strong":{r+=n.strong(s);break}case"em":{r+=n.em(s);break}case"codespan":{r+=n.codespan(s);break}case"br":{r+=n.br(s);break}case"del":{r+=n.del(s);break}case"text":{r+=n.text(s);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},Br=class{options;block;constructor(t){this.options=t||En}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?ot.lex:ot.lexInline}provideParser(t=this.block){return t?it.parse:it.parseInline}},Fl=class{defaults=Ml();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=it;Renderer=as;TextRenderer=zl;Lexer=ot;Tokenizer=ss;Hooks=Br;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let o=r;for(let i of o.header)n=n.concat(this.walkTokens(i.tokens,e));for(let i of o.rows)for(let s of i)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let o=r;n=n.concat(this.walkTokens(o.items,e));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(i=>{let s=o[i].flat(1/0);n=n.concat(this.walkTokens(s,e))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let i=e.renderers[o.name];i?e.renderers[o.name]=function(...s){let a=o.renderer.apply(this,s);return a===!1&&(a=i.apply(this,s)),a}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[o.level];i?i.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),r.extensions=e),n.renderer){let o=this.defaults.renderer||new as(this.defaults);for(let i in n.renderer){if(!(i in o))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let s=i,a=n.renderer[s],l=o[s];o[s]=(...c)=>{let u=a.apply(o,c);return u===!1&&(u=l.apply(o,c)),u||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new ss(this.defaults);for(let i in n.tokenizer){if(!(i in o))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let s=i,a=n.tokenizer[s],l=o[s];o[s]=(...c)=>{let u=a.apply(o,c);return u===!1&&(u=l.apply(o,c)),u}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new Br;for(let i in n.hooks){if(!(i in o))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let s=i,a=n.hooks[s],l=o[s];Br.passThroughHooks.has(i)?o[s]=c=>{if(this.defaults.async&&Br.passThroughHooksRespectAsync.has(i))return(async()=>{let m=await a.call(o,c);return l.call(o,m)})();let u=a.call(o,c);return l.call(o,u)}:o[s]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,c);return m===!1&&(m=await l.apply(o,c)),m})();let u=a.apply(o,c);return u===!1&&(u=l.apply(o,c)),u}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,i=n.walkTokens;r.walkTokens=function(s){let a=[];return a.push(i.call(this,s)),o&&(a=a.concat(o.call(this,s))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return ot.lex(t,e??this.defaults)}parser(t,e){return it.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=t),o.async)return(async()=>{let s=o.hooks?await o.hooks.preprocess(e):e,a=await(o.hooks?await o.hooks.provideLexer(t):t?ot.lex:ot.lexInline)(s,o),l=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(l,o.walkTokens));let c=await(o.hooks?await o.hooks.provideParser(t):t?it.parse:it.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(i);try{o.hooks&&(e=o.hooks.preprocess(e));let s=(o.hooks?o.hooks.provideLexer(t):t?ot.lex:ot.lexInline)(e,o);o.hooks&&(s=o.hooks.processAllTokens(s)),o.walkTokens&&this.walkTokens(s,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(t):t?it.parse:it.parseInline)(s,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(s){return i(s)}}}onError(t,e){return n=>{if(n.message+=`
128
- Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+gt(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},xn=new Fl;function oe(t,e){return xn.parse(t,e)}oe.options=oe.setOptions=function(t){return xn.setOptions(t),oe.defaults=xn.defaults,Qh(oe.defaults),oe};oe.getDefaults=Ml;oe.defaults=En;function Rx(...t){return xn.use(...t),oe.defaults=xn.defaults,Qh(oe.defaults),oe}oe.use=Rx;oe.walkTokens=function(t,e){return xn.walkTokens(t,e)};oe.parseInline=xn.parseInline;oe.Parser=it;oe.parser=it.parse;oe.Renderer=as;oe.TextRenderer=zl;oe.Lexer=ot;oe.lexer=ot.lex;oe.Tokenizer=ss;oe.Hooks=Br;oe.parse=oe;var xI=oe.options,EI=oe.setOptions,_I=oe.walkTokens,TI=oe.parseInline;var SI=it.parse,AI=ot.lex;var Cx=new Fl({gfm:!0,breaks:!0}),lp=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],cp=["href","title","class","target","rel"],dp={ALLOWED_TAGS:lp,ALLOWED_ATTR:cp,ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1},Nx={...dp,ALLOWED_TAGS:[...lp,"img"],ALLOWED_ATTR:[...cp,"src","alt","width","height"]},Ox=/^language-[A-Za-z0-9_+#.-]+$/,Mx=new Set(["CODE","PRE"]);function Lx(t){t.nodeName==="A"&&t.hasAttribute("href")?(t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer")):(t.removeAttribute("target"),t.removeAttribute("rel"));let e=t.getAttribute("class");if(e===null)return;let n=Mx.has(t.nodeName)?e.split(/\s+/).filter(r=>Ox.test(r)):[];if(n.length===0){t.removeAttribute("class");return}t.setAttribute("class",n.join(" "))}var cs=null;function Px(){return cs===null&&(cs=Vh(),cs.addHook("afterSanitizeAttributes",Lx)),cs}function ds(t,e){let n=e?.allowImages===!0,r=Cx.parse(t,{async:!1});return Px().sanitize(r,n?Nx:dp).trim()}function hp(t,e){let n=document.createElement("div");n.className=`resize-handle resize-handle--${us(t)}`,n.setAttribute("part",`resize-handle resize-handle-${us(t)}`),n.setAttribute("role","separator"),t.x===void 0?n.setAttribute("aria-orientation","horizontal"):t.y===void 0&&n.setAttribute("aria-orientation","vertical"),n.setAttribute("aria-label",e.label),n.tabIndex=0,n.addEventListener("pointerdown",i=>{let s=e.axis();if(s==="none"||!up(t,s))return;let a=e.rect(),l=u=>{e.apply($l(t,s,a,u.clientX,u.clientY))},c=u=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",c),n.removeAttribute("data-dragging"),e.commit($l(t,s,a,u.clientX,u.clientY))};n.setAttribute("data-dragging","true"),window.addEventListener("pointermove",l),window.addEventListener("pointerup",c),i.preventDefault()});let r=null,o=()=>{if(r===null)return;let i=r;r=null,e.commit(i)};return n.addEventListener("keydown",i=>{let s=e.axis();if(s==="none"||!up(t,s))return;let a=i.shiftKey?64:16,l=e.rect(),c=Dx[i.key];if(c===void 0||c.x!==0&&t.x===void 0||c.y!==0&&t.y===void 0)return;i.preventDefault();let u=(t.x==="left"?l.left:l.right)+c.x*a,m=(t.y==="top"?l.top:l.bottom)+c.y*a,w=$l(t,s,l,u,m);e.apply(w),r=w}),n.addEventListener("keyup",o),n.addEventListener("blur",o),n}var Dx={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function us(t){return[t.y,t.x].filter(e=>e!==void 0).join("-")}function up(t,e){return e==="both"||t.x!==void 0}function $l(t,e,n,r,o){let i=t.x==="left"?Math.min(r,n.right-280):n.left,s=t.x==="right"?Math.max(r,n.left+280):n.right,a=e==="both",l=a&&t.y==="top"?Math.min(o,n.bottom-240):n.top,c=a&&t.y==="bottom"?Math.max(o,n.top+240):n.bottom;return{left:i,top:l,right:s,bottom:c}}function pp(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):pp(n,e)}function fp(t){let e=[];pp(t,e);let n=0;for(let{node:r,parent:o}of e){let i=document.createDocumentFragment();for(let s of r.data.split(/(\s+)/)){if(s==="")continue;if(/\s/.test(s)){i.appendChild(document.createTextNode(s));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=s,i.appendChild(a),n+=1}o.replaceChild(i,r)}}function Bl(t,e,n,r){let o=document.createElement("div");o.className=`run-notice run-notice--${n}`,o.setAttribute("part",`run-notice run-notice-${n}`),o.setAttribute("role","status");let i=document.createElement("span");i.className="run-notice-icon",i.setAttribute("part","run-notice-icon"),i.textContent=t,i.setAttribute("aria-hidden","true");let s=document.createElement("span");if(s.className="run-notice-text",s.setAttribute("part","run-notice-text"),s.textContent=e,o.append(i,s),r!==void 0){let a=document.createElement("button");a.type="button",a.className="run-notice-undo",a.setAttribute("part","run-notice-undo"),a.textContent=r.label,a.addEventListener("click",()=>{a.disabled=!0,r.onActivate()}),o.append(a)}return o}var hs=class{chips;palette;#t;#n=[];#e=!1;#s=!1;#r=[];#i=0;constructor(e){this.#t=e,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.setAttribute("part","skill-chips"),this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("part","skill-palette"),this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(e){this.#n=e,this.#l()}enableChips(e){this.#e=e,this.#l()}enableSlash(e){this.#s=e}isOpen(){return!this.palette.hidden}onInput(e){this.#s&&e.startsWith("/")?this.#o(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#u(1),!0):e.key==="ArrowUp"?(this.#u(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#r.slice(this.#i,this.#i+1).forEach(n=>{this.#h(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#o(e){let n=e.trim().toLowerCase(),r=this.#n.filter(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#r=r,this.#i=0,this.#c(),this.palette.hidden=!1}#u(e){let n=this.#r.length;this.#i=(this.#i+e+n)%n,this.#c()}#h(e){this.close(),this.#t(e)}#l(){this.chips.replaceChildren();let e=this.#e?this.#n.filter(n=>n.chip===!0):[];this.chips.hidden=e.length===0;for(let n of e){let r=document.createElement("button");r.type="button",r.className="skill-chip",r.setAttribute("part","skill-chip"),r.textContent=n.title,r.title=`/${n.name}`,r.addEventListener("click",()=>this.#h(n)),this.chips.appendChild(r)}}#c(){this.palette.replaceChildren(),this.#r.forEach((e,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("part","skill-item"),r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#i?"true":"false");let o=document.createElement("span");o.className="skill-item-title",o.setAttribute("part","skill-item-title");let i=document.createElement("code");if(i.className="skill-item-token",i.setAttribute("part","skill-item-token"),i.textContent=`/${e.name}`,o.append(i,document.createTextNode(` ${e.title}`)),r.appendChild(o),e.description!==void 0){let s=document.createElement("span");s.className="skill-item-desc",s.setAttribute("part","skill-item-desc"),s.textContent=e.description,r.appendChild(s)}r.addEventListener("click",()=>this.#h(e)),this.palette.appendChild(r)})}};function mp({viewport:t,onMissedContent:e}){let n=!0,r=!1,o=()=>t.scrollHeight-t.scrollTop-t.clientHeight<=4,i=u=>{u!==r&&(r=u,e(r))},s=()=>{t.scrollTop=t.scrollHeight},a=()=>{n=o(),n&&i(!1)},l=()=>{if(n){s();return}i(!0)};t.addEventListener("scroll",a,{passive:!0});let c=new ResizeObserver(()=>{n&&s()});return c.observe(t),{follow:l,jump:()=>{n=!0,i(!1),s()},following:()=>n,dispose:()=>{t.removeEventListener("scroll",a),c.disconnect()}}}var gp=`
61
+ `;function pl(t){let{within:e,exclude:n,onQuote:r}=t,o=new CSSStyleSheet;o.replaceSync(zy),document.adoptedStyleSheets=[...document.adoptedStyleSheets,o];let i=document.createElement("button");i.type="button",i.className="ag-ui-quote-offer",i.textContent=t.label,i.hidden=!0,document.body.append(i);let s="",a=()=>{i.hidden=!0,s=""},l=u=>{if(u.composedPath().includes(n)){a();return}if(Fy()){a();return}let m=u instanceof MouseEvent?{x:u.clientX,y:u.clientY}:void 0,w=Mr(e,[],m);if(w===null){a();return}s=w.text,$y(i,w.rect)},c=u=>{i.contains(u.target)||a()};return e.addEventListener("mouseup",l),e.addEventListener("keyup",l),e.addEventListener("mousedown",c),document.addEventListener("scroll",a,!0),window.addEventListener("resize",a),i.addEventListener("mousedown",u=>{u.preventDefault()}),i.addEventListener("click",()=>{let u=s;window.getSelection()?.removeAllRanges(),a(),r(u)}),{element:i,detach(){e.removeEventListener("mouseup",l),e.removeEventListener("keyup",l),e.removeEventListener("mousedown",c),document.removeEventListener("scroll",a,!0),window.removeEventListener("resize",a),i.remove(),document.adoptedStyleSheets=document.adoptedStyleSheets.filter(u=>u!==o)}}}function Fy(){let t=document.activeElement;return t===null?!1:t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable===!0}function $y(t,e){t.hidden=!1;let n=e.top<hl+t.offsetHeight;t.dataset.below=String(n),t.style.top=`${n?e.bottom+hl:e.top-hl}px`;let r=t.offsetWidth/2,o=e.left+e.width/2,i=document.documentElement.clientWidth;t.style.left=`${Math.min(Math.max(o,r),i-r)}px`}function Lr(t,e=Date.now(),n=ae){if(!Number.isFinite(t))return n.justNow;let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let o=Math.round(r/60);if(o<60)return n.minutesAgo.replace("{n}",String(o));let i=Math.round(o/60);if(i<24)return n.hoursAgo.replace("{n}",String(i));let s=Math.round(i/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}function vh(t){return t.preview!==void 0&&t.preview!==null&&t.preview!==""?t.preview:null}function yh(t){return t.replace(/\s+/g," ").trim()}var Pr=class{element;#t;#n;#e;#s=null;#r=null;#i;#o=[];constructor(e,n=ae){this.#t=e,this.#i=n,this.element=document.createElement("div"),this.element.className="checkpoints",this.element.setAttribute("part","checkpoints"),this.element.setAttribute("role","dialog"),this.element.setAttribute("aria-label",n.checkpoints),this.element.tabIndex=-1,this.element.hidden=!0;let r=document.createElement("div");r.className="checkpoints-header",r.setAttribute("part","checkpoints-header"),this.#e=document.createElement("span"),this.#e.className="checkpoints-title",this.#e.setAttribute("part","checkpoints-title"),this.#e.textContent=n.checkpoints,r.append(this.#e),this.#n=document.createElement("div"),this.#n.className="checkpoints-list",this.#n.setAttribute("part","checkpoints-list"),this.element.append(r,this.#n),this.element.addEventListener("keydown",o=>this.#c(o))}setRuns(e){this.#o=e,this.#d()}setRelativeTimeFormatter(e){this.#r=e}#u(e){return this.#r!==null?this.#r(e):Lr(e,Date.now(),this.#i)}setStrings(e){this.#i=e,this.element.setAttribute("aria-label",e.checkpoints),this.#e.textContent=e.checkpoints,this.#d()}open(){this.open_||(this.#s=this.#h(),this.element.hidden=!1,(this.#l()[0]??this.element).focus())}close(){this.open_&&(this.element.hidden=!0,this.#s?.focus(),this.#s=null)}#h(){return this.element.getRootNode().activeElement}#l(){return Array.from(this.element.querySelectorAll("button, [tabindex]")).filter(e=>!e.hidden)}#c(e){if(e.key==="Escape"){e.stopPropagation(),this.close();return}if(e.key!=="Tab")return;let n=this.#l(),r=n[0],o=n[n.length-1],i=this.#h();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}get open_(){return!this.element.hidden}#d(){if(this.#n.replaceChildren(),this.#o.length===0){let n=document.createElement("div");n.className="checkpoints-empty",n.setAttribute("part","checkpoints-empty"),n.textContent=this.#i.noCheckpoints,this.#n.append(n);return}let e=this.#p();for(let n of this.#o)this.#n.append(this.#y(n,e))}#p(){let e=new Set,n=new Set;for(let r of this.#o){let o=vh(r);if(o===null)continue;let i=yh(o);e.has(i)&&n.add(i),e.add(i)}return n}#y(e,n){let r=document.createElement("div");r.className="checkpoint-row",r.setAttribute("part","checkpoint-row");let o=vh(e),i=e.started_at===null?null:this.#u(Date.parse(e.started_at)),s=document.createElement("span");if(s.className="checkpoint-label",s.setAttribute("part","checkpoint-label"),s.textContent=o??i??e.run_id,r.append(s),o!==null&&i!==null){let l=document.createElement("span");l.className="checkpoint-time",l.setAttribute("part","checkpoint-time"),l.textContent=i,r.append(l)}if((o===null?i!==null:n.has(yh(o)))&&e.run_id!==""){let l=document.createElement("span");l.className="checkpoint-id",l.setAttribute("part","checkpoint-id"),l.textContent=e.run_id.slice(0,8),l.title=e.run_id,r.append(l)}if(e.parent_run_id!==null){let l=document.createElement("span");l.className="checkpoint-branch",l.setAttribute("part","checkpoint-branch"),l.textContent=this.#i.forkedRun,l.title=e.parent_run_id,r.append(l)}return r.append(this.#m(e.run_id,"resume",this.#i.resumeRun),this.#m(e.run_id,"fork",this.#i.forkRun)),r}#m(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`checkpoint-action checkpoint-${n}`,o.setAttribute("part",`checkpoint-action checkpoint-${n}`),o.textContent=r,o.addEventListener("click",()=>{this.close(),this.#t(e,n)}),o}};var By=8,rs=class{element;#t;#n;#e;#s;#r;#i=null;#o;#u=[];#h="";#l;#c;#d="";#p=!0;#y=null;constructor(e,n=ae){this.#t=e,this.#o=n,this.element=document.createElement("div"),this.element.className="drawer",this.element.setAttribute("part","drawer"),this.element.hidden=!0;let r=document.createElement("div");r.className="drawer-backdrop",r.setAttribute("part","drawer-backdrop"),r.addEventListener("click",()=>this.close()),this.#n=document.createElement("div"),this.#n.className="drawer-panel",this.#n.setAttribute("part","drawer-panel"),this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true"),this.#n.setAttribute("aria-label",n.chatHistory),this.#n.addEventListener("keydown",i=>this.#T(i));let o=document.createElement("div");o.className="drawer-header",o.setAttribute("part","drawer-header"),this.#e=document.createElement("span"),this.#e.className="drawer-title",this.#e.setAttribute("part","drawer-title"),this.#e.textContent=n.chats,this.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#t.onNew()}),this.#l=document.createElement("button"),this.#l.type="button",this.#l.className="drawer-close",this.#l.setAttribute("part","drawer-close"),this.#l.title=n.closeHistory,this.#l.setAttribute("aria-label",n.closeHistory),this.#l.append(document.createTextNode("\xD7")),this.#l.addEventListener("click",()=>this.close()),o.append(this.#e,this.#s,this.#l),this.#c=document.createElement("input"),this.#c.type="search",this.#c.className="drawer-filter",this.#c.setAttribute("part","drawer-filter"),this.#c.placeholder=n.searchConversations,this.#c.setAttribute("aria-label",n.searchConversations),this.#c.addEventListener("input",()=>{this.#d=this.#c.value.trim().toLowerCase(),this.#x()}),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#n.append(o,this.#c,this.#r),this.element.append(r,this.#n)}setRelativeTimeFormatter(e){this.#i=e}#m(e){return this.#i!==null?this.#i(e):Lr(e,void 0,this.#o)}setStrings(e){this.#o=e,this.#n.setAttribute("aria-label",e.chatHistory),this.#e.textContent=e.chats,this.#s.textContent=e.newChat,this.#l.title=e.closeHistory,this.#l.setAttribute("aria-label",e.closeHistory),this.#c.placeholder=e.searchConversations,this.#c.setAttribute("aria-label",e.searchConversations),this.#x()}setModal(e){this.#p=e,e?(this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true")):(this.#n.setAttribute("role","region"),this.#n.removeAttribute("aria-modal"))}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#y=this.#N(),this.element.hidden=!1,this.#p&&this.#s.focus(),this.#t.onVisibility?.(!0))}close(){this.isOpen()&&(this.element.hidden=!0,this.#p&&this.#y?.focus(),this.#y=null,this.#t.onVisibility?.(!1))}toggle(){this.isOpen()?this.close():this.open()}#N(){return this.element.getRootNode().activeElement}#T(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab"||!this.#p)return;let n=Array.from(this.#n.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],o=n[n.length-1],i=this.#N();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#u=e,this.#h=n,this.#x()}#x(){this.#r.replaceChildren();let e=this.#u.length<By;this.#c.hidden=e,e&&this.#d!==""&&(this.#c.value="",this.#d="");let n=this.#G();if(n.length===0){let r=document.createElement("div");r.className="drawer-empty",r.setAttribute("part","drawer-empty"),r.textContent=this.#u.length===0?this.#o.noConversations:this.#o.noMatches,this.#r.appendChild(r);return}for(let r of n)this.#r.appendChild(this.#le(r))}#G(){return this.#d===""?this.#u:this.#u.filter(e=>e.title.toLowerCase().includes(this.#d)||e.preview.toLowerCase().includes(this.#d))}#le(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#h&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let o=document.createElement("span");o.className="drawer-row-title",o.setAttribute("part","drawer-row-title"),o.textContent=e.title;let i=document.createElement("span");i.className="drawer-row-time",i.setAttribute("part","drawer-row-time"),i.textContent=this.#m(e.updatedAt);let s=document.createElement("span");s.className="drawer-row-preview",s.setAttribute("part","drawer-row-preview"),s.textContent=e.preview,r.append(o,i,s),r.addEventListener("click",()=>{this.close(),this.#t.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.setAttribute("part","drawer-row-rename"),a.title=this.#o.rename,a.setAttribute("aria-label",this.#o.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#z(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#o.delete,l.setAttribute("aria-label",this.#o.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#b(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#z(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.setAttribute("part","drawer-rename-input"),r.value=n.title;let o=!1,i=()=>{if(o)return;o=!0;let a=r.value.trim();a===""||a===n.title?this.#x():this.#t.onRename(n.threadId,a)},s=()=>{o||(o=!0,this.#x())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>i()),e.replaceChildren(r),r.focus(),r.select()}#b(e,n){let r=document.createElement("div");r.className="drawer-confirm",r.setAttribute("part","drawer-confirm");let o=document.createElement("span");o.className="drawer-confirm-label",o.setAttribute("part","drawer-confirm-label"),o.textContent=this.#o.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.setAttribute("part","drawer-confirm-yes"),i.textContent=this.#o.delete,i.addEventListener("click",()=>this.#t.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.setAttribute("part","drawer-confirm-no"),s.textContent=this.#o.cancel,s.addEventListener("click",()=>this.#x()),r.append(o,i,s),e.replaceChildren(r)}};function wh(t,e){let n=document.createElement("button");return n.type="button",n.className=`approval-btn approval-btn--${t}`,n.setAttribute("part",`approval-button approval-${t}`),n.textContent=e,n}function fl(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="approval",i.setAttribute("part","approval"),e.toolName!==void 0&&i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.approveAction);let s=document.createElement("div");s.className="approval-body",s.setAttribute("part","approval-body"),s.textContent=e.message??r.approvalPrompt;let a=Vy(e,n,r),l=document.createElement("div");l.className="approval-actions",l.setAttribute("part","approval-actions");let c=wh("deny",r.deny),u=wh("approve",r.approve),m=!1,w=p=>{m||(m=!0,c.disabled=!0,u.disabled=!0,i.setAttribute("data-resolved",p?"approved":"denied"),o(p))};if(c.addEventListener("click",()=>w(!1)),u.addEventListener("click",()=>{a!==null&&!a.commit()||w(!0)}),n.signal?.addEventListener("abort",()=>w(!1),{once:!0}),l.append(c,u),i.append(s,...a===null?[]:[a.root],l),t.appendChild(i),n.signal?.aborted===!0){w(!1);return}u.focus()})}function Vy(t,e,n){let{onEdit:r}=e;if(r===void 0||t.args===void 0)return null;let o=JSON.stringify(t.args,null,2),i=document.createElement("div");i.className="approval-edit",i.setAttribute("part","approval-edit");let s=document.createElement("textarea");s.className="approval-args",s.setAttribute("part","approval-args"),s.setAttribute("aria-label",n.approvalEditArgs),s.rows=Math.min(10,o.split(`
62
+ `).length),s.value=o;let a=document.createElement("div");return a.className="approval-error",a.setAttribute("part","approval-error"),a.setAttribute("role","alert"),a.hidden=!0,i.append(s,a),{root:i,commit:()=>{if(s.value===o)return!0;let l;try{l=JSON.parse(s.value)}catch{return a.textContent=n.approvalArgsInvalid,a.hidden=!1,s.focus(),!1}return typeof l!="object"||l===null||Array.isArray(l)?(a.textContent=n.approvalArgsNotAnObject,a.hidden=!1,s.focus(),!1):(a.hidden=!0,r(l),!0)}}}function ml(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.setAttribute("part",`confirm-button confirm-${t}`),n.textContent=e,n}function gl(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="confirm",i.setAttribute("part","confirm"),i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.confirmAction);let s=document.createElement("div");s.className="confirm-body",s.setAttribute("part","confirm-body"),s.textContent=e.message??r.confirmRun.replace("{tool}",e.toolName);let a=document.createElement("pre");a.className="confirm-args",a.setAttribute("part","confirm-args"),a.textContent=JSON.stringify(e.args,null,2),a.hidden=Object.keys(e.args).length===0;let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=ml("cancel",r.cancel),u=n.onAlwaysAllow===void 0?null:ml("always",r.confirmAlways.replace("{tool}",e.toolName)),m=ml("confirm",r.confirm),w=!1,p=h=>{w||(w=!0,i.remove(),o(h))};if(c.addEventListener("click",()=>p(!1)),m.addEventListener("click",()=>p(!0)),u?.addEventListener("click",()=>{n.onAlwaysAllow?.(),p(!0)}),n.signal?.addEventListener("abort",()=>p(!1),{once:!0}),l.append(c,...u===null?[]:[u],m),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){p(!1);return}m.focus()})}function jy(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function bl(t,e,n={}){let r=n.strings??ae,o=e.options??[],i=o.length>0,s=!i||e.allowCustom===!0;return new Promise(a=>{let l=document.createElement("div");l.className="question",l.setAttribute("part","question"),l.setAttribute("role","group"),l.setAttribute("aria-label",r.askUserAction);let c=document.createElement("div");c.className="question-body",c.setAttribute("part","question-body"),c.textContent=e.question;let u=document.createElement("div");u.className="question-options",u.setAttribute("part","question-options");let m=`q-${o.length}-${e.question.length}`,w=[];for(let v of o){let A=document.createElement("label");A.className="question-choice",A.setAttribute("part","question-choice");let E=document.createElement("input");E.type="radio",E.name=m,E.value=v,E.setAttribute("part","question-radio");let R=document.createElement("span");R.setAttribute("part","question-choice-text"),R.textContent=v,A.append(E,R),u.appendChild(A),w.push(E)}let p=null,h=null;if(s){if(h=jy(r.answerPlaceholder),i){let v=document.createElement("label");v.className="question-choice",v.setAttribute("part","question-choice"),p=document.createElement("input"),p.type="radio",p.name=m,p.value="",p.setAttribute("part","question-radio");let A=document.createElement("span");A.setAttribute("part","question-choice-text"),A.textContent=r.otherOption,v.append(p,A),u.appendChild(v),h.disabled=!0}u.appendChild(h)}let g=document.createElement("div");g.className="question-actions",g.setAttribute("part","question-actions");let x=document.createElement("button");x.type="button",x.className="question-btn",x.setAttribute("part","question-button"),x.textContent=r.submit,g.appendChild(x);let T=!1,S=()=>{let v=w.find(A=>A.checked);if(v!==void 0)return v.value;if(h!==null&&(p===null||p.checked)){let A=h.value.trim();return A===""?null:A}return null},L=()=>{h!==null&&p!==null&&(h.disabled=!p.checked),x.disabled=S()===null},z=v=>{if(!T){T=!0,x.disabled=!0;for(let A of w)A.disabled=!0;p!==null&&(p.disabled=!0),h!==null&&(h.disabled=!0),l.setAttribute("data-resolved",v===""?"cancelled":"answered"),a(v)}};for(let v of[...w,...p!==null?[p]:[]])v.addEventListener("change",L);if(h?.addEventListener("input",L),h?.addEventListener("keydown",v=>{if(v.key==="Enter"){v.preventDefault();let A=S();A!==null&&z(A)}}),x.addEventListener("click",()=>{let v=S();v!==null&&z(v)}),n.signal?.addEventListener("abort",()=>z(""),{once:!0}),l.append(c,u,g),t.appendChild(l),n.signal?.aborted===!0){z("");return}L(),(i?w[0]:h)?.focus()})}function Dt(t,e,n=Je){let r=Math.min(n,Math.max(0,(e.width-t.width)/2)),o=Math.min(n,Math.max(0,(e.height-t.height)/2));return{left:Math.max(e.left+r,Math.min(t.left,e.left+e.width-t.width-r)),top:Math.max(e.top+o,Math.min(t.top,e.top+e.height-t.height-o))}}function Dr(t,e,n=Bt){let r=t.right-t.left,o=t.bottom-t.top,i=Math.max(e.left+n,Math.min(t.left,e.left+e.width-n-r)),s=Math.max(e.top+n,Math.min(t.top,e.top+e.height-n-o));return{left:i,top:s,right:i+r,bottom:s+o}}var qy=4,Wy=16,Xy=64;function xh(t,e){let n=!1;t.addEventListener("click",i=>{!n||i.detail===0||(n=!1,i.stopPropagation(),i.preventDefault())},!0),t.addEventListener("pointerdown",i=>{if(n=!1,!e.enabled())return;let s=e.rect(),a=i.clientX,l=i.clientY,c=!1,u=w=>{let p=w.clientX-a,h=w.clientY-l;if(!c&&Math.hypot(p,h)<qy)return;c=!0,t.setAttribute("data-dragging","true");let g=Dt({...s,left:s.left+p,top:s.top+h},e.viewport());e.apply(g.left,g.top)},m=w=>{if(window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),!c)return;t.removeAttribute("data-dragging"),n=!0;let p=Dt({...s,left:s.left+(w.clientX-a),top:s.top+(w.clientY-l)},e.viewport());e.commit(p.left,p.top)};window.addEventListener("pointermove",u),window.addEventListener("pointerup",m),window.addEventListener("pointercancel",m)});let r=null,o=()=>{if(r===null)return;let{left:i,top:s}=r;r=null,e.commit(i,s)};t.addEventListener("keydown",i=>{if(!e.enabled())return;let s=i.shiftKey?Xy:Wy,a=e.rect(),l=null;if(i.key==="ArrowLeft"?l={left:a.left-s,top:a.top}:i.key==="ArrowRight"?l={left:a.left+s,top:a.top}:i.key==="ArrowUp"?l={left:a.left,top:a.top-s}:i.key==="ArrowDown"&&(l={left:a.left,top:a.top+s}),l===null)return;i.preventDefault();let c=Dt({...a,...l},e.viewport());e.apply(c.left,c.top),r=c}),t.addEventListener("keyup",o),t.addEventListener("blur",o)}function Ur(t,e,n,r){return{hostInset:Eh({top:n.y==="top"?t.top:null,right:n.x==="right"?r.width-t.right:null,bottom:n.y==="bottom"?r.height-t.bottom:null,left:n.x==="left"?t.left:null}),launcherInset:Eh({top:n.y==="top"?e.top-t.top:null,right:n.x==="right"?t.right-(e.left+e.width):null,bottom:n.y==="bottom"?t.bottom-(e.top+e.height):null,left:n.x==="left"?e.left-t.left:null})}}function Eh(t){let e=n=>n===null?"auto":`${Math.round(n)}px`;return`${e(t.top)} ${e(t.right)} ${e(t.bottom)} ${e(t.left)}`}function vl(t,e,n,r,o=Je){let i=n.left+n.width-t.left,s=t.left+t.width-n.left,a=n.top+n.height-t.top,l=t.top+t.height-n.top,c={x:i>=s?"left":"right",y:a>=l?"top":"bottom"},u=c.x==="left"?t.left:t.left+t.width-e.width,m=c.y==="top"?t.top:t.top+t.height-e.height,w=Dr({left:u,top:m,right:u+e.width,bottom:m+e.height},n,o);return{corner:c,...Ur(w,t,c,r)}}var Yy="button, a[href], input, select, textarea, [contenteditable]";function _h(t,e){t.addEventListener("pointerdown",n=>{if(n.button!==0||!e.enabled()||Ky(n,t))return;let r=e.rect(),o=n.clientX,i=n.clientY,s=!1,a=(u,m)=>{let w=u-o,p=m-i;return{left:r.left+w,top:r.top+p,right:r.right+w,bottom:r.bottom+p}},l=u=>{!s&&Math.hypot(u.clientX-o,u.clientY-i)<4||(s=!0,t.setAttribute("data-dragging","true"),e.apply(a(u.clientX,u.clientY),r))},c=u=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),s&&(t.removeAttribute("data-dragging"),e.commit(a(u.clientX,u.clientY),r))};n.preventDefault(),window.addEventListener("pointermove",l),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c)})}function Ky(t,e){let n=t.composedPath();return n.slice(0,n.indexOf(e)).some(r=>r instanceof Element&&r.matches(Yy))}function Sh(t,e){let n=document.createElement("div");n.className=`resize-handle resize-handle--${os(t)}`,n.setAttribute("part",`resize-handle resize-handle-${os(t)}`),n.setAttribute("role","separator"),t.x===void 0?n.setAttribute("aria-orientation","horizontal"):t.y===void 0&&n.setAttribute("aria-orientation","vertical"),n.setAttribute("aria-label",e.label),n.tabIndex=0,n.addEventListener("pointerdown",i=>{let s=e.axis();if(s==="none"||!Th(t,s))return;let a=e.rect(),l=u=>{e.apply(yl(t,s,a,u.clientX,u.clientY))},c=u=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",c),n.removeAttribute("data-dragging"),e.commit(yl(t,s,a,u.clientX,u.clientY))};n.setAttribute("data-dragging","true"),window.addEventListener("pointermove",l),window.addEventListener("pointerup",c),i.preventDefault()});let r=null,o=()=>{if(r===null)return;let i=r;r=null,e.commit(i)};return n.addEventListener("keydown",i=>{let s=e.axis();if(s==="none"||!Th(t,s))return;let a=i.shiftKey?64:16,l=e.rect(),c=Zy[i.key];if(c===void 0||c.x!==0&&t.x===void 0||c.y!==0&&t.y===void 0)return;i.preventDefault();let u=(t.x==="left"?l.left:l.right)+c.x*a,m=(t.y==="top"?l.top:l.bottom)+c.y*a,w=yl(t,s,l,u,m);e.apply(w),r=w}),n.addEventListener("keyup",o),n.addEventListener("blur",o),n}var Zy={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function os(t){return[t.y,t.x].filter(e=>e!==void 0).join("-")}function Th(t,e){return e==="both"||t.x!==void 0}function yl(t,e,n,r,o){let i=t.x==="left"?Math.min(r,n.right-280):n.left,s=t.x==="right"?Math.max(r,n.left+280):n.right,a=e==="both",l=a&&t.y==="top"?Math.min(o,n.bottom-240):n.top,c=a&&t.y==="bottom"?Math.max(o,n.top+240):n.bottom;return{left:i,top:l,right:s,bottom:c}}function wl(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function xl(t,e,n,r){let o=document.createElement("div");o.className=`run-notice run-notice--${n}`,o.setAttribute("part",`run-notice run-notice-${n}`),o.setAttribute("role","status");let i=document.createElement("span");i.className="run-notice-icon",i.setAttribute("part","run-notice-icon"),i.textContent=t,i.setAttribute("aria-hidden","true");let s=document.createElement("span");if(s.className="run-notice-text",s.setAttribute("part","run-notice-text"),s.textContent=e,o.append(i,s),r!==void 0){let a=document.createElement("button");a.type="button",a.className="run-notice-undo",a.setAttribute("part","run-notice-undo"),a.textContent=r.label,a.addEventListener("click",()=>{a.disabled=!0,r.onActivate()}),o.append(a)}return o}var is=class{element;get agent(){return this.#r}#t;#n;#e;#s=new Map;#r=null;constructor(e=ae){this.element=document.createElement("div"),this.element.className="subagent",this.element.setAttribute("part","subagent"),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="subagent-row",this.#t.setAttribute("part","subagent-row"),this.#t.setAttribute("aria-expanded","false"),this.#t.disabled=!0;let n=document.createElement("span");n.className="subagent-icon",n.setAttribute("part","subagent-icon"),n.setAttribute("aria-hidden","true"),this.#n=document.createElement("span"),this.#n.className="subagent-status",this.#n.setAttribute("part","subagent-status"),this.#n.textContent=e.subAgentWorking,this.#t.append(n,this.#n),this.#e=document.createElement("div"),this.#e.className="subagent-steps",this.#e.setAttribute("part","subagent-steps"),this.#e.setAttribute("role","list"),this.#e.setAttribute("aria-label",e.subAgentSteps),this.#e.hidden=!0,this.#t.addEventListener("click",()=>{this.#u(this.#t.getAttribute("aria-expanded")!=="true")}),this.element.append(this.#t,this.#e)}report(e){this.element.setAttribute("data-phase",e.phase),e.agent!==null&&(this.#r=e.agent,this.element.setAttribute("data-agent",e.agent)),e.status!==null&&(this.#n.textContent=e.status),e.tool!==null&&this.#i(e.tool)}#i(e){let n=this.#s.get(e.toolCallId)??this.#o(e);if(e.ok===null){n.removeAttribute("data-ok");return}n.setAttribute("data-ok",String(e.ok))}#o(e){let n=document.createElement("div");n.className="subagent-step",n.setAttribute("part","subagent-step"),n.setAttribute("role","listitem"),n.setAttribute("data-tool-call-id",e.toolCallId);let r=document.createElement("span");r.className="subagent-step-icon",r.setAttribute("part","subagent-step-icon"),r.setAttribute("aria-hidden","true");let o=document.createElement("span");return o.className="subagent-step-name",o.setAttribute("part","subagent-step-name"),o.textContent=e.name,n.append(r,o),this.#e.appendChild(n),this.#s.set(e.toolCallId,n),this.#t.disabled=!1,n}#u(e){this.#e.hidden=!e,this.#t.setAttribute("aria-expanded",String(e))}};var Qy=Object.values(Cn);function Ah(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Hr(t){return typeof t=="string"&&t!==""?t:null}function Jy(t){let e=Ah(t);if(e===null)return null;let n=Hr(e.toolCallId),r=Hr(e.name),o=e.ok;return n===null||r===null||o!==null&&typeof o!="boolean"?null:{toolCallId:n,name:r,ok:o}}function kh(t){let e=Ah(t);if(e===null)return null;let n=Hr(e.delegationId),r=e.phase;return n===null||typeof r!="string"||!Qy.includes(r)?null:{delegationId:n,phase:r,agent:Hr(e.agent),status:Hr(e.status),tool:Jy(e.tool)}}var ss=class{element;#t;#n;#e;#s;#r=!1;constructor(e=ae){this.#s=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="thoughts-toggle",this.#e.setAttribute("part","thoughts-toggle"),this.#e.setAttribute("aria-expanded","true"),this.#t=document.createElement("span"),this.#t.className="thoughts-label",this.#t.setAttribute("part","thoughts-label"),this.#t.textContent=e.thinking,this.#e.append(this.#t),this.#n=document.createElement("pre"),this.#n.className="thoughts-body",this.#n.setAttribute("part","thoughts-body"),this.#e.addEventListener("click",()=>{this.#i(!this.#r)}),this.element.append(this.#e,this.#n)}stream(e){this.#n.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#t.textContent=this.#s.thoughts,this.#i(!0))}#i(e){this.#r=e,this.#n.hidden=e,this.#e.setAttribute("aria-expanded",String(!e))}};function El(t){return{[re.PENDING]:t.toolRunning,[re.DEFERRED]:t.toolDeferred,[re.DONE]:t.toolDone,[re.ERROR]:t.toolError,[re.DECLINED]:t.toolDeclined}}function ew(t){return{[re.DONE]:t.resultLabel,[re.ERROR]:t.errorLabel,[re.DECLINED]:t.declinedLabel}}function tw(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var Gr=class{element;approvalSlot;subagentSlot;#t;#n;#e;#s;#r;#i;#o;args;#u;#h;#l=!1;constructor(e,n,r,o=ae,i={}){this.#o=o,this.args=n,this.#u=e,this.#h=i.formatPayload??null,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",re.PENDING),this.element.setAttribute("data-expanded","false");let s=document.createElement("div");s.className="tool-call-head",s.setAttribute("part","tool-card-head");let a=document.createElement("span");a.className="tool-call-icon",a.setAttribute("part","tool-card-icon"),a.setAttribute("aria-hidden","true");let l=document.createElement("span");l.className="tool-call-name",l.setAttribute("part","tool-card-name"),l.textContent=r??e,this.#t=document.createElement("span"),this.#t.className="tool-call-status",this.#t.setAttribute("part","tool-card-status"),this.#t.textContent=El(o)[re.PENDING],this.#n=document.createElement("span"),this.#n.className="tool-call-decision",this.#n.setAttribute("part","tool-card-decision"),this.#n.hidden=!0,s.append(a,l,this.#t,this.#n);let c=this.#d("args",o.argumentsLabel);this.#c(c.body,{kind:"arguments",toolName:e,args:n},JSON.stringify(n,null,2)),c.root.hidden=Object.keys(n).length===0;let u=this.#d("result",o.resultLabel);this.#s=u.root,this.#r=u.label,this.#i=u.body,u.root.hidden=!0,this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="tool-call-toggle",this.#e.setAttribute("part","tool-card-toggle"),this.#e.setAttribute("aria-expanded","false"),this.#e.textContent=o.details,this.#e.addEventListener("click",()=>this.#y(!this.#p()));let m=document.createElement("div");m.className="tool-call-body",m.setAttribute("part","tool-card-body"),m.append(c.root,u.root),this.approvalSlot=document.createElement("div"),this.approvalSlot.className="tool-call-approval",this.approvalSlot.setAttribute("part","tool-card-approval"),this.subagentSlot=document.createElement("div"),this.subagentSlot.className="tool-call-subagent",this.subagentSlot.setAttribute("part","tool-card-subagent"),this.element.append(s,this.subagentSlot,this.#e,m,this.approvalSlot)}mark(e){this.#l||(this.element.setAttribute("data-status",e),this.#t.textContent=El(this.#o)[e])}recordDecision(e){this.element.setAttribute("data-decision",e),this.#n.textContent=e==="approved"?this.#o.decisionApproved:this.#o.decisionDeclined,this.#n.hidden=!1}get settled(){return this.#l}settle(e,n){this.#l||(this.#l=!0,this.element.setAttribute("data-status",e),this.#t.textContent=El(this.#o)[e],this.#r.textContent=ew(this.#o)[e],this.#c(this.#i,{kind:"result",toolName:this.#u,status:e,text:n},tw(n)),this.#s.hidden=!1)}#c(e,n,r){let o=this.#h===null?null:this.#h(n);if(o===null){e.textContent=r;return}if(e.setAttribute("data-formatted","true"),typeof o=="string"){e.textContent=o;return}e.replaceChildren(o)}#d(e,n){let r=document.createElement("div");r.className=`tool-call-section tool-call-section--${e}`,r.setAttribute("part",`tool-card-section tool-card-${e}-section`);let o=document.createElement("span");o.className="tool-call-section-label",o.setAttribute("part",`tool-card-section-label tool-card-${e}-label`),o.textContent=n;let i=document.createElement("pre");return i.className=`tool-call-${e}`,i.setAttribute("part",`tool-card-${e}`),r.append(o,i),{root:r,label:o,body:i}}#p(){return this.element.getAttribute("data-expanded")==="true"}#y(e){this.element.setAttribute("data-expanded",String(e)),this.#e.setAttribute("aria-expanded",String(e))}};var Ih=`
129
63
  /* \u2500\u2500 Token defaults \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
130
64
  Every public --ag-ui-* token is read here into a private --_* alias, and
131
65
  only the alias is used by the rules below.
@@ -3663,9 +3597,75 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
3663
3597
  border-right: none;
3664
3598
  box-shadow: none;
3665
3599
  }
3666
- `;var ps=class{element;get agent(){return this.#r}#t;#n;#e;#s=new Map;#r=null;constructor(e=ae){this.element=document.createElement("div"),this.element.className="subagent",this.element.setAttribute("part","subagent"),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="subagent-row",this.#t.setAttribute("part","subagent-row"),this.#t.setAttribute("aria-expanded","false"),this.#t.disabled=!0;let n=document.createElement("span");n.className="subagent-icon",n.setAttribute("part","subagent-icon"),n.setAttribute("aria-hidden","true"),this.#n=document.createElement("span"),this.#n.className="subagent-status",this.#n.setAttribute("part","subagent-status"),this.#n.textContent=e.subAgentWorking,this.#t.append(n,this.#n),this.#e=document.createElement("div"),this.#e.className="subagent-steps",this.#e.setAttribute("part","subagent-steps"),this.#e.setAttribute("role","list"),this.#e.setAttribute("aria-label",e.subAgentSteps),this.#e.hidden=!0,this.#t.addEventListener("click",()=>{this.#u(this.#t.getAttribute("aria-expanded")!=="true")}),this.element.append(this.#t,this.#e)}report(e){this.element.setAttribute("data-phase",e.phase),e.agent!==null&&(this.#r=e.agent,this.element.setAttribute("data-agent",e.agent)),e.status!==null&&(this.#n.textContent=e.status),e.tool!==null&&this.#i(e.tool)}#i(e){let n=this.#s.get(e.toolCallId)??this.#o(e);if(e.ok===null){n.removeAttribute("data-ok");return}n.setAttribute("data-ok",String(e.ok))}#o(e){let n=document.createElement("div");n.className="subagent-step",n.setAttribute("part","subagent-step"),n.setAttribute("role","listitem"),n.setAttribute("data-tool-call-id",e.toolCallId);let r=document.createElement("span");r.className="subagent-step-icon",r.setAttribute("part","subagent-step-icon"),r.setAttribute("aria-hidden","true");let o=document.createElement("span");return o.className="subagent-step-name",o.setAttribute("part","subagent-step-name"),o.textContent=e.name,n.append(r,o),this.#e.appendChild(n),this.#s.set(e.toolCallId,n),this.#t.disabled=!1,n}#u(e){this.#e.hidden=!e,this.#t.setAttribute("aria-expanded",String(e))}};var Ux=Object.values(Cn);function bp(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function qr(t){return typeof t=="string"&&t!==""?t:null}function Hx(t){let e=bp(t);if(e===null)return null;let n=qr(e.toolCallId),r=qr(e.name),o=e.ok;return n===null||r===null||o!==null&&typeof o!="boolean"?null:{toolCallId:n,name:r,ok:o}}function vp(t){let e=bp(t);if(e===null)return null;let n=qr(e.delegationId),r=e.phase;return n===null||typeof r!="string"||!Ux.includes(r)?null:{delegationId:n,phase:r,agent:qr(e.agent),status:qr(e.status),tool:Hx(e.tool)}}var Gx=4,zx=120;function yp(t){if(typeof t!="object"||t===null)return null;let e=t.prompts;if(!Array.isArray(e))return null;let n=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r!==""&&r.length<=120).slice(0,4);return n.length===0?null:n}function fs(t,e,n){let r=yp(t);if(r===null)return null;let o=document.createElement("div");o.className="suggestions",o.setAttribute("part","suggestions"),o.setAttribute("role","group"),o.setAttribute("aria-label",e.suggestions);for(let i of r){let s=document.createElement("button");s.type="button",s.className="suggestion-chip",s.setAttribute("part","suggestion-chip"),s.textContent=i,s.addEventListener("click",()=>n(i)),o.appendChild(s)}return o}var ms=class{element;#t;#n;#e;#s;#r=!1;constructor(e=ae){this.#s=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="thoughts-toggle",this.#e.setAttribute("part","thoughts-toggle"),this.#e.setAttribute("aria-expanded","true"),this.#t=document.createElement("span"),this.#t.className="thoughts-label",this.#t.setAttribute("part","thoughts-label"),this.#t.textContent=e.thinking,this.#e.append(this.#t),this.#n=document.createElement("pre"),this.#n.className="thoughts-body",this.#n.setAttribute("part","thoughts-body"),this.#e.addEventListener("click",()=>{this.#i(!this.#r)}),this.element.append(this.#e,this.#n)}stream(e){this.#n.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#t.textContent=this.#s.thoughts,this.#i(!0))}#i(e){this.#r=e,this.#n.hidden=e,this.#e.setAttribute("aria-expanded",String(!e))}};var Fx=8,gs=class{element;#t;#n;#e;#s;#r;#i=null;#o;#u=[];#h="";#l;#c;#d="";#p=!0;#y=null;constructor(e,n=ae){this.#t=e,this.#o=n,this.element=document.createElement("div"),this.element.className="drawer",this.element.setAttribute("part","drawer"),this.element.hidden=!0;let r=document.createElement("div");r.className="drawer-backdrop",r.setAttribute("part","drawer-backdrop"),r.addEventListener("click",()=>this.close()),this.#n=document.createElement("div"),this.#n.className="drawer-panel",this.#n.setAttribute("part","drawer-panel"),this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true"),this.#n.setAttribute("aria-label",n.chatHistory),this.#n.addEventListener("keydown",i=>this.#T(i));let o=document.createElement("div");o.className="drawer-header",o.setAttribute("part","drawer-header"),this.#e=document.createElement("span"),this.#e.className="drawer-title",this.#e.setAttribute("part","drawer-title"),this.#e.textContent=n.chats,this.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#t.onNew()}),this.#l=document.createElement("button"),this.#l.type="button",this.#l.className="drawer-close",this.#l.setAttribute("part","drawer-close"),this.#l.title=n.closeHistory,this.#l.setAttribute("aria-label",n.closeHistory),this.#l.append(document.createTextNode("\xD7")),this.#l.addEventListener("click",()=>this.close()),o.append(this.#e,this.#s,this.#l),this.#c=document.createElement("input"),this.#c.type="search",this.#c.className="drawer-filter",this.#c.setAttribute("part","drawer-filter"),this.#c.placeholder=n.searchConversations,this.#c.setAttribute("aria-label",n.searchConversations),this.#c.addEventListener("input",()=>{this.#d=this.#c.value.trim().toLowerCase(),this.#x()}),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#n.append(o,this.#c,this.#r),this.element.append(r,this.#n)}setRelativeTimeFormatter(e){this.#i=e}#m(e){return this.#i!==null?this.#i(e):Mr(e,void 0,this.#o)}setStrings(e){this.#o=e,this.#n.setAttribute("aria-label",e.chatHistory),this.#e.textContent=e.chats,this.#s.textContent=e.newChat,this.#l.title=e.closeHistory,this.#l.setAttribute("aria-label",e.closeHistory),this.#c.placeholder=e.searchConversations,this.#c.setAttribute("aria-label",e.searchConversations),this.#x()}setModal(e){this.#p=e,e?(this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true")):(this.#n.setAttribute("role","region"),this.#n.removeAttribute("aria-modal"))}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#y=this.#N(),this.element.hidden=!1,this.#p&&this.#s.focus(),this.#t.onVisibility?.(!0))}close(){this.isOpen()&&(this.element.hidden=!0,this.#p&&this.#y?.focus(),this.#y=null,this.#t.onVisibility?.(!1))}toggle(){this.isOpen()?this.close():this.open()}#N(){return this.element.getRootNode().activeElement}#T(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab"||!this.#p)return;let n=Array.from(this.#n.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],o=n[n.length-1],i=this.#N();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#u=e,this.#h=n,this.#x()}#x(){this.#r.replaceChildren();let e=this.#u.length<Fx;this.#c.hidden=e,e&&this.#d!==""&&(this.#c.value="",this.#d="");let n=this.#G();if(n.length===0){let r=document.createElement("div");r.className="drawer-empty",r.setAttribute("part","drawer-empty"),r.textContent=this.#u.length===0?this.#o.noConversations:this.#o.noMatches,this.#r.appendChild(r);return}for(let r of n)this.#r.appendChild(this.#ae(r))}#G(){return this.#d===""?this.#u:this.#u.filter(e=>e.title.toLowerCase().includes(this.#d)||e.preview.toLowerCase().includes(this.#d))}#ae(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#h&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let o=document.createElement("span");o.className="drawer-row-title",o.setAttribute("part","drawer-row-title"),o.textContent=e.title;let i=document.createElement("span");i.className="drawer-row-time",i.setAttribute("part","drawer-row-time"),i.textContent=this.#m(e.updatedAt);let s=document.createElement("span");s.className="drawer-row-preview",s.setAttribute("part","drawer-row-preview"),s.textContent=e.preview,r.append(o,i,s),r.addEventListener("click",()=>{this.close(),this.#t.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.setAttribute("part","drawer-row-rename"),a.title=this.#o.rename,a.setAttribute("aria-label",this.#o.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#z(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#o.delete,l.setAttribute("aria-label",this.#o.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#b(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#z(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.setAttribute("part","drawer-rename-input"),r.value=n.title;let o=!1,i=()=>{if(o)return;o=!0;let a=r.value.trim();a===""||a===n.title?this.#x():this.#t.onRename(n.threadId,a)},s=()=>{o||(o=!0,this.#x())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>i()),e.replaceChildren(r),r.focus(),r.select()}#b(e,n){let r=document.createElement("div");r.className="drawer-confirm",r.setAttribute("part","drawer-confirm");let o=document.createElement("span");o.className="drawer-confirm-label",o.setAttribute("part","drawer-confirm-label"),o.textContent=this.#o.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.setAttribute("part","drawer-confirm-yes"),i.textContent=this.#o.delete,i.addEventListener("click",()=>this.#t.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.setAttribute("part","drawer-confirm-no"),s.textContent=this.#o.cancel,s.addEventListener("click",()=>this.#x()),r.append(o,i,s),e.replaceChildren(r)}};function Vl(t){return{[re.PENDING]:t.toolRunning,[re.DEFERRED]:t.toolDeferred,[re.DONE]:t.toolDone,[re.ERROR]:t.toolError,[re.DECLINED]:t.toolDeclined}}function $x(t){return{[re.DONE]:t.resultLabel,[re.ERROR]:t.errorLabel,[re.DECLINED]:t.declinedLabel}}function Bx(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var Wr=class{element;approvalSlot;subagentSlot;#t;#n;#e;#s;#r;#i;#o;args;#u;#h;#l=!1;constructor(e,n,r,o=ae,i={}){this.#o=o,this.args=n,this.#u=e,this.#h=i.formatPayload??null,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",re.PENDING),this.element.setAttribute("data-expanded","false");let s=document.createElement("div");s.className="tool-call-head",s.setAttribute("part","tool-card-head");let a=document.createElement("span");a.className="tool-call-icon",a.setAttribute("part","tool-card-icon"),a.setAttribute("aria-hidden","true");let l=document.createElement("span");l.className="tool-call-name",l.setAttribute("part","tool-card-name"),l.textContent=r??e,this.#t=document.createElement("span"),this.#t.className="tool-call-status",this.#t.setAttribute("part","tool-card-status"),this.#t.textContent=Vl(o)[re.PENDING],this.#n=document.createElement("span"),this.#n.className="tool-call-decision",this.#n.setAttribute("part","tool-card-decision"),this.#n.hidden=!0,s.append(a,l,this.#t,this.#n);let c=this.#d("args",o.argumentsLabel);this.#c(c.body,{kind:"arguments",toolName:e,args:n},JSON.stringify(n,null,2)),c.root.hidden=Object.keys(n).length===0;let u=this.#d("result",o.resultLabel);this.#s=u.root,this.#r=u.label,this.#i=u.body,u.root.hidden=!0,this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="tool-call-toggle",this.#e.setAttribute("part","tool-card-toggle"),this.#e.setAttribute("aria-expanded","false"),this.#e.textContent=o.details,this.#e.addEventListener("click",()=>this.#y(!this.#p()));let m=document.createElement("div");m.className="tool-call-body",m.setAttribute("part","tool-card-body"),m.append(c.root,u.root),this.approvalSlot=document.createElement("div"),this.approvalSlot.className="tool-call-approval",this.approvalSlot.setAttribute("part","tool-card-approval"),this.subagentSlot=document.createElement("div"),this.subagentSlot.className="tool-call-subagent",this.subagentSlot.setAttribute("part","tool-card-subagent"),this.element.append(s,this.subagentSlot,this.#e,m,this.approvalSlot)}mark(e){this.#l||(this.element.setAttribute("data-status",e),this.#t.textContent=Vl(this.#o)[e])}recordDecision(e){this.element.setAttribute("data-decision",e),this.#n.textContent=e==="approved"?this.#o.decisionApproved:this.#o.decisionDeclined,this.#n.hidden=!1}get settled(){return this.#l}settle(e,n){this.#l||(this.#l=!0,this.element.setAttribute("data-status",e),this.#t.textContent=Vl(this.#o)[e],this.#r.textContent=$x(this.#o)[e],this.#c(this.#i,{kind:"result",toolName:this.#u,status:e,text:n},Bx(n)),this.#s.hidden=!1)}#c(e,n,r){let o=this.#h===null?null:this.#h(n);if(o===null){e.textContent=r;return}if(e.setAttribute("data-formatted","true"),typeof o=="string"){e.textContent=o;return}e.replaceChildren(o)}#d(e,n){let r=document.createElement("div");r.className=`tool-call-section tool-call-section--${e}`,r.setAttribute("part",`tool-card-section tool-card-${e}-section`);let o=document.createElement("span");o.className="tool-call-section-label",o.setAttribute("part",`tool-card-section-label tool-card-${e}-label`),o.textContent=n;let i=document.createElement("pre");return i.className=`tool-call-${e}`,i.setAttribute("part",`tool-card-${e}`),r.append(o,i),{root:r,label:o,body:i}}#p(){return this.element.getAttribute("data-expanded")==="true"}#y(e){this.element.setAttribute("data-expanded",String(e)),this.#e.setAttribute("aria-expanded",String(e))}};var wp=12e4,bs=class{element;#t;#n;#e;#s="idle";#r=null;#i=null;#o=[];#u=null;#h=!1;#l=!1;constructor(e){this.#t=e.transcribe,this.#n=e.onText,this.#e=e.strings??ae,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button");let n=document.createElement("slot");n.name="icon-voice",n.innerHTML=Dc,this.element.append(n),this.#T("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#d();return}this.#s!=="transcribing"&&await this.#c()}async#c(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#N(this.#e.transcriptionFailed);return}this.#i=e,this.#o=[],this.#h=!1;let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#o.push(r.data)}),n.addEventListener("stop",()=>{this.#y(n.mimeType)}),this.#r=n,n.start(),this.#u=setTimeout(()=>{this.#h=!0,this.#d()},wp),this.#T("recording")}#d(){this.#p(),this.#r?.stop()}#p(){this.#u!==null&&(clearTimeout(this.#u),this.#u=null)}dispose(){this.#l=!0,this.#p(),this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#m()}async#y(e){if(this.#l)return;this.#m(),this.#T("transcribing");let n=new Blob(this.#o,{type:e||"audio/webm"});try{let r=await this.#t(n);this.#T("idle"),this.#h&&(this.element.title=this.#e.recordingLimit.replace("{n}",String(wp/6e4))),r!==""&&this.#n(r)}catch(r){this.#N(r instanceof Error?r.message:this.#e.transcriptionFailed)}finally{this.#r=null}}#m(){for(let e of this.#i?.getTracks()??[])e.stop();this.#i=null}#N(e){this.#m(),this.#r=null,this.#T("idle"),this.element.title=e}#T(e){this.#s=e,this.element.dataset.state=e;let n=this.#x(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#x(e){return e==="recording"?this.#e.stopRecording:e==="transcribing"?this.#e.transcribing:this.#e.recordVoice}};var vs=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},sr=class{#t;#n;#e;#s;#r;#i;#o;#u=new Set;#h=new Map;#l;#c;#d=!1;constructor(e){this.#t=e.agent,this.#n=e.handlers,this.#e=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#i=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#l=e.connectionLostMessage??"Connection lost";let n=e.maxToolRounds??Nn;this.#c=n>=1?Math.floor(n):Nn;let r=e.onStateChanged;r!==void 0&&this.#t.subscribe({onStateChanged:({state:o})=>{r(o)}})}get state(){return this.#t.state}setState(e){this.#t.setState({...e})}get running(){return this.#t.isRunning}get messages(){return this.#t.messages}async send(e,n=[]){let r={id:Ie(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#t.addMessage(r),this.#m(),await this.#p()}truncateToLastUser(){let e=[...this.#t.messages],n=-1;for(let[o,i]of e.entries())i.role==="user"&&(n=o);if(n===-1)return null;let r=e.slice(0,n+1);return this.#t.setMessages(r),this.#m(),r}async resume(){await this.#p()}addToolResult(e,n){this.#t.addMessage({id:Ie(),role:"tool",content:n,toolCallId:e}),this.#m()}cancel(){this.#d=!0,this.#t.abortRun()}async#p(){this.#d=!1;try{await this.#N(),this.#d&&this.#y()}catch(e){this.#d||Vx(e)?this.#y():this.#n.onError(e instanceof Error?e.message:String(e))}finally{this.#n.onSettled()}}#y(){this.#m(),this.#n.onCancelled()}#m(){let e=this.#t.messages;if(this.#h.size===0){this.#o(e);return}this.#o(e.map(n=>{if(n.role!=="tool")return n;let r=this.#h.get(n.toolCallId);return r===void 0?n:{...n,outcome:r}}))}async#N(){let e;for(let n=0;n<this.#c;n+=1){if(this.#d)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#e(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#t.runAgent(i,this.#T(r,o)),e=void 0,this.#m(),this.#d)return;if(!o.terminal)throw new vs(this.#l);if(o.errored)return;if(o.interrupts.length>0){if(this.#i===null)return;let a=await this.#i(o.interrupts);if(this.#d)return;e=eh(o.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;l.outcome!==void 0&&this.#h.set(a.id,l.outcome),this.#t.addMessage({id:Ie(),role:"tool",content:l.content,toolCallId:a.id}),this.#m(),s=!0}}if(!s)return}}#T(e,n){let r=this.#n,o=this.#u,i=this.#h,s=()=>this.#d,a=new Set;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:l}){o.has(l.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${l.messageId}", which was already closed. Its content will be appended to that earlier message rather than starting a new one, and the merged result is what gets persisted. Issue a fresh id per message.`)},onTextMessageContentEvent({textMessageBuffer:l}){r.onTextDelta(l)},onTextMessageEndEvent({event:l,textMessageBuffer:c}){o.add(l.messageId),r.onTextEnd(c)},onToolCallEndEvent({event:l,toolCallName:c,toolCallArgs:u}){let m={id:l.toolCallId,name:c,args:u};e.push(m),r.onToolCall(m)},onToolCallResultEvent({event:l}){let c=l.outcome;typeof c=="string"&&i.set(l.toolCallId,c),r.onToolResult(l.toolCallId,l.content,c)},onActivitySnapshotEvent({event:l,messages:c}){if(c.some(m=>m.id===l.messageId&&m.role==="activity")){r.onActivityChanged(l.messageId,l.activityType,l.content);return}r.onActivity(l.activityType,l.content,l.messageId)},onActivityDeltaEvent({event:l}){a.add(l.messageId)},onCustomEvent({event:l}){r.onCustomEvent(l.name,l.value)},onSubagentStartedEvent({event:l}){r.onSubAgentStarted(l.subagentRunId,l.name,l.parentToolCallId??null)},onSubagentFinishedEvent({event:l}){r.onSubAgentFinished(l.subagentRunId)},onSubagentErrorEvent({event:l}){r.onSubAgentError(l.subagentRunId,l.message)},onMessagesSnapshotEvent({event:l}){r.onMessagesSnapshot(l.messages)},onMessagesChanged({messages:l}){if(a.size!==0){for(let c of a){let u=l.find(m=>m.id===c);u!==void 0&&u.role==="activity"&&r.onActivityChanged(c,u.activityType,u.content)}a.clear()}},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningMessageEndEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(l){n.terminal=!0,l.outcome==="interrupt"&&(n.interrupts=l.interrupts)},onRunErrorEvent({event:l}){n.terminal=!0,n.errored=!0,!s()&&r.onError(l.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Vx(t){return t instanceof Error?t.name==="AbortError"||t instanceof TypeError&&/abort/i.test(t.message):!1}function jl(t){let e=t.attachments;return Array.isArray(e)?e.filter(jx):[]}function jx(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.name=="string"&&typeof e.mime=="string"&&typeof e.size=="number"&&(e.url===void 0||typeof e.url=="string")}var xp="ag-ui-chat",ar="thread",ql="threads",Xr="messages:",ws="checkpoint:",Yr="minted:",qx=60,Wx=100,Xx="New conversation",Ep=!1;function bt(t,e){try{sessionStorage.setItem(t,e)}catch{if(Ep)return;Ep=!0,console.warn("<ag-ui-chat>: the browser refused a sessionStorage write \u2014 the quota is full, or storage is disabled for this context. The conversation continues, but it will not survive a page reload. Deleting a long conversation from the history drawer frees the quota.")}}function ys(t){return t===""?xp:`${xp}@${t}`}var Ze=class t{#t;constructor(e=""){this.#t=ys(e),e!==""&&t.adopt("",e)}static adopt(e,n){let r=`${ys(e)}:`,o=`${ys(n)}:`;for(let[i,s]of _p(r)){let a=sessionStorage.getItem(i),l=o+s;a!==null&&sessionStorage.getItem(l)===null&&bt(l,a),sessionStorage.removeItem(i)}}static purge(e){for(let[n]of _p(`${ys(e)}:`))sessionStorage.removeItem(n)}threadId(){return sessionStorage.getItem(this.#r(ar))??this.newThread()}newThread(){let e=Ie();return bt(this.#r(ar),e),bt(this.#r(Yr+e),"1"),e}isUnsent(e){return sessionStorage.getItem(this.#r(Yr+e))!==null&&sessionStorage.getItem(this.#r(Xr+e))===null}loadMessages(e){return Promise.resolve(this.#i(this.#r(Xr+e)))}saveMessages(e,n){bt(this.#r(Xr+e),JSON.stringify(n)),sessionStorage.removeItem(this.#r(Yr+e)),this.#n(e,n)}loadCheckpoint(e){return this.#i(this.#r(ws+e))}saveCheckpoint(e,n){let r=this.#r(ws+e);if(n===null){sessionStorage.removeItem(r);return}bt(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Xr+e)),sessionStorage.removeItem(this.#r(ws+e)),sessionStorage.removeItem(this.#r(Yr+e)),this.#s(this.#e().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(ar))===e&&sessionStorage.removeItem(this.#r(ar))}listThreads(){let e=this.#e().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){bt(this.#r(ar),e)}renameThread(e,n){let r=this.#e(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#s(r))}#n(e,n){let r=this.#e(),o=r.find(a=>a.threadId===e),i=Kx(n),s=Date.now();o===void 0?r.push({threadId:e,title:Tp(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=Tp(n))),this.#s(r)}#e(){return this.#i(this.#r(ql))??[]}#s(e){let n=this.#r(ql);if(e.length===0){sessionStorage.removeItem(n);return}bt(n,JSON.stringify(e))}#r(e){return`${this.#t}:${e}`}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function _p(t){let e=[];for(let n=0;n<sessionStorage.length;n+=1){let r=sessionStorage.key(n);if(r===null||!r.startsWith(t))continue;let o=r.slice(t.length);Yx(o)&&e.push([r,o])}return e}function Yx(t){return t===ar||t===ql||t.startsWith(Xr)||t.startsWith(ws)||t.startsWith(Yr)}function Tp(t){for(let e of t)if(e.role==="user"){let n=Sp(e.content);if(n!=="")return Ap(n,qx)}return Xx}function Kx(t){for(let e of[...t].reverse()){let n=Sp(e.content);if(n!=="")return Ap(n,Wx)}return""}function Sp(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Ap(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Qe(t,e){return e===void 0?t:{...t,credentials:e}}function xs(t){if(t.newThread!==void 0)return t.newThread();let e=Ie();return t.setActiveThread(e),e}function Es(t,e,n,r){if(e.length===0)return;let o=new URL(String(t),location.href).origin;o===location.origin||n.includes(o)||r.has(o)||(r.add(o),console.warn(`<ag-ui-chat>: sending host credentials (${e.join(", ")}) to ${o}, which is not this page's origin (${location.origin}). Those headers are the page's own authentication, and whichever server answers the browser's preflight receives them \u2014 so a URL attribute built from a query parameter or from tenant-authored configuration is a channel for the token to leave on. If this destination is deliberate, name it in \`trustedOrigins\` to confirm it and silence this notice. Reported once per origin.`))}function Wl(t){let e=t.headers??{},n=new Set;return new th({url:t.endpoint,headers:e,initialState:{...t.initialState??{}},fetch:(r,o)=>{let i=t.getHeaders?.(),s=[...new Set([...Object.keys(e),...Object.keys(i??{})])].sort();if(Es(r,s,t.trustedOrigins??[],n),i===void 0)return fetch(r,Qe(o,t.credentials));let a=new Headers(o?.headers);for(let[l,c]of Object.entries(i))a.set(l,c);return fetch(r,Qe({...o,headers:a},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var Kr=class{#t;#n;#e;#s;#r;#i=new Set;#o=new Map;constructor(e,n=()=>({}),r=new Ze,o=()=>{},i=!0){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r,this.#s=o,this.#r=i}threadId(){return this.#e.threadId()}setActiveThread(e){this.#e.setActiveThread(e)}newThread(){return xs(this.#e)}isUnsent(e){return this.#e.isUnsent?.(e)===!0}saveMessages(e,n){this.#e.saveMessages(e,this.#r?n:[])}loadCheckpoint(e){return this.#e.loadCheckpoint(e)}saveCheckpoint(e,n){this.#e.saveCheckpoint(e,n)}renameThread(e,n){this.#e.renameThread(e,n),this.#o.set(e,n),this.#d(e,"PATCH",{title:n})}clear(e){this.#e.clear(e),this.#i.add(e),this.#d(e,"DELETE")}async listThreads(){let e=await this.#u();return e===null?this.#e.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#l(n))}async loadMessages(e){if(this.#e.isUnsent?.(e)===!0)return null;let n=await this.#c(`${this.#t}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#e.loadMessages(e);let r=await this.#h(n);return r===null?this.#e.loadMessages(e):r.messages??null}async#u(){let e=await this.#c(this.#t);if(e===null||!e.ok)return null;let n=await this.#h(e);return n===null?null:n.threads??[]}async#h(e){try{return await e.json()}catch{return null}}#l(e){return{threadId:e.thread_id,title:this.#o.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#c(e){try{return await fetch(e,Qe({headers:this.#n()},this.#s()))}catch{return null}}async#d(e,n,r){let o=this.#n();try{await fetch(`${this.#t}${encodeURIComponent(e)}/`,Qe({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#s()))}catch{}}};var Zr=class{#t;#n;#e;constructor(e,n=()=>({}),r=()=>{}){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r}async list(){try{let e=await fetch(this.#t,Qe({method:"GET",headers:{Accept:"application/json",...this.#n()}},this.#e()));return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#s("resume",e)}forkUrl(e){return this.#s("fork",e)}#s(e,n){return`${this.#t.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};function _s(t){return t===It.FAILED?re.ERROR:t===It.DENIED?re.DECLINED:re.DONE}async function Xl(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,Qe({method:"POST",headers:{...e.headers??{}},body:n},e.credentials));if(!r.ok)throw new Error(await Zx(r));let o=await r.json();if(typeof o=="object"&&o!==null&&typeof o.text=="string")return o.text;throw new Error("transcription returned an unreadable response")}async function Zx(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Yl(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url),i.withCredentials=e.credentials==="include";for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Qx(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Jx(i)))}),i.addEventListener("error",()=>r(new Error("upload failed"))),i.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>i.abort()),i.send(o)})}function Qx(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,i=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:o,size:i,url:s}:{id:n,name:r,mime:o,size:i}}function Jx(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var eE=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-threads-cache","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],ec=["omit","same-origin","include"];function Kl(t){return ec.includes(t)}var kp="ag-ui-chat:collapsed",Ip="ag-ui-chat:size",Rp="ag-ui-chat:theme",Zl="ag-ui-chat:launcher";function tE(t){if(typeof t!="object"||t===null)return null;let{left:e,top:n}=t;return typeof e=="number"&&typeof n=="number"?{left:e,top:n}:null}var Cp=new Set([null,"","floating","bottom-left"]),nE=[{y:"top"},{y:"bottom"},{x:"left"},{x:"right"},{x:"left",y:"top"},{x:"right",y:"top"},{x:"left",y:"bottom"},{x:"right",y:"bottom"}],Ql=6,Jl=new Set,Qr=class extends HTMLElement{agentFactory=Wl;headers={};getHeaders=null;trustedOrigins=[];allowImages=!1;formatRelativeTime=null;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;approveWithEdits=!1;confirmPredicate=null;getTools=()=>[...this.#At().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#r.tools()];getContext=()=>[...rl(this.getPageMap,this.autoInjectPageMap)];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Ze;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};formatToolPayload=null;strings={};resolvePageTarget=e=>document.querySelector(e);#t={};#n=new Set;#e=ae;#s=new Set;#r=new Ir;#i=new Map;#o=new Map;#u=new Map;#h=new Map;#l=new Set;#c=new Map;#d=new Map;#p=new Set;#y=[];#m=new Set;#N=null;#T=new Set;#x;#G=document.createElement("div");#ae=document.createElement("div");#z=document.createElement("button");#b=document.createElement("button");#je="";#le=null;#Ie=document.createElement("div");#w;#K=null;#Re=!1;#E;#v;#a;#S;#Ce;#F;#R;#A;#qe=null;#C;#O;#M;#Ne;#$;#f;#B;#ce=document.createElement("span");#Oe=0;#Z;#k=null;#_=null;#de=[];#Q=[];#V=document.createElement("div");#J=null;#D=null;#ee=null;#te={x:"right",y:"bottom"};#xt=new Map;#ue=()=>{this.#Ut(),!this.#dn()&&(this.#st(),this.#R.isOpen()&&(this.#R.setModal(!this.#dt()),this.#ut()))};#cn(e){let n=this.#L(),r=n.left+Je,o=n.top+Je,i=n.left+n.width-Je,s=n.top+n.height-Je;return{left:Math.min(Math.max(e.left,r),e.right),top:Math.min(Math.max(e.top,o),e.bottom),right:Math.max(Math.min(e.right,i),e.left),bottom:Math.max(Math.min(e.bottom,s),e.top)}}#dn(){return this.#f.hasAttribute("data-dragging")||this.#x.querySelector(".header[data-dragging]")!==null}#Me;#We=null;#he=!1;#ne=null;#pe={};#W=!1;#Xe=null;#U=null;#Le=null;#Ye=0;#Pe="";#re=null;#De=null;#j=null;#oe=null;#g="";#fe="";#Ue=null;#Ke="";#Et="";#ye=null;#Ze=0;#Qe=[];#_t=[];#Tt=[];#St=[];constructor(){super(),this.#x=this.attachShadow({mode:"open"}),this.#E=document.createElement("div"),this.#v=document.createElement("div"),this.#a=document.createElement("textarea"),this.#S=document.createElement("button"),this.#Ce=document.createElement("span"),this.#C=document.createElement("div"),this.#O=document.createElement("button"),this.#M=document.createElement("input"),this.#Ne=document.createElement("div"),this.#Me=document.createElement("span"),this.#$=document.createElement("button"),this.#f=document.createElement("button"),this.#B=document.createElement("span"),this.#Z=document.createElement("div"),this.registerActivityRenderer({type:ea,render:e=>{let n=aE(e);return n===null?null:Bl("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(n)),"compaction")}}),this.registerActivityRenderer({type:Ks,render:e=>fs(e,this.#e,n=>{this.sendMessage(n)})}),this.#F=new hs(e=>this.#Un(e)),this.#R=new gs({onSelect:e=>{this.#Jn(e)},onNew:()=>{this.newChat(),this.#Ae()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Ae()},onDelete:e=>{this.#er(e)},onVisibility:()=>{this.#ut()}}),this.#A=new Lr((e,n)=>{this.#un(e,n)})}#Je(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#qe===null&&(this.#qe=new Zr(e,()=>this.#xe(e),()=>this.#He())),this.#qe)}async#un(e,n){let r=this.#Je();if(r===null)return;let o=this.#a.value.trim();if(o===""){this.#C.textContent=this.#e.continueNeedsTurn,this.#C.hidden=!1,this.#a.focus();return}this.#a.value="",this.#Y();let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#g,initialMessages:[]});await new sr({agent:s,handlers:this.#tn(),getTools:()=>this.#kt(),getContext:()=>this.#Xt(),executeTool:l=>this.#Jt(l),resolveInterrupts:l=>this.#en(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#hn(){let e=this.#Je();this.#A.setRelativeTimeFormatter(this.formatRelativeTime),this.#A.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials","user-key",...eE]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Kl(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${ec.join(" / ")}) \u2014 it is being ignored, so requests use the browser default and cross-origin cookies will not be sent.`);return}if(e==="placement"){this.#$n(),this.#Wn(),!this.#ze()&&this.collapsed&&this.setCollapsed(!1),requestAnimationFrame(()=>this.#me());return}if(e==="title-text"){this.#Ce.textContent=r??this.#e.title,this.#ce.textContent=this.#Ce.textContent;return}if(e==="user-key"){this.#he&&(n??"")!==(r??"")&&this.#Zn(n??"",r??"");return}n===r||!this.#he||console.warn(`<ag-ui-chat>: "${e}" was changed after the element connected, and is read only while connecting \u2014 this assignment has no effect. Set it before the element enters the DOM (in the markup, or on the element before appending it); frameworks that patch attributes after mount should bind it at creation. To apply a new value now, remove and re-insert the element.`)}registerTool(e){this.#r.register(e)}get sharedState(){return this.#ne?.state??this.#pe}set sharedState(e){this.#pe={...e},this.#ne?.setState(this.#pe)}registerPageState(e){for(let n of Ki(e))this.#r.register(n)}registerStateHook(e){this.registerPageState(e)}#pn(){return this.routeMap.length===0?[]:il(()=>this.routeMap,()=>this.navigate)}#fn(){let e=this.getPageMap;return e===null?[]:[{name:Qs,description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[xe]:"Read the page"},handler:()=>e()}]}#mn(){let e=this.getAttribute("data-page-actions");if(e===null)return[];let n=new Set(e.split(",").map(r=>r.trim()).filter(r=>r!==""));return[...nl(n,r=>this.resolvePageTarget(r)),...n.has(Nr.CHAT)?ja(this):[]]}#At(){return[...this.#pn(),...this.#fn(),...this.#mn(),...this.#gn()]}#gn(){return this.askUser?[{name:"ask_user",description:"Ask the user a question and wait for their answer. Provide `options` for a multiple-choice prompt; set `allow_custom` to also accept a free-text answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user."},options:{type:"array",items:{type:"string"},description:"Preset choices offered as radio buttons."},allow_custom:{type:"boolean",description:"Allow a free-text answer in addition to any options."}},required:["question"]},handler:e=>this.#bn(e)}]:[]}async#bn(e){let r={question:typeof e.question=="string"?e.question:""},o=e.options;Array.isArray(o)&&(r.options=o.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#U=new AbortController;let i=this.#U.signal;this.#H();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await xl(this.#P(),r,{signal:i,strings:this.#e});return this.#U=null,this.#I(),this.#w.follow(),s}#kt(){let e=this.getTools();return this.#s=new Set(e.map(n=>n.name)),e}#et(e){let n=this.#At().find(r=>r.name===e);return n!==void 0?n:this.#r.has(e)?this.#r.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get userKey(){return this.getAttribute("user-key")??""}set userKey(e){this.setAttribute("user-key",e)}get credentials(){let e=this.getAttribute("credentials");return e!==null&&Kl(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Kl(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${ec.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#we(){return{...this.headers,...this.getHeaders?.()}}#xe(e){let n=this.#we();return Es(e,Object.keys(n),this.trustedOrigins,this.#n),n}#He(){return this.credentials??void 0}#Ge(){let e=this.#He();return e===void 0?{}:{credentials:e}}#It(e){return Qe({headers:this.#xe(e)},this.#He())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===On.INLINE||e===On.MINIMAL||e===On.COMPACT?e:On.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#fe=this.#Kn(),this.#ot(this.#Bt()),requestAnimationFrame(()=>{this.#st(),this.#me()}),this.#e=sl({...this.#yn(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#lt(Rp);e!==null&&this.setAttribute("theme",e)}if(this.#ir(),this.#R.setStrings(this.#e),this.#A.setStrings(this.#e),this.#ze()&&this.#Gn()&&this.setAttribute("collapsed",""),this.#Zt(),this.#Pn(),this.conversationStore instanceof Ze){let e=this.#at();this.#ye=e===""?this.conversationStore:new Ze(e),this.conversationStore=this.#ye}window.addEventListener("resize",this.#ue),window.visualViewport?.addEventListener("resize",this.#ue),window.visualViewport?.addEventListener("scroll",this.#ue),this.#Ut(),this.#Ot(),this.#wn(),this.#En(),this.#g=this.conversationStore.threadId(),queueMicrotask(()=>this.#vn()),this.#Fe(),this.#he=!0}#vn(){this.#he&&(this.#Mt(),this.#Lt())}async reload(){this.#X(),this.#Se(),this.#ie(!1),await Promise.all([this.#Mt(),this.#Lt(),this.#Fe()])}disconnectedCallback(){this.#he=!1,window.removeEventListener("resize",this.#ue),window.visualViewport?.removeEventListener("resize",this.#ue),window.visualViewport?.removeEventListener("scroll",this.#ue),this.#Ue!==null&&(Jl.delete(this.#Ue),this.#Ue=null),this.#X(),this.#le?.detach(),this.#le=null,this.#k?.dispose(),this.#We?.dispose(),this.#w.dispose(),this.#K!==null&&(clearTimeout(this.#K),this.#K=null)}#Rt(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#Ct(e){let n=this.getAttribute(e);if(n===null)return null;try{return JSON.parse(n)}catch{return console.warn(`<ag-ui-chat>: ${e} is not valid JSON, so it was ignored entirely and the built-in default is being used. Check the quoting -- JSON inside an HTML attribute needs single quotes around the attribute value, or its own double quotes escaped.`),null}}#yn(){let e=this.#Ct("data-strings");return typeof e=="object"&&e!==null?e:{}}#wn(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#xn(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new Qi({upload:n,maxBytes:this.#Rn(),accept:r,strings:this.#e,onChange:()=>this.#fr(o)});this.#k=o,this.#Ne.appendChild(this.#k.element),this.#M.accept=r,this.#O.hidden=!1,this.#Nn(),this.#Ln(o)}#xn(e){return e===null?null:(n,r,o)=>Yl(n,{url:e,headers:this.#xe(e),...this.#Ge(),onProgress:r,signal:o})}#En(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#_n(e);n!==null&&(this.#We=new bs({transcribe:n,onText:r=>this.#Tn(r),strings:this.#e}),this.#Me.appendChild(this.#We.element))}#_n(e){return e===null?null:n=>Xl(n,{url:e,headers:this.#xe(e),...this.#Ge()})}#Tn(e){let n=this.#a.value.trim();this.#a.value=n===""?e:`${n} ${e}`,this.#Qt(),this.#a.focus()}quote(e){let n=bl(e);if(n==="")return;let r=this.#a.value.replace(/\s+$/,"");this.#a.value=r===""?n:`${r}
3600
+ `;var nw=1500;function Tl(t,e){if(Ch(t)!==null)return;let n=as(t,e.strings),r=e.text;r!==void 0&&n.appendChild(rw(e.strings,r,e.html)),e.onFeedback!==void 0&&n.append(Rh("up",e.strings.feedbackUp,e.onFeedback),Rh("down",e.strings.feedbackDown,e.onFeedback))}function as(t,e){let n=Ch(t);if(n!==null)return n;let r=document.createElement("div");return r.className="message-actions",r.setAttribute("part","message-actions"),r.setAttribute("role","group"),r.setAttribute("aria-label",e.messageActions),t.after(r),r}function Ch(t){let e=t.nextElementSibling;return e?.classList.contains("message-actions")===!0?e:null}function ls(t,e,n){let r=document.createElement("button");r.type="button",r.className=`message-action message-action--${t}`,r.setAttribute("part",`message-action message-action-${t}`),_l(r,e);let o=document.createElement("span");return o.className="message-action-icon",o.setAttribute("part",`message-action-icon message-action-icon-${t}`),o.setAttribute("aria-hidden","true"),o.innerHTML=n,r.appendChild(o),r}function _l(t,e){t.title=e,t.setAttribute("aria-label",e),t.dataset.tooltip=e}function rw(t,e,n){let r=ls("copy",t.copyMessage,zc);return r.addEventListener("click",()=>{ow(e(),n?.()).then(o=>{iw(r,o?t.copied:t.copyFailed,t.copyMessage)})}),r}async function ow(t,e){let n=navigator.clipboard;if(n===void 0)return!1;if(e!==void 0&&typeof ClipboardItem=="function")try{return await n.write([new ClipboardItem({"text/plain":new Blob([t],{type:"text/plain"}),"text/html":new Blob([e],{type:"text/html"})})]),!0}catch{}try{return await n.writeText(t),!0}catch{return!1}}function Rh(t,e,n){let r=ls(t==="up"?"up":"down",e,t==="up"?$c:Bc);return r.addEventListener("click",()=>{let o=r.getAttribute("aria-pressed")==="true";r.setAttribute("aria-pressed",o?"false":"true"),n(t)}),r.setAttribute("aria-pressed","false"),r}function iw(t,e,n){_l(t,e),t.classList.add("message-action--confirmed"),setTimeout(()=>{_l(t,n),t.classList.remove("message-action--confirmed")},nw)}function Nh(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function sw(t){if(Array.isArray(t))return t}function aw(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,i,s,a=[],l=!0,c=!1;try{if(i=(n=n.call(t)).next,e!==0)for(;!(l=(r=i.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(u){c=!0,o=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw o}}return a}}function lw(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3601
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function cw(t,e){return sw(t)||aw(t,e)||dw(t,e)||lw()}function dw(t,e){if(t){if(typeof t=="string")return Nh(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Nh(t,e):void 0}}var qh=Object.entries,Oh=Object.setPrototypeOf,uw=Object.isFrozen,hw=Object.getPrototypeOf,pw=Object.getOwnPropertyDescriptor,ye=Object.freeze,_e=Object.seal,nr=Object.create,Wh=typeof Reflect<"u"&&Reflect,Nl=Wh.apply,Ol=Wh.construct;ye||(ye=function(e){return e});_e||(_e=function(e){return e});Nl||(Nl=function(e,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];return e.apply(n,o)});Ol||(Ol=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new e(...r)});var yn=ve(Array.prototype.forEach),fw=ve(Array.prototype.lastIndexOf),Mh=ve(Array.prototype.pop),zr=ve(Array.prototype.push),mw=ve(Array.prototype.splice),rr=Array.isArray,Br=ve(String.prototype.toLowerCase),Sl=ve(String.prototype.toString),Lh=ve(String.prototype.match),Fr=ve(String.prototype.replace),Ph=ve(String.prototype.indexOf),gw=ve(String.prototype.trim),bw=ve(Number.prototype.toString),vw=ve(Boolean.prototype.toString),Dh=typeof BigInt>"u"?null:ve(BigInt.prototype.toString),Uh=typeof Symbol>"u"?null:ve(Symbol.prototype.toString),He=ve(Object.prototype.hasOwnProperty),$r=ve(Object.prototype.toString),Ce=ve(RegExp.prototype.test),vn=yw(TypeError);function ve(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Nl(t,e,r)}}function yw(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Ol(t,n)}}function ee(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Br;if(Oh&&Oh(t,null),!rr(e))return t;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let i=n(o);i!==o&&(uw(e)||(e[r]=i),o=i)}t[o]=!0}return t}function ww(t){for(let e=0;e<t.length;e++)He(t,e)||(t[e]=null);return t}function Ve(t){let e=nr(null);for(let r of qh(t)){var n=cw(r,2);let o=n[0],i=n[1];He(t,o)&&(rr(i)?e[o]=ww(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=Ve(i):e[o]=i)}return e}function xw(t){switch(typeof t){case"string":return t;case"number":return bw(t);case"boolean":return vw(t);case"bigint":return Dh?Dh(t):"0";case"symbol":return Uh?Uh(t):"Symbol()";case"undefined":return $r(t);case"function":case"object":{if(t===null)return $r(t);let e=t,n=rt(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:$r(r)}return $r(t)}default:return $r(t)}}function rt(t,e){for(;t!==null;){let r=pw(t,e);if(r){if(r.get)return ve(r.get);if(typeof r.value=="function")return ve(r.value)}t=hw(t)}function n(){return null}return n}function Ew(t){try{return Ce(t,""),!0}catch{return!1}}var Hh=ye(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Al=ye(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),kl=ye(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),_w=ye(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Il=ye(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Tw=ye(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Gh=ye(["#text"]),zh=ye(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Rl=ye(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Fh=ye(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),cs=ye(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Sw=_e(/{{[\w\W]*|^[\w\W]*}}/g),Aw=_e(/<%[\w\W]*|^[\w\W]*%>/g),kw=_e(/\${[\w\W]*/g),Iw=_e(/^data-[\-\w.\u00B7-\uFFFF]+$/),Rw=_e(/^aria-[\-\w]+$/),$h=_e(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Cw=_e(/^(?:\w+script|data):/i),Nw=_e(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ow=_e(/^html$/i),Mw=_e(/^[a-z][.\w]*(-[.\w]+)+$/i),Bh=_e(/<[/\w!]/g),Vh=_e(/<[/\w]/g),Lw=_e(/<\/no(script|embed|frames)/i),Pw=_e(/\/>/i),Be={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Xh=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],Dw=ye(ee({},Xh)),Uw=(function(){let t={};return yn(Xh,e=>{t[e]=_e(new RegExp("</"+e+"(?=[\\t\\n\\f\\r />])","i"))}),ye(t)})(),Hw=function(){return typeof window>"u"?null:window},Gw=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},jh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Ut=function(e,n,r,o){return He(e,n)&&rr(e[n])?ee(o.base?Ve(o.base):{},e[n],o.transform):r},Cl=function(e,n,r){let o=He(e,n)?e[n]:void 0;return o&&typeof o=="object"?Ve(o):r()};function Yh(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Hw(),e=I=>Yh(I);if(e.version="3.4.14",e.removed=[],!t||!t.document||t.document.nodeType!==Be.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,o=r.currentScript;t.DocumentFragment;let i=t.HTMLTemplateElement,s=t.Node,a=t.Element,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let u=t.DOMParser,m=t.trustedTypes,w=a.prototype,p=rt(w,"cloneNode"),h=rt(w,"remove"),g=rt(w,"nextSibling"),x=rt(w,"childNodes"),T=rt(w,"parentNode"),S=rt(w,"shadowRoot"),L=rt(w,"attributes"),z=s&&s.prototype?rt(s.prototype,"nodeType"):null,v=s&&s.prototype?rt(s.prototype,"nodeName"):null,A=s&&s.prototype?rt(s.prototype,"ownerDocument"):null,E=function(f){return z?z(f):f.nodeType},R=function(f){return v?v(f):f.nodeName};if(typeof i=="function"){let I=n.createElement("template");I.content&&I.content.ownerDocument&&(n=I.content.ownerDocument)}let B,le="",we,je=!1,lr=0,tc=function(){if(lr>0)throw vn('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},_n=function(f){tc(),lr++;try{return B.createHTML(f)}finally{lr--}},Op=function(f){tc(),lr++;try{return B.createScriptURL(f)}finally{lr--}},Mp=function(){return je||(we=Gw(m,o),je=!0),we},Jr=n,Ts=Jr.implementation,nc=Jr.createNodeIterator,Lp=Jr.createDocumentFragment,Pp=Jr.getElementsByTagName,Dp=r.importNode,de=jh();e.isSupported=typeof qh=="function"&&typeof T=="function"&&Ts&&Ts.createHTMLDocument!==void 0;let Up=Sw,Hp=Aw,Gp=kw,zp=Iw,Fp=Rw,$p=Cw,rc=Nw,Bp=Mw,oc=$h,ue=null,Ss=ee({},[...Hh,...Al,...kl,...Il,...Gh]),he=null,As=ee({},[...zh,...Rl,...Fh,...cs]),st=Object.seal(nr(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),cr=null,ic=null,St=Object.seal(nr(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),sc=!0,ks=!0,ac=!1,lc=!0,At=!1,Gt=!0,zt=!1,Is=!1,eo=null,to=null,Rs=!1,Tn=!1,no=!1,ro=!1,cc=!0,dc=!1,uc="user-content-",Cs=!0,Ns=!1,Sn={},An=null,hc=ee({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),pc=null,fc=ee({},["audio","video","img","source","image","track"]),mc=null,gc=ee({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),oo="http://www.w3.org/1998/Math/MathML",io="http://www.w3.org/2000/svg",at="http://www.w3.org/1999/xhtml",kn=at,Os=!1,Ms=null,Vp=ee({},[oo,io,at],Sl),bc=ye(["mi","mo","mn","ms","mtext"]),Ls=ee({},bc),vc=ye(["annotation-xml"]),Ps=ee({},vc),jp=ee({},["title","style","font","a","script"]),dr=null,qp=["application/xhtml+xml","text/html"],Wp="text/html",ge=null,In=null,Xp=n.createElement("form"),yc=function(f){return f instanceof RegExp||f instanceof Function},Ds=function(){let f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(In&&In===f)return;(!f||typeof f!="object")&&(f={}),f=Ve(f),dr=qp.indexOf(f.PARSER_MEDIA_TYPE)===-1?Wp:f.PARSER_MEDIA_TYPE,ge=dr==="application/xhtml+xml"?Sl:Br,ue=Ut(f,"ALLOWED_TAGS",Ss,{transform:ge}),he=Ut(f,"ALLOWED_ATTR",As,{transform:ge}),Ms=Ut(f,"ALLOWED_NAMESPACES",Vp,{transform:Sl}),mc=Ut(f,"ADD_URI_SAFE_ATTR",gc,{transform:ge,base:gc}),pc=Ut(f,"ADD_DATA_URI_TAGS",fc,{transform:ge,base:fc}),An=Ut(f,"FORBID_CONTENTS",hc,{transform:ge}),cr=Ut(f,"FORBID_TAGS",Ve({}),{transform:ge}),ic=Ut(f,"FORBID_ATTR",Ve({}),{transform:ge}),Sn=He(f,"USE_PROFILES")?f.USE_PROFILES&&typeof f.USE_PROFILES=="object"?Ve(f.USE_PROFILES):f.USE_PROFILES:!1,sc=f.ALLOW_ARIA_ATTR!==!1,ks=f.ALLOW_DATA_ATTR!==!1,ac=f.ALLOW_UNKNOWN_PROTOCOLS||!1,lc=f.ALLOW_SELF_CLOSE_IN_ATTR!==!1,At=f.SAFE_FOR_TEMPLATES||!1,Gt=f.SAFE_FOR_XML!==!1,zt=f.WHOLE_DOCUMENT||!1,Tn=f.RETURN_DOM||!1,no=f.RETURN_DOM_FRAGMENT||!1,ro=f.RETURN_TRUSTED_TYPE||!1,Rs=f.FORCE_BODY||!1,cc=f.SANITIZE_DOM!==!1,dc=f.SANITIZE_NAMED_PROPS||!1,Cs=f.KEEP_CONTENT!==!1,Ns=f.IN_PLACE||!1,oc=Ew(f.ALLOWED_URI_REGEXP)?f.ALLOWED_URI_REGEXP:$h,kn=typeof f.NAMESPACE=="string"?f.NAMESPACE:at,Ls=Cl(f,"MATHML_TEXT_INTEGRATION_POINTS",()=>ee({},bc)),Ps=Cl(f,"HTML_INTEGRATION_POINTS",()=>ee({},vc));let y=Cl(f,"CUSTOM_ELEMENT_HANDLING",()=>nr(null));if(st=nr(null),He(y,"tagNameCheck")&&yc(y.tagNameCheck)&&(st.tagNameCheck=y.tagNameCheck),He(y,"attributeNameCheck")&&yc(y.attributeNameCheck)&&(st.attributeNameCheck=y.attributeNameCheck),He(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(st.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),_e(st),At&&(ks=!1),no&&(Tn=!0),Sn&&(ue=ee({},Gh),he=nr(null),Sn.html===!0&&(ee(ue,Hh),ee(he,zh)),Sn.svg===!0&&(ee(ue,Al),ee(he,Rl),ee(he,cs)),Sn.svgFilters===!0&&(ee(ue,kl),ee(he,Rl),ee(he,cs)),Sn.mathMl===!0&&(ee(ue,Il),ee(he,Fh),ee(he,cs))),St.tagCheck=null,St.attributeCheck=null,He(f,"ADD_TAGS")&&(typeof f.ADD_TAGS=="function"?St.tagCheck=f.ADD_TAGS:rr(f.ADD_TAGS)&&(ue===Ss&&(ue=Ve(ue)),ee(ue,f.ADD_TAGS,ge))),He(f,"ADD_ATTR")&&(typeof f.ADD_ATTR=="function"?St.attributeCheck=f.ADD_ATTR:rr(f.ADD_ATTR)&&(he===As&&(he=Ve(he)),ee(he,f.ADD_ATTR,ge))),He(f,"ADD_FORBID_CONTENTS")&&rr(f.ADD_FORBID_CONTENTS)&&(An===hc&&(An=Ve(An)),ee(An,f.ADD_FORBID_CONTENTS,ge)),Cs&&(ue["#text"]=!0),zt&&ee(ue,["html","head","body"]),ue.table&&(ee(ue,["tbody"]),delete cr.tbody),f.TRUSTED_TYPES_POLICY){if(typeof f.TRUSTED_TYPES_POLICY.createHTML!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof f.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw vn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let _=B;B=f.TRUSTED_TYPES_POLICY;try{le=_n("")}catch(O){throw B=_,O}}else f.TRUSTED_TYPES_POLICY===null?(B=void 0,le=""):(B===void 0&&(B=Mp()),B&&typeof le=="string"&&(le=_n("")));ye&&ye(f),In=f},wc=ee({},[...Al,...kl,..._w]),xc=ee({},[...Il,...Tw]),Yp=function(f,y,_){return y.namespaceURI===at?f==="svg":y.namespaceURI===oo?f==="svg"&&(_==="annotation-xml"||Ls[_]):!!wc[f]},Kp=function(f,y,_){return y.namespaceURI===at?f==="math":y.namespaceURI===io?f==="math"&&Ps[_]:!!xc[f]},Zp=function(f,y,_){return y.namespaceURI===io&&!Ps[_]||y.namespaceURI===oo&&!Ls[_]?!1:!xc[f]&&(jp[f]||!wc[f])},Qp=function(f){let y=T(f);(!y||!y.tagName)&&(y={namespaceURI:kn,tagName:"template"});let _=Br(f.tagName),O=Br(y.tagName);return Ms[f.namespaceURI]?f.namespaceURI===io?Yp(_,y,O):f.namespaceURI===oo?Kp(_,y,O):f.namespaceURI===at?Zp(_,y,O):!!(dr==="application/xhtml+xml"&&Ms[f.namespaceURI]):!1},kt=function(f){zr(e.removed,{element:f});try{T(f).removeChild(f)}catch{if(h(f),!T(f))throw vn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ec=function(f,y,_){try{f.removeAttributeNode(y)}catch{try{f.removeAttribute(_)}catch{}}},so=function(f){ao(f);let y=x(f);if(y){let O=[];yn(y,H=>{zr(O,H)}),yn(O,H=>{try{h(H)}catch{}})}let _=L(f);if(_)for(let O=_.length-1;O>=0;--O){let H=_[O],V=H&&H.name;typeof V=="string"&&Ec(f,H,V)}},Ft=function(f,y,_){if(!_)try{_=y.getAttributeNode(f)}catch{_=null}zr(e.removed,{attribute:_||null,from:y});try{_?y.removeAttributeNode(_):y.removeAttribute(f)}catch{try{y.removeAttribute(f)}catch{}}if(f==="is")if(Tn||no)try{kt(y)}catch{}else try{y.setAttribute(f,"")}catch{}},Jp=function(f){let y=L(f);if(y)for(let _=y.length-1;_>=0;--_){let O=y[_],H=O&&O.name;typeof H!="string"||he[ge(H)]||Ec(f,O,H)}},ao=function(f){let y=[f];for(;y.length>0;){let _=y.pop();E(_)===Be.element&&Jp(_);let H=x(_);if(H)for(let V=H.length-1;V>=0;--V)y.push(H[V])}},_c=function(f,y){return Gt?f==="patchsrc"?!0:f==="for"&&y!=="label"&&y!=="output":!1},ef=function(f){if(!Gt)return;let y=[f];for(;y.length>0;){let _=y.pop(),O=E(_);if(O===Be.processingInstruction||O===Be.comment&&Ce(Vh,_.data)){try{h(_)}catch{}continue}if(O===Be.element){let V=_,ie=ge(R(_));try{V.hasAttribute&&V.hasAttribute("patchsrc")&&V.removeAttribute("patchsrc"),V.hasAttribute&&V.hasAttribute("for")&&_c("for",ie)&&V.removeAttribute("for")}catch{}}let H=x(_);if(H)for(let V=H.length-1;V>=0;--V)y.push(H[V])}},Tc=function(f){let y=null,_=null;if(Rs)f="<remove></remove>"+f;else{let V=Lh(f,/^[\r\n\t ]+/);_=V&&V[0]}dr==="application/xhtml+xml"&&kn===at&&(f='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+f+"</body></html>");let O=B?_n(f):f;if(kn===at)try{y=new u().parseFromString(O,dr)}catch{}if(!y||!y.documentElement){y=Ts.createDocument(kn,"template",null);try{y.documentElement.innerHTML=Os?le:O}catch{}}let H=y.body||y.documentElement;return f&&_&&H.insertBefore(n.createTextNode(_),H.childNodes[0]||null),kn===at?Pp.call(y,zt?"html":"body")[0]:zt?y.documentElement:H},Sc=function(f){let y=A?A(f):f.ownerDocument;return nc.call(y||f,f,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},lo=function(f){return f=Fr(f,Up," "),f=Fr(f,Hp," "),f=Fr(f,Gp," "),f},Us=function(f){var y;f.normalize();let _=A?A(f):f.ownerDocument,O=nc.call(_||f,f,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),H=O.nextNode();for(;H;)H.data=lo(H.data),H=O.nextNode();let V=(y=f.querySelectorAll)===null||y===void 0?void 0:y.call(f,"template");V&&yn(V,ie=>{Rn(ie.content)&&Us(ie.content)})},co=function(f){let y=v?v(f):null;return typeof y!="string"||ge(y)!=="form"?!1:typeof f.nodeName!="string"||typeof f.textContent!="string"||typeof f.removeChild!="function"||f.attributes!==L(f)||typeof f.removeAttribute!="function"||typeof f.setAttribute!="function"||typeof f.namespaceURI!="string"||typeof f.insertBefore!="function"||typeof f.hasChildNodes!="function"||f.nodeType!==z(f)||f.childNodes!==x(f)},Rn=function(f){if(!z||typeof f!="object"||f===null)return!1;try{return z(f)===Be.documentFragment}catch{return!1}},ur=function(f){if(!z||typeof f!="object"||f===null)return!1;try{return typeof z(f)=="number"}catch{return!1}};function lt(I,f,y){I.length!==0&&yn(I,_=>{_.call(e,f,y,In)})}let tf=function(f,y){return!!(Gt&&f.hasChildNodes()&&!ur(f.firstElementChild)&&Ce(Bh,f.textContent)&&Ce(Bh,f.innerHTML)||Gt&&f.namespaceURI===at&&Dw[y]&&(ur(f.firstElementChild)||typeof f.textContent=="string"&&Ce(Uw[y],f.textContent))||f.nodeType===Be.processingInstruction||Gt&&f.nodeType===Be.comment&&Ce(Vh,f.data))},uo=function(f,y){if(f instanceof RegExp)return Ce(f,y);if(f instanceof Function){for(var _=arguments.length,O=new Array(_>2?_-2:0),H=2;H<_;H++)O[H-2]=arguments[H];return!!f(y,...O)}return!1},nf=function(f,y,_){if(!cr[y]&&Cc(y)&&uo(st.tagNameCheck,y))return!1;if(Cs&&!An[y]){let O=T(f),H=x(f);if(H&&O){let V=H.length;for(let ie=V-1;ie>=0;--ie){let pe=f===_?p(H[ie],!0):H[ie];O.insertBefore(pe,g(f))}}}return kt(f),!0},Ac=function(f,y,_,O){return f.length===0?y:y===_||y===O?Ve(y):y},kc=function(f,y){return f===y||T(f)!==null?!1:(Ns&&ao(f),!0)},Ic=function(f,y){if(lt(de.beforeSanitizeElements,f,null),kc(f,y))return!0;if(co(f))return kt(f),!0;let _=ge(R(f));if(ue=Ac(de.uponSanitizeElement,ue,Ss,eo),lt(de.uponSanitizeElement,f,{tagName:_,allowedTags:ue}),kc(f,y))return!0;if(tf(f,_))return kt(f),!0;if(cr[_]||!(St.tagCheck instanceof Function&&St.tagCheck(_))&&!ue[_]){let H=nf(f,_,y);return H===!1&&lt(de.afterSanitizeElements,f,null),H}if(E(f)===Be.element&&!Qp(f)||(_==="noscript"||_==="noembed"||_==="noframes")&&Ce(Lw,f.innerHTML))return kt(f),!0;if(At&&f.nodeType===Be.text){let H=lo(f.textContent);f.textContent!==H&&(zr(e.removed,{element:f.cloneNode()}),f.textContent=H)}return lt(de.afterSanitizeElements,f,null),!1},Rc=function(f,y,_){if(ic[y]||_c(y,f)||cc&&(y==="id"||y==="name")&&(_ in n||_ in Xp))return!1;let O=he[y]||St.attributeCheck instanceof Function&&St.attributeCheck(y,f);return ks&&Ce(zp,y)||sc&&Ce(Fp,y)?!0:O?mc[y]||Ce(oc,Fr(_,rc,""))||(y==="src"||y==="xlink:href"||y==="href")&&f!=="script"&&Ph(_,"data:")===0&&pc[f]||ac&&!Ce($p,Fr(_,rc,""))?!0:!_:Cc(f)&&uo(st.tagNameCheck,f)&&uo(st.attributeNameCheck,y,f)||y==="is"&&st.allowCustomizedBuiltInElements&&uo(st.tagNameCheck,_)},rf=ee({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Cc=function(f){return!rf[Br(f)]&&Ce(Bp,f)},of=function(f,y,_,O){if(B&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!_)switch(m.getAttributeType(f,y)){case"TrustedHTML":return _n(O);case"TrustedScriptURL":return Op(O)}return O},sf=function(f,y,_,O){try{_?f.setAttributeNS(_,y,O):f.setAttribute(y,O),co(f)?kt(f):Mh(e.removed)}catch{Ft(y,f)}},Nc=function(f){lt(de.beforeSanitizeAttributes,f,null);let y=f.attributes;if(!y||co(f))return;he=Ac(de.uponSanitizeAttribute,he,As,to);let _={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:he,forceKeepAttr:void 0},O=y.length,H=ge(f.nodeName);for(;O--;){let V=y[O],ie=V.name,pe=V.namespaceURI,Me=V.value,Le=ge(ie),Gs=Me,Oe=ie==="value"?Gs:gw(Gs);if(_.attrName=Le,_.attrValue=Oe,_.keepAttr=!0,_.forceKeepAttr=void 0,lt(de.uponSanitizeAttribute,f,_),Oe=_.attrValue,dc&&(Le==="id"||Le==="name")&&Ph(Oe,uc)!==0&&(Ft(ie,f,V),Oe=uc+Oe),Gt&&Ce(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Oe)){Ft(ie,f,V);continue}if(Le==="attributename"&&Lh(Oe,"href")){Ft(ie,f,V);continue}if(!_.forceKeepAttr){if(!_.keepAttr){Ft(ie,f,V);continue}if(!lc&&Ce(Pw,Oe)){Ft(ie,f,V);continue}if(At&&(Oe=lo(Oe)),!Rc(H,Le,Oe)){Ft(ie,f,V);continue}Oe=of(H,Le,pe,Oe),Oe!==Gs&&sf(f,ie,pe,Oe)}}lt(de.afterSanitizeAttributes,f,null)},ho=function(f){let y=null,_=Sc(f);for(lt(de.beforeSanitizeShadowDOM,f,null);y=_.nextNode();)if(lt(de.uponSanitizeShadowNode,y,null),Ic(y,f),Nc(y),Rn(y.content)&&ho(y.content),E(y)===Be.element){let O=S(y);Rn(O)&&(Hs(O),ho(O))}lt(de.afterSanitizeShadowDOM,f,null)},Hs=function(f){let y=[{node:f,shadow:null}];for(;y.length>0;){let _=y.pop();if(_.shadow){ho(_.shadow);continue}let O=_.node,V=E(O)===Be.element,ie=x(O);if(ie)for(let pe=ie.length-1;pe>=0;--pe)y.push({node:ie[pe],shadow:null});if(V){let pe=v?v(O):null;if(typeof pe=="string"&&ge(pe)==="template"){let Me=O.content;Rn(Me)&&y.push({node:Me,shadow:null})}}if(V){let pe=S(O);Rn(pe)&&y.push({node:null,shadow:pe},{node:pe,shadow:null})}}};return e.sanitize=function(I){let f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,_=null,O=null,H=null;if(Os=!I,Os&&(I="<!-->"),typeof I!="string"&&!ur(I)&&(I=xw(I),typeof I!="string"))throw vn("dirty is not a string, aborting");if(!e.isSupported)return I;Is?(ue=eo,he=to):Ds(f),(de.uponSanitizeElement.length>0||de.uponSanitizeAttribute.length>0)&&(ue=Ve(ue)),de.uponSanitizeAttribute.length>0&&(he=Ve(he)),e.removed=[];let V=Ns&&typeof I!="string"&&ur(I);if(V){ef(I);let Me=R(I);if(typeof Me=="string"){let Le=ge(Me);if(!ue[Le]||cr[Le])throw so(I),vn("root node is forbidden and cannot be sanitized in-place")}if(co(I))throw so(I),vn("root node is clobbered and cannot be sanitized in-place");try{Hs(I)}catch(Le){throw so(I),Le}}else if(ur(I))y=Tc("<!---->"),_=y.ownerDocument.importNode(I,!0),_.nodeType===Be.element&&_.nodeName==="BODY"||_.nodeName==="HTML"?y=_:y.appendChild(_),Hs(_);else{if(!Tn&&!At&&!zt&&I.indexOf("<")===-1)return B&&ro?_n(I):I;if(y=Tc(I),!y)return Tn?null:ro?le:""}y&&Rs&&kt(y.firstChild);let ie=V?I:y;try{let Me=Sc(ie);for(;O=Me.nextNode();)Ic(O,ie),Nc(O),Rn(O.content)&&ho(O.content)}catch(Me){throw V&&(so(I),yn(e.removed,Le=>{Le.element&&ao(Le.element)})),Me}if(V)return yn(e.removed,Me=>{Me.element&&ao(Me.element)}),At&&Us(I),I;if(Tn){if(At&&Us(y),no)for(H=Lp.call(y.ownerDocument);y.firstChild;)H.appendChild(y.firstChild);else H=y;return(he.shadowroot||he.shadowrootmode)&&(H=Dp.call(r,H,!0)),H}let pe=zt?y.outerHTML:y.innerHTML;return zt&&ue["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&Ce(Ow,y.ownerDocument.doctype.name)&&(pe="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
3602
+ `+pe),At&&(pe=lo(pe)),B&&ro?_n(pe):pe},e.setConfig=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ds(I),Is=!0,eo=ue,to=he},e.clearConfig=function(){In=null,Is=!1,eo=null,to=null,B=we,le=""},e.isValidAttribute=function(I,f,y){In||Ds({});let _=ge(I),O=ge(f);return Rc(_,O,y)},e.addHook=function(I,f){typeof f=="function"&&He(de,I)&&zr(de[I],f)},e.removeHook=function(I,f){if(He(de,I)){if(f!==void 0){let y=fw(de[I],f);return y===-1?void 0:mw(de[I],y,1)[0]}return Mh(de[I])}},e.removeHooks=function(I){He(de,I)&&(de[I]=[])},e.removeAllHooks=function(){de=jh()},e}var Kh=Yh();function Dl(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var En=Dl();function op(t){En=t}var wn={exec:()=>null};function or(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),o=e[r];return o||(o=t(r),e[r]=o),o}}function Z(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(o,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(Ne.caret,"$1"),n=n.replace(o,s),r},getRegex:()=>new RegExp(n,e)};return r}var zw=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Ne={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:or(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:or(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:or(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:or(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:or(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:or(t=>new RegExp(`^ {0,${t}}>`))},Fw=/^(?:[ \t]*(?:\n|$))+/,$w=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Bw=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,qr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Vw=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ul=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ip=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,sp=Z(ip).replace(/bull/g,Ul).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),jw=Z(ip).replace(/bull/g,Ul).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Hl=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,qw=/^[^\n]+/,Gl=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ww=Z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Gl).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Xw=Z(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Ul).getRegex(),fs="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",zl=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Yw=Z("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",zl).replace("tag",fs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ap=t=>Z(Hl).replace("hr",qr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",t).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",fs).getRegex(),Kw=ap(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Zw=ap(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Qw=Z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Zw).getRegex(),Fl={blockquote:Qw,code:$w,def:Ww,fences:Bw,heading:Vw,hr:qr,html:Yw,lheading:sp,list:Xw,newline:Fw,paragraph:Kw,table:wn,text:qw},Zh=Z("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",qr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",fs).getRegex(),Jw={...Fl,lheading:jw,table:Zh,paragraph:Z(Hl).replace("hr",qr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Zh).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",fs).getRegex()},ex={...Fl,html:Z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",zl).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:wn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Z(Hl).replace("hr",qr).replace("heading",` *#{1,6} *[^
3603
+ ]`).replace("lheading",sp).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},tx=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,nx=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,lp=/^( {2,}|\\)\n(?!\s*$)/,rx=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Tt=/[\p{P}\p{S}]/u,ir=/[\s\p{P}\p{S}]/u,Wr=/[^\s\p{P}\p{S}]/u,ox=Z(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ir).getRegex(),ix=/[\p{Pi}\p{Ps}"']/u,cp=/(?!~)[\p{P}\p{S}]/u,sx=/(?!~)[\s\p{P}\p{S}]/u,ax=/(?:[^\s\p{P}\p{S}]|~)/u,lx=Z(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",zw?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),dp=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,cx=Z(dp,"u").replace(/punct/g,Tt).getRegex(),dx=Z(dp,"u").replace(/punct/g,cp).getRegex(),ux=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,hx=Z(ux,"u").replace(/openQuote/g,ix).replace(/punct/g,Tt).getRegex(),up="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",px=Z(up,"gu").replace(/notPunctSpace/g,Wr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),fx=Z(up,"gu").replace(/notPunctSpace/g,ax).replace(/punctSpace/g,sx).replace(/punct/g,cp).getRegex(),mx="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",gx=Z(mx,"gu").replace(/notPunctSpace/g,Wr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),bx=Z("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Wr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),vx="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",yx=Z(vx,"gu").replace(/notPunctSpace/g,Wr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),wx=Z(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Tt).getRegex(),xx="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ex=Z(xx,"gu").replace(/notPunctSpace/g,Wr).replace(/punctSpace/g,ir).replace(/punct/g,Tt).getRegex(),_x=Z(/\\(punct)/,"gu").replace(/punct/g,Tt).getRegex(),Tx=Z(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Sx=Z(zl).replace("(?:-->|$)","-->").getRegex(),Ax=Z("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Sx).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),us=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,kx=Z(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",us).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),hp=Z(/^!?\[(label)\]\[(ref)\]/).replace("label",us).replace("ref",Gl).getRegex(),pp=Z(/^!?\[(ref)\](?:\[\])?/).replace("ref",Gl).getRegex(),Ix=Z("reflink|nolink(?!\\()","g").replace("reflink",hp).replace("nolink",pp).getRegex(),Qh=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,$l={_backpedal:wn,anyPunctuation:_x,autolink:Tx,blockSkip:lx,br:lp,code:nx,del:wn,delLDelim:wn,delRDelim:wn,emStrongLDelim:cx,emStrongRDelimAst:px,emStrongRDelimUnd:bx,escape:tx,link:kx,nolink:pp,punctuation:ox,reflink:hp,reflinkSearch:Ix,tag:Ax,text:rx,url:wn},Rx={...$l,emStrongLDelim:hx,emStrongRDelimAst:gx,emStrongRDelimUnd:yx,link:Z(/^!?\[(label)\]\((.*?)\)/).replace("label",us).getRegex(),reflink:Z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",us).getRegex()},Ml={...$l,emStrongRDelimAst:fx,emStrongLDelim:dx,delLDelim:wx,delRDelim:Ex,url:Z(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Qh).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Z(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Qh).getRegex()},Cx={...Ml,br:Z(lp).replace("{2,}","*").getRegex(),text:Z(Ml.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ds={normal:Fl,gfm:Jw,pedantic:ex},Vr={normal:$l,gfm:Ml,breaks:Cx,pedantic:Rx},Nx={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Jh=t=>Nx[t];function gt(t,e){if(e){if(Ne.escapeTest.test(t))return t.replace(Ne.escapeReplace,Jh)}else if(Ne.escapeTestNoEncode.test(t))return t.replace(Ne.escapeReplaceNoEncode,Jh);return t}function ep(t){try{t=encodeURI(t).replace(Ne.percentDecode,"%")}catch{return null}return t}function tp(t,e){let n=t.replace(Ne.findPipe,(i,s,a)=>{let l=!1,c=s;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Ne.splitPipe),o=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(Ne.slashPipe,"|");return r}function Ht(t,e,n){let r=t.length;if(r===0)return"";let o=0;for(;o<r;){let i=t.charAt(r-o-1);if(i===e&&!n)o++;else if(i!==e&&n)o++;else break}return t.slice(0,r-o)}function np(t){let e=t.split(`
3604
+ `),n=e.length-1;for(;n>=0&&Ne.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
3605
+ `)}function Ox(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function Mx(t,e=0){let n=e,r="";for(let o of t)if(o===" "){let i=4-n%4;r+=" ".repeat(i),n+=i}else r+=o,n++;return r}function rp(t,e,n,r,o){let i=e.href,s=e.title||null,a=t[1].replace(o.other.outputLinkReplace,"$1"),l=t[0].charAt(0)==="!";r.state.inLink=!0;let c=r.state.linkEmitted,u=r.state.inRawBlock;r.state.linkEmitted=!1;let m=r.inlineTokens(a),w=r.state.linkEmitted;if(r.state.linkEmitted=c,r.state.inLink=!1,!l){if(w){r.state.inRawBlock=u;return}r.state.linkEmitted=!0}return{type:l?"image":"link",raw:n,href:i,title:s,text:a,tokens:m}}function Lx(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let o=r[1];return e.split(`
3606
+ `).map(i=>{let s=i.match(n.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=o.length?i.slice(o.length):i}).join(`
3607
+ `)}var hs=class{options;rules;lexer;constructor(t){this.options=t||En}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=this.options.pedantic?e[0]:np(e[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=Lx(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=Ht(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:Ht(e[0],`
3608
+ `),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:Ht(e[0],`
3609
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=Ht(e[0],`
3610
+ `).split(`
3611
+ `),r="",o="",i=[];for(;n.length>0;){let s=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),s=!0;else if(!s)a.push(n[l]);else break;n=n.slice(l);let c=a.join(`
3612
+ `),u=c.replace(this.rules.other.blockquoteSetextReplace,`
3613
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
3614
+ ${c}`:c,o=o?`${o}
3615
+ ${u}`:u;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,i,!0),this.lexer.state.top=m,n.length===0)break;let w=i.at(-1);if(w?.type==="code")break;if(w?.type==="blockquote"){let p=w,h=n.join(`
3616
+ `),g=p.raw+`
3617
+ `+h.replace(this.rules.other.blockquoteSetextReplace2,""),x=this.blockquote(g);i[i.length-1]=x,r=`${r}
3618
+ ${h}`,o=o.substring(0,o.length-p.text.length)+x.text;break}else if(w?.type==="list"){let p=w,h=p.raw+`
3619
+ `+n.join(`
3620
+ `),g=this.list(h);i[i.length-1]=g,r=r.substring(0,r.length-w.raw.length)+g.raw,o=o.substring(0,o.length-p.raw.length)+g.raw,n=h.substring(i.at(-1).raw.length).split(`
3621
+ `);continue}}return{type:"blockquote",raw:r,tokens:i,text:o}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,o={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let i=this.rules.other.listItemRegex(n),s=!1;for(;t;){let l=!1,c="",u="";if(!(e=i.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=Mx(e[2].split(`
3622
+ `,1)[0],e[1].length),w=t.split(`
3623
+ `,1)[0],p=!m.trim(),h=0;if(this.options.pedantic?(h=2,u=m.trimStart()):p?h=e[1].length+1:(h=m.search(this.rules.other.nonSpaceChar),h=h>4?1:h,u=m.slice(h),h+=e[1].length),p&&this.rules.other.blankLine.test(w)&&(c+=w+`
3624
+ `,t=t.substring(w.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(h),x=this.rules.other.hrRegex(h),T=this.rules.other.fencesBeginRegex(h),S=this.rules.other.headingBeginRegex(h),L=this.rules.other.htmlBeginRegex(h),z=this.rules.other.blockquoteBeginRegex(h);for(;t;){let v=t.split(`
3625
+ `,1)[0],A;if(w=v,this.options.pedantic?(w=w.replace(this.rules.other.listReplaceNesting," "),A=w):A=w.replace(this.rules.other.tabCharGlobal," "),T.test(w)||S.test(w)||L.test(w)||z.test(w)||g.test(w)||x.test(w))break;if(A.search(this.rules.other.nonSpaceChar)>=h||!w.trim())u+=`
3626
+ `+A.slice(h);else{if(p||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||T.test(m)||S.test(m)||x.test(m))break;u+=`
3627
+ `+w}p=!w.trim(),c+=v+`
3628
+ `,t=t.substring(v.length+1),m=A.slice(h)}}o.loose||(s?o.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),o.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=c}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let l of o.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!o.loose){let c=l.tokens.filter(m=>m.type==="space"),u=c.length>0&&c.some(m=>this.rules.other.anyLine.test(m.raw));o.loose=u}for(let l of o.items){let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let m={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=m.checked,o.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=m.raw+l.tokens[0].raw,l.tokens[0].text=m.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(m)):l.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):l.tokens.unshift(m)}}else l.task&&(l.task=!1)}if(o.loose)for(let l of o.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=np(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:Ht(e[0],`
3629
+ `),href:r,title:o}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=tp(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
3630
+ `):[],i={type:"table",raw:Ht(e[0],`
3631
+ `),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?i.align.push("right"):this.rules.other.tableAlignCenter.test(s)?i.align.push("center"):this.rules.other.tableAlignLeft.test(s)?i.align.push("left"):i.align.push(null);for(let s=0;s<n.length;s++)i.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:i.align[s]});for(let s of o)i.rows.push(tp(s,i.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:i.align[l]})));return i}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:Ht(e[0],`
3632
+ `),depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
3633
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Ht(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=Ox(e[2],"()");if(i===-2)return;if(i>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],o="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],o=i[3])}else o=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),rp(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[r.toLowerCase()];if(!o){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return rp(n,o,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=0,c=r[0][0],u=n===c,m=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,e=e.slice(-1*t.length+o);(r=m.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(s=[...i].length,r[3]||r[4]){a+=s;continue}else if(r[5]||r[6]){if(o%3&&!((o+s)%3)){l+=s;continue}if(u)break}if(a-=s,a>0)continue;s=Math.min(s,s+a+l);let w=[...r[0]][0].length,p=t.slice(0,o+r.index+w+s);if(Math.min(o,s)%2){let g=p.slice(1,-1);return{type:"em",raw:p,text:g,tokens:this.lexer.inlineTokens(g)}}let h=p.slice(2,-2);return{type:"strong",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),o=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&o&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+o);(r=l.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(s=[...i].length,s!==o))continue;if(r[3]||r[4]){a+=s;continue}if(a-=s,a>0)continue;s=Math.min(s,s+a);let c=[...r[0]][0].length,u=t.slice(0,o+r.index+c+s),m=u.slice(o,-o);return{type:"del",raw:u,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let o;do o=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(o!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},ot=class Ll{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||En,this.options.tokenizer=this.options.tokenizer||new hs,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let n={other:Ne,block:ds.normal,inline:Vr.normal};this.options.pedantic?(n.block=ds.pedantic,n.inline=Vr.pedantic):this.options.gfm&&(n.block=ds.gfm,this.options.breaks?n.inline=Vr.breaks:n.inline=Vr.gfm),this.tokenizer.rules=n}static get rules(){return{block:ds,inline:Vr}}static lex(e,n){return new Ll(n).lex(e)}static lexInline(e,n){return new Ll(n).inlineTokens(e)}lex(e){e=e.replace(Ne.carriageReturn,`
3634
+ `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Ne.tabCharGlobal," ").replace(Ne.spaceLine,""));let o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(a=>(i=a.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let a=n.at(-1);i.raw.length===1&&a!==void 0?a.raw+=`
3635
+ `:n.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
3636
+ `)?"":`
3637
+ `)+i.raw,a.text+=`
3638
+ `+i.text,this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
3639
+ `)?"":`
3640
+ `)+i.raw,a.text+=`
3641
+ `+i.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},n.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),n.push(i);continue}let s=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),c;this.options.extensions.startBlock.forEach(u=>{c=u.call({lexer:this},l),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(s=e.substring(0,a+1))}if(this.state.top&&(i=this.tokenizer.paragraph(s))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
3642
+ `)?"":`
3643
+ `)+i.raw,a.text+=`
3644
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i),r=s.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
3645
+ `)?"":`
3646
+ `)+i.raw,a.text+=`
3647
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}linkInText(e){if(!e.includes("["))return!1;let n=this.tokenizer.rules.inline.link;for(let r of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(n.test(r[0])&&e.charAt(r.index-1)!=="!")return!0;for(let r of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let o=r[0],i=o.lastIndexOf("[");if(!(o.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,o.slice(i+1,-1)))&&!(i>1&&this.linkInText(o.slice(1,i-1))))return!0}return!1}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e;if(this.tokens.links&&e.includes("[")){let a=this.tokenizer.rules.inline.reflinkSearch,l=c=>{let u=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(u+1,-1)))return c;if(u>1&&c.charAt(0)!=="!"){let m=c.slice(1,u-1);if(this.linkInText(m))return"["+m.replace(a,l)+"]["+"a".repeat(c.length-u-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};r=r.replace(a,l)}r=r.replace(this.tokenizer.rules.inline.anyPunctuation,a=>"+".repeat(a.length)),r=r.replace(this.tokenizer.rules.inline.blockSkip,(a,l,c)=>{let u=c?c.length:0;return a.slice(0,u)+"["+"a".repeat(a.length-u-2)+"]"}),r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,i="",s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}o||(i=""),o=!1;let a;if(this.options.extensions?.inline?.some(c=>(a=c.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let c=n.at(-1);a.type==="text"&&c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,r,i)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,r,i)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let l=e;if(this.options.extensions?.startInline){let c=1/0,u=e.slice(1),m;this.options.extensions.startInline.forEach(w=>{m=w.call({lexer:this},u),typeof m=="number"&&m>=0&&(c=Math.min(c,m))}),c<1/0&&c>=0&&(l=e.substring(0,c+1))}if(a=this.tokenizer.inlineText(l)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(i=a.raw.slice(-1)),o=!0;let c=n.at(-1);c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):n.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}infiniteLoopError(e){let n="Infinite loop on byte: "+e;if(this.options.silent)console.error(n);else throw new Error(n)}},ps=class{options;parser;constructor(t){this.options=t||En}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(Ne.notSpaceStart)?.[0],o=t.replace(Ne.endingNewline,"")+`
3648
+ `;return r?'<pre><code class="language-'+gt(r)+'">'+(n?o:gt(o,!0))+`</code></pre>
3649
+ `:"<pre><code>"+(n?o:gt(o,!0))+`</code></pre>
3650
+ `}blockquote({tokens:t}){return`<blockquote>
3651
+ ${this.parser.parse(t)}</blockquote>
3652
+ `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
3653
+ `}hr(t){return`<hr>
3654
+ `}list(t){let e=t.ordered,n=t.start,r="";for(let s=0;s<t.items.length;s++){let a=t.items[s];r+=this.listitem(a)}let o=e?"ol":"ul",i=e&&n!==1?' start="'+n+'"':"";return"<"+o+i+`>
3655
+ `+r+"</"+o+`>
3656
+ `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
3657
+ `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
3658
+ `}table(t){let e="",n="";for(let o=0;o<t.header.length;o++)n+=this.tablecell(t.header[o]);e+=this.tablerow({text:n});let r="";for(let o=0;o<t.rows.length;o++){let i=t.rows[o];n="";for(let s=0;s<i.length;s++)n+=this.tablecell(i[s]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
3659
+ <thead>
3660
+ `+e+`</thead>
3661
+ `+r+`</table>
3662
+ `}tablerow({text:t}){return`<tr>
3663
+ ${t}</tr>
3664
+ `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
3665
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${gt(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),o=ep(t);if(o===null)return r;t=o;let i='<a href="'+t+'"';return e&&(i+=' title="'+gt(e)+'"'),i+=">"+r+"</a>",i}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=ep(t);if(o===null)return gt(n);t=o;let i=`<img src="${t}" alt="${gt(n)}"`;return e&&(i+=` title="${gt(e)}"`),i+=">",i}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:gt(t.text)}},Bl=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},it=class Pl{options;renderer;textRenderer;constructor(e){this.options=e||En,this.options.renderer=this.options.renderer||new ps,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Bl}static parse(e,n){return new Pl(n).parse(e)}static parseInline(e,n){return new Pl(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let s=o,a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(s.type)){n+=a||"";continue}}let i=o;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let s='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<e.length;o++){let i=e[o];if(this.options.extensions?.renderers?.[i.type]){let a=this.options.extensions.renderers[i.type].call({parser:this},i);if(a!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(i.type)){r+=a||"";continue}}let s=i;switch(s.type){case"escape":{r+=n.text(s);break}case"html":{r+=n.html(s);break}case"link":{r+=n.link(s);break}case"image":{r+=n.image(s);break}case"checkbox":{r+=n.checkbox(s);break}case"strong":{r+=n.strong(s);break}case"em":{r+=n.em(s);break}case"codespan":{r+=n.codespan(s);break}case"br":{r+=n.br(s);break}case"del":{r+=n.del(s);break}case"text":{r+=n.text(s);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},jr=class{options;block;constructor(t){this.options=t||En}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?ot.lex:ot.lexInline}provideParser(t=this.block){return t?it.parse:it.parseInline}},Vl=class{defaults=Dl();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=it;Renderer=ps;TextRenderer=Bl;Lexer=ot;Tokenizer=hs;Hooks=jr;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let o=r;for(let i of o.header)n=n.concat(this.walkTokens(i.tokens,e));for(let i of o.rows)for(let s of i)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let o=r;n=n.concat(this.walkTokens(o.items,e));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(i=>{let s=o[i].flat(1/0);n=n.concat(this.walkTokens(s,e))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let i=e.renderers[o.name];i?e.renderers[o.name]=function(...s){let a=o.renderer.apply(this,s);return a===!1&&(a=i.apply(this,s)),a}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[o.level];i?i.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),r.extensions=e),n.renderer){let o=this.defaults.renderer||new ps(this.defaults);for(let i in n.renderer){if(!(i in o))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let s=i,a=n.renderer[s],l=o[s];o[s]=(...c)=>{let u=a.apply(o,c);return u===!1&&(u=l.apply(o,c)),u||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new hs(this.defaults);for(let i in n.tokenizer){if(!(i in o))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let s=i,a=n.tokenizer[s],l=o[s];o[s]=(...c)=>{let u=a.apply(o,c);return u===!1&&(u=l.apply(o,c)),u}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new jr;for(let i in n.hooks){if(!(i in o))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let s=i,a=n.hooks[s],l=o[s];jr.passThroughHooks.has(i)?o[s]=c=>{if(this.defaults.async&&jr.passThroughHooksRespectAsync.has(i))return(async()=>{let m=await a.call(o,c);return l.call(o,m)})();let u=a.call(o,c);return l.call(o,u)}:o[s]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,c);return m===!1&&(m=await l.apply(o,c)),m})();let u=a.apply(o,c);return u===!1&&(u=l.apply(o,c)),u}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,i=n.walkTokens;r.walkTokens=function(s){let a=[];return a.push(i.call(this,s)),o&&(a=a.concat(o.call(this,s))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return ot.lex(t,e??this.defaults)}parser(t,e){return it.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=t),o.async)return(async()=>{let s=o.hooks?await o.hooks.preprocess(e):e,a=await(o.hooks?await o.hooks.provideLexer(t):t?ot.lex:ot.lexInline)(s,o),l=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(l,o.walkTokens));let c=await(o.hooks?await o.hooks.provideParser(t):t?it.parse:it.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(i);try{o.hooks&&(e=o.hooks.preprocess(e));let s=(o.hooks?o.hooks.provideLexer(t):t?ot.lex:ot.lexInline)(e,o);o.hooks&&(s=o.hooks.processAllTokens(s)),o.walkTokens&&this.walkTokens(s,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(t):t?it.parse:it.parseInline)(s,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(s){return i(s)}}}onError(t,e){return n=>{if(n.message+=`
3666
+ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+gt(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},xn=new Vl;function oe(t,e){return xn.parse(t,e)}oe.options=oe.setOptions=function(t){return xn.setOptions(t),oe.defaults=xn.defaults,op(oe.defaults),oe};oe.getDefaults=Dl;oe.defaults=En;function Px(...t){return xn.use(...t),oe.defaults=xn.defaults,op(oe.defaults),oe}oe.use=Px;oe.walkTokens=function(t,e){return xn.walkTokens(t,e)};oe.parseInline=xn.parseInline;oe.Parser=it;oe.parser=it.parse;oe.Renderer=ps;oe.TextRenderer=Bl;oe.Lexer=ot;oe.lexer=ot.lex;oe.Tokenizer=hs;oe.Hooks=jr;oe.parse=oe;var zI=oe.options,FI=oe.setOptions,$I=oe.walkTokens,BI=oe.parseInline;var VI=it.parse,jI=ot.lex;var Dx=new Vl({gfm:!0,breaks:!0}),fp=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],mp=["href","title","class","target","rel"],gp={ALLOWED_TAGS:fp,ALLOWED_ATTR:mp,ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1},Ux={...gp,ALLOWED_TAGS:[...fp,"img"],ALLOWED_ATTR:[...mp,"src","alt","width","height"]},Hx=/^language-[A-Za-z0-9_+#.-]+$/,Gx=new Set(["CODE","PRE"]);function zx(t){t.nodeName==="A"&&t.hasAttribute("href")?(t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer")):(t.removeAttribute("target"),t.removeAttribute("rel"));let e=t.getAttribute("class");if(e===null)return;let n=Gx.has(t.nodeName)?e.split(/\s+/).filter(r=>Hx.test(r)):[];if(n.length===0){t.removeAttribute("class");return}t.setAttribute("class",n.join(" "))}var ms=null;function Fx(){return ms===null&&(ms=Kh(),ms.addHook("afterSanitizeAttributes",zx)),ms}function gs(t,e){let n=e?.allowImages===!0,r=Dx.parse(t,{async:!1});return Fx().sanitize(r,n?Ux:gp).trim()}function bp(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):bp(n,e)}function vp(t){let e=[];bp(t,e);let n=0;for(let{node:r,parent:o}of e){let i=document.createDocumentFragment();for(let s of r.data.split(/(\s+)/)){if(s==="")continue;if(/\s/.test(s)){i.appendChild(document.createTextNode(s));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=s,i.appendChild(a),n+=1}o.replaceChild(i,r)}}function yp({viewport:t,onMissedContent:e}){let n=!0,r=!1,o=()=>t.scrollHeight-t.scrollTop-t.clientHeight<=4,i=u=>{u!==r&&(r=u,e(r))},s=()=>{t.scrollTop=t.scrollHeight},a=()=>{n=o(),n&&i(!1)},l=()=>{if(n){s();return}i(!0)};t.addEventListener("scroll",a,{passive:!0});let c=new ResizeObserver(()=>{n&&s()});return c.observe(t),{follow:l,jump:()=>{n=!0,i(!1),s()},following:()=>n,dispose:()=>{t.removeEventListener("scroll",a),c.disconnect()}}}var $x=4,Bx=120;function wp(t){if(typeof t!="object"||t===null)return null;let e=t.prompts;if(!Array.isArray(e))return null;let n=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r!==""&&r.length<=120).slice(0,4);return n.length===0?null:n}function bs(t,e,n){let r=wp(t);if(r===null)return null;let o=document.createElement("div");o.className="suggestions",o.setAttribute("part","suggestions"),o.setAttribute("role","group"),o.setAttribute("aria-label",e.suggestions);for(let i of r){let s=document.createElement("button");s.type="button",s.className="suggestion-chip",s.setAttribute("part","suggestion-chip"),s.textContent=i,s.addEventListener("click",()=>n(i)),o.appendChild(s)}return o}var vs=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},sr=class{#t;#n;#e;#s;#r;#i;#o;#u=new Set;#h=new Map;#l;#c;#d=!1;constructor(e){this.#t=e.agent,this.#n=e.handlers,this.#e=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#i=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#l=e.connectionLostMessage??"Connection lost";let n=e.maxToolRounds??Nn;this.#c=n>=1?Math.floor(n):Nn;let r=e.onStateChanged;r!==void 0&&this.#t.subscribe({onStateChanged:({state:o})=>{r(o)}})}get state(){return this.#t.state}setState(e){this.#t.setState({...e})}get running(){return this.#t.isRunning}get messages(){return this.#t.messages}async send(e,n=[]){let r={id:Ie(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#t.addMessage(r),this.#m(),await this.#p()}truncateToLastUser(){let e=[...this.#t.messages],n=-1;for(let[o,i]of e.entries())i.role==="user"&&(n=o);if(n===-1)return null;let r=e.slice(0,n+1);return this.#t.setMessages(r),this.#m(),r}async resume(){await this.#p()}addToolResult(e,n){this.#t.addMessage({id:Ie(),role:"tool",content:n,toolCallId:e}),this.#m()}cancel(){this.#d=!0,this.#t.abortRun()}async#p(){this.#d=!1;try{await this.#N(),this.#d&&this.#y()}catch(e){this.#d||Vx(e)?this.#y():this.#n.onError(e instanceof Error?e.message:String(e))}finally{this.#n.onSettled()}}#y(){this.#m(),this.#n.onCancelled()}#m(){let e=this.#t.messages;if(this.#h.size===0){this.#o(e);return}this.#o(e.map(n=>{if(n.role!=="tool")return n;let r=this.#h.get(n.toolCallId);return r===void 0?n:{...n,outcome:r}}))}async#N(){let e;for(let n=0;n<this.#c;n+=1){if(this.#d)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#e(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#t.runAgent(i,this.#T(r,o)),e=void 0,this.#m(),this.#d)return;if(!o.terminal)throw new vs(this.#l);if(o.errored)return;if(o.interrupts.length>0){if(this.#i===null)return;let a=await this.#i(o.interrupts);if(this.#d)return;e=eh(o.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;l.outcome!==void 0&&this.#h.set(a.id,l.outcome),this.#t.addMessage({id:Ie(),role:"tool",content:l.content,toolCallId:a.id}),this.#m(),s=!0}}if(!s)return}}#T(e,n){let r=this.#n,o=this.#u,i=this.#h,s=()=>this.#d,a=new Set;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:l}){o.has(l.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${l.messageId}", which was already closed. Its content will be appended to that earlier message rather than starting a new one, and the merged result is what gets persisted. Issue a fresh id per message.`)},onTextMessageContentEvent({textMessageBuffer:l}){r.onTextDelta(l)},onTextMessageEndEvent({event:l,textMessageBuffer:c}){o.add(l.messageId),r.onTextEnd(c)},onToolCallEndEvent({event:l,toolCallName:c,toolCallArgs:u}){let m={id:l.toolCallId,name:c,args:u};e.push(m),r.onToolCall(m)},onToolCallResultEvent({event:l}){let c=l.outcome;typeof c=="string"&&i.set(l.toolCallId,c),r.onToolResult(l.toolCallId,l.content,c)},onActivitySnapshotEvent({event:l,messages:c}){if(c.some(m=>m.id===l.messageId&&m.role==="activity")){r.onActivityChanged(l.messageId,l.activityType,l.content);return}r.onActivity(l.activityType,l.content,l.messageId)},onActivityDeltaEvent({event:l}){a.add(l.messageId)},onCustomEvent({event:l}){r.onCustomEvent(l.name,l.value)},onSubagentStartedEvent({event:l}){r.onSubAgentStarted(l.subagentRunId,l.name,l.parentToolCallId??null)},onSubagentFinishedEvent({event:l}){r.onSubAgentFinished(l.subagentRunId)},onSubagentErrorEvent({event:l}){r.onSubAgentError(l.subagentRunId,l.message)},onMessagesSnapshotEvent({event:l}){r.onMessagesSnapshot(l.messages)},onMessagesChanged({messages:l}){if(a.size!==0){for(let c of a){let u=l.find(m=>m.id===c);u!==void 0&&u.role==="activity"&&r.onActivityChanged(c,u.activityType,u.content)}a.clear()}},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningMessageEndEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(l){n.terminal=!0,l.outcome==="interrupt"&&(n.interrupts=l.interrupts)},onRunErrorEvent({event:l}){n.terminal=!0,n.errored=!0,!s()&&r.onError(l.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Vx(t){return t instanceof Error?t.name==="AbortError"||t instanceof TypeError&&/abort/i.test(t.message):!1}function jl(t){let e=t.attachments;return Array.isArray(e)?e.filter(jx):[]}function jx(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.name=="string"&&typeof e.mime=="string"&&typeof e.size=="number"&&(e.url===void 0||typeof e.url=="string")}var xp="ag-ui-chat",ar="thread",ql="threads",Xr="messages:",ws="checkpoint:",Yr="minted:",qx=60,Wx=100,Xx="New conversation",Ep=!1;function bt(t,e){try{sessionStorage.setItem(t,e)}catch{if(Ep)return;Ep=!0,console.warn("<ag-ui-chat>: the browser refused a sessionStorage write \u2014 the quota is full, or storage is disabled for this context. The conversation continues, but it will not survive a page reload. Deleting a long conversation from the history drawer frees the quota.")}}function ys(t){return t===""?xp:`${xp}@${t}`}var Ze=class t{#t;constructor(e=""){this.#t=ys(e),e!==""&&t.adopt("",e)}static adopt(e,n){let r=`${ys(e)}:`,o=`${ys(n)}:`;for(let[i,s]of _p(r)){let a=sessionStorage.getItem(i),l=o+s;a!==null&&sessionStorage.getItem(l)===null&&bt(l,a),sessionStorage.removeItem(i)}}static purge(e){for(let[n]of _p(`${ys(e)}:`))sessionStorage.removeItem(n)}threadId(){return sessionStorage.getItem(this.#r(ar))??this.newThread()}newThread(){let e=Ie();return bt(this.#r(ar),e),bt(this.#r(Yr+e),"1"),e}isUnsent(e){return sessionStorage.getItem(this.#r(Yr+e))!==null&&sessionStorage.getItem(this.#r(Xr+e))===null}loadMessages(e){return Promise.resolve(this.#i(this.#r(Xr+e)))}saveMessages(e,n){bt(this.#r(Xr+e),JSON.stringify(n)),sessionStorage.removeItem(this.#r(Yr+e)),this.#n(e,n)}loadCheckpoint(e){return this.#i(this.#r(ws+e))}saveCheckpoint(e,n){let r=this.#r(ws+e);if(n===null){sessionStorage.removeItem(r);return}bt(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Xr+e)),sessionStorage.removeItem(this.#r(ws+e)),sessionStorage.removeItem(this.#r(Yr+e)),this.#s(this.#e().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(ar))===e&&sessionStorage.removeItem(this.#r(ar))}listThreads(){let e=this.#e().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){bt(this.#r(ar),e)}renameThread(e,n){let r=this.#e(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#s(r))}#n(e,n){let r=this.#e(),o=r.find(a=>a.threadId===e),i=Kx(n),s=Date.now();o===void 0?r.push({threadId:e,title:Tp(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=Tp(n))),this.#s(r)}#e(){return this.#i(this.#r(ql))??[]}#s(e){let n=this.#r(ql);if(e.length===0){sessionStorage.removeItem(n);return}bt(n,JSON.stringify(e))}#r(e){return`${this.#t}:${e}`}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function _p(t){let e=[];for(let n=0;n<sessionStorage.length;n+=1){let r=sessionStorage.key(n);if(r===null||!r.startsWith(t))continue;let o=r.slice(t.length);Yx(o)&&e.push([r,o])}return e}function Yx(t){return t===ar||t===ql||t.startsWith(Xr)||t.startsWith(ws)||t.startsWith(Yr)}function Tp(t){for(let e of t)if(e.role==="user"){let n=Sp(e.content);if(n!=="")return Ap(n,qx)}return Xx}function Kx(t){for(let e of[...t].reverse()){let n=Sp(e.content);if(n!=="")return Ap(n,Wx)}return""}function Sp(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Ap(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Qe(t,e){return e===void 0?t:{...t,credentials:e}}function xs(t){if(t.newThread!==void 0)return t.newThread();let e=Ie();return t.setActiveThread(e),e}function Es(t,e,n,r){if(e.length===0)return;let o=new URL(String(t),location.href).origin;o===location.origin||n.includes(o)||r.has(o)||(r.add(o),console.warn(`<ag-ui-chat>: sending host credentials (${e.join(", ")}) to ${o}, which is not this page's origin (${location.origin}). Those headers are the page's own authentication, and whichever server answers the browser's preflight receives them \u2014 so a URL attribute built from a query parameter or from tenant-authored configuration is a channel for the token to leave on. If this destination is deliberate, name it in \`trustedOrigins\` to confirm it and silence this notice. Reported once per origin.`))}function Wl(t){let e=t.headers??{},n=new Set;return new th({url:t.endpoint,headers:e,initialState:{...t.initialState??{}},fetch:(r,o)=>{let i=t.getHeaders?.(),s=[...new Set([...Object.keys(e),...Object.keys(i??{})])].sort();if(Es(r,s,t.trustedOrigins??[],n),i===void 0)return fetch(r,Qe(o,t.credentials));let a=new Headers(o?.headers);for(let[l,c]of Object.entries(i))a.set(l,c);return fetch(r,Qe({...o,headers:a},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var Kr=class{#t;#n;#e;#s;#r;#i=new Set;#o=new Map;constructor(e,n=()=>({}),r=new Ze,o=()=>{},i=!0){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r,this.#s=o,this.#r=i}threadId(){return this.#e.threadId()}setActiveThread(e){this.#e.setActiveThread(e)}newThread(){return xs(this.#e)}isUnsent(e){return this.#e.isUnsent?.(e)===!0}saveMessages(e,n){this.#e.saveMessages(e,this.#r?n:[])}loadCheckpoint(e){return this.#e.loadCheckpoint(e)}saveCheckpoint(e,n){this.#e.saveCheckpoint(e,n)}renameThread(e,n){this.#e.renameThread(e,n),this.#o.set(e,n),this.#d(e,"PATCH",{title:n})}clear(e){this.#e.clear(e),this.#i.add(e),this.#d(e,"DELETE")}async listThreads(){let e=await this.#u();return e===null?this.#e.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#l(n))}async loadMessages(e){if(this.#e.isUnsent?.(e)===!0)return null;let n=await this.#c(`${this.#t}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#e.loadMessages(e);let r=await this.#h(n);return r===null?this.#e.loadMessages(e):r.messages??null}async#u(){let e=await this.#c(this.#t);if(e===null||!e.ok)return null;let n=await this.#h(e);return n===null?null:n.threads??[]}async#h(e){try{return await e.json()}catch{return null}}#l(e){return{threadId:e.thread_id,title:this.#o.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#c(e){try{return await fetch(e,Qe({headers:this.#n()},this.#s()))}catch{return null}}async#d(e,n,r){let o=this.#n();try{await fetch(`${this.#t}${encodeURIComponent(e)}/`,Qe({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#s()))}catch{}}};var Zr=class{#t;#n;#e;constructor(e,n=()=>({}),r=()=>{}){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r}async list(){try{let e=await fetch(this.#t,Qe({method:"GET",headers:{Accept:"application/json",...this.#n()}},this.#e()));return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#s("resume",e)}forkUrl(e){return this.#s("fork",e)}#s(e,n){return`${this.#t.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};function _s(t){return t===It.FAILED?re.ERROR:t===It.DENIED?re.DECLINED:re.DONE}async function Xl(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,Qe({method:"POST",headers:{...e.headers??{}},body:n},e.credentials));if(!r.ok)throw new Error(await Zx(r));let o=await r.json();if(typeof o=="object"&&o!==null&&typeof o.text=="string")return o.text;throw new Error("transcription returned an unreadable response")}async function Zx(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Yl(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url),i.withCredentials=e.credentials==="include";for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Qx(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Jx(i)))}),i.addEventListener("error",()=>r(new Error("upload failed"))),i.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>i.abort()),i.send(o)})}function Qx(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,i=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:o,size:i,url:s}:{id:n,name:r,mime:o,size:i}}function Jx(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var eE=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-threads-cache","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],ec=["omit","same-origin","include"];function Kl(t){return ec.includes(t)}var kp="ag-ui-chat:collapsed",Ip="ag-ui-chat:size",Rp="ag-ui-chat:theme",Zl="ag-ui-chat:launcher";function tE(t){if(typeof t!="object"||t===null)return null;let{left:e,top:n}=t;return typeof e=="number"&&typeof n=="number"?{left:e,top:n}:null}var Cp=new Set([null,"","floating","bottom-left"]),nE=[{y:"top"},{y:"bottom"},{x:"left"},{x:"right"},{x:"left",y:"top"},{x:"right",y:"top"},{x:"left",y:"bottom"},{x:"right",y:"bottom"}],Ql=6,Jl=new Set,Qr=class extends HTMLElement{agentFactory=Wl;headers={};getHeaders=null;trustedOrigins=[];allowImages=!1;formatRelativeTime=null;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;approveWithEdits=!1;confirmPredicate=null;getTools=()=>[...this.#At().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#r.tools()];getContext=()=>[...rl(this.getPageMap,this.autoInjectPageMap)];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Ze;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};formatToolPayload=null;strings={};resolvePageTarget=e=>document.querySelector(e);#t={};#n=new Set;#e=ae;#s=new Set;#r=new Ir;#i=new Map;#o=new Map;#u=new Map;#h=new Map;#l=new Set;#c=new Map;#d=new Map;#p=new Set;#y=[];#m=new Set;#N=null;#T=new Set;#x;#G=document.createElement("div");#le=document.createElement("div");#z=document.createElement("button");#b=document.createElement("button");#je="";#ce=null;#Ie=document.createElement("div");#w;#K=null;#Re=!1;#E;#v;#a;#S;#Ce;#F;#R;#A;#qe=null;#C;#O;#M;#Ne;#$;#f;#B;#de=document.createElement("span");#Oe=0;#Z;#k=null;#_=null;#ue=[];#Q=[];#V=document.createElement("div");#J=null;#D=null;#ee=null;#te={x:"right",y:"bottom"};#xt=new Map;#he=()=>{this.#Ut(),!this.#dn()&&(this.#st(),this.#R.isOpen()&&(this.#R.setModal(!this.#dt()),this.#ut()))};#cn(e){let n=this.#L(),r=n.left+Je,o=n.top+Je,i=n.left+n.width-Je,s=n.top+n.height-Je;return{left:Math.min(Math.max(e.left,r),e.right),top:Math.min(Math.max(e.top,o),e.bottom),right:Math.max(Math.min(e.right,i),e.left),bottom:Math.max(Math.min(e.bottom,s),e.top)}}#dn(){return this.#f.hasAttribute("data-dragging")||this.#x.querySelector(".header[data-dragging]")!==null}#Me;#We=null;#pe=!1;#ne=null;#fe={};#W=!1;#Xe=null;#U=null;#Le=null;#Ye=0;#Pe="";#re=null;#De=null;#j=null;#oe=null;#g="";#me="";#Ue=null;#Ke="";#Et="";#ye=null;#Ze=0;#Qe=[];#_t=[];#Tt=[];#St=[];constructor(){super(),this.#x=this.attachShadow({mode:"open"}),this.#E=document.createElement("div"),this.#v=document.createElement("div"),this.#a=document.createElement("textarea"),this.#S=document.createElement("button"),this.#Ce=document.createElement("span"),this.#C=document.createElement("div"),this.#O=document.createElement("button"),this.#M=document.createElement("input"),this.#Ne=document.createElement("div"),this.#Me=document.createElement("span"),this.#$=document.createElement("button"),this.#f=document.createElement("button"),this.#B=document.createElement("span"),this.#Z=document.createElement("div"),this.registerActivityRenderer({type:ea,render:e=>{let n=aE(e);return n===null?null:xl("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(n)),"compaction")}}),this.registerActivityRenderer({type:Ks,render:e=>bs(e,this.#e,n=>{this.sendMessage(n)})}),this.#F=new es(e=>this.#Un(e)),this.#R=new rs({onSelect:e=>{this.#Jn(e)},onNew:()=>{this.newChat(),this.#Ae()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Ae()},onDelete:e=>{this.#er(e)},onVisibility:()=>{this.#ut()}}),this.#A=new Pr((e,n)=>{this.#un(e,n)})}#Je(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#qe===null&&(this.#qe=new Zr(e,()=>this.#xe(e),()=>this.#He())),this.#qe)}async#un(e,n){let r=this.#Je();if(r===null)return;let o=this.#a.value.trim();if(o===""){this.#C.textContent=this.#e.continueNeedsTurn,this.#C.hidden=!1,this.#a.focus();return}this.#a.value="",this.#Y();let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#g,initialMessages:[]});await new sr({agent:s,handlers:this.#tn(),getTools:()=>this.#kt(),getContext:()=>this.#Xt(),executeTool:l=>this.#Jt(l),resolveInterrupts:l=>this.#en(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#hn(){let e=this.#Je();this.#A.setRelativeTimeFormatter(this.formatRelativeTime),this.#A.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials","user-key",...eE]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Kl(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${ec.join(" / ")}) \u2014 it is being ignored, so requests use the browser default and cross-origin cookies will not be sent.`);return}if(e==="placement"){this.#$n(),this.#Wn(),!this.#ze()&&this.collapsed&&this.setCollapsed(!1),requestAnimationFrame(()=>this.#ge());return}if(e==="title-text"){this.#Ce.textContent=r??this.#e.title,this.#de.textContent=this.#Ce.textContent;return}if(e==="user-key"){this.#pe&&(n??"")!==(r??"")&&this.#Zn(n??"",r??"");return}n===r||!this.#pe||console.warn(`<ag-ui-chat>: "${e}" was changed after the element connected, and is read only while connecting \u2014 this assignment has no effect. Set it before the element enters the DOM (in the markup, or on the element before appending it); frameworks that patch attributes after mount should bind it at creation. To apply a new value now, remove and re-insert the element.`)}registerTool(e){this.#r.register(e)}get sharedState(){return this.#ne?.state??this.#fe}set sharedState(e){this.#fe={...e},this.#ne?.setState(this.#fe)}registerPageState(e){for(let n of Ki(e))this.#r.register(n)}registerStateHook(e){this.registerPageState(e)}#pn(){return this.routeMap.length===0?[]:il(()=>this.routeMap,()=>this.navigate)}#fn(){let e=this.getPageMap;return e===null?[]:[{name:Qs,description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[xe]:"Read the page"},handler:()=>e()}]}#mn(){let e=this.getAttribute("data-page-actions");if(e===null)return[];let n=new Set(e.split(",").map(r=>r.trim()).filter(r=>r!==""));return[...nl(n,r=>this.resolvePageTarget(r)),...n.has(Nr.CHAT)?ja(this):[]]}#At(){return[...this.#pn(),...this.#fn(),...this.#mn(),...this.#gn()]}#gn(){return this.askUser?[{name:"ask_user",description:"Ask the user a question and wait for their answer. Provide `options` for a multiple-choice prompt; set `allow_custom` to also accept a free-text answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user."},options:{type:"array",items:{type:"string"},description:"Preset choices offered as radio buttons."},allow_custom:{type:"boolean",description:"Allow a free-text answer in addition to any options."}},required:["question"]},handler:e=>this.#bn(e)}]:[]}async#bn(e){let r={question:typeof e.question=="string"?e.question:""},o=e.options;Array.isArray(o)&&(r.options=o.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#U=new AbortController;let i=this.#U.signal;this.#H();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await bl(this.#P(),r,{signal:i,strings:this.#e});return this.#U=null,this.#I(),this.#w.follow(),s}#kt(){let e=this.getTools();return this.#s=new Set(e.map(n=>n.name)),e}#et(e){let n=this.#At().find(r=>r.name===e);return n!==void 0?n:this.#r.has(e)?this.#r.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get userKey(){return this.getAttribute("user-key")??""}set userKey(e){this.setAttribute("user-key",e)}get credentials(){let e=this.getAttribute("credentials");return e!==null&&Kl(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Kl(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${ec.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#we(){return{...this.headers,...this.getHeaders?.()}}#xe(e){let n=this.#we();return Es(e,Object.keys(n),this.trustedOrigins,this.#n),n}#He(){return this.credentials??void 0}#Ge(){let e=this.#He();return e===void 0?{}:{credentials:e}}#It(e){return Qe({headers:this.#xe(e)},this.#He())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===On.INLINE||e===On.MINIMAL||e===On.COMPACT?e:On.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#me=this.#Kn(),this.#ot(this.#Bt()),requestAnimationFrame(()=>{this.#st(),this.#ge()}),this.#e=cl({...this.#yn(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#lt(Rp);e!==null&&this.setAttribute("theme",e)}if(this.#ir(),this.#R.setStrings(this.#e),this.#A.setStrings(this.#e),this.#ze()&&this.#Gn()&&this.setAttribute("collapsed",""),this.#Zt(),this.#Pn(),this.conversationStore instanceof Ze){let e=this.#at();this.#ye=e===""?this.conversationStore:new Ze(e),this.conversationStore=this.#ye}window.addEventListener("resize",this.#he),window.visualViewport?.addEventListener("resize",this.#he),window.visualViewport?.addEventListener("scroll",this.#he),this.#Ut(),this.#Ot(),this.#wn(),this.#En(),this.#g=this.conversationStore.threadId(),queueMicrotask(()=>this.#vn()),this.#Fe(),this.#pe=!0}#vn(){this.#pe&&(this.#Mt(),this.#Lt())}async reload(){this.#X(),this.#Se(),this.#ie(!1),await Promise.all([this.#Mt(),this.#Lt(),this.#Fe()])}disconnectedCallback(){this.#pe=!1,window.removeEventListener("resize",this.#he),window.visualViewport?.removeEventListener("resize",this.#he),window.visualViewport?.removeEventListener("scroll",this.#he),this.#Ue!==null&&(Jl.delete(this.#Ue),this.#Ue=null),this.#X(),this.#ce?.detach(),this.#ce=null,this.#k?.dispose(),this.#We?.dispose(),this.#w.dispose(),this.#K!==null&&(clearTimeout(this.#K),this.#K=null)}#Rt(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#Ct(e){let n=this.getAttribute(e);if(n===null)return null;try{return JSON.parse(n)}catch{return console.warn(`<ag-ui-chat>: ${e} is not valid JSON, so it was ignored entirely and the built-in default is being used. Check the quoting -- JSON inside an HTML attribute needs single quotes around the attribute value, or its own double quotes escaped.`),null}}#yn(){let e=this.#Ct("data-strings");return typeof e=="object"&&e!==null?e:{}}#wn(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#xn(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new Ji({upload:n,maxBytes:this.#Rn(),accept:r,strings:this.#e,onChange:()=>this.#fr(o)});this.#k=o,this.#Ne.appendChild(this.#k.element),this.#M.accept=r,this.#O.hidden=!1,this.#Nn(),this.#Ln(o)}#xn(e){return e===null?null:(n,r,o)=>Yl(n,{url:e,headers:this.#xe(e),...this.#Ge(),onProgress:r,signal:o})}#En(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#_n(e);n!==null&&(this.#We=new ts({transcribe:n,onText:r=>this.#Tn(r),strings:this.#e}),this.#Me.appendChild(this.#We.element))}#_n(e){return e===null?null:n=>Xl(n,{url:e,headers:this.#xe(e),...this.#Ge()})}#Tn(e){let n=this.#a.value.trim();this.#a.value=n===""?e:`${n} ${e}`,this.#Qt(),this.#a.focus()}quote(e){let n=ul(e);if(n==="")return;let r=this.#a.value.replace(/\s+$/,"");this.#a.value=r===""?n:`${r}
3667
3667
 
3668
- ${n}`,this.#Y(),this.#a.focus();let o=this.#a.value.length;this.#a.setSelectionRange(o,o)}offerQuoteInPage(e=document.body){this.#le?.detach();let n=yl({within:e,label:this.#e.quoteSelection,exclude:this,onQuote:r=>this.quote(r)});return this.#le=n,()=>{n.detach(),this.#le===n&&(this.#le=null)}}#Sn(){return this.getAttribute("data-quote-selection")!=="false"}#Nt(e){if(!this.#Sn())return;let n=e===void 0?void 0:{x:e.clientX,y:e.clientY},r=Ur(this.#v,[this.#x],n);if(r===null){this.#tt();return}this.#je=r.text,this.#An(r.rect)}#An(e){this.#b.hidden=!1;let n=this.#Ie.getBoundingClientRect(),r=e.top-n.top,o=r<Ql+this.#b.offsetHeight;this.#b.dataset.below=String(o),this.#b.style.top=`${o?e.bottom-n.top+Ql:r-Ql}px`;let i=this.#b.offsetWidth/2,s=e.left+e.width/2-n.left;this.#b.style.left=`${Math.min(Math.max(s,i),n.width-i)}px`}#tt(){this.#b.hidden=!0,this.#je=""}#kn(){let e=this.getAttribute("data-max-tool-rounds");return e===null?Nn:Number.parseInt(e,10)}#In(){let e=this.getAttribute("data-message-actions");return e===null?new Set([$t.COPY,$t.RETRY]):new Set(e.split(",").map(n=>n.trim()).filter(n=>n!==""))}#Rn(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Js;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Js}#Cn(){let e=this.#M.files;if(e!==null)for(let n of Array.from(e))this.#k?.add(n);this.#M.value=""}#Nn(){this.#E.addEventListener("dragover",e=>{e.preventDefault(),this.#E.classList.add("chat--dragover")}),this.#E.addEventListener("dragleave",()=>{this.#E.classList.remove("chat--dragover")}),this.#E.addEventListener("drop",e=>{e.preventDefault(),this.#E.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#k?.add(r)})}#On(e,n,r){let o=this.#Mn(),i=n.getData("text/plain");if(o===null||i.length<o)return;e.preventDefault();let s=new Date().toISOString().replace(/[:.]/g,"-");r.add(new File([i],`pasted-${s}.txt`,{type:"text/plain"}))}#Mn(){let e=this.getAttribute("data-paste-attach");if(e===null)return go;if(e==="off")return null;let n=Number.parseInt(e,10);return Number.isNaN(n)||n<=0?(console.warn(`<ag-ui-chat>: data-paste-attach="${e}" is neither "off" nor a positive number of characters, so the default of ${go} is used.`),go):n}#Ln(e){this.#E.addEventListener("paste",n=>{let r=n.clipboardData??null;if(r===null)return;let o=Array.from(r.files);if(o.length===0){this.#On(n,r,e);return}r.getData("text/plain")===""&&n.preventDefault();for(let i of o)this.#k?.add(iE(i))})}#Ot(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new Kr(e,()=>this.#xe(e),this.conversationStore,()=>this.#He(),this.getAttribute("data-threads-cache")!=="false"))}async#Mt(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#t=ol(await n.json())}catch{}}setSkills(e){this.#St=e,this.#nt()}#Pn(){this.#F.enableChips(this.#Rt("data-prompt-chips")),this.#F.enableSlash(this.#Rt("data-slash-commands")),this.#Tt=this.#Dn(),this.#nt()}#Dn(){return Va(this.#Ct("data-skills"))}async#Lt(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#_t=Va(await n.json()),this.#nt()}catch{}}#nt(){let e=new Map;for(let n of[...this.#_t,...this.#Tt,...this.#St])e.set(n.name,n);this.#F.setSkills([...e.values()])}#Un(e){if(e.prompt===void 0){this.#C.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=nh(e.prompt,this.skillContext());if(r.length>0){this.#C.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#C.hidden=!1,this.#a.value=n,this.#Y(),this.#a.focus(),this.#Hn(n);return}if(this.#C.hidden=!0,this.#a.value=n,this.#Y(),e.sendImmediately===!1){this.#a.focus();return}this.#ft()}#Hn(e){let n=e.indexOf("{");this.#a.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e,n={}){e&&!this.#ze()||(n.announce===!0&&e&&!this.collapsed&&this.#sn(this.#e.chatMinimised,null),e||this.#st(),e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),bt(this.#Te(kp),e?"1":"0"),this.#Be(0),this.dispatchEvent(new CustomEvent($s,{detail:{collapsed:e},bubbles:!0,composed:!0})))}get unread(){return this.#Oe}#Gn(){let e=this.#jt(kp);return e!==null?e==="1":Cp.has(this.getAttribute("placement"))&&!this.hasAttribute("data-start-open")}#ze(){return this.getAttribute("placement")!=="page"}describeSurface(){let e=this.getBoundingClientRect(),n=this.#L(),r=e.width>=n.width-1&&e.height>=n.height-1;return{placement:this.getAttribute("placement"),collapsed:this.collapsed,collapsible:this.#ze(),movable:this.#q()&&!r,draggable:this.#q(),fullBleed:r,box:{left:Math.round(e.left),top:Math.round(e.top),width:Math.round(e.width),height:Math.round(e.height)},viewport:{left:Math.round(n.left),top:Math.round(n.top),width:Math.round(n.width),height:Math.round(n.height)}}}moveTo(e,n={}){if(!this.#q())return!1;let r=n.announce===!0?this.#zn():null,o=this.#L(),i=this.getBoundingClientRect();if(i.width>=o.width-1&&i.height>=o.height-1)return!1;let[s,a]=e.split("-"),l=o.left+Bt,c=o.top+Bt,u=a==="left"?l:Math.max(l,o.left+o.width-Bt-i.width),m=s==="top"?c:Math.max(c,o.top+o.height-Bt-i.height),w={left:u,top:m,right:u+i.width,bottom:m+i.height},p=this.#f.offsetWidth,h=this.#f.offsetHeight;return this.#it(w,{left:a==="left"?w.left:w.right-p,top:s==="top"?w.top:w.bottom-h,width:p,height:h}),this.#_e(),r!==null&&this.#sn(this.#e.chatMoved,r),!0}#zn(){let e=this.style.getPropertyValue("--ag-ui-inset"),n=this.style.getPropertyValue("--ag-ui-launcher-inset"),r=this.getAttribute("data-expand-corner"),o=this.#_,i=this.#D,s=this.#ee;return()=>{let a=(l,c)=>{c===""?this.style.removeProperty(l):this.style.setProperty(l,c)};a("--ag-ui-inset",e),a("--ag-ui-launcher-inset",n),r===null?this.removeAttribute("data-expand-corner"):this.setAttribute("data-expand-corner",r),this.#_=o,this.#D=i,this.#ee=s,o===null?this.#Qn(Zl):this.#_e(),this.#me()}}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),this.#ct(Rp,e),this.#qt()}#rt(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#Fn(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height"),o=this.#Pt(e,-1),i=o.x===null||o.y===null?this.#Pt(e,1):o;return this.#Dt("--ag-ui-width",n),this.#Dt("--ag-ui-height",r),{x:o.x??i.x??"right",y:o.y??i.y??"bottom"}}#Pt(e,n){this.#ot({width:e.width+n,height:e.height+n});let r=this.getBoundingClientRect(),o=(i,s)=>Math.abs(i-s)>=.5;return{x:o(r.width,e.width)?o(r.left,e.left)?"right":"left":null,y:o(r.height,e.height)?o(r.top,e.top)?"bottom":"top":null}}#me(){if(!this.#he)return;let e=this.#ee??this.#Fn();this.#te=e,this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`),this.#$t()}#Dt(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ot(e){let n=this.#rt();n!=="none"&&(e.width!==void 0&&this.style.setProperty("--ag-ui-width",`${e.width}px`),e.height!==void 0&&n==="both"&&this.style.setProperty("--ag-ui-height",`${e.height}px`))}#$n(){let e=this.#rt();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#q(){return this.getAttribute("data-launcher-drag")!=="false"&&Cp.has(this.getAttribute("placement"))}#L(){let e=window.visualViewport,n=e?.width??window.innerWidth,r=e?.height??window.innerHeight,o=getComputedStyle(this.#ae),i=l=>{let c=Number.parseFloat(o.getPropertyValue(l));return Number.isFinite(c)?c:0},s=i("padding-left"),a=i("padding-top");return{left:s,top:a,width:Math.max(0,n-s-i("padding-right")),height:Math.max(0,r-a-i("padding-bottom"))}}#Ee(){let e=document.documentElement;return{width:e.clientWidth||window.innerWidth,height:e.clientHeight||window.innerHeight}}#Ut(){let e=window.visualViewport;if(e==null)return;if(Math.abs(e.height-window.innerHeight)<1){this.style.removeProperty("--ag-ui-visual-viewport-height"),this.style.removeProperty("--ag-ui-visual-viewport-inset-bottom");return}this.style.setProperty("--ag-ui-visual-viewport-height",`${Math.round(e.height)}px`);let n=window.innerHeight-e.height-e.offsetTop;this.style.setProperty("--ag-ui-visual-viewport-inset-bottom",`${Math.max(0,Math.round(n))}px`)}#ge(){let e=this.#f.offsetWidth,n=this.#f.offsetHeight,r=this.#_;if(r!==null)return{left:r.left,top:r.top,width:e,height:n};let o=this.#f.getBoundingClientRect();return{left:o.left+o.width/2-e/2,top:o.top+o.height/2-n/2,width:e,height:n}}#Ht(e){if(!this.#q())return;this.#_=e,this.#D=null;let n=this.getBoundingClientRect(),r=fl(this.#ge(),{width:n.width,height:n.height},this.#L(),this.#Ee());this.style.setProperty("--ag-ui-inset",r.hostInset),this.style.setProperty("--ag-ui-launcher-inset",r.launcherInset),this.#ee=r.corner,this.setAttribute("data-expand-corner",`${r.corner.y}-${r.corner.x}`),this.#me()}#Gt(e,n){this.#Ht({left:e,top:n})}#Bn(e,n){this.#Gt(e,n),this.#_e()}#zt(e,n){if(!this.#q())return{held:e,launcher:null};if(this.#_===null){let c=this.#ge();this.#_={left:c.left,top:c.top}}let r=this.#_,o=Pr(e,this.#L(),Je),i=this.#ee??this.#te,s=this.#Ee();this.style.setProperty("--ag-ui-inset",[i.y==="top"?`${Math.round(o.top)}px`:"auto",i.x==="right"?`${Math.round(s.width-o.right)}px`:"auto",i.y==="bottom"?`${Math.round(s.height-o.bottom)}px`:"auto",i.x==="left"?`${Math.round(o.left)}px`:"auto"].join(" ")),this.#D={left:o.left,top:o.top};let a={...this.#ge(),left:r.left+(o.left-n.left),top:r.top+(o.top-n.top)},l={...a,...Dt(a,this.#L())};return this.style.setProperty("--ag-ui-launcher-inset",Dr(o,l,i,this.#Ee()).launcherInset),{held:o,launcher:l}}#Vn(e,n){let{held:r,launcher:o}=this.#zt(e,n);o!==null&&(this.#it(r,o),this.#_e())}#it(e,n){let r=this.#L(),o=this.#Ee(),i={width:e.right-e.left,height:e.bottom-e.top},{corner:s}=fl(n,i,r,o),a=Dr(e,n,s,o);this.style.setProperty("--ag-ui-inset",a.hostInset),this.style.setProperty("--ag-ui-launcher-inset",a.launcherInset),this.#_={left:n.left,top:n.top},this.#D={left:e.left,top:e.top},this.#ee=s,this.setAttribute("data-expand-corner",`${s.y}-${s.x}`),this.#me()}#jn(e){if(!this.#q())return;let n=this.getBoundingClientRect(),r=Pr({left:e.left,top:e.top,right:e.left+n.width,bottom:e.top+n.height},this.#L(),Je),o=this.#ge(),i={...o,left:o.left+(r.left-e.left),top:o.top+(r.top-e.top)};this.#it(r,{...i,...Dt(i,this.#L())})}#_e(){let e=this.#_;if(e===null)return;let n=this.#D;this.#ct(Zl,JSON.stringify(n===null?e:{...e,panel:n}))}#st(){let e=this.#qn(),n=this.#_??e;if(n===null)return;let r=this.#D??e?.panel??null;if(r!==null){this.#_={left:n.left,top:n.top},this.#jn(r);return}let o=this.#ge();this.#Ht(Dt({...o,left:n.left,top:n.top},this.#L()))}#qn(){let e=this.#lt(Zl);if(e===null)return null;try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;let{left:r,top:o,panel:i}=n;if(typeof r!="number"||typeof o!="number")return null;let s=tE(i);return s===null?{left:r,top:o}:{left:r,top:o,panel:s}}catch{return null}}#Wn(){this.#q()||(this.#_=null,this.#D=null,this.#ee=null,this.style.removeProperty("--ag-ui-inset"),this.style.removeProperty("--ag-ui-launcher-inset"),this.removeAttribute("data-expand-corner"))}#Ft(e,n){if(n=this.#cn(n),this.#ot({width:n.right-n.left,height:n.bottom-n.top}),e.x!==this.#te.x&&e.y!==this.#te.y)return n;let r=this.#Ee(),o=this.#te,i=s=>`${Math.round(s)}px`;if(this.style.setProperty("--ag-ui-inset",[o.y==="top"?i(n.top):"auto",o.x==="right"?i(r.width-n.right):"auto",o.y==="bottom"?i(r.height-n.bottom):"auto",o.x==="left"?i(n.left):"auto"].join(" ")),this.#_!==null){let s=this.#f.offsetWidth;this.#_={left:o.x==="left"?n.left:n.right-s,top:o.y==="top"?n.top:n.bottom-s}}return this.#D!==null&&(this.#D={left:n.left,top:n.top}),n}#Xn(e,n){let r=this.#Ft(e,n);this.#Yn({width:r.right-r.left,height:r.bottom-r.top}),this.#_e(),this.#me()}#$t(){let e=`${this.#te.y==="top"?"bottom":"top"}-${this.#te.x==="left"?"right":"left"}`;for(let[n,r]of this.#xt){let o=n===e;r.tabIndex=o?0:-1,o?r.removeAttribute("aria-hidden"):r.setAttribute("aria-hidden","true")}}#Yn(e){let n={...this.#Bt(),...e};this.#ct(Ip,JSON.stringify(n))}#Bt(){let e=this.#lt(Ip);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#Kn(){let e=this.id!==""?this.id:this.endpoint;return e===""?"":this.#Et===e?this.#Ke:Jl.has(e)?(this.#Et=e,this.#Ke=`${e}~${Ie()}`,console.warn(`<ag-ui-chat>: another element on this page already stores its conversation under "${e}", so this one has been given a throwaway namespace of its own \u2014 the two would otherwise share a thread pointer, a history drawer and every message. Give each <ag-ui-chat> its own id to keep them apart and let this one restore its conversation across reloads.`),this.#Ke):(Jl.add(e),this.#Ue=e,e)}#at(e=this.userKey){return e===""?this.#fe:`${this.#fe}#${e}`}#Zn(e,n){let r=this.#at(e),o=this.#at(n);if(e===""){Ze.adopt(r,o),this.#Vt(o);return}Ze.purge(r),this.#Vt(o),this.#X(),this.#Se(),this.#ie(!1),this.#Be(0),this.#g=this.conversationStore.threadId(),this.#Fe(),this.#Ae()}#Vt(e){this.#ye!==null&&(this.#ye=new Ze(e),this.conversationStore=this.#ye,this.#Ot())}#Te(e){return this.#fe===""?e:`${e}:${this.#fe}`}#jt(e){let n=sessionStorage.getItem(this.#Te(e));return n!==null||this.#fe===""?n:sessionStorage.getItem(e)}#lt(e){try{let n=localStorage.getItem(this.#Te(e));if(n!==null)return n}catch{}return this.#jt(e)}#ct(e,n){let r=this.#Te(e);try{localStorage.setItem(r,n)}catch{}bt(r,n)}#Qn(e){let n=this.#Te(e);try{localStorage.removeItem(n)}catch{}try{sessionStorage.removeItem(n)}catch{}}#qt(){let e=this.getAttribute("theme")==="dark";this.#$.replaceChildren(this.#pt("theme","theme-icon",e?Hc:Uc,null))}openThreads(){this.#A.close(),this.#Ae(),this.#R.setModal(!this.#dt()),this.#R.open(),this.#ut()}#dt(){return this.getAttribute("placement")==="page"&&this.getBoundingClientRect().width>=Kc}#ut(){this.#R.isOpen()&&this.#dt()?this.setAttribute("data-threads-docked",""):this.removeAttribute("data-threads-docked")}openCheckpoints(){this.#R.close(),this.#hn(),this.#A.open()}closeThreads(){this.#R.close()}closeCheckpoints(){this.#A.close()}toggleCheckpoints(){if(this.#A.open_){this.#A.close();return}this.openCheckpoints()}newChat(){this.#X(),this.conversationStore.isUnsent?.(this.#g)===!0&&this.conversationStore.clear(this.#g),this.#Se(),this.#g=xs(this.conversationStore),this.#ie(!1),this.#Be(0)}#Se(){this.#ne=null,this.#Wt(),this.#Qe=[],this.#de.length=0,this.#J=null}#Wt(){this.#ve(),this.#j=null,this.#oe=null,this.#H(),this.#i.clear(),this.#o.clear(),this.#u.clear(),this.#p.clear(),this.#c.clear(),this.#d.clear(),this.#N=null,this.#k?.clear(),this.#v.replaceChildren(this.#Z),this.#I()}async retryLastTurn(){if(this.#W)return!1;let e=this.#mt(),n=e.truncateToLastUser();if(n===null)return!1;this.#Wt();for(let r of n)this.#Yt(r);return await e.resume(),!0}async#Jn(e){e!==this.#g&&(this.#X(),this.#Se(),this.conversationStore.setActiveThread(e),this.#g=e,this.#ie(!1),await this.#Fe())}#er(e){let n=e===this.#g;n&&this.#X(),this.conversationStore.clear(e),n&&(this.#Se(),this.#g=this.conversationStore.threadId(),this.#ie(!1)),this.#Ae()}async#Ae(){this.#R.setRelativeTimeFormatter(this.formatRelativeTime),this.#R.setThreads(await this.conversationStore.listThreads(),this.#g)}async#Fe(){this.#Ze+=1;let e=this.#Ze,n=await this.conversationStore.loadMessages(this.#g);if(e!==this.#Ze)return;if(n!==null){this.#Qe=n;for(let o of n)this.#Yt(o)}let r=this.conversationStore.loadCheckpoint(this.#g);if(r!==null){await this.#or(r);return}this.#nr(n)}#Xt(){return this.#Xe=window.location.href,this.getContext()}#tr(){return this.#Xe!==null&&this.#Xe!==window.location.href}#nr(e){let n=e?.at(-1);n===void 0||n.role!==qe.USER||this.#se("\u26A0",this.#e.runInterrupted,"interrupted")}#Yt(e){let n=typeof e.content=="string"?e.content:"";if(e.role===qe.USER){let r=jl(e);if(n!==""||r.length>0){let o=this.appendMessage(qe.USER,n);r.length>0&&o.appendChild(cl(r))}return}if(e.role===qe.ASSISTANT){if(n!==""){let r=this.appendMessage(qe.ASSISTANT,n);r.classList.add("message--restored"),this.#gt(r)}for(let r of oE(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#rr(r.function.arguments)};if(this.#in(o))continue;this.#c.set(o.id,this.#wt(o).element);let i=this.#et(o.name)?.render;i!==void 0&&this.#an(i,o)}return}if(e.role==="activity"){let r=e;typeof r.activityType=="string"&&this.#yt(e.id,r.activityType,r.content);return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(_s(e.outcome),e.content)}}#rr(e){if(typeof e!="string")return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Kt(e){this.getAttribute("data-text-animation")==="word"&&fp(e)}async#or(e){this.conversationStore.saveCheckpoint(this.#g,null);let n=this.#mt();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===qe.ASSISTANT?(r.innerHTML=ds(n,{allowImages:this.allowImages}),ll(r,this.#e),this.#P().appendChild(r)):(this.#j=null,r.textContent=n,this.#v.appendChild(r)),this.#I(),e===qe.USER?this.#w.jump():this.#w.follow(),r}#P(){if(this.#j===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#j=e,this.#v.appendChild(e),this.#I()}return this.#j}#ir(){this.#E.className="chat",this.#E.setAttribute("part","panel");let e=document.createElement("div");e.className="header",e.setAttribute("part","header");let n=this.#Ce;n.className="header-title",n.setAttribute("part","title"),n.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&e.append(this.#pt("icon","icon",null));let r=document.createElement("slot");r.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let i=this.#$e("history",this.#e.chatHistory,"\u2630");i.addEventListener("click",()=>this.openThreads());let s=this.#$e("checkpoints",this.#e.checkpoints,"\u21BA");s.addEventListener("click",()=>this.toggleCheckpoints());let a=this.#$e("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#$e("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),this.#Je()!==null?o.append(i,s,a):o.append(i,a),this.getAttribute("data-theme-toggle")!==null&&(this.#$.type="button",this.#$.className="header-btn header-btn--theme",this.#$.setAttribute("part","header-button theme-toggle"),this.#$.title=this.#e.toggleTheme,this.#$.setAttribute("aria-label",this.#e.toggleTheme),this.#$.addEventListener("click",()=>this.toggleTheme()),this.#qt(),o.append(this.#$)),o.append(l),e.append(n,r,o),Th(e,{enabled:()=>!this.collapsed&&this.#q(),rect:()=>this.getBoundingClientRect(),apply:(g,x)=>this.#zt(g,x),commit:(g,x)=>this.#Vn(g,x)}),this.#v.className="messages",this.#v.setAttribute("part","messages"),this.#v.setAttribute("role","log"),this.#v.setAttribute("aria-live","off"),this.#v.setAttribute("aria-label",this.#e.conversation),this.#z.className="jump-latest",this.#z.type="button",this.#z.setAttribute("part","jump-latest"),this.#z.textContent=this.#e.jumpToLatest,this.#z.addEventListener("click",()=>{this.#w.jump()}),this.#b.className="quote-selection",this.#b.type="button",this.#b.setAttribute("part","quote-selection"),this.#b.textContent=this.#e.quoteSelection,this.#b.hidden=!0,this.#b.addEventListener("mousedown",g=>{g.preventDefault()}),this.#b.addEventListener("click",()=>{this.quote(this.#je),window.getSelection()?.removeAllRanges(),this.#tt()}),this.#v.addEventListener("mouseup",g=>this.#Nt(g)),this.#v.addEventListener("keyup",()=>this.#Nt()),this.#v.addEventListener("mousedown",()=>this.#tt()),this.#w=mp({viewport:this.#v,onMissedContent:g=>{this.#z.dataset.missed=String(g)}}),this.#G.className="sr-only",this.#G.setAttribute("role","status"),this.#G.setAttribute("aria-live","polite"),this.#G.setAttribute("aria-atomic","true"),this.#Z.className="empty",this.#Z.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty";let u=this.#dr();u!==null&&c.append(u),this.#Z.append(c),this.#V.className="queued",this.#V.setAttribute("part","queued"),this.#V.setAttribute("role","group"),this.#V.setAttribute("aria-label",this.#e.queued),this.#V.hidden=!0,this.#v.append(this.#Z);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer");let w=document.createElement("div");w.className="composer",w.setAttribute("part","composer-surface");let p=document.createElement("div");p.className="composer-tools",p.setAttribute("part","composer-tools"),this.#a.className="input",this.#a.setAttribute("part","input"),this.#a.setAttribute("aria-label",this.#e.message),this.#a.rows=1,this.#a.placeholder=this.#e.inputPlaceholder,this.#a.addEventListener("keydown",g=>this.#ur(g)),this.#a.addEventListener("input",()=>this.#Qt()),this.#S.className="send",this.#S.type="button",this.#S.setAttribute("part","send"),this.#S.append(this.#ht("icon-send","send-send",Mc),this.#ht("icon-stop","send-stop",Lc)),this.#S.title=this.#e.send,this.#S.setAttribute("aria-label",this.#e.send),this.#S.dataset.state="idle",this.#S.addEventListener("click",()=>{if(this.#W){this.#X();return}this.#ft()}),this.#C.className="skill-hint",this.#C.setAttribute("part","skill-hint"),this.#C.hidden=!0,this.#O.className="attach-btn",this.#O.type="button",this.#O.setAttribute("part","attach-button"),this.#O.append(this.#ht("icon-attach","attach-glyph",Pc)),this.#O.title=this.#e.attachFiles,this.#O.setAttribute("aria-label",this.#e.attachFiles),this.#O.hidden=!0,this.#O.addEventListener("click",()=>this.#M.click()),this.#M.className="attach-input",this.#M.type="file",this.#M.multiple=!0,this.#M.hidden=!0,this.#M.addEventListener("change",()=>this.#Cn()),this.#Ne.className="attachment-slot",this.#Me.className="voice-slot";let h=document.createElement("slot");h.name="footer",p.append(this.#O,this.#Me,this.#S),w.append(this.#a,p),m.append(w,this.#M),this.#Ie.className="messages-wrap",this.#Ie.append(this.#v,this.#z,this.#b),this.#E.append(e,this.#Ie,this.#F.palette,this.#F.chips,this.#C,this.#V,this.#Ne,m,h,this.#R.element,this.#A.element),this.#E.addEventListener("pointerdown",g=>{if(!this.#A.open_)return;let x=g.composedPath();x.includes(this.#A.element)||x.includes(s)||this.#A.close()}),this.#f.className="launcher",this.#f.type="button",this.#f.setAttribute("part","launcher"),this.#f.setAttribute("aria-label",this.#e.expand),this.#B.className="launcher-badge",this.#B.setAttribute("part","launcher-badge"),this.#B.setAttribute("aria-hidden","true"),this.#B.hidden=!0,this.#ce.className="rail-label",this.#ce.setAttribute("part","rail-label"),this.#ce.setAttribute("aria-hidden","true"),this.#ce.textContent=this.getAttribute("title-text")??this.#e.title,this.#f.append(this.#pt("launcher","launcher-icon",Gc,this.#ar()),this.#ce,this.#B),this.#f.addEventListener("click",()=>this.setCollapsed(!1)),yh(this.#f,{enabled:()=>this.collapsed&&this.#q(),rect:()=>this.#ge(),viewport:()=>this.#L(),apply:(g,x)=>this.#Gt(g,x),commit:(g,x)=>this.#Bn(g,x)});for(let g of nE){let x=hp(g,{axis:()=>this.#rt(),rect:()=>this.getBoundingClientRect(),apply:T=>this.#Ft(g,T),commit:T=>this.#Xn(g,T),label:this.#e.resizePanel});x.tabIndex=-1,x.setAttribute("aria-hidden","true"),this.#xt.set(us(g),x),this.#E.appendChild(x)}this.#$t(),this.#sr(),this.#ae.className="viewport-probe",this.#ae.setAttribute("aria-hidden","true"),this.#x.append(this.#ae,this.#G,this.#E,this.#f)}#ke(e){this.#K!==null&&clearTimeout(this.#K),this.#G.textContent=e,this.#K=setTimeout(()=>{this.#K=null,this.#G.textContent=""},Xc)}#sr(){let e=new CSSStyleSheet;e.replaceSync(gp),this.#x.adoptedStyleSheets=[e]}#$e(e,n,r){let o=document.createElement("button");o.type="button",o.className=`header-btn header-btn--${e}`,o.setAttribute("part",`header-button ${e}-button`),o.title=n,o.setAttribute("aria-label",n);let i=document.createElement("slot");return i.name=`icon-${e}`,i.append(document.createTextNode(r)),o.append(i),o}#ht(e,n,r){let o=document.createElement("slot");return o.name=e,o.className=n,o.innerHTML=r,o}#ar(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#pt(e,n,r,o=this.getAttribute("data-icon-url")){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let s=document.createElement("slot");if(s.name=e,o!==null){let a=document.createElement("img");a.className="icon-img",a.src=o,a.alt="",s.append(a)}else r!==null&&(s.innerHTML=r);return i.append(s),i}#Zt(){this.#f.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#Oe;this.#B.textContent=e>9?"9+":String(e),this.#B.hidden=e===0||!this.#lr();let n=this.#B.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#f.setAttribute("aria-label",n),this.#f.title=n}#lr(){return this.getAttribute("data-unread-badge")!=="false"}#Be(e){this.#Oe=e,this.#Zt(),this.dispatchEvent(new CustomEvent(Bs,{detail:{unread:e},bubbles:!0,composed:!0}))}#cr(){this.collapsed&&this.#Be(this.#Oe+1)}#dr(){let e=this.getAttribute("data-starters");if(e===null)return null;let n;try{n=JSON.parse(e)}catch{return console.warn(`<ag-ui-chat>: data-starters is not valid JSON, so no starters are shown. It takes an array of strings, e.g. data-starters='["Summarise this page"]'.`),null}return fs({prompts:n},this.#e,r=>{this.sendMessage(r)})}#I(){this.#Z.hidden=this.#v.childElementCount>1}#Qt(){this.#F.onInput(this.#a.value),this.#C.hidden=!0,this.#Y(),this.#J=null}#ur(e){if(this.#F.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#W){e.preventDefault(),this.#X();return}if(e.key==="Enter"&&!e.shiftKey){e.preventDefault(),this.#ft();return}this.#hr(e)}#hr(e){let n=e.key==="ArrowUp";if(!n&&e.key!=="ArrowDown"||this.#F.isOpen())return;let r=this.#de;if(r.length===0||this.#J===null&&(!n||this.#a.value!==""))return;let o=this.#J===null?0:this.#J+(n?1:-1);o>=r.length||(e.preventDefault(),this.#J=o<0?null:o,this.#a.value=o<0?"":r[o],this.#a.setSelectionRange(this.#a.value.length,this.#a.value.length),this.#Y())}#X(){for(let e of this.#Q)this.#de[0]!==e&&this.#de.unshift(e);this.#Q.length=0,this.#Ve(),this.#U?.abort(),this.#ne?.cancel()}#ie(e){let n=this.#W&&!e;this.#W=e;let r=e?this.#e.stop:this.#e.send;this.#S.title=r,this.#S.setAttribute("aria-label",r),this.#S.dataset.state=e?"running":"idle",n&&this.#pr()}#pr(){let e=this.#Q.shift();this.#Ve(),e!==void 0&&this.sendMessage(e)}#Ve(){this.#V.replaceChildren(),this.#V.hidden=this.#Q.length===0;for(let[e,n]of this.#Q.entries()){let r=document.createElement("button");r.type="button",r.className="queued-chip",r.setAttribute("part","queued-chip"),r.textContent=n,r.title=this.#e.removeQueued.replace("{text}",n),r.setAttribute("aria-label",r.title),r.addEventListener("click",()=>{this.#Q.splice(e,1),this.#Ve()}),this.#V.appendChild(r)}}#Y(){this.#a.style.height="auto",this.#a.style.height=`${this.#a.scrollHeight}px`}async#ft(){let e=this.#a.value.trim(),n=this.#k?.readyRefs()??[];if(!(e===""&&n.length===0)){if(this.#W){e!==""&&(this.#Q.push(e),this.#Ve(),this.#a.value="",this.#Y());return}e!==""&&this.#de[0]!==e&&this.#de.unshift(e),this.#J=null,this.#a.value="",this.#Y(),this.#k?.hasPending()===!0&&this.#se("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#k.pendingCount())),"attachment-pending"),this.#k?.clearReady(),await this.sendMessage(e,n)}}async sendMessage(e,n=[]){if(this.#W||e===""&&n.length===0)return;let r=this.appendMessage(qe.USER,e);n.length>0&&r.appendChild(cl(n)),this.dispatchEvent(new CustomEvent(Fs,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#mr(e,n)}attachFile(e){return this.#k===null?!1:(this.#k.add(e),!0)}#fr(e){this.dispatchEvent(new CustomEvent(js,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#mr(e,n){if(this.endpoint===""){console.error('<ag-ui-chat>: no endpoint is set, so this message was not sent and no request was made. Point the element at your AG-UI mount with the endpoint attribute (endpoint="/agent/"), or assign chat.endpoint before sending.'),this.#se("\u26A0",this.#e.notConnected,"not-connected");return}await this.#mt().send(e,n)}#mt(){if(this.#ne===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#g,initialMessages:this.#Qe,initialState:this.#pe});this.#ne=new sr({agent:e,handlers:this.#tn(),getTools:()=>this.#kt(),getContext:()=>this.#Xt(),executeTool:n=>this.#Jt(n),resolveInterrupts:n=>this.#en(n),onPersist:n=>this.conversationStore.saveMessages(this.#g,n),onStateChanged:n=>this.#gr(n),connectionLostMessage:this.#e.connectionLost,maxToolRounds:this.#kn()})}return this.#ne}#gr(e){this.#pe={...e},this.dispatchEvent(new CustomEvent(Vs,{detail:{state:this.#pe},bubbles:!0,composed:!0}))}#gt(e,n={}){let r=this.#In(),o=r.has($t.COPY),i=n.rateable!==!1&&r.has($t.FEEDBACK);(o||i)&&gl(e,{strings:this.#e,...o?{text:()=>es(e).text,html:()=>es(e).html}:{},...i?{onFeedback:s=>{this.dispatchEvent(new CustomEvent(Ys,{detail:{content:es(e).text,rating:s},bubbles:!0,composed:!0}))}}:{}}),r.has($t.RETRY)&&this.#br(ts(e,this.#e))}#br(e){this.#N?.querySelector(".message-action--retry")?.remove();let n=ns("retry",this.#e.retryMessage,Fc);n.addEventListener("click",()=>{this.retryLastTurn()}),e.prepend(n),this.#N=e}async#vr(e,n){return this.autoConfirm?null:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0?"predicate":null:this.#m.has(e.name)?null:qa(n.parameters)?"destructive":null}async#Jt(e){if(Np(e)!==null)return null;let n=this.#wt(e);this.#i.delete(e.id),this.#c.set(e.id,n.element);let r=this.#s.has(e.name)?this.#et(e.name):null;if(r===null)return this.#p.has(e.id)||n.settle(re.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Qs&&!qi(r.parameters)&&this.#tr()){let s=this.#e.pageMoved;return n.settle(re.ERROR,s),this.#be(),{content:`Error: ${s}`,error:s,outcome:It.FAILED}}let o=await this.#vr(e,r);if(o!==null){let s={toolName:e.name,args:e.args},a=r.parameters[fo];typeof a=="string"&&(s.message=a),this.#U=new AbortController;let l=pl(this.#P(),s,{signal:this.#U.signal,strings:this.#e,...o==="destructive"?{onAlwaysAllow:()=>this.#m.add(e.name)}:{}});this.#I(),this.#w.follow();let c=await l;if(this.#U=null,n.recordDecision(c?"approved":"declined"),!c){let u=this.#e.declinedAction;return n.settle(re.DECLINED,u),this.#be(),{content:u,outcome:It.DENIED}}}let i=qi(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#g,{toolCallId:e.id});try{let s=await r.handler(e.args,e.id);if(r.render!==void 0&&this.#an(r.render,e),i)return n.settle(re.DONE,this.#e.navigating),{content:"",halt:!0};let a=JSON.stringify(s??null);return n.settle(re.DONE,a),this.#be(),{content:a}}catch(s){i&&this.conversationStore.saveCheckpoint(this.#g,null);let a=s instanceof Error?s.message:String(s);return n.settle(re.ERROR,a),this.#be(),{content:`Error: ${a}`,error:a,outcome:It.FAILED}}}async#en(e){this.#U=new AbortController,this.#ke(this.#e.announceAwaitingDecision.replace("{count}",String(e.length))),this.#H();let n=this.#U.signal,r=await Promise.all(e.map(async i=>{let s=i.toolCallId!==void 0?this.#i.get(i.toolCallId):void 0,a={},l=rE(i)??i.message;l!==void 0&&(a.message=l);let c=s?.element.getAttribute("data-tool-name");c!=null&&(a.toolName=c);let u,m=this.approveWithEdits&&s!==void 0;m&&(a.args=s.args),s?.mark(re.DEFERRED);let w=this.approvalRenderer!==null?await this.approvalRenderer(a,{signal:n}):await al(s?.approvalSlot??this.#P(),a,{signal:n,strings:this.#e,...m?{onEdit:p=>{u=p}}:{}});return s?.recordDecision(w?"approved":"declined"),w?s?.mark(re.PENDING):s?.settle(re.DECLINED,this.#e.declinedAction),{id:i.id,approved:w,editedArgs:u}}));this.#I(),this.#w.follow(),this.#U=null;let o={};for(let{id:i,approved:s,editedArgs:a}of r)o[i]=s?{status:"resolved",payload:a===void 0?{approved:!0}:{approved:!0,editedArgs:a}}:{status:"cancelled"};return o}#tn(){return{onRunStart:()=>{this.#W||(this.#Re=!1,this.#ke(this.#e.announceResponding)),this.#ie(!0),this.#P(),this.#be()},onReasoningStart:()=>{this.#H(),this.#rn()},onReasoningDelta:e=>{this.#rn().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#H(),this.#oe?.collapse(),this.#Tr(e),this.#Ye+=1},onTextEnd:e=>{let n=this.#vt(e);this.#Ye<=1&&this.#Kt(n),ll(n,this.#e),this.#gt(n),this.#ve(),this.#cr()},onToolCall:e=>{this.#H(),!this.#in(e)&&(this.#y.push({id:e.id,name:e.name}),this.#wt(e))},onActivity:(e,n,r)=>{this.#yt(r,e,n)},onCustomEvent:(e,n)=>{if(e===Zs){this.#wr(n);return}if(e===Oc){this.#xr(n);return}this.dispatchEvent(new CustomEvent(Ws,{detail:{name:e,value:n},bubbles:!0,composed:!0}))},onSubAgentStarted:(e,n,r)=>{r!==null&&(this.#u.set(e,r),this.#bt({delegationId:r,agent:n===""?null:n,phase:Cn.STARTED,status:this.#e.subAgentDelegatedTo.replace("{agent}",n),tool:null}))},onSubAgentFinished:e=>{this.#nn(e,Cn.FINISHED,null)},onSubAgentError:(e,n)=>{this.#nn(e,Cn.FAILED,n===""?this.#e.subAgentFailed:n)},onMessagesSnapshot:()=>{this.#se("\u{1F504}",this.#e.historyReplaced,"history-replaced")},onToolResult:(e,n,r)=>{let o=this.#i.get(e);o!==void 0&&(o.settle(_s(r),n),this.#p.add(e),this.#be())},onActivityChanged:(e,n,r)=>{this.#yt(e,n,r)},onRunEnd:()=>{this.#H(),this.#ve()},onError:e=>{this.#Re=!0,this.#ke(this.#e.announceFailed),this.#H();let n=this.appendMessage(qe.ASSISTANT,`\u26A0\uFE0F ${e}`);n.classList.add("message--failed"),this.#gt(n,{rateable:!1}),this.#Kt(n),this.#ve()},onCancelled:()=>{this.#Re=!0,this.#ke(this.#e.announceStopped),this.#H(),this.#_r(),this.#ve()},onSettled:()=>{this.#Re||this.#ke(this.#e.announceAnswerReady),this.#H(),this.#ie(!1),this.#ve();for(let e of this.#i.values())e.settled||e.settle(re.DONE,this.#e.noResult);this.#j!==null&&this.#j.childElementCount===0&&(this.#j.remove(),this.#I()),this.#j=null,this.#oe=null,this.#yr()}}}#yr(){let e=this.#y.map(({id:r,name:o})=>({name:o,side:this.#p.has(r)?"server":"client"}));this.#y=[];let n=[...this.#T];this.#T=new Set,this.dispatchEvent(new CustomEvent(qs,{detail:{tools:e,invalidated:n},bubbles:!0,composed:!0}))}#wr(e){let n=e??{},r=Array.isArray(n.keys)?n.keys.filter(o=>typeof o=="string"):[];if(r.length!==0){for(let o of r)this.#T.add(o);this.dispatchEvent(new CustomEvent(Xs,{detail:{keys:r,reason:typeof n.reason=="string"?n.reason:null},bubbles:!0,composed:!0}))}}#xr(e){let n=vp(e);n!==null&&this.#bt(n)}#nn(e,n,r){let o=this.#u.get(e);if(o===void 0)return;let i=this.#o.get(o)?.agent??null;this.#bt({delegationId:o,agent:i,phase:n,status:r===null?this.#Er(i):r,tool:null})}#Er(e){return e===null?this.#e.subAgentWorking:this.#e.subAgentFinished.replace("{agent}",e)}#bt(e){let n=this.#i.get(e.delegationId);if(n===void 0)return;let r=this.#o.get(e.delegationId);r===void 0&&(r=new ps(this.#e),this.#o.set(e.delegationId,r),n.subagentSlot.appendChild(r.element)),r.report(e),this.#w.follow()}#_r(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#P().appendChild(e),this.#I(),this.#w.follow()}#be(){if(this.#De!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#De=e,this.#P().appendChild(e),this.#I(),this.#w.follow()}#H(){this.#De?.remove(),this.#De=null}#rn(){if(this.#oe===null){this.#oe=new ms(this.#e);let e=this.#P();e.insertBefore(this.#oe.element,e.firstChild),this.#I(),this.#w.follow()}return this.#oe}#on(){return this.#Le===null&&(this.#Le=this.appendMessage(qe.ASSISTANT,""),this.#Ye=0),this.#Le}#Tr(e){this.#Pe=e,this.#on(),this.#re===null&&(this.#re=requestAnimationFrame(()=>{this.#re=null,this.#vt(this.#Pe)}))}#vt(e){this.#re!==null&&(cancelAnimationFrame(this.#re),this.#re=null),this.#Pe=e;let n=this.#on();return n.innerHTML=ds(e,{allowImages:this.allowImages}),this.#w.follow(),n}#ve(){this.#re!==null&&this.#vt(this.#Pe),this.#Le=null}#in(e){let n=Np(e);return n===null?!1:(this.#se("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#se(e,n,r,o){this.#P().appendChild(Bl(e,n,r,o)),this.#I(),this.#w.follow()}#sn(e,n){this.#se("\u2922",e,"surface",n===null?void 0:{label:this.#e.undo,onActivate:n})}enableCharts(e=["tool","activity"]){let n=!this.#h.has(mo)&&!this.#r.has(Ji);e.includes("activity")&&this.registerActivityRenderer({type:mo,render:r=>{let o=tr(r);return o===null?null:Or(o)},removedNotice:this.#e.chartUndrawable}),e.includes("tool")&&this.registerTool(ph()),n&&this.isConnected&&this.reload()}#an(e,n){let r;try{r=e(n.args)}catch(o){console.warn(`ag-ui-chat: render failed for tool ${n.name}`,o);return}r!==null&&(this.#c.get(n.id)?.after(r),this.#ln())}registerActivityRenderer(e){this.#h.set(e.type,e),this.#l.delete(e.type)}get unhandledActivityTypes(){return[...this.#l]}#yt(e,n,r){let o=this.#h.get(n);if(o===void 0){this.#l.add(n);return}let i;try{i=o.render(r)}catch(a){console.warn(`ag-ui-chat: render failed for activity ${n}`,a),i=null}if(i===null){this.#Sr(e,n,o.removedNotice,r);return}let s=this.#d.get(e);s===void 0?this.#P().appendChild(i):s.replaceWith(i),this.#d.set(e,i),this.#ln()}#Sr(e,n,r,o){let i=this.#d.has(e);this.#d.get(e)?.remove(),this.#d.delete(e),console.warn(`ag-ui-chat: activity ${e} (${n}) was not drawable and has been removed. A chart's points must each be a finite JSON number; a numeric column serialised as a string (a Decimal, typically) is rejected rather than coerced.`,o),i&&r!==void 0&&this.#se("\u{1F4C9}",r,"chart-undrawable")}#ln(){this.#I(),this.#w.follow()}#wt(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#et(e.name)?.parameters[xe],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#t[e.name]?.summary??wl(e.name),i=new Wr(e.name,e.args,o,this.#e,{formatPayload:s=>this.formatToolPayload?.(s)??null});return this.#i.set(e.id,i),this.#P().appendChild(i.element),this.#I(),this.#w.follow(),i}};function rE(t){let e=t.metadata?.[fo];return typeof e=="string"&&e.trim()!==""?e:void 0}function oE(t){return Array.isArray(t)?t.filter(sE):[]}function iE(t){if(t.name!=="")return t;let e=t.type.split("/")[1]??t.type,n=new Date().toISOString().replace(/[:.]/g,"-");return new File([t],e===""?`pasted-${n}`:`pasted-${n}.${e}`,{type:t.type})}function sE(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function Np(t){if(t.name!==ta)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function aE(t){let e=t?.removed;return typeof e=="number"?e:null}function lE(){customElements.get(po)===void 0&&customElements.define(po,Qr)}async function cE(t,e,n={}){await _t(t),await Qa(t,{...n,flashMs:n.flashMs??0}),await Ka(t,e,n)}async function dE(t,e={}){await _t(t),await Za(t,e)}async function uE(t,e={}){await _t(t),await Ja(t,e)}async function hE(t,e,n={}){await _t(t),await el(t,e,n)}async function pE(t,e,n={}){await _t(t),await tl(t,e,n)}function fE(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Rr(t,!!e):mn(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var mE="0.37.0";export{js as ATTACHMENT_EVENT,Qr as AgUiChat,sr as AgUiClient,mo as CHART_ACTIVITY_TYPE,Ji as CHART_TOOL_NAME,ji as CHAT_CORNERS,ea as COMPACTION_ACTIVITY_TYPE,Ws as CUSTOM_AGENT_EVENT,Lr as CheckpointMenu,Ir as ClientToolRegistry,vs as ConnectionLostError,ae as DEFAULT_UI_STRINGS,po as ELEMENT_TAG,Ys as FEEDBACK_EVENT,Zs as INVALIDATE_CUSTOM_NAME,Xs as INVALIDATE_EVENT,ta as LOAD_CAPABILITY_TOOL,Py as MAX_QUOTE_CHARS,Gx as MAX_SUGGESTIONS,zx as MAX_SUGGESTION_CHARS,Nn as MAX_TOOL_ROUNDS,$t as MESSAGE_ACTIONS,qe as MESSAGE_ROLE,Nr as PAGE_ACTIONS,qs as RUN_FINISHED_EVENT,Kr as RemoteConversationStore,Zr as RunIndex,Vs as STATE_EVENT,Fs as SUBMIT_EVENT,Ks as SUGGESTIONS_ACTIVITY_TYPE,Ze as SessionStorageStore,$s as TOGGLE_EVENT,re as TOOL_CALL_STATUS,On as TOOL_DISPLAY,It as TOOL_OUTCOME,Wr as ToolCallCard,Bs as UNREAD_EVENT,mE as VERSION,fo as X_CONFIRM_KEY,hr as X_DESTRUCTIVE_KEY,pr as X_NAVIGATES_KEY,xe as X_SUMMARY_KEY,bl as asQuote,gl as attachMessageActions,yl as attachQuoteOffer,tr as chartSpecFrom,dE as clickElement,ja as createChatSurfaceTools,Wl as createHttpAgent,nl as createPageActionTools,rl as createPageMapContext,Ki as createPageStateTools,il as createRouteTools,Bv as createStateHookTools,lE as defineAgUiChat,cE as fillField,Hv as flash,Qa as focusWithFlash,Za as highlightThenClick,rh as isChatCorner,qa as isDestructive,qi as isNavigates,sl as mergeUiStrings,ts as messageActionBar,jl as messageAttachments,ol as parseToolCatalog,Xi as prefersReducedMotion,uE as pressButton,Ja as pressThenClick,wl as prettifyToolName,Ur as quotableSelection,Mr as relativeTime,Or as renderChart,ds as renderMarkdown,fs as renderSuggestionChips,al as requestApproval,pl as requestConfirmation,xl as requestQuestion,_t as scrollIntoCenterView,hE as selectControl,el as selectOption,fE as setControlValue,Rr as setNativeChecked,mn as setNativeValue,Wa as showHighlightOverlay,yp as suggestionPrompts,pE as toggleCheckbox,tl as toggleControl,_s as toolStatusFromOutcome,Xl as transcribeAudio,Ka as typeInto,Yl as uploadAttachment};
3668
+ ${n}`,this.#Y(),this.#a.focus();let o=this.#a.value.length;this.#a.setSelectionRange(o,o)}offerQuoteInPage(e=document.body){this.#ce?.detach();let n=pl({within:e,label:this.#e.quoteSelection,exclude:this,onQuote:r=>this.quote(r)});return this.#ce=n,()=>{n.detach(),this.#ce===n&&(this.#ce=null)}}#Sn(){return this.getAttribute("data-quote-selection")!=="false"}#Nt(e){if(!this.#Sn())return;let n=e===void 0?void 0:{x:e.clientX,y:e.clientY},r=Mr(this.#v,[this.#x],n);if(r===null){this.#tt();return}this.#je=r.text,this.#An(r.rect)}#An(e){this.#b.hidden=!1;let n=this.#Ie.getBoundingClientRect(),r=e.top-n.top,o=r<Ql+this.#b.offsetHeight;this.#b.dataset.below=String(o),this.#b.style.top=`${o?e.bottom-n.top+Ql:r-Ql}px`;let i=this.#b.offsetWidth/2,s=e.left+e.width/2-n.left;this.#b.style.left=`${Math.min(Math.max(s,i),n.width-i)}px`}#tt(){this.#b.hidden=!0,this.#je=""}#kn(){let e=this.getAttribute("data-max-tool-rounds");return e===null?Nn:Number.parseInt(e,10)}#In(){let e=this.getAttribute("data-message-actions");return e===null?new Set([$t.COPY,$t.RETRY]):new Set(e.split(",").map(n=>n.trim()).filter(n=>n!==""))}#Rn(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Js;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Js}#Cn(){let e=this.#M.files;if(e!==null)for(let n of Array.from(e))this.#k?.add(n);this.#M.value=""}#Nn(){this.#E.addEventListener("dragover",e=>{e.preventDefault(),this.#E.classList.add("chat--dragover")}),this.#E.addEventListener("dragleave",()=>{this.#E.classList.remove("chat--dragover")}),this.#E.addEventListener("drop",e=>{e.preventDefault(),this.#E.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#k?.add(r)})}#On(e,n,r){let o=this.#Mn(),i=n.getData("text/plain");if(o===null||i.length<o)return;e.preventDefault();let s=new Date().toISOString().replace(/[:.]/g,"-");r.add(new File([i],`pasted-${s}.txt`,{type:"text/plain"}))}#Mn(){let e=this.getAttribute("data-paste-attach");if(e===null)return go;if(e==="off")return null;let n=Number.parseInt(e,10);return Number.isNaN(n)||n<=0?(console.warn(`<ag-ui-chat>: data-paste-attach="${e}" is neither "off" nor a positive number of characters, so the default of ${go} is used.`),go):n}#Ln(e){this.#E.addEventListener("paste",n=>{let r=n.clipboardData??null;if(r===null)return;let o=Array.from(r.files);if(o.length===0){this.#On(n,r,e);return}r.getData("text/plain")===""&&n.preventDefault();for(let i of o)this.#k?.add(iE(i))})}#Ot(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new Kr(e,()=>this.#xe(e),this.conversationStore,()=>this.#He(),this.getAttribute("data-threads-cache")!=="false"))}async#Mt(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#t=ol(await n.json())}catch{}}setSkills(e){this.#St=e,this.#nt()}#Pn(){this.#F.enableChips(this.#Rt("data-prompt-chips")),this.#F.enableSlash(this.#Rt("data-slash-commands")),this.#Tt=this.#Dn(),this.#nt()}#Dn(){return Va(this.#Ct("data-skills"))}async#Lt(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#_t=Va(await n.json()),this.#nt()}catch{}}#nt(){let e=new Map;for(let n of[...this.#_t,...this.#Tt,...this.#St])e.set(n.name,n);this.#F.setSkills([...e.values()])}#Un(e){if(e.prompt===void 0){this.#C.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=nh(e.prompt,this.skillContext());if(r.length>0){this.#C.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#C.hidden=!1,this.#a.value=n,this.#Y(),this.#a.focus(),this.#Hn(n);return}if(this.#C.hidden=!0,this.#a.value=n,this.#Y(),e.sendImmediately===!1){this.#a.focus();return}this.#ft()}#Hn(e){let n=e.indexOf("{");this.#a.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e,n={}){e&&!this.#ze()||(n.announce===!0&&e&&!this.collapsed&&this.#sn(this.#e.chatMinimised,null),e||this.#st(),e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),bt(this.#Te(kp),e?"1":"0"),this.#Be(0),this.dispatchEvent(new CustomEvent($s,{detail:{collapsed:e},bubbles:!0,composed:!0})))}get unread(){return this.#Oe}#Gn(){let e=this.#jt(kp);return e!==null?e==="1":Cp.has(this.getAttribute("placement"))&&!this.hasAttribute("data-start-open")}#ze(){return this.getAttribute("placement")!=="page"}describeSurface(){let e=this.getBoundingClientRect(),n=this.#L(),r=e.width>=n.width-1&&e.height>=n.height-1;return{placement:this.getAttribute("placement"),collapsed:this.collapsed,collapsible:this.#ze(),movable:this.#q()&&!r,draggable:this.#q(),fullBleed:r,box:{left:Math.round(e.left),top:Math.round(e.top),width:Math.round(e.width),height:Math.round(e.height)},viewport:{left:Math.round(n.left),top:Math.round(n.top),width:Math.round(n.width),height:Math.round(n.height)}}}moveTo(e,n={}){if(!this.#q())return!1;let r=n.announce===!0?this.#zn():null,o=this.#L(),i=this.getBoundingClientRect();if(i.width>=o.width-1&&i.height>=o.height-1)return!1;let[s,a]=e.split("-"),l=o.left+Bt,c=o.top+Bt,u=a==="left"?l:Math.max(l,o.left+o.width-Bt-i.width),m=s==="top"?c:Math.max(c,o.top+o.height-Bt-i.height),w={left:u,top:m,right:u+i.width,bottom:m+i.height},p=this.#f.offsetWidth,h=this.#f.offsetHeight;return this.#it(w,{left:a==="left"?w.left:w.right-p,top:s==="top"?w.top:w.bottom-h,width:p,height:h}),this.#_e(),r!==null&&this.#sn(this.#e.chatMoved,r),!0}#zn(){let e=this.style.getPropertyValue("--ag-ui-inset"),n=this.style.getPropertyValue("--ag-ui-launcher-inset"),r=this.getAttribute("data-expand-corner"),o=this.#_,i=this.#D,s=this.#ee;return()=>{let a=(l,c)=>{c===""?this.style.removeProperty(l):this.style.setProperty(l,c)};a("--ag-ui-inset",e),a("--ag-ui-launcher-inset",n),r===null?this.removeAttribute("data-expand-corner"):this.setAttribute("data-expand-corner",r),this.#_=o,this.#D=i,this.#ee=s,o===null?this.#Qn(Zl):this.#_e(),this.#ge()}}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),this.#ct(Rp,e),this.#qt()}#rt(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#Fn(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height"),o=this.#Pt(e,-1),i=o.x===null||o.y===null?this.#Pt(e,1):o;return this.#Dt("--ag-ui-width",n),this.#Dt("--ag-ui-height",r),{x:o.x??i.x??"right",y:o.y??i.y??"bottom"}}#Pt(e,n){this.#ot({width:e.width+n,height:e.height+n});let r=this.getBoundingClientRect(),o=(i,s)=>Math.abs(i-s)>=.5;return{x:o(r.width,e.width)?o(r.left,e.left)?"right":"left":null,y:o(r.height,e.height)?o(r.top,e.top)?"bottom":"top":null}}#ge(){if(!this.#pe)return;let e=this.#ee??this.#Fn();this.#te=e,this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`),this.#$t()}#Dt(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ot(e){let n=this.#rt();n!=="none"&&(e.width!==void 0&&this.style.setProperty("--ag-ui-width",`${e.width}px`),e.height!==void 0&&n==="both"&&this.style.setProperty("--ag-ui-height",`${e.height}px`))}#$n(){let e=this.#rt();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#q(){return this.getAttribute("data-launcher-drag")!=="false"&&Cp.has(this.getAttribute("placement"))}#L(){let e=window.visualViewport,n=e?.width??window.innerWidth,r=e?.height??window.innerHeight,o=getComputedStyle(this.#le),i=l=>{let c=Number.parseFloat(o.getPropertyValue(l));return Number.isFinite(c)?c:0},s=i("padding-left"),a=i("padding-top");return{left:s,top:a,width:Math.max(0,n-s-i("padding-right")),height:Math.max(0,r-a-i("padding-bottom"))}}#Ee(){let e=document.documentElement;return{width:e.clientWidth||window.innerWidth,height:e.clientHeight||window.innerHeight}}#Ut(){let e=window.visualViewport;if(e==null)return;if(Math.abs(e.height-window.innerHeight)<1){this.style.removeProperty("--ag-ui-visual-viewport-height"),this.style.removeProperty("--ag-ui-visual-viewport-inset-bottom");return}this.style.setProperty("--ag-ui-visual-viewport-height",`${Math.round(e.height)}px`);let n=window.innerHeight-e.height-e.offsetTop;this.style.setProperty("--ag-ui-visual-viewport-inset-bottom",`${Math.max(0,Math.round(n))}px`)}#be(){let e=this.#f.offsetWidth,n=this.#f.offsetHeight,r=this.#_;if(r!==null)return{left:r.left,top:r.top,width:e,height:n};let o=this.#f.getBoundingClientRect();return{left:o.left+o.width/2-e/2,top:o.top+o.height/2-n/2,width:e,height:n}}#Ht(e){if(!this.#q())return;this.#_=e,this.#D=null;let n=this.getBoundingClientRect(),r=vl(this.#be(),{width:n.width,height:n.height},this.#L(),this.#Ee());this.style.setProperty("--ag-ui-inset",r.hostInset),this.style.setProperty("--ag-ui-launcher-inset",r.launcherInset),this.#ee=r.corner,this.setAttribute("data-expand-corner",`${r.corner.y}-${r.corner.x}`),this.#ge()}#Gt(e,n){this.#Ht({left:e,top:n})}#Bn(e,n){this.#Gt(e,n),this.#_e()}#zt(e,n){if(!this.#q())return{held:e,launcher:null};if(this.#_===null){let c=this.#be();this.#_={left:c.left,top:c.top}}let r=this.#_,o=Dr(e,this.#L(),Je),i=this.#ee??this.#te,s=this.#Ee();this.style.setProperty("--ag-ui-inset",[i.y==="top"?`${Math.round(o.top)}px`:"auto",i.x==="right"?`${Math.round(s.width-o.right)}px`:"auto",i.y==="bottom"?`${Math.round(s.height-o.bottom)}px`:"auto",i.x==="left"?`${Math.round(o.left)}px`:"auto"].join(" ")),this.#D={left:o.left,top:o.top};let a={...this.#be(),left:r.left+(o.left-n.left),top:r.top+(o.top-n.top)},l={...a,...Dt(a,this.#L())};return this.style.setProperty("--ag-ui-launcher-inset",Ur(o,l,i,this.#Ee()).launcherInset),{held:o,launcher:l}}#Vn(e,n){let{held:r,launcher:o}=this.#zt(e,n);o!==null&&(this.#it(r,o),this.#_e())}#it(e,n){let r=this.#L(),o=this.#Ee(),i={width:e.right-e.left,height:e.bottom-e.top},{corner:s}=vl(n,i,r,o),a=Ur(e,n,s,o);this.style.setProperty("--ag-ui-inset",a.hostInset),this.style.setProperty("--ag-ui-launcher-inset",a.launcherInset),this.#_={left:n.left,top:n.top},this.#D={left:e.left,top:e.top},this.#ee=s,this.setAttribute("data-expand-corner",`${s.y}-${s.x}`),this.#ge()}#jn(e){if(!this.#q())return;let n=this.getBoundingClientRect(),r=Dr({left:e.left,top:e.top,right:e.left+n.width,bottom:e.top+n.height},this.#L(),Je),o=this.#be(),i={...o,left:o.left+(r.left-e.left),top:o.top+(r.top-e.top)};this.#it(r,{...i,...Dt(i,this.#L())})}#_e(){let e=this.#_;if(e===null)return;let n=this.#D;this.#ct(Zl,JSON.stringify(n===null?e:{...e,panel:n}))}#st(){let e=this.#qn(),n=this.#_??e;if(n===null)return;let r=this.#D??e?.panel??null;if(r!==null){this.#_={left:n.left,top:n.top},this.#jn(r);return}let o=this.#be();this.#Ht(Dt({...o,left:n.left,top:n.top},this.#L()))}#qn(){let e=this.#lt(Zl);if(e===null)return null;try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;let{left:r,top:o,panel:i}=n;if(typeof r!="number"||typeof o!="number")return null;let s=tE(i);return s===null?{left:r,top:o}:{left:r,top:o,panel:s}}catch{return null}}#Wn(){this.#q()||(this.#_=null,this.#D=null,this.#ee=null,this.style.removeProperty("--ag-ui-inset"),this.style.removeProperty("--ag-ui-launcher-inset"),this.removeAttribute("data-expand-corner"))}#Ft(e,n){if(n=this.#cn(n),this.#ot({width:n.right-n.left,height:n.bottom-n.top}),e.x!==this.#te.x&&e.y!==this.#te.y)return n;let r=this.#Ee(),o=this.#te,i=s=>`${Math.round(s)}px`;if(this.style.setProperty("--ag-ui-inset",[o.y==="top"?i(n.top):"auto",o.x==="right"?i(r.width-n.right):"auto",o.y==="bottom"?i(r.height-n.bottom):"auto",o.x==="left"?i(n.left):"auto"].join(" ")),this.#_!==null){let s=this.#f.offsetWidth;this.#_={left:o.x==="left"?n.left:n.right-s,top:o.y==="top"?n.top:n.bottom-s}}return this.#D!==null&&(this.#D={left:n.left,top:n.top}),n}#Xn(e,n){let r=this.#Ft(e,n);this.#Yn({width:r.right-r.left,height:r.bottom-r.top}),this.#_e(),this.#ge()}#$t(){let e=`${this.#te.y==="top"?"bottom":"top"}-${this.#te.x==="left"?"right":"left"}`;for(let[n,r]of this.#xt){let o=n===e;r.tabIndex=o?0:-1,o?r.removeAttribute("aria-hidden"):r.setAttribute("aria-hidden","true")}}#Yn(e){let n={...this.#Bt(),...e};this.#ct(Ip,JSON.stringify(n))}#Bt(){let e=this.#lt(Ip);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#Kn(){let e=this.id!==""?this.id:this.endpoint;return e===""?"":this.#Et===e?this.#Ke:Jl.has(e)?(this.#Et=e,this.#Ke=`${e}~${Ie()}`,console.warn(`<ag-ui-chat>: another element on this page already stores its conversation under "${e}", so this one has been given a throwaway namespace of its own \u2014 the two would otherwise share a thread pointer, a history drawer and every message. Give each <ag-ui-chat> its own id to keep them apart and let this one restore its conversation across reloads.`),this.#Ke):(Jl.add(e),this.#Ue=e,e)}#at(e=this.userKey){return e===""?this.#me:`${this.#me}#${e}`}#Zn(e,n){let r=this.#at(e),o=this.#at(n);if(e===""){Ze.adopt(r,o),this.#Vt(o);return}Ze.purge(r),this.#Vt(o),this.#X(),this.#Se(),this.#ie(!1),this.#Be(0),this.#g=this.conversationStore.threadId(),this.#Fe(),this.#Ae()}#Vt(e){this.#ye!==null&&(this.#ye=new Ze(e),this.conversationStore=this.#ye,this.#Ot())}#Te(e){return this.#me===""?e:`${e}:${this.#me}`}#jt(e){let n=sessionStorage.getItem(this.#Te(e));return n!==null||this.#me===""?n:sessionStorage.getItem(e)}#lt(e){try{let n=localStorage.getItem(this.#Te(e));if(n!==null)return n}catch{}return this.#jt(e)}#ct(e,n){let r=this.#Te(e);try{localStorage.setItem(r,n)}catch{}bt(r,n)}#Qn(e){let n=this.#Te(e);try{localStorage.removeItem(n)}catch{}try{sessionStorage.removeItem(n)}catch{}}#qt(){let e=this.getAttribute("theme")==="dark";this.#$.replaceChildren(this.#pt("theme","theme-icon",e?Hc:Uc,null))}openThreads(){this.#A.close(),this.#Ae(),this.#R.setModal(!this.#dt()),this.#R.open(),this.#ut()}#dt(){return this.getAttribute("placement")==="page"&&this.getBoundingClientRect().width>=Kc}#ut(){this.#R.isOpen()&&this.#dt()?this.setAttribute("data-threads-docked",""):this.removeAttribute("data-threads-docked")}openCheckpoints(){this.#R.close(),this.#hn(),this.#A.open()}closeThreads(){this.#R.close()}closeCheckpoints(){this.#A.close()}toggleCheckpoints(){if(this.#A.open_){this.#A.close();return}this.openCheckpoints()}newChat(){this.#X(),this.conversationStore.isUnsent?.(this.#g)===!0&&this.conversationStore.clear(this.#g),this.#Se(),this.#g=xs(this.conversationStore),this.#ie(!1),this.#Be(0)}#Se(){this.#ne=null,this.#Wt(),this.#Qe=[],this.#ue.length=0,this.#J=null}#Wt(){this.#se(),this.#j=null,this.#oe=null,this.#H(),this.#i.clear(),this.#o.clear(),this.#u.clear(),this.#p.clear(),this.#c.clear(),this.#d.clear(),this.#N=null,this.#k?.clear(),this.#v.replaceChildren(this.#Z),this.#I()}async retryLastTurn(){if(this.#W)return!1;let e=this.#mt(),n=e.truncateToLastUser();if(n===null)return!1;this.#Wt();for(let r of n)this.#Yt(r);return await e.resume(),!0}async#Jn(e){e!==this.#g&&(this.#X(),this.#Se(),this.conversationStore.setActiveThread(e),this.#g=e,this.#ie(!1),await this.#Fe())}#er(e){let n=e===this.#g;n&&this.#X(),this.conversationStore.clear(e),n&&(this.#Se(),this.#g=this.conversationStore.threadId(),this.#ie(!1)),this.#Ae()}async#Ae(){this.#R.setRelativeTimeFormatter(this.formatRelativeTime),this.#R.setThreads(await this.conversationStore.listThreads(),this.#g)}async#Fe(){this.#Ze+=1;let e=this.#Ze,n=await this.conversationStore.loadMessages(this.#g);if(e!==this.#Ze)return;if(n!==null){this.#Qe=n;for(let o of n)this.#Yt(o)}let r=this.conversationStore.loadCheckpoint(this.#g);if(r!==null){await this.#or(r);return}this.#nr(n)}#Xt(){return this.#Xe=window.location.href,this.getContext()}#tr(){return this.#Xe!==null&&this.#Xe!==window.location.href}#nr(e){let n=e?.at(-1);n===void 0||n.role!==qe.USER||this.#ae("\u26A0",this.#e.runInterrupted,"interrupted")}#Yt(e){let n=typeof e.content=="string"?e.content:"";if(e.role===qe.USER){let r=jl(e);if(n!==""||r.length>0){let o=this.appendMessage(qe.USER,n);r.length>0&&o.appendChild(al(r))}return}if(e.role===qe.ASSISTANT){if(n!==""){let r=this.appendMessage(qe.ASSISTANT,n);r.classList.add("message--restored"),this.#gt(r)}for(let r of oE(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#rr(r.function.arguments)};if(this.#in(o))continue;this.#c.set(o.id,this.#wt(o).element);let i=this.#et(o.name)?.render;i!==void 0&&this.#an(i,o)}return}if(e.role==="activity"){let r=e;typeof r.activityType=="string"&&this.#yt(e.id,r.activityType,r.content);return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(_s(e.outcome),e.content)}}#rr(e){if(typeof e!="string")return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Kt(e){this.getAttribute("data-text-animation")==="word"&&vp(e)}async#or(e){this.conversationStore.saveCheckpoint(this.#g,null);let n=this.#mt();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===qe.ASSISTANT?(r.innerHTML=gs(n,{allowImages:this.allowImages}),dl(r,this.#e),this.#P().appendChild(r)):(this.#j=null,r.textContent=n,this.#v.appendChild(r)),this.#I(),e===qe.USER?this.#w.jump():this.#w.follow(),r}#P(){if(this.#j===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#j=e,this.#v.appendChild(e),this.#I()}return this.#j}#ir(){this.#E.className="chat",this.#E.setAttribute("part","panel");let e=document.createElement("div");e.className="header",e.setAttribute("part","header");let n=this.#Ce;n.className="header-title",n.setAttribute("part","title"),n.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&e.append(this.#pt("icon","icon",null));let r=document.createElement("slot");r.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let i=this.#$e("history",this.#e.chatHistory,"\u2630");i.addEventListener("click",()=>this.openThreads());let s=this.#$e("checkpoints",this.#e.checkpoints,"\u21BA");s.addEventListener("click",()=>this.toggleCheckpoints());let a=this.#$e("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#$e("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),this.#Je()!==null?o.append(i,s,a):o.append(i,a),this.getAttribute("data-theme-toggle")!==null&&(this.#$.type="button",this.#$.className="header-btn header-btn--theme",this.#$.setAttribute("part","header-button theme-toggle"),this.#$.title=this.#e.toggleTheme,this.#$.setAttribute("aria-label",this.#e.toggleTheme),this.#$.addEventListener("click",()=>this.toggleTheme()),this.#qt(),o.append(this.#$)),o.append(l),e.append(n,r,o),_h(e,{enabled:()=>!this.collapsed&&this.#q(),rect:()=>this.getBoundingClientRect(),apply:(g,x)=>this.#zt(g,x),commit:(g,x)=>this.#Vn(g,x)}),this.#v.className="messages",this.#v.setAttribute("part","messages"),this.#v.setAttribute("role","log"),this.#v.setAttribute("aria-live","off"),this.#v.setAttribute("aria-label",this.#e.conversation),this.#z.className="jump-latest",this.#z.type="button",this.#z.setAttribute("part","jump-latest"),this.#z.textContent=this.#e.jumpToLatest,this.#z.addEventListener("click",()=>{this.#w.jump()}),this.#b.className="quote-selection",this.#b.type="button",this.#b.setAttribute("part","quote-selection"),this.#b.textContent=this.#e.quoteSelection,this.#b.hidden=!0,this.#b.addEventListener("mousedown",g=>{g.preventDefault()}),this.#b.addEventListener("click",()=>{this.quote(this.#je),window.getSelection()?.removeAllRanges(),this.#tt()}),this.#v.addEventListener("mouseup",g=>this.#Nt(g)),this.#v.addEventListener("keyup",()=>this.#Nt()),this.#v.addEventListener("mousedown",()=>this.#tt()),this.#w=yp({viewport:this.#v,onMissedContent:g=>{this.#z.dataset.missed=String(g)}}),this.#G.className="sr-only",this.#G.setAttribute("role","status"),this.#G.setAttribute("aria-live","polite"),this.#G.setAttribute("aria-atomic","true"),this.#Z.className="empty",this.#Z.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty";let u=this.#dr();u!==null&&c.append(u),this.#Z.append(c),this.#V.className="queued",this.#V.setAttribute("part","queued"),this.#V.setAttribute("role","group"),this.#V.setAttribute("aria-label",this.#e.queued),this.#V.hidden=!0,this.#v.append(this.#Z);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer");let w=document.createElement("div");w.className="composer",w.setAttribute("part","composer-surface");let p=document.createElement("div");p.className="composer-tools",p.setAttribute("part","composer-tools"),this.#a.className="input",this.#a.setAttribute("part","input"),this.#a.setAttribute("aria-label",this.#e.message),this.#a.rows=1,this.#a.placeholder=this.#e.inputPlaceholder,this.#a.addEventListener("keydown",g=>this.#ur(g)),this.#a.addEventListener("input",()=>this.#Qt()),this.#S.className="send",this.#S.type="button",this.#S.setAttribute("part","send"),this.#S.append(this.#ht("icon-send","send-send",Mc),this.#ht("icon-stop","send-stop",Lc)),this.#S.title=this.#e.send,this.#S.setAttribute("aria-label",this.#e.send),this.#S.dataset.state="idle",this.#S.addEventListener("click",()=>{if(this.#W){this.#X();return}this.#ft()}),this.#C.className="skill-hint",this.#C.setAttribute("part","skill-hint"),this.#C.hidden=!0,this.#O.className="attach-btn",this.#O.type="button",this.#O.setAttribute("part","attach-button"),this.#O.append(this.#ht("icon-attach","attach-glyph",Pc)),this.#O.title=this.#e.attachFiles,this.#O.setAttribute("aria-label",this.#e.attachFiles),this.#O.hidden=!0,this.#O.addEventListener("click",()=>this.#M.click()),this.#M.className="attach-input",this.#M.type="file",this.#M.multiple=!0,this.#M.hidden=!0,this.#M.addEventListener("change",()=>this.#Cn()),this.#Ne.className="attachment-slot",this.#Me.className="voice-slot";let h=document.createElement("slot");h.name="footer",p.append(this.#O,this.#Me,this.#S),w.append(this.#a,p),m.append(w,this.#M),this.#Ie.className="messages-wrap",this.#Ie.append(this.#v,this.#z,this.#b),this.#E.append(e,this.#Ie,this.#F.palette,this.#F.chips,this.#C,this.#V,this.#Ne,m,h,this.#R.element,this.#A.element),this.#E.addEventListener("pointerdown",g=>{if(!this.#A.open_)return;let x=g.composedPath();x.includes(this.#A.element)||x.includes(s)||this.#A.close()}),this.#f.className="launcher",this.#f.type="button",this.#f.setAttribute("part","launcher"),this.#f.setAttribute("aria-label",this.#e.expand),this.#B.className="launcher-badge",this.#B.setAttribute("part","launcher-badge"),this.#B.setAttribute("aria-hidden","true"),this.#B.hidden=!0,this.#de.className="rail-label",this.#de.setAttribute("part","rail-label"),this.#de.setAttribute("aria-hidden","true"),this.#de.textContent=this.getAttribute("title-text")??this.#e.title,this.#f.append(this.#pt("launcher","launcher-icon",Gc,this.#ar()),this.#de,this.#B),this.#f.addEventListener("click",()=>this.setCollapsed(!1)),xh(this.#f,{enabled:()=>this.collapsed&&this.#q(),rect:()=>this.#be(),viewport:()=>this.#L(),apply:(g,x)=>this.#Gt(g,x),commit:(g,x)=>this.#Bn(g,x)});for(let g of nE){let x=Sh(g,{axis:()=>this.#rt(),rect:()=>this.getBoundingClientRect(),apply:T=>this.#Ft(g,T),commit:T=>this.#Xn(g,T),label:this.#e.resizePanel});x.tabIndex=-1,x.setAttribute("aria-hidden","true"),this.#xt.set(os(g),x),this.#E.appendChild(x)}this.#$t(),this.#sr(),this.#le.className="viewport-probe",this.#le.setAttribute("aria-hidden","true"),this.#x.append(this.#le,this.#G,this.#E,this.#f)}#ke(e){this.#K!==null&&clearTimeout(this.#K),this.#G.textContent=e,this.#K=setTimeout(()=>{this.#K=null,this.#G.textContent=""},Xc)}#sr(){let e=new CSSStyleSheet;e.replaceSync(Ih),this.#x.adoptedStyleSheets=[e]}#$e(e,n,r){let o=document.createElement("button");o.type="button",o.className=`header-btn header-btn--${e}`,o.setAttribute("part",`header-button ${e}-button`),o.title=n,o.setAttribute("aria-label",n);let i=document.createElement("slot");return i.name=`icon-${e}`,i.append(document.createTextNode(r)),o.append(i),o}#ht(e,n,r){let o=document.createElement("slot");return o.name=e,o.className=n,o.innerHTML=r,o}#ar(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#pt(e,n,r,o=this.getAttribute("data-icon-url")){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let s=document.createElement("slot");if(s.name=e,o!==null){let a=document.createElement("img");a.className="icon-img",a.src=o,a.alt="",s.append(a)}else r!==null&&(s.innerHTML=r);return i.append(s),i}#Zt(){this.#f.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#Oe;this.#B.textContent=e>9?"9+":String(e),this.#B.hidden=e===0||!this.#lr();let n=this.#B.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#f.setAttribute("aria-label",n),this.#f.title=n}#lr(){return this.getAttribute("data-unread-badge")!=="false"}#Be(e){this.#Oe=e,this.#Zt(),this.dispatchEvent(new CustomEvent(Bs,{detail:{unread:e},bubbles:!0,composed:!0}))}#cr(){this.collapsed&&this.#Be(this.#Oe+1)}#dr(){let e=this.getAttribute("data-starters");if(e===null)return null;let n;try{n=JSON.parse(e)}catch{return console.warn(`<ag-ui-chat>: data-starters is not valid JSON, so no starters are shown. It takes an array of strings, e.g. data-starters='["Summarise this page"]'.`),null}return bs({prompts:n},this.#e,r=>{this.sendMessage(r)})}#I(){this.#Z.hidden=this.#v.childElementCount>1}#Qt(){this.#F.onInput(this.#a.value),this.#C.hidden=!0,this.#Y(),this.#J=null}#ur(e){if(this.#F.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#W){e.preventDefault(),this.#X();return}if(e.key==="Enter"&&!e.shiftKey){e.preventDefault(),this.#ft();return}this.#hr(e)}#hr(e){let n=e.key==="ArrowUp";if(!n&&e.key!=="ArrowDown"||this.#F.isOpen())return;let r=this.#ue;if(r.length===0||this.#J===null&&(!n||this.#a.value!==""))return;let o=this.#J===null?0:this.#J+(n?1:-1);o>=r.length||(e.preventDefault(),this.#J=o<0?null:o,this.#a.value=o<0?"":r[o],this.#a.setSelectionRange(this.#a.value.length,this.#a.value.length),this.#Y())}#X(){for(let e of this.#Q)this.#ue[0]!==e&&this.#ue.unshift(e);this.#Q.length=0,this.#Ve(),this.#U?.abort(),this.#ne?.cancel()}#ie(e){let n=this.#W&&!e;this.#W=e;let r=e?this.#e.stop:this.#e.send;this.#S.title=r,this.#S.setAttribute("aria-label",r),this.#S.dataset.state=e?"running":"idle",n&&this.#pr()}#pr(){let e=this.#Q.shift();this.#Ve(),e!==void 0&&this.sendMessage(e)}#Ve(){this.#V.replaceChildren(),this.#V.hidden=this.#Q.length===0;for(let[e,n]of this.#Q.entries()){let r=document.createElement("button");r.type="button",r.className="queued-chip",r.setAttribute("part","queued-chip"),r.textContent=n,r.title=this.#e.removeQueued.replace("{text}",n),r.setAttribute("aria-label",r.title),r.addEventListener("click",()=>{this.#Q.splice(e,1),this.#Ve()}),this.#V.appendChild(r)}}#Y(){this.#a.style.height="auto",this.#a.style.height=`${this.#a.scrollHeight}px`}async#ft(){let e=this.#a.value.trim(),n=this.#k?.readyRefs()??[];if(!(e===""&&n.length===0)){if(this.#W){e!==""&&(this.#Q.push(e),this.#Ve(),this.#a.value="",this.#Y());return}e!==""&&this.#ue[0]!==e&&this.#ue.unshift(e),this.#J=null,this.#a.value="",this.#Y(),this.#k?.hasPending()===!0&&this.#ae("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#k.pendingCount())),"attachment-pending"),this.#k?.clearReady(),await this.sendMessage(e,n)}}async sendMessage(e,n=[]){if(this.#W||e===""&&n.length===0)return;let r=this.appendMessage(qe.USER,e);n.length>0&&r.appendChild(al(n)),this.dispatchEvent(new CustomEvent(Fs,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#mr(e,n)}attachFile(e){return this.#k===null?!1:(this.#k.add(e),!0)}#fr(e){this.dispatchEvent(new CustomEvent(js,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#mr(e,n){if(this.endpoint===""){console.error('<ag-ui-chat>: no endpoint is set, so this message was not sent and no request was made. Point the element at your AG-UI mount with the endpoint attribute (endpoint="/agent/"), or assign chat.endpoint before sending.'),this.#ae("\u26A0",this.#e.notConnected,"not-connected");return}await this.#mt().send(e,n)}#mt(){if(this.#ne===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#g,initialMessages:this.#Qe,initialState:this.#fe});this.#ne=new sr({agent:e,handlers:this.#tn(),getTools:()=>this.#kt(),getContext:()=>this.#Xt(),executeTool:n=>this.#Jt(n),resolveInterrupts:n=>this.#en(n),onPersist:n=>this.conversationStore.saveMessages(this.#g,n),onStateChanged:n=>this.#gr(n),connectionLostMessage:this.#e.connectionLost,maxToolRounds:this.#kn()})}return this.#ne}#gr(e){this.#fe={...e},this.dispatchEvent(new CustomEvent(Vs,{detail:{state:this.#fe},bubbles:!0,composed:!0}))}#gt(e,n={}){let r=this.#In(),o=r.has($t.COPY),i=n.rateable!==!1&&r.has($t.FEEDBACK);(o||i)&&Tl(e,{strings:this.#e,...o?{text:()=>ns(e).text,html:()=>ns(e).html}:{},...i?{onFeedback:s=>{this.dispatchEvent(new CustomEvent(Ys,{detail:{content:ns(e).text,rating:s},bubbles:!0,composed:!0}))}}:{}}),r.has($t.RETRY)&&this.#br(as(e,this.#e))}#br(e){this.#N?.querySelector(".message-action--retry")?.remove();let n=ls("retry",this.#e.retryMessage,Fc);n.addEventListener("click",()=>{this.retryLastTurn()}),e.prepend(n),this.#N=e}async#vr(e,n){return this.autoConfirm?null:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0?"predicate":null:this.#m.has(e.name)?null:qa(n.parameters)?"destructive":null}async#Jt(e){if(Np(e)!==null)return null;let n=this.#wt(e);this.#i.delete(e.id),this.#c.set(e.id,n.element);let r=this.#s.has(e.name)?this.#et(e.name):null;if(r===null)return this.#p.has(e.id)||n.settle(re.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Qs&&!qi(r.parameters)&&this.#tr()){let s=this.#e.pageMoved;return n.settle(re.ERROR,s),this.#ve(),{content:`Error: ${s}`,error:s,outcome:It.FAILED}}let o=await this.#vr(e,r);if(o!==null){let s={toolName:e.name,args:e.args},a=r.parameters[fo];typeof a=="string"&&(s.message=a),this.#U=new AbortController;let l=gl(this.#P(),s,{signal:this.#U.signal,strings:this.#e,...o==="destructive"?{onAlwaysAllow:()=>this.#m.add(e.name)}:{}});this.#I(),this.#w.follow();let c=await l;if(this.#U=null,n.recordDecision(c?"approved":"declined"),!c){let u=this.#e.declinedAction;return n.settle(re.DECLINED,u),this.#ve(),{content:u,outcome:It.DENIED}}}let i=qi(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#g,{toolCallId:e.id});try{let s=await r.handler(e.args,e.id);if(r.render!==void 0&&this.#an(r.render,e),i)return n.settle(re.DONE,this.#e.navigating),{content:"",halt:!0};let a=JSON.stringify(s??null);return n.settle(re.DONE,a),this.#ve(),{content:a}}catch(s){i&&this.conversationStore.saveCheckpoint(this.#g,null);let a=s instanceof Error?s.message:String(s);return n.settle(re.ERROR,a),this.#ve(),{content:`Error: ${a}`,error:a,outcome:It.FAILED}}}async#en(e){this.#U=new AbortController,this.#ke(this.#e.announceAwaitingDecision.replace("{count}",String(e.length))),this.#H();let n=this.#U.signal,r=await Promise.all(e.map(async i=>{let s=i.toolCallId!==void 0?this.#i.get(i.toolCallId):void 0,a={},l=rE(i)??i.message;l!==void 0&&(a.message=l);let c=s?.element.getAttribute("data-tool-name");c!=null&&(a.toolName=c);let u,m=this.approveWithEdits&&s!==void 0;m&&(a.args=s.args),s?.mark(re.DEFERRED);let w=this.approvalRenderer!==null?await this.approvalRenderer(a,{signal:n}):await fl(s?.approvalSlot??this.#P(),a,{signal:n,strings:this.#e,...m?{onEdit:p=>{u=p}}:{}});return s?.recordDecision(w?"approved":"declined"),w?s?.mark(re.PENDING):s?.settle(re.DECLINED,this.#e.declinedAction),{id:i.id,approved:w,editedArgs:u}}));this.#I(),this.#w.follow(),this.#U=null;let o={};for(let{id:i,approved:s,editedArgs:a}of r)o[i]=s?{status:"resolved",payload:a===void 0?{approved:!0}:{approved:!0,editedArgs:a}}:{status:"cancelled"};return o}#tn(){return{onRunStart:()=>{this.#W||(this.#Re=!1,this.#ke(this.#e.announceResponding)),this.#ie(!0),this.#P(),this.#ve()},onReasoningStart:()=>{this.#H(),this.#rn()},onReasoningDelta:e=>{this.#rn().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#H(),this.#oe?.collapse(),this.#Tr(e),this.#Ye+=1},onTextEnd:e=>{if(e===""){this.#se();return}let n=this.#vt(e);this.#Ye<=1&&this.#Kt(n),dl(n,this.#e),this.#gt(n),this.#se(),this.#cr()},onToolCall:e=>{this.#H(),!this.#in(e)&&(this.#y.push({id:e.id,name:e.name}),this.#wt(e))},onActivity:(e,n,r)=>{this.#yt(r,e,n)},onCustomEvent:(e,n)=>{if(e===Zs){this.#wr(n);return}if(e===Oc){this.#xr(n);return}this.dispatchEvent(new CustomEvent(Ws,{detail:{name:e,value:n},bubbles:!0,composed:!0}))},onSubAgentStarted:(e,n,r)=>{r!==null&&(this.#u.set(e,r),this.#bt({delegationId:r,agent:n===""?null:n,phase:Cn.STARTED,status:this.#e.subAgentDelegatedTo.replace("{agent}",n),tool:null}))},onSubAgentFinished:e=>{this.#nn(e,Cn.FINISHED,null)},onSubAgentError:(e,n)=>{this.#nn(e,Cn.FAILED,n===""?this.#e.subAgentFailed:n)},onMessagesSnapshot:()=>{this.#ae("\u{1F504}",this.#e.historyReplaced,"history-replaced")},onToolResult:(e,n,r)=>{let o=this.#i.get(e);o!==void 0&&(o.settle(_s(r),n),this.#p.add(e),this.#ve())},onActivityChanged:(e,n,r)=>{this.#yt(e,n,r)},onRunEnd:()=>{this.#H(),this.#se()},onError:e=>{this.#Re=!0,this.#ke(this.#e.announceFailed),this.#H();let n=this.appendMessage(qe.ASSISTANT,`\u26A0\uFE0F ${e}`);n.classList.add("message--failed"),this.#gt(n,{rateable:!1}),this.#Kt(n),this.#se()},onCancelled:()=>{this.#Re=!0,this.#ke(this.#e.announceStopped),this.#H(),this.#_r(),this.#se()},onSettled:()=>{this.#Re||this.#ke(this.#e.announceAnswerReady),this.#H(),this.#ie(!1),this.#se();for(let e of this.#i.values())e.settled||e.settle(re.DONE,this.#e.noResult);this.#j!==null&&this.#j.childElementCount===0&&(this.#j.remove(),this.#I()),this.#j=null,this.#oe=null,this.#yr()}}}#yr(){let e=this.#y.map(({id:r,name:o})=>({name:o,side:this.#p.has(r)?"server":"client"}));this.#y=[];let n=[...this.#T];this.#T=new Set,this.dispatchEvent(new CustomEvent(qs,{detail:{tools:e,invalidated:n},bubbles:!0,composed:!0}))}#wr(e){let n=e??{},r=Array.isArray(n.keys)?n.keys.filter(o=>typeof o=="string"):[];if(r.length!==0){for(let o of r)this.#T.add(o);this.dispatchEvent(new CustomEvent(Xs,{detail:{keys:r,reason:typeof n.reason=="string"?n.reason:null},bubbles:!0,composed:!0}))}}#xr(e){let n=kh(e);n!==null&&this.#bt(n)}#nn(e,n,r){let o=this.#u.get(e);if(o===void 0)return;let i=this.#o.get(o)?.agent??null;this.#bt({delegationId:o,agent:i,phase:n,status:r===null?this.#Er(i):r,tool:null})}#Er(e){return e===null?this.#e.subAgentWorking:this.#e.subAgentFinished.replace("{agent}",e)}#bt(e){let n=this.#i.get(e.delegationId);if(n===void 0)return;let r=this.#o.get(e.delegationId);r===void 0&&(r=new is(this.#e),this.#o.set(e.delegationId,r),n.subagentSlot.appendChild(r.element)),r.report(e),this.#w.follow()}#_r(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#P().appendChild(e),this.#I(),this.#w.follow()}#ve(){if(this.#De!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#De=e,this.#P().appendChild(e),this.#I(),this.#w.follow()}#H(){this.#De?.remove(),this.#De=null}#rn(){if(this.#oe===null){this.#oe=new ss(this.#e);let e=this.#P();e.insertBefore(this.#oe.element,e.firstChild),this.#I(),this.#w.follow()}return this.#oe}#on(){return this.#Le===null&&(this.#Le=this.appendMessage(qe.ASSISTANT,""),this.#Ye=0),this.#Le}#Tr(e){this.#Pe=e,this.#on(),this.#re===null&&(this.#re=requestAnimationFrame(()=>{this.#re=null,this.#vt(this.#Pe)}))}#vt(e){this.#re!==null&&(cancelAnimationFrame(this.#re),this.#re=null),this.#Pe=e;let n=this.#on();return n.innerHTML=gs(e,{allowImages:this.allowImages}),this.#w.follow(),n}#se(){this.#re!==null&&this.#vt(this.#Pe),this.#Le=null}#in(e){let n=Np(e);return n===null?!1:(this.#ae("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#ae(e,n,r,o){this.#P().appendChild(xl(e,n,r,o)),this.#I(),this.#w.follow()}#sn(e,n){this.#ae("\u2922",e,"surface",n===null?void 0:{label:this.#e.undo,onActivate:n})}enableCharts(e=["tool","activity"]){let n=!this.#h.has(mo)&&!this.#r.has(Zi);e.includes("activity")&&this.registerActivityRenderer({type:mo,render:r=>{let o=tr(r);return o===null?null:Or(o)},removedNotice:this.#e.chartUndrawable}),e.includes("tool")&&this.registerTool(hh()),n&&this.isConnected&&this.reload()}#an(e,n){let r;try{r=e(n.args)}catch(o){console.warn(`ag-ui-chat: render failed for tool ${n.name}`,o);return}r!==null&&(this.#c.get(n.id)?.after(r),this.#ln())}registerActivityRenderer(e){this.#h.set(e.type,e),this.#l.delete(e.type)}get unhandledActivityTypes(){return[...this.#l]}#yt(e,n,r){let o=this.#h.get(n);if(o===void 0){this.#l.add(n);return}let i;try{i=o.render(r)}catch(a){console.warn(`ag-ui-chat: render failed for activity ${n}`,a),i=null}if(i===null){this.#Sr(e,n,o.removedNotice,r);return}let s=this.#d.get(e);s===void 0?this.#P().appendChild(i):s.replaceWith(i),this.#d.set(e,i),this.#ln()}#Sr(e,n,r,o){let i=this.#d.has(e);this.#d.get(e)?.remove(),this.#d.delete(e),console.warn(`ag-ui-chat: activity ${e} (${n}) was not drawable and has been removed. A chart's points must each be a finite JSON number; a numeric column serialised as a string (a Decimal, typically) is rejected rather than coerced.`,o),i&&r!==void 0&&this.#ae("\u{1F4C9}",r,"chart-undrawable")}#ln(){this.#I(),this.#w.follow()}#wt(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#et(e.name)?.parameters[xe],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#t[e.name]?.summary??wl(e.name),i=new Gr(e.name,e.args,o,this.#e,{formatPayload:s=>this.formatToolPayload?.(s)??null});return this.#i.set(e.id,i),this.#P().appendChild(i.element),this.#I(),this.#w.follow(),i}};function rE(t){let e=t.metadata?.[fo];return typeof e=="string"&&e.trim()!==""?e:void 0}function oE(t){return Array.isArray(t)?t.filter(sE):[]}function iE(t){if(t.name!=="")return t;let e=t.type.split("/")[1]??t.type,n=new Date().toISOString().replace(/[:.]/g,"-");return new File([t],e===""?`pasted-${n}`:`pasted-${n}.${e}`,{type:t.type})}function sE(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function Np(t){if(t.name!==ta)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function aE(t){let e=t?.removed;return typeof e=="number"?e:null}function lE(){customElements.get(po)===void 0&&customElements.define(po,Qr)}async function cE(t,e,n={}){await _t(t),await Qa(t,{...n,flashMs:n.flashMs??0}),await Ka(t,e,n)}async function dE(t,e={}){await _t(t),await Za(t,e)}async function uE(t,e={}){await _t(t),await Ja(t,e)}async function hE(t,e,n={}){await _t(t),await el(t,e,n)}async function pE(t,e,n={}){await _t(t),await tl(t,e,n)}function fE(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Rr(t,!!e):mn(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var mE="0.38.0";export{js as ATTACHMENT_EVENT,Qr as AgUiChat,sr as AgUiClient,mo as CHART_ACTIVITY_TYPE,Zi as CHART_TOOL_NAME,ji as CHAT_CORNERS,ea as COMPACTION_ACTIVITY_TYPE,Ws as CUSTOM_AGENT_EVENT,Pr as CheckpointMenu,Ir as ClientToolRegistry,vs as ConnectionLostError,ae as DEFAULT_UI_STRINGS,po as ELEMENT_TAG,Ys as FEEDBACK_EVENT,Zs as INVALIDATE_CUSTOM_NAME,Xs as INVALIDATE_EVENT,ta as LOAD_CAPABILITY_TOOL,ky as MAX_QUOTE_CHARS,$x as MAX_SUGGESTIONS,Bx as MAX_SUGGESTION_CHARS,Nn as MAX_TOOL_ROUNDS,$t as MESSAGE_ACTIONS,qe as MESSAGE_ROLE,Nr as PAGE_ACTIONS,qs as RUN_FINISHED_EVENT,Kr as RemoteConversationStore,Zr as RunIndex,Vs as STATE_EVENT,Fs as SUBMIT_EVENT,Ks as SUGGESTIONS_ACTIVITY_TYPE,Ze as SessionStorageStore,$s as TOGGLE_EVENT,re as TOOL_CALL_STATUS,On as TOOL_DISPLAY,It as TOOL_OUTCOME,Gr as ToolCallCard,Bs as UNREAD_EVENT,mE as VERSION,fo as X_CONFIRM_KEY,hr as X_DESTRUCTIVE_KEY,pr as X_NAVIGATES_KEY,xe as X_SUMMARY_KEY,ul as asQuote,Tl as attachMessageActions,pl as attachQuoteOffer,tr as chartSpecFrom,dE as clickElement,ja as createChatSurfaceTools,Wl as createHttpAgent,nl as createPageActionTools,rl as createPageMapContext,Ki as createPageStateTools,il as createRouteTools,Bv as createStateHookTools,lE as defineAgUiChat,cE as fillField,Hv as flash,Qa as focusWithFlash,Za as highlightThenClick,rh as isChatCorner,qa as isDestructive,qi as isNavigates,cl as mergeUiStrings,as as messageActionBar,jl as messageAttachments,ol as parseToolCatalog,Xi as prefersReducedMotion,uE as pressButton,Ja as pressThenClick,wl as prettifyToolName,Mr as quotableSelection,Lr as relativeTime,Or as renderChart,gs as renderMarkdown,bs as renderSuggestionChips,fl as requestApproval,gl as requestConfirmation,bl as requestQuestion,_t as scrollIntoCenterView,hE as selectControl,el as selectOption,fE as setControlValue,Rr as setNativeChecked,mn as setNativeValue,Wa as showHighlightOverlay,wp as suggestionPrompts,pE as toggleCheckbox,tl as toggleControl,_s as toolStatusFromOutcome,Xl as transcribeAudio,Ka as typeInto,Yl as uploadAttachment};
3669
3669
  /*! Bundled license information:
3670
3670
 
3671
3671
  fast-json-patch/module/helpers.mjs: