diff --git a/pyproject.toml b/pyproject.toml index 869bd29..e8a34bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-dev" -version = "0.0.63" +version = "0.0.64" description = "UiPath Developer Console" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/src/uipath/dev/server/__init__.py b/src/uipath/dev/server/__init__.py index ad80bc7..facf47c 100644 --- a/src/uipath/dev/server/__init__.py +++ b/src/uipath/dev/server/__init__.py @@ -27,7 +27,7 @@ from uipath.dev.models.eval_data import EvalItemResult, EvalRunState from uipath.dev.models.execution import ExecutionRun from uipath.dev.server.debug_bridge import WebDebugBridge -from uipath.dev.services.agent_service import AgentService +from uipath.dev.services.agent import AgentService from uipath.dev.services.eval_service import EvalService from uipath.dev.services.run_service import RunService from uipath.dev.services.skill_service import SkillService @@ -102,13 +102,7 @@ def __init__( self.agent_service = AgentService( skill_service=self.skill_service, - on_status=self._on_agent_status, - on_text=self._on_agent_text, - on_plan=self._on_agent_plan, - on_tool_use=self._on_agent_tool_use, - on_tool_result=self._on_agent_tool_result, - on_tool_approval=self._on_agent_tool_approval, - on_error=self._on_agent_error, + on_event=self._on_agent_event, ) def create_app(self) -> Any: @@ -291,47 +285,52 @@ def _on_eval_run_completed(self, run: EvalRunState) -> None: """Broadcast eval run completed to all connected clients.""" self.connection_manager.broadcast_eval_run_completed(run) - def _on_agent_status(self, session_id: str, status: str) -> None: - """Broadcast agent status to all connected clients.""" - self.connection_manager.broadcast_agent_status(session_id, status) - - def _on_agent_text(self, session_id: str, content: str, done: bool) -> None: - """Broadcast agent text to all connected clients.""" - self.connection_manager.broadcast_agent_text(session_id, content, done) - - def _on_agent_plan(self, session_id: str, items: list[dict[str, str]]) -> None: - """Broadcast agent plan to all connected clients.""" - self.connection_manager.broadcast_agent_plan(session_id, items) - - def _on_agent_tool_use( - self, session_id: str, tool: str, args: dict[str, Any] - ) -> None: - """Broadcast agent tool use to all connected clients.""" - self.connection_manager.broadcast_agent_tool_use(session_id, tool, args) - - def _on_agent_tool_result( - self, session_id: str, tool: str, result: str, is_error: bool - ) -> None: - """Broadcast agent tool result to all connected clients.""" - self.connection_manager.broadcast_agent_tool_result( - session_id, tool, result, is_error - ) - - def _on_agent_tool_approval( - self, - session_id: str, - tool_call_id: str, - tool: str, - args: dict[str, Any], - ) -> None: - """Broadcast agent tool approval request to all connected clients.""" - self.connection_manager.broadcast_agent_tool_approval( - session_id, tool_call_id, tool, args + def _on_agent_event(self, event: Any) -> None: + """Route agent events to the appropriate broadcast method.""" + from uipath.dev.services.agent import ( + ErrorOccurred, + PlanUpdated, + StatusChanged, + TextDelta, + TextGenerated, + ThinkingGenerated, + TokenUsageUpdated, + ToolApprovalRequired, + ToolCompleted, + ToolStarted, ) - def _on_agent_error(self, session_id: str, message: str) -> None: - """Broadcast agent error to all connected clients.""" - self.connection_manager.broadcast_agent_error(session_id, message) + cm = self.connection_manager + match event: + case StatusChanged(session_id=sid, status=status): + cm.broadcast_agent_status(sid, status) + case TextGenerated(session_id=sid, content=content, done=done): + cm.broadcast_agent_text(sid, content, done) + case TextDelta(session_id=sid, delta=delta): + cm.broadcast_agent_text_delta(sid, delta) + case ThinkingGenerated(session_id=sid, content=content): + cm.broadcast_agent_thinking(sid, content) + case PlanUpdated(session_id=sid, items=items): + cm.broadcast_agent_plan(sid, items) + case ToolStarted(session_id=sid, tool=tool, args=args): + cm.broadcast_agent_tool_use(sid, tool, args) + case ToolCompleted( + session_id=sid, tool=tool, result=result, is_error=is_error + ): + cm.broadcast_agent_tool_result(sid, tool, result, is_error) + case ToolApprovalRequired( + session_id=sid, tool_call_id=tcid, tool=tool, args=args + ): + cm.broadcast_agent_tool_approval(sid, tcid, tool, args) + case ErrorOccurred(session_id=sid, message=message): + cm.broadcast_agent_error(sid, message) + case TokenUsageUpdated( + session_id=sid, + prompt_tokens=pt, + completion_tokens=ct, + total_session_tokens=total, + ): + cm.broadcast_agent_token_usage(sid, pt, ct, total) @staticmethod def _find_free_port(host: str, start_port: int, max_attempts: int = 100) -> int: diff --git a/src/uipath/dev/server/frontend/src/components/agent/AgentChatSidebar.tsx b/src/uipath/dev/server/frontend/src/components/agent/AgentChatSidebar.tsx index abe0130..3b70af9 100644 --- a/src/uipath/dev/server/frontend/src/components/agent/AgentChatSidebar.tsx +++ b/src/uipath/dev/server/frontend/src/components/agent/AgentChatSidebar.tsx @@ -85,6 +85,9 @@ export default function AgentChatSidebar() { }); const isBusy = status === "thinking" || status === "executing" || status === "planning"; + const lastMsg = messages[messages.length - 1]; + const isStreaming = isBusy && lastMsg?.role === "assistant" && !lastMsg.done; + const showBusyIndicator = isBusy && !isStreaming; const textareaRef = useRef(null); @@ -191,7 +194,7 @@ export default function AgentChatSidebar() { {messages.map((msg) => ( ))} - {isBusy && ( + {showBusyIndicator && (
diff --git a/src/uipath/dev/server/frontend/src/components/agent/AgentMessage.tsx b/src/uipath/dev/server/frontend/src/components/agent/AgentMessage.tsx index efca995..d6bd831 100644 --- a/src/uipath/dev/server/frontend/src/components/agent/AgentMessage.tsx +++ b/src/uipath/dev/server/frontend/src/components/agent/AgentMessage.tsx @@ -15,8 +15,39 @@ const ROLE_CONFIG: Record = { assistant: { label: "AI", color: "var(--success)" }, tool: { label: "Tool", color: "var(--warning)" }, plan: { label: "Plan", color: "var(--accent)" }, + thinking: { label: "Reasoning", color: "var(--text-muted)" }, }; +function ThinkingCard({ message }: Props) { + const [expanded, setExpanded] = useState(false); + return ( +
+ + {expanded && ( +
+ {message.content} +
+ )} +
+ ); +} + function PlanCard({ message }: Props) { const items = message.planItems ?? []; return ( @@ -234,6 +265,7 @@ function ToolCard({ message }: Props) { } export default function AgentMessageComponent({ message }: Props) { + if (message.role === "thinking") return ; if (message.role === "plan") return ; if (message.role === "tool") return ; diff --git a/src/uipath/dev/server/frontend/src/store/useAgentStore.ts b/src/uipath/dev/server/frontend/src/store/useAgentStore.ts index f609479..e32d896 100644 --- a/src/uipath/dev/server/frontend/src/store/useAgentStore.ts +++ b/src/uipath/dev/server/frontend/src/store/useAgentStore.ts @@ -26,6 +26,7 @@ interface AgentStore { addToolResult: (tool: string, result: string, isError: boolean) => void; addToolApprovalRequest: (toolCallId: string, tool: string, args: Record) => void; resolveToolApproval: (toolCallId: string, approved: boolean) => void; + appendThinking: (content: string) => void; addError: (message: string) => void; setSessionId: (id: string) => void; setModels: (models: AgentModel[]) => void; @@ -188,6 +189,24 @@ export const useAgentStore = create((set) => ({ return { messages: msgs }; }), + appendThinking: (content) => + set((state) => { + const msgs = [...state.messages]; + const last = msgs[msgs.length - 1]; + if (last && last.role === "thinking") { + // Append to existing thinking message + msgs[msgs.length - 1] = { ...last, content: last.content + content }; + } else { + msgs.push({ + id: nextId(), + role: "thinking", + content, + timestamp: Date.now(), + }); + } + return { messages: msgs }; + }), + addError: (message) => set((state) => ({ status: "error" as AgentStatus, diff --git a/src/uipath/dev/server/frontend/src/store/useWebSocket.ts b/src/uipath/dev/server/frontend/src/store/useWebSocket.ts index beac2d4..ba4aea2 100644 --- a/src/uipath/dev/server/frontend/src/store/useWebSocket.ts +++ b/src/uipath/dev/server/frontend/src/store/useWebSocket.ts @@ -167,6 +167,22 @@ export function useWebSocket() { agent.addToolApprovalRequest(tool_call_id, tool, args); break; } + case "agent.thinking": { + const { content } = msg.payload as { session_id: string; content: string }; + useAgentStore.getState().appendThinking(content); + break; + } + case "agent.text_delta": { + const { session_id: deltaSid, delta } = msg.payload as { session_id: string; delta: string }; + const agentDelta = useAgentStore.getState(); + if (!agentDelta.sessionId) agentDelta.setSessionId(deltaSid); + agentDelta.appendAssistantText(delta, false); + break; + } + case "agent.token_usage": { + // Token usage received — could store for display if needed + break; + } case "agent.error": { const { message: errMsg } = msg.payload as { session_id: string; message: string }; useAgentStore.getState().addError(errMsg); diff --git a/src/uipath/dev/server/frontend/src/types/agent.ts b/src/uipath/dev/server/frontend/src/types/agent.ts index 268dcc2..b06b39f 100644 --- a/src/uipath/dev/server/frontend/src/types/agent.ts +++ b/src/uipath/dev/server/frontend/src/types/agent.ts @@ -14,7 +14,7 @@ export interface AgentToolCall { export interface AgentMessage { id: string; - role: "user" | "assistant" | "plan" | "tool"; + role: "user" | "assistant" | "plan" | "tool" | "thinking"; content: string; timestamp: number; toolCall?: AgentToolCall; diff --git a/src/uipath/dev/server/frontend/src/types/ws.ts b/src/uipath/dev/server/frontend/src/types/ws.ts index 2818ca7..ac08143 100644 --- a/src/uipath/dev/server/frontend/src/types/ws.ts +++ b/src/uipath/dev/server/frontend/src/types/ws.ts @@ -16,7 +16,10 @@ export type ServerEventType = | "agent.tool_use" | "agent.tool_result" | "agent.tool_approval" - | "agent.error"; + | "agent.error" + | "agent.thinking" + | "agent.text_delta" + | "agent.token_usage"; export interface ServerMessage { type: ServerEventType; diff --git a/src/uipath/dev/server/static/assets/ChatPanel-BcW6Jtpz.js b/src/uipath/dev/server/static/assets/ChatPanel-DAnMwTFj.js similarity index 99% rename from src/uipath/dev/server/static/assets/ChatPanel-BcW6Jtpz.js rename to src/uipath/dev/server/static/assets/ChatPanel-DAnMwTFj.js index 23b01f2..02b77bb 100644 --- a/src/uipath/dev/server/static/assets/ChatPanel-BcW6Jtpz.js +++ b/src/uipath/dev/server/static/assets/ChatPanel-DAnMwTFj.js @@ -1,2 +1,2 @@ -import{j as e,a as y}from"./vendor-react-BN_uQvcy.js";import{M,r as T,a as O,u as S}from"./index-B2xfJE6O.js";import"./vendor-reactflow-BP_V7ttx.js";const J={user:{label:"You",color:"var(--info)"},tool:{label:"Tool",color:"var(--warning)"},assistant:{label:"AI",color:"var(--success)"}};function A({message:t,onToolCallClick:r,toolCallIndices:o}){const i=t.role==="user",l=t.tool_calls&&t.tool_calls.length>0,a=J[i?"user":l?"tool":"assistant"];return e.jsxs("div",{className:"py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:a.color}}),e.jsx("span",{className:"text-[11px] font-semibold",style:{color:a.color},children:a.label})]}),t.content&&(i?e.jsx("div",{className:"text-sm leading-relaxed pl-2.5 max-w-prose",style:{color:"var(--text-primary)"},children:t.content}):e.jsx("div",{className:"text-sm leading-relaxed pl-2.5 max-w-prose chat-markdown",style:{color:"var(--text-secondary)"},children:e.jsx(M,{remarkPlugins:[O],rehypePlugins:[T],children:t.content})})),t.tool_calls&&t.tool_calls.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1 pl-2.5",children:t.tool_calls.map((p,c)=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] font-mono px-2 py-1 rounded cursor-pointer hover:brightness-125",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:p.has_result?"var(--success)":"var(--text-muted)"},onClick:()=>r==null?void 0:r(p.name,(o==null?void 0:o[c])??0),children:[p.has_result?"✓":"•"," ",p.name]},`${p.name}-${c}`))})]})}function L({onSend:t,disabled:r,placeholder:o}){const[i,l]=y.useState(""),u=()=>{const c=i.trim();c&&(t(c),l(""))},a=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),u())},p=!r&&i.trim().length>0;return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-t",style:{borderColor:"var(--border)"},children:[e.jsx("input",{value:i,onChange:c=>l(c.target.value),onKeyDown:a,disabled:r,placeholder:o??"Message...",className:"flex-1 bg-transparent text-sm py-1 disabled:opacity-40 placeholder:text-[var(--text-muted)]",style:{color:"var(--text-primary)"}}),e.jsx("button",{onClick:u,disabled:!p,className:"text-xs font-semibold px-3 py-1.5 rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed","aria-label":"Send message",style:{color:p?"var(--accent)":"var(--text-muted)",background:"transparent"},onMouseEnter:c=>{p&&(c.currentTarget.style.background="color-mix(in srgb, var(--accent) 10%, transparent)")},onMouseLeave:c=>{c.currentTarget.style.background="transparent"},children:"Send"})]})}function $(t){if(typeof t!="object"||t===null)return!1;const r=t;return typeof r.properties=="object"&&r.properties!==null&&Object.keys(r.properties).length>0}const f={color:"var(--text-primary)",border:"1px solid var(--border)",background:"var(--bg-primary)"},j="w-full text-[11px] font-mono py-1 px-2 rounded focus:outline-none";function R({name:t,prop:r,value:o,onChange:i}){const l=e.jsxs("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:[t,r.description&&e.jsxs("span",{className:"font-normal normal-case tracking-normal ml-1",style:{color:"var(--text-muted)",opacity:.7},children:["— ",r.description]})]});if(r.enum&&Array.isArray(r.enum))return e.jsxs("div",{children:[l,e.jsx("select",{value:String(o??""),onChange:a=>i(a.target.value),className:j,style:f,children:r.enum.map(a=>e.jsx("option",{value:String(a),children:String(a)},String(a)))})]});if(r.type==="boolean")return e.jsxs("div",{children:[l,e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer py-1",children:[e.jsx("input",{type:"checkbox",checked:!!o,onChange:a=>i(a.target.checked),className:"accent-[var(--accent)]"}),e.jsx("span",{className:"text-[11px] font-mono",style:{color:"var(--text-secondary)"},children:o?"true":"false"})]})]});if(r.type==="number"||r.type==="integer")return e.jsxs("div",{children:[l,e.jsx("input",{type:"number",value:o==null?"":String(o),onChange:a=>i(a.target.value===""?null:Number(a.target.value)),step:r.type==="integer"?1:"any",className:j,style:f})]});if(r.type==="object"||r.type==="array"){const a=typeof o=="string"?o:JSON.stringify(o??null,null,2);return e.jsxs("div",{children:[l,e.jsx("textarea",{value:a,onChange:p=>i(p.target.value),rows:3,className:`${j} resize-y`,style:f})]})}const u=o==null?"":String(o);return u.length>100||u.includes(` +import{j as e,a as y}from"./vendor-react-BN_uQvcy.js";import{M,r as T,a as O,u as S}from"./index-DYl0Xnov.js";import"./vendor-reactflow-BP_V7ttx.js";const J={user:{label:"You",color:"var(--info)"},tool:{label:"Tool",color:"var(--warning)"},assistant:{label:"AI",color:"var(--success)"}};function A({message:t,onToolCallClick:r,toolCallIndices:o}){const i=t.role==="user",l=t.tool_calls&&t.tool_calls.length>0,a=J[i?"user":l?"tool":"assistant"];return e.jsxs("div",{className:"py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:a.color}}),e.jsx("span",{className:"text-[11px] font-semibold",style:{color:a.color},children:a.label})]}),t.content&&(i?e.jsx("div",{className:"text-sm leading-relaxed pl-2.5 max-w-prose",style:{color:"var(--text-primary)"},children:t.content}):e.jsx("div",{className:"text-sm leading-relaxed pl-2.5 max-w-prose chat-markdown",style:{color:"var(--text-secondary)"},children:e.jsx(M,{remarkPlugins:[O],rehypePlugins:[T],children:t.content})})),t.tool_calls&&t.tool_calls.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1 pl-2.5",children:t.tool_calls.map((p,c)=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] font-mono px-2 py-1 rounded cursor-pointer hover:brightness-125",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:p.has_result?"var(--success)":"var(--text-muted)"},onClick:()=>r==null?void 0:r(p.name,(o==null?void 0:o[c])??0),children:[p.has_result?"✓":"•"," ",p.name]},`${p.name}-${c}`))})]})}function L({onSend:t,disabled:r,placeholder:o}){const[i,l]=y.useState(""),u=()=>{const c=i.trim();c&&(t(c),l(""))},a=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),u())},p=!r&&i.trim().length>0;return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-t",style:{borderColor:"var(--border)"},children:[e.jsx("input",{value:i,onChange:c=>l(c.target.value),onKeyDown:a,disabled:r,placeholder:o??"Message...",className:"flex-1 bg-transparent text-sm py-1 disabled:opacity-40 placeholder:text-[var(--text-muted)]",style:{color:"var(--text-primary)"}}),e.jsx("button",{onClick:u,disabled:!p,className:"text-xs font-semibold px-3 py-1.5 rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed","aria-label":"Send message",style:{color:p?"var(--accent)":"var(--text-muted)",background:"transparent"},onMouseEnter:c=>{p&&(c.currentTarget.style.background="color-mix(in srgb, var(--accent) 10%, transparent)")},onMouseLeave:c=>{c.currentTarget.style.background="transparent"},children:"Send"})]})}function $(t){if(typeof t!="object"||t===null)return!1;const r=t;return typeof r.properties=="object"&&r.properties!==null&&Object.keys(r.properties).length>0}const f={color:"var(--text-primary)",border:"1px solid var(--border)",background:"var(--bg-primary)"},j="w-full text-[11px] font-mono py-1 px-2 rounded focus:outline-none";function R({name:t,prop:r,value:o,onChange:i}){const l=e.jsxs("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:[t,r.description&&e.jsxs("span",{className:"font-normal normal-case tracking-normal ml-1",style:{color:"var(--text-muted)",opacity:.7},children:["— ",r.description]})]});if(r.enum&&Array.isArray(r.enum))return e.jsxs("div",{children:[l,e.jsx("select",{value:String(o??""),onChange:a=>i(a.target.value),className:j,style:f,children:r.enum.map(a=>e.jsx("option",{value:String(a),children:String(a)},String(a)))})]});if(r.type==="boolean")return e.jsxs("div",{children:[l,e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer py-1",children:[e.jsx("input",{type:"checkbox",checked:!!o,onChange:a=>i(a.target.checked),className:"accent-[var(--accent)]"}),e.jsx("span",{className:"text-[11px] font-mono",style:{color:"var(--text-secondary)"},children:o?"true":"false"})]})]});if(r.type==="number"||r.type==="integer")return e.jsxs("div",{children:[l,e.jsx("input",{type:"number",value:o==null?"":String(o),onChange:a=>i(a.target.value===""?null:Number(a.target.value)),step:r.type==="integer"?1:"any",className:j,style:f})]});if(r.type==="object"||r.type==="array"){const a=typeof o=="string"?o:JSON.stringify(o??null,null,2);return e.jsxs("div",{children:[l,e.jsx("textarea",{value:a,onChange:p=>i(p.target.value),rows:3,className:`${j} resize-y`,style:f})]})}const u=o==null?"":String(o);return u.length>100||u.includes(` `)?e.jsxs("div",{children:[l,e.jsx("textarea",{value:u,onChange:a=>i(a.target.value),rows:3,className:`${j} resize-y`,style:f})]}):e.jsxs("div",{children:[l,e.jsx("input",{type:"text",value:u,onChange:a=>i(a.target.value),className:j,style:f})]})}function _({label:t,color:r,onClick:o}){return e.jsx("button",{onClick:o,className:"text-xs font-semibold px-3 py-1.5 rounded cursor-pointer transition-colors",style:{background:`color-mix(in srgb, var(--${r}) 15%, var(--bg-secondary))`,color:`var(--${r})`,border:`1px solid color-mix(in srgb, var(--${r}) 30%, var(--border))`},onMouseEnter:i=>{i.currentTarget.style.background=`color-mix(in srgb, var(--${r}) 25%, var(--bg-secondary))`},onMouseLeave:i=>{i.currentTarget.style.background=`color-mix(in srgb, var(--${r}) 15%, var(--bg-secondary))`},children:t})}function F({interrupt:t,onRespond:r}){const[o,i]=y.useState(""),[l,u]=y.useState(!1),[a,p]=y.useState({}),[c,N]=y.useState(""),[k,h]=y.useState(null),g=t.input_schema,b=$(g),C=y.useCallback(()=>{const s=typeof t.input_value=="object"&&t.input_value!==null?t.input_value:{};if(b){const d={...s};for(const m of Object.keys(g.properties))m in d||(d[m]=null);const x=g.properties;for(const[m,v]of Object.entries(x))(v.type==="object"||v.type==="array")&&typeof d[m]!="string"&&(d[m]=JSON.stringify(d[m]??null,null,2));p(d)}else N(typeof t.input_value=="string"?t.input_value:JSON.stringify(t.input_value??null,null,2));h(null),u(!0)},[t.input_value,b,g]),E=()=>{u(!1),h(null)},w=()=>{if(b){const s={},d=g.properties;for(const[x,m]of Object.entries(a)){const v=d[x];if(((v==null?void 0:v.type)==="object"||(v==null?void 0:v.type)==="array")&&typeof m=="string")try{s[x]=JSON.parse(m)}catch{h(`Invalid JSON for "${x}"`);return}else s[x]=m}r({approved:!0,input:s})}else try{const s=JSON.parse(c);r({approved:!0,input:s})}catch{h("Invalid JSON");return}},n=y.useCallback((s,d)=>{p(x=>({...x,[s]:d}))},[]);return t.interrupt_type==="tool_call_confirmation"?e.jsxs("div",{className:"mx-3 my-2 rounded-lg overflow-hidden",style:{border:"1px solid color-mix(in srgb, var(--warning) 40%, var(--border))"},children:[e.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"color-mix(in srgb, var(--warning) 10%, var(--bg-secondary))"},children:[e.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--warning)"},children:l?"Edit Arguments":"Action Required"}),t.tool_name&&e.jsx("span",{className:"text-[11px] font-mono px-1.5 py-0.5 rounded",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--text-primary)"},children:t.tool_name}),!l&&(t.input_value!=null||b)&&e.jsx("button",{onClick:C,className:"ml-auto p-1.5 rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)"},"aria-label":"Edit arguments",onMouseEnter:s=>{s.currentTarget.style.color="var(--warning)"},onMouseLeave:s=>{s.currentTarget.style.color="var(--text-muted)"},title:"Edit arguments",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),l?e.jsxs("div",{className:"px-3 py-2 space-y-3 overflow-y-auto",style:{background:"var(--bg-secondary)",maxHeight:300},children:[b?Object.entries(g.properties).map(([s,d])=>e.jsx(R,{name:s,prop:d,value:a[s],onChange:x=>n(s,x)},s)):e.jsx("textarea",{value:c,onChange:s=>{N(s.target.value),h(null)},rows:8,className:"w-full text-[11px] font-mono py-1 px-2 rounded focus:outline-none resize-y",style:f}),k&&e.jsx("p",{className:"text-[11px]",style:{color:"var(--error)"},children:k})]}):t.input_value!=null&&e.jsx("pre",{className:"px-3 py-2 text-[11px] font-mono whitespace-pre-wrap break-words overflow-y-auto leading-normal",style:{background:"var(--bg-secondary)",color:"var(--text-secondary)",maxHeight:200},children:typeof t.input_value=="string"?t.input_value:JSON.stringify(t.input_value,null,2)}),e.jsx("div",{className:"flex items-center gap-2 px-3 py-2",style:{background:"var(--bg-secondary)",borderTop:"1px solid var(--border)"},children:l?e.jsxs(e.Fragment,{children:[e.jsx(_,{label:"Approve",color:"success",onClick:w}),e.jsx(_,{label:"Cancel",color:"text-muted",onClick:E})]}):e.jsxs(e.Fragment,{children:[e.jsx(_,{label:"Approve",color:"success",onClick:()=>r({approved:!0})}),e.jsx(_,{label:"Reject",color:"error",onClick:()=>r({approved:!1})})]})})]}):e.jsxs("div",{className:"mx-3 my-2 rounded-lg overflow-hidden",style:{border:"1px solid color-mix(in srgb, var(--accent) 40%, var(--border))"},children:[e.jsx("div",{className:"px-3 py-2",style:{background:"color-mix(in srgb, var(--accent) 10%, var(--bg-secondary))"},children:e.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--accent)"},children:"Input Required"})}),t.content!=null&&e.jsx("div",{className:"px-3 py-2 text-sm leading-relaxed",style:{background:"var(--bg-secondary)",color:"var(--text-secondary)"},children:typeof t.content=="string"?t.content:JSON.stringify(t.content,null,2)}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",style:{background:"var(--bg-secondary)",borderTop:"1px solid var(--border)"},children:[e.jsx("input",{value:o,onChange:s=>i(s.target.value),onKeyDown:s=>{s.key==="Enter"&&!s.shiftKey&&o.trim()&&(s.preventDefault(),r({response:o.trim()}))},placeholder:"Type your response...",className:"flex-1 bg-transparent text-sm py-1 placeholder:text-[var(--text-muted)]",style:{color:"var(--text-primary)"}}),e.jsx("button",{onClick:()=>{o.trim()&&r({response:o.trim()})},disabled:!o.trim(),className:"text-xs font-semibold px-3 py-1.5 rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed",style:{color:o.trim()?"var(--accent)":"var(--text-muted)",background:"transparent"},children:"Send"})]})]})}function I({messages:t,runId:r,runStatus:o,ws:i}){const l=y.useRef(null),u=y.useRef(!0),a=S(n=>n.addLocalChatMessage),p=S(n=>n.setFocusedSpan),c=S(n=>n.activeInterrupt[r]??null),N=S(n=>n.setActiveInterrupt),k=y.useMemo(()=>{const n=new Map,s=new Map;for(const d of t)if(d.tool_calls){const x=[];for(const m of d.tool_calls){const v=s.get(m.name)??0;x.push(v),s.set(m.name,v+1)}n.set(d.message_id,x)}return n},[t]),[h,g]=y.useState(!1),b=()=>{const n=l.current;if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight<40;u.current=s,g(n.scrollTop>100)};y.useEffect(()=>{u.current&&l.current&&(l.current.scrollTop=l.current.scrollHeight)});const C=n=>{u.current=!0,a(r,{message_id:`local-${Date.now()}`,role:"user",content:n}),i.sendChatMessage(r,n)},E=n=>{u.current=!0,i.sendInterruptResponse(r,n),N(r,null)},w=o==="running"||!!c;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[e.jsxs("div",{ref:l,onScroll:b,className:"h-full overflow-y-auto px-3 py-2 space-y-0.5",children:[t.length===0&&e.jsx("p",{className:"text-[var(--text-muted)] text-sm text-center py-6",children:"No messages yet"}),t.map(n=>e.jsx(A,{message:n,toolCallIndices:k.get(n.message_id),onToolCallClick:(s,d)=>p({name:s,index:d})},n.message_id)),c&&e.jsx(F,{interrupt:c,onRespond:E})]}),h&&e.jsx("button",{onClick:()=>{var n;return(n=l.current)==null?void 0:n.scrollTo({top:0,behavior:"smooth"})},className:"absolute top-2 right-3 w-6 h-6 flex items-center justify-center rounded-full cursor-pointer transition-opacity opacity-70 hover:opacity-100",style:{background:"var(--bg-tertiary)",color:"var(--text-primary)"},title:"Scroll to top",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"18 15 12 9 6 15"})})})]}),e.jsx(L,{onSend:C,disabled:w,placeholder:c?"Respond to the interrupt above...":w?"Waiting for response...":"Message..."})]})}export{I as default}; diff --git a/src/uipath/dev/server/static/assets/index-B2xfJE6O.js b/src/uipath/dev/server/static/assets/index-DYl0Xnov.js similarity index 59% rename from src/uipath/dev/server/static/assets/index-B2xfJE6O.js rename to src/uipath/dev/server/static/assets/index-DYl0Xnov.js index 93e6772..0f429f0 100644 --- a/src/uipath/dev/server/static/assets/index-B2xfJE6O.js +++ b/src/uipath/dev/server/static/assets/index-DYl0Xnov.js @@ -1,10 +1,10 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-elk-CzxJ-xdZ.js","assets/vendor-react-BN_uQvcy.js","assets/ChatPanel-BcW6Jtpz.js","assets/vendor-reactflow-BP_V7ttx.js","assets/vendor-reactflow-B5DZHykP.css"])))=>i.map(i=>d[i]); -var Nl=Object.defineProperty;var Sl=(e,t,n)=>t in e?Nl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Rt=(e,t,n)=>Sl(e,typeof t!="symbol"?t+"":t,n);import{W as Tn,a as S,j as a,F as Tl,g as Gr,b as Cl}from"./vendor-react-BN_uQvcy.js";import{H as gt,P as bt,B as Al,M as Ml,u as Rl,a as Il,R as Ol,b as Ll,C as jl,c as Dl,d as Pl}from"./vendor-reactflow-BP_V7ttx.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();const Ci=e=>{let t;const n=new Set,r=(c,d)=>{const p=typeof c=="function"?c(t):c;if(!Object.is(p,t)){const m=t;t=d??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(f=>f(t,m))}},i=()=>t,l={setState:r,getState:i,getInitialState:()=>u,subscribe:c=>(n.add(c),()=>n.delete(c))},u=t=e(r,i,l);return l},Bl=(e=>e?Ci(e):Ci),Fl=e=>e;function zl(e,t=Fl){const n=Tn.useSyncExternalStore(e.subscribe,Tn.useCallback(()=>t(e.getState()),[e,t]),Tn.useCallback(()=>t(e.getInitialState()),[e,t]));return Tn.useDebugValue(n),n}const Ai=e=>{const t=Bl(e),n=r=>zl(t,r);return Object.assign(n,t),n},Ot=(e=>e?Ai(e):Ai),Ee=Ot(e=>({runs:{},selectedRunId:null,traces:{},logs:{},chatMessages:{},entrypoints:[],setRuns:t=>e(n=>{var s;let r=n.breakpoints;for(const o of t)(s=o.breakpoints)!=null&&s.length&&!r[o.id]&&(r={...r,[o.id]:Object.fromEntries(o.breakpoints.map(l=>[l,!0]))});const i={runs:Object.fromEntries(t.map(o=>[o.id,o]))};return r!==n.breakpoints&&(i.breakpoints=r),i}),upsertRun:t=>e(n=>{var i;const r={runs:{...n.runs,[t.id]:t}};if((i=t.breakpoints)!=null&&i.length&&!n.breakpoints[t.id]&&(r.breakpoints={...n.breakpoints,[t.id]:Object.fromEntries(t.breakpoints.map(s=>[s,!0]))}),(t.status==="completed"||t.status==="failed")&&n.activeNodes[t.id]){const{[t.id]:s,...o}=n.activeNodes;r.activeNodes=o}if(t.status!=="suspended"&&n.activeInterrupt[t.id]){const{[t.id]:s,...o}=n.activeInterrupt;r.activeInterrupt=o}return r}),selectRun:t=>e({selectedRunId:t}),addTrace:t=>e(n=>{const r=n.traces[t.run_id]??[],i=r.findIndex(o=>o.span_id===t.span_id),s=i>=0?r.map((o,l)=>l===i?t:o):[...r,t];return{traces:{...n.traces,[t.run_id]:s}}}),setTraces:(t,n)=>e(r=>({traces:{...r.traces,[t]:n}})),addLog:t=>e(n=>{const r=n.logs[t.run_id]??[];return{logs:{...n.logs,[t.run_id]:[...r,t]}}}),setLogs:(t,n)=>e(r=>({logs:{...r.logs,[t]:n}})),addChatEvent:(t,n)=>e(r=>{const i=r.chatMessages[t]??[],s=n.message;if(!s)return r;const o=s.messageId??s.message_id,l=s.role??"assistant",d=(s.contentParts??s.content_parts??[]).filter(x=>{const y=x.mimeType??x.mime_type??"";return y.startsWith("text/")||y==="application/json"}).map(x=>{const y=x.data;return(y==null?void 0:y.inline)??""}).join(` -`).trim(),p=(s.toolCalls??s.tool_calls??[]).map(x=>({name:x.name??"",has_result:!!x.result})),m={message_id:o,role:l,content:d,tool_calls:p.length>0?p:void 0},f=i.findIndex(x=>x.message_id===o);if(f>=0)return{chatMessages:{...r.chatMessages,[t]:i.map((x,y)=>y===f?m:x)}};if(l==="user"){const x=i.findIndex(y=>y.message_id.startsWith("local-")&&y.role==="user"&&y.content===d);if(x>=0)return{chatMessages:{...r.chatMessages,[t]:i.map((y,b)=>b===x?m:y)}}}const g=[...i,m];return{chatMessages:{...r.chatMessages,[t]:g}}}),addLocalChatMessage:(t,n)=>e(r=>{const i=r.chatMessages[t]??[];return{chatMessages:{...r.chatMessages,[t]:[...i,n]}}}),setChatMessages:(t,n)=>e(r=>({chatMessages:{...r.chatMessages,[t]:n}})),setEntrypoints:t=>e({entrypoints:t}),breakpoints:{},toggleBreakpoint:(t,n)=>e(r=>{const i={...r.breakpoints[t]??{}};return i[n]?delete i[n]:i[n]=!0,{breakpoints:{...r.breakpoints,[t]:i}}}),clearBreakpoints:t=>e(n=>{const{[t]:r,...i}=n.breakpoints;return{breakpoints:i}}),activeNodes:{},setActiveNode:(t,n,r)=>e(i=>{const s=i.activeNodes[t]??{executing:{},prev:null};return{activeNodes:{...i.activeNodes,[t]:{executing:{...s.executing,[n]:r??null},prev:s.prev}}}}),removeActiveNode:(t,n)=>e(r=>{const i=r.activeNodes[t];if(!i)return r;const{[n]:s,...o}=i.executing;return{activeNodes:{...r.activeNodes,[t]:{executing:o,prev:n}}}}),resetRunGraphState:t=>e(n=>({stateEvents:{...n.stateEvents,[t]:[]},activeNodes:{...n.activeNodes,[t]:{executing:{},prev:null}}})),stateEvents:{},addStateEvent:(t,n,r,i,s)=>e(o=>{const l=o.stateEvents[t]??[];return{stateEvents:{...o.stateEvents,[t]:[...l,{node_name:n,qualified_node_name:i,phase:s,timestamp:Date.now(),payload:r}]}}}),setStateEvents:(t,n)=>e(r=>({stateEvents:{...r.stateEvents,[t]:n}})),focusedSpan:null,setFocusedSpan:t=>e({focusedSpan:t}),activeInterrupt:{},setActiveInterrupt:(t,n)=>e(r=>({activeInterrupt:{...r.activeInterrupt,[t]:n}})),reloadPending:!1,setReloadPending:t=>e({reloadPending:t}),graphCache:{},setGraphCache:(t,n)=>e(r=>({graphCache:{...r.graphCache,[t]:n}}))})),Vn="/api";async function Ul(e){const t=await fetch(`${Vn}/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({environment:e})});if(!t.ok)throw new Error(`Login failed: ${t.status}`);return t.json()}async function sr(){const e=await fetch(`${Vn}/auth/status`);if(!e.ok)throw new Error(`Status check failed: ${e.status}`);return e.json()}async function $l(e){const t=await fetch(`${Vn}/auth/select-tenant`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenant_name:e})});if(!t.ok)throw new Error(`Tenant selection failed: ${t.status}`);return t.json()}async function Hl(){await fetch(`${Vn}/auth/logout`,{method:"POST"})}const gs="uipath-env",Wl=["cloud","staging","alpha"];function Kl(){const e=localStorage.getItem(gs);return Wl.includes(e)?e:"cloud"}const zn=Ot((e,t)=>({enabled:!0,status:"unauthenticated",environment:Kl(),tenants:[],uipathUrl:null,pollTimer:null,expiryTimer:null,init:async()=>{try{const n=await fetch("/api/config");if(n.ok&&!(await n.json()).auth_enabled){e({enabled:!1});return}const r=await sr();e({status:r.status,tenants:r.tenants??[],uipathUrl:r.uipath_url??null}),r.status==="authenticated"&&t().startExpiryCheck()}catch(n){console.error("Auth init failed",n)}},setEnvironment:n=>{localStorage.setItem(gs,n),e({environment:n})},startLogin:async()=>{const{environment:n}=t();try{const r=await Ul(n);e({status:"pending"}),window.open(r.auth_url,"_blank"),t().pollStatus()}catch(r){console.error("Login failed",r)}},pollStatus:()=>{const{pollTimer:n}=t();if(n)return;const r=setInterval(async()=>{try{const i=await sr();i.status!=="pending"&&(t().stopPolling(),e({status:i.status,tenants:i.tenants??[],uipathUrl:i.uipath_url??null}),i.status==="authenticated"&&t().startExpiryCheck())}catch{}},2e3);e({pollTimer:r})},stopPolling:()=>{const{pollTimer:n}=t();n&&(clearInterval(n),e({pollTimer:null}))},startExpiryCheck:()=>{const{expiryTimer:n}=t();if(n)return;const r=setInterval(async()=>{try{(await sr()).status==="expired"&&(t().stopExpiryCheck(),e({status:"expired"}))}catch{}},3e4);e({expiryTimer:r})},stopExpiryCheck:()=>{const{expiryTimer:n}=t();n&&(clearInterval(n),e({expiryTimer:null}))},selectTenant:async n=>{try{const r=await $l(n);e({status:"authenticated",uipathUrl:r.uipath_url,tenants:[]}),t().startExpiryCheck()}catch(r){console.error("Tenant selection failed",r)}},logout:async()=>{t().stopPolling(),t().stopExpiryCheck();try{await Hl()}catch{}e({status:"unauthenticated",tenants:[],uipathUrl:null})}})),bs=Ot(e=>({projectName:null,projectVersion:null,projectAuthors:null,init:async()=>{try{const t=await fetch("/api/config");if(t.ok){const n=await t.json();e({projectName:n.project_name??null,projectVersion:n.project_version??null,projectAuthors:n.project_authors??null})}}catch{}}}));class Gl{constructor(t){Rt(this,"ws",null);Rt(this,"url");Rt(this,"handlers",new Set);Rt(this,"reconnectTimer",null);Rt(this,"shouldReconnect",!0);Rt(this,"pendingMessages",[]);Rt(this,"activeSubscriptions",new Set);const n=window.location.protocol==="https:"?"wss:":"ws:";this.url=t??`${n}//${window.location.host}/ws`}connect(){var t;((t=this.ws)==null?void 0:t.readyState)!==WebSocket.OPEN&&(this.ws=new WebSocket(this.url),this.ws.onopen=()=>{console.log("[ws] connected");for(const n of this.activeSubscriptions)this.sendRaw(JSON.stringify({type:"subscribe",payload:{run_id:n}}));for(const n of this.pendingMessages)this.sendRaw(n);this.pendingMessages=[]},this.ws.onmessage=n=>{let r;try{r=JSON.parse(n.data)}catch{console.warn("[ws] failed to parse message",n.data);return}this.handlers.forEach(i=>{try{i(r)}catch(s){console.error("[ws] handler error",s)}})},this.ws.onclose=()=>{console.log("[ws] disconnected"),this.shouldReconnect&&(this.reconnectTimer=setTimeout(()=>this.connect(),2e3))},this.ws.onerror=()=>{var n;(n=this.ws)==null||n.close()})}disconnect(){var t;this.shouldReconnect=!1,this.reconnectTimer&&clearTimeout(this.reconnectTimer),(t=this.ws)==null||t.close(),this.ws=null}onMessage(t){return this.handlers.add(t),()=>this.handlers.delete(t)}sendRaw(t){var n;((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(t)}send(t,n){var i;const r=JSON.stringify({type:t,payload:n});((i=this.ws)==null?void 0:i.readyState)===WebSocket.OPEN?this.ws.send(r):this.pendingMessages.push(r)}subscribe(t){this.activeSubscriptions.add(t),this.send("subscribe",{run_id:t})}unsubscribe(t){this.activeSubscriptions.delete(t),this.send("unsubscribe",{run_id:t})}sendChatMessage(t,n){this.send("chat.message",{run_id:t,text:n})}sendInterruptResponse(t,n){this.send("chat.interrupt_response",{run_id:t,data:n})}debugStep(t){this.send("debug.step",{run_id:t})}debugContinue(t){this.send("debug.continue",{run_id:t})}debugStop(t){this.send("debug.stop",{run_id:t})}setBreakpoints(t,n){this.send("debug.set_breakpoints",{run_id:t,breakpoints:n})}sendAgentMessage(t,n,r,i){this.send("agent.message",{text:t,model:n,session_id:r??void 0,skill_ids:i&&i.length>0?i:void 0})}sendAgentStop(t){this.send("agent.stop",{session_id:t})}sendToolApproval(t,n,r){this.send("agent.tool_response",{session_id:t,tool_call_id:n,approved:r})}}const Ae=Ot(e=>({evaluators:[],localEvaluators:[],evalSets:{},evalRuns:{},setEvaluators:t=>e({evaluators:t}),setLocalEvaluators:t=>e({localEvaluators:t}),addLocalEvaluator:t=>e(n=>({localEvaluators:[...n.localEvaluators,t]})),upsertLocalEvaluator:t=>e(n=>({localEvaluators:n.localEvaluators.some(r=>r.id===t.id)?n.localEvaluators.map(r=>r.id===t.id?t:r):[...n.localEvaluators,t]})),setEvalSets:t=>e({evalSets:Object.fromEntries(t.map(n=>[n.id,n]))}),addEvalSet:t=>e(n=>({evalSets:{...n.evalSets,[t.id]:t}})),updateEvalSetEvaluators:(t,n)=>e(r=>{const i=r.evalSets[t];return i?{evalSets:{...r.evalSets,[t]:{...i,evaluator_ids:n}}}:r}),incrementEvalSetCount:(t,n=1)=>e(r=>{const i=r.evalSets[t];return i?{evalSets:{...r.evalSets,[t]:{...i,eval_count:i.eval_count+n}}}:r}),setEvalRuns:t=>e({evalRuns:Object.fromEntries(t.map(n=>[n.id,n]))}),upsertEvalRun:t=>e(n=>({evalRuns:{...n.evalRuns,[t.id]:t}})),updateEvalRunProgress:(t,n,r)=>e(i=>{const s=i.evalRuns[t];return s?{evalRuns:{...i.evalRuns,[t]:{...s,progress_completed:n,progress_total:r,status:"running"}}}:i}),completeEvalRun:(t,n,r)=>e(i=>{const s=i.evalRuns[t];return s?{evalRuns:{...i.evalRuns,[t]:{...s,status:"completed",overall_score:n,evaluator_scores:r,end_time:new Date().toISOString()}}}:i})}));let ql=0;function Vt(){return`agent-msg-${++ql}`}const ht=Ot(e=>({sessionId:null,status:"idle",messages:[],plan:[],models:[],selectedModel:null,modelsLoading:!1,skills:[],selectedSkillIds:[],skillsLoading:!1,setStatus:t=>e({status:t}),addUserMessage:t=>e(n=>({messages:[...n.messages,{id:Vt(),role:"user",content:t,timestamp:Date.now()}]})),appendAssistantText:(t,n)=>e(r=>{const i=[...r.messages],s=i[i.length-1];return s&&s.role==="assistant"&&!s.done?i[i.length-1]={...s,content:s.content+t,done:n}:i.push({id:Vt(),role:"assistant",content:t,timestamp:Date.now(),done:n}),{messages:i}}),setPlan:t=>e(n=>{const r=[...n.messages],i=r.findIndex(o=>o.role==="plan"),s={id:i>=0?r[i].id:Vt(),role:"plan",content:"",timestamp:Date.now(),planItems:t};return i>=0?r[i]=s:r.push(s),{messages:r,plan:t}}),addToolUse:(t,n)=>e(r=>{const i=[...r.messages],s=i[i.length-1],o={tool:t,args:n};return s&&s.role==="tool"&&s.toolCalls?i[i.length-1]={...s,toolCalls:[...s.toolCalls,o]}:i.push({id:Vt(),role:"tool",content:"",timestamp:Date.now(),toolCalls:[o]}),{messages:i}}),addToolResult:(t,n,r)=>e(i=>{const s=[...i.messages];for(let o=s.length-1;o>=0;o--){const l=s[o];if(l.role==="tool"&&l.toolCalls){const u=[...l.toolCalls];for(let c=u.length-1;c>=0;c--)if(u[c].tool===t&&u[c].result===void 0)return u[c]={...u[c],result:n,is_error:r},s[o]={...l,toolCalls:u},{messages:s}}}return{messages:s}}),addToolApprovalRequest:(t,n,r)=>e(i=>{const s=[...i.messages],o={tool:n,args:r,tool_call_id:t,status:"pending"},l=s[s.length-1];return l&&l.role==="tool"&&l.toolCalls?s[s.length-1]={...l,toolCalls:[...l.toolCalls,o]}:s.push({id:Vt(),role:"tool",content:"",timestamp:Date.now(),toolCalls:[o]}),{messages:s}}),resolveToolApproval:(t,n)=>e(r=>{const i=[...r.messages];for(let s=i.length-1;s>=0;s--){const o=i[s];if(o.role==="tool"&&o.toolCalls){const l=[...o.toolCalls];for(let u=l.length-1;u>=0;u--)if(l[u].tool_call_id===t)return l[u]={...l[u],status:n?"approved":"denied"},i[s]={...o,toolCalls:l},{messages:i}}}return{messages:i}}),addError:t=>e(n=>({status:"error",messages:[...n.messages,{id:Vt(),role:"assistant",content:`Error: ${t}`,timestamp:Date.now(),done:!0}]})),setSessionId:t=>e({sessionId:t}),setModels:t=>e({models:t}),setSelectedModel:t=>e({selectedModel:t}),setModelsLoading:t=>e({modelsLoading:t}),setSkills:t=>e({skills:t}),setSelectedSkillIds:t=>e({selectedSkillIds:t}),toggleSkill:t=>e(n=>({selectedSkillIds:n.selectedSkillIds.includes(t)?n.selectedSkillIds.filter(i=>i!==t):[...n.selectedSkillIds,t]})),setSkillsLoading:t=>e({skillsLoading:t}),clearSession:()=>e({sessionId:null,status:"idle",messages:[],plan:[]})})),Me=Ot(e=>({children:{},expanded:{},selectedFile:null,openTabs:[],fileCache:{},dirty:{},buffers:{},loadingDirs:{},loadingFile:!1,setChildren:(t,n)=>e(r=>({children:{...r.children,[t]:n}})),toggleExpanded:t=>e(n=>({expanded:{...n.expanded,[t]:!n.expanded[t]}})),setSelectedFile:t=>e({selectedFile:t}),openTab:t=>e(n=>({selectedFile:t,openTabs:n.openTabs.includes(t)?n.openTabs:[...n.openTabs,t]})),closeTab:t=>e(n=>{const r=n.openTabs.filter(c=>c!==t);let i=n.selectedFile;if(i===t){const c=n.openTabs.indexOf(t);i=r[Math.min(c,r.length-1)]??null}const{[t]:s,...o}=n.dirty,{[t]:l,...u}=n.buffers;return{openTabs:r,selectedFile:i,dirty:o,buffers:u}}),setFileContent:(t,n)=>e(r=>({fileCache:{...r.fileCache,[t]:n}})),updateBuffer:(t,n)=>e(r=>({buffers:{...r.buffers,[t]:n},dirty:{...r.dirty,[t]:!0}})),markClean:t=>e(n=>{const{[t]:r,...i}=n.dirty,{[t]:s,...o}=n.buffers;return{dirty:i,buffers:o}}),setLoadingDir:(t,n)=>e(r=>({loadingDirs:{...r.loadingDirs,[t]:n}})),setLoadingFile:t=>e({loadingFile:t})})),qr="/api";async function Vr(e,t){const n=await fetch(e,t);if(!n.ok){let r;try{r=(await n.json()).detail||n.statusText}catch{r=n.statusText}const i=new Error(`HTTP ${n.status}`);throw i.detail=r,i.status=n.status,i}return n.json()}async function Yr(e){return Vr(`${qr}/files/tree?path=${encodeURIComponent(e)}`)}async function xs(e){return Vr(`${qr}/files/content?path=${encodeURIComponent(e)}`)}async function Vl(e,t){await Vr(`${qr}/files/content?path=${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})})}let Cn=null;function Xr(){return Cn||(Cn=new Gl,Cn.connect()),Cn}function Yl(){const e=S.useRef(Xr()),{upsertRun:t,addTrace:n,addLog:r,addChatEvent:i,setActiveInterrupt:s,setActiveNode:o,removeActiveNode:l,resetRunGraphState:u,addStateEvent:c,setReloadPending:d}=Ee(),{upsertEvalRun:p,updateEvalRunProgress:m,completeEvalRun:f}=Ae();return S.useEffect(()=>e.current.onMessage(y=>{switch(y.type){case"run.updated":t(y.payload);break;case"trace":n(y.payload);break;case"log":r(y.payload);break;case"chat":{const b=y.payload.run_id;i(b,y.payload);break}case"chat.interrupt":{const b=y.payload.run_id;s(b,y.payload);break}case"state":{const b=y.payload.run_id,k=y.payload.node_name,A=y.payload.qualified_node_name??null,j=y.payload.phase??null,L=y.payload.payload;k==="__start__"&&j==="started"&&u(b),j==="started"?o(b,k,A):j==="completed"&&l(b,k),c(b,k,L,A,j);break}case"reload":d(!0);break;case"files.changed":{const b=y.payload.files,k=new Set(b),A=Me.getState();for(const L of A.openTabs)A.dirty[L]||!k.has(L)||xs(L).then(T=>{var O;const B=Me.getState();B.dirty[L]||((O=B.fileCache[L])==null?void 0:O.content)!==T.content&&B.setFileContent(L,T)}).catch(()=>{});const j=new Set;for(const L of b){const T=L.lastIndexOf("/"),B=T===-1?"":L.substring(0,T);B in A.children&&j.add(B)}for(const L of j)Yr(L).then(T=>Me.getState().setChildren(L,T)).catch(()=>{});break}case"eval_run.created":p(y.payload);break;case"eval_run.progress":{const{run_id:b,completed:k,total:A,item_result:j}=y.payload;m(b,k,A,j);break}case"eval_run.completed":{const{run_id:b,overall_score:k,evaluator_scores:A}=y.payload;f(b,k,A);break}case"agent.status":{const{session_id:b,status:k}=y.payload,A=ht.getState();A.sessionId||A.setSessionId(b),A.setStatus(k);break}case"agent.text":{const{session_id:b,content:k,done:A}=y.payload,j=ht.getState();j.sessionId||j.setSessionId(b),j.appendAssistantText(k,A);break}case"agent.plan":{const{session_id:b,items:k}=y.payload,A=ht.getState();A.sessionId||A.setSessionId(b),A.setPlan(k);break}case"agent.tool_use":{const{session_id:b,tool:k,args:A}=y.payload,j=ht.getState();j.sessionId||j.setSessionId(b),j.addToolUse(k,A);break}case"agent.tool_result":{const{tool:b,result:k,is_error:A}=y.payload;ht.getState().addToolResult(b,k,A);break}case"agent.tool_approval":{const{session_id:b,tool_call_id:k,tool:A,args:j}=y.payload,L=ht.getState();L.sessionId||L.setSessionId(b),L.addToolApprovalRequest(k,A,j);break}case"agent.error":{const{message:b}=y.payload;ht.getState().addError(b);break}}}),[t,n,r,i,s,o,l,u,c,d,p,m,f]),e.current}const Lt="/api";async function jt(e,t){const n=await fetch(e,t);if(!n.ok){let r;try{r=(await n.json()).detail||n.statusText}catch{r=n.statusText}const i=new Error(`HTTP ${n.status}`);throw i.detail=r,i.status=n.status,i}return n.json()}async function ys(){return jt(`${Lt}/entrypoints`)}async function Xl(e){return jt(`${Lt}/entrypoints/${encodeURIComponent(e)}/schema`)}async function Zl(e){return jt(`${Lt}/entrypoints/${encodeURIComponent(e)}/mock-input`)}async function Jl(e){return jt(`${Lt}/entrypoints/${encodeURIComponent(e)}/graph`)}async function Mi(e,t,n="run",r=[]){return jt(`${Lt}/runs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrypoint:e,input_data:t,mode:n,breakpoints:r})})}async function Ql(){return jt(`${Lt}/runs`)}async function ar(e){return jt(`${Lt}/runs/${e}`)}async function ec(){return jt(`${Lt}/reload`,{method:"POST"})}function tc(e){const t=e.replace(/^#\/?/,""),n={section:"debug",view:"new",runId:null,tab:"traces",setupEntrypoint:null,setupMode:null,evalCreating:!1,evalSetId:null,evalRunId:null,evalRunItemName:null,evaluatorId:null,evaluatorCreateType:null,evaluatorFilter:null,explorerFile:null};if(!t||t==="new"||t==="debug"||t==="debug/new")return n;const r=t.match(/^(?:debug\/)?setup\/([^/]+)\/(run|chat)$/);if(r)return{...n,view:"setup",setupEntrypoint:decodeURIComponent(r[1]),setupMode:r[2]};const i=t.match(/^(?:debug\/)?runs\/([^/]+)(?:\/(traces|output))?$/);if(i)return{...n,view:"details",runId:i[1],tab:i[2]??"traces"};if(t==="evals/new")return{...n,section:"evals",evalCreating:!0};const s=t.match(/^evals\/runs\/([^/]+?)(?:\/([^/]+))?$/);if(s)return{...n,section:"evals",evalRunId:s[1],evalRunItemName:s[2]?decodeURIComponent(s[2]):null};const o=t.match(/^evals\/sets\/([^/]+)$/);if(o)return{...n,section:"evals",evalSetId:o[1]};if(t==="evals")return{...n,section:"evals"};const l=t.match(/^evaluators\/new(?:\/(deterministic|llm|tool))?$/);if(l)return{...n,section:"evaluators",evaluatorCreateType:l[1]??"any"};const u=t.match(/^evaluators\/category\/(deterministic|llm|tool)$/);if(u)return{...n,section:"evaluators",evaluatorFilter:u[1]};const c=t.match(/^evaluators\/([^/]+)$/);if(c)return{...n,section:"evaluators",evaluatorId:c[1]};if(t==="evaluators")return{...n,section:"evaluators"};const d=t.match(/^explorer\/file\/(.+)$/);return d?{...n,section:"explorer",explorerFile:decodeURIComponent(d[1])}:t==="explorer"?{...n,section:"explorer"}:n}function nc(){return window.location.hash}function rc(e){return window.addEventListener("hashchange",e),()=>window.removeEventListener("hashchange",e)}function ot(){const e=S.useSyncExternalStore(rc,nc),t=tc(e),n=S.useCallback(r=>{window.location.hash=r},[]);return{...t,navigate:n}}const Ri="(max-width: 767px)";function ic(){const[e,t]=S.useState(()=>window.matchMedia(Ri).matches);return S.useEffect(()=>{const n=window.matchMedia(Ri),r=i=>t(i.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const oc=[{section:"debug",label:"Developer Console",icon:a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{x:"8",y:"6",width:"8",height:"14",rx:"4"}),a.jsx("path",{d:"M6 10H4"}),a.jsx("path",{d:"M6 18H4"}),a.jsx("path",{d:"M18 10h2"}),a.jsx("path",{d:"M18 18h2"}),a.jsx("path",{d:"M8 14h8"}),a.jsx("path",{d:"M9 6l-1.5-2"}),a.jsx("path",{d:"M15 6l1.5-2"}),a.jsx("path",{d:"M6 14H4"}),a.jsx("path",{d:"M18 14h2"})]})},{section:"evals",label:"Evals",icon:a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M9 3h6"}),a.jsx("path",{d:"M10 3v6.5L5 20a1 1 0 0 0 .9 1.4h12.2a1 1 0 0 0 .9-1.4L14 9.5V3"}),a.jsx("path",{d:"M8.5 14h7"})]})},{section:"evaluators",label:"Evaluators",icon:a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M12 2l7 4v5c0 5.25-3.5 9.74-7 11-3.5-1.26-7-5.75-7-11V6l7-4z"}),a.jsx("path",{d:"M9 12l2 2 4-4"})]})},{section:"explorer",label:"Explorer",icon:a.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",children:a.jsx("path",{d:"M7.5 22.5H17.595C17.07 23.4 16.11 24 15 24H7.5C4.185 24 1.5 21.315 1.5 18V6C1.5 4.89 2.1 3.93 3 3.405V18C3 20.475 5.025 22.5 7.5 22.5ZM21 8.121V18C21 19.6545 19.6545 21 18 21H7.5C5.8455 21 4.5 19.6545 4.5 18V3C4.5 1.3455 5.8455 0 7.5 0H12.879C13.4715 0 14.0505 0.24 14.4705 0.6585L20.3415 6.5295C20.766 6.954 21 7.5195 21 8.121ZM13.5 6.75C13.5 7.164 13.8375 7.5 14.25 7.5H19.1895L13.5 1.8105V6.75ZM19.5 18V9H14.25C13.0095 9 12 7.9905 12 6.75V1.5H7.5C6.672 1.5 6 2.1735 6 3V18C6 18.8265 6.672 19.5 7.5 19.5H18C18.828 19.5 19.5 18.8265 19.5 18Z"})})}];function sc({section:e,onSectionChange:t}){return a.jsx("div",{className:"w-12 flex flex-col items-center shrink-0 border-r",style:{background:"var(--activity-bar-bg)",borderColor:"var(--border)"},children:a.jsx("div",{className:"flex flex-col items-center gap-1 pt-2",children:oc.map(n=>{const r=e===n.section;return a.jsxs("button",{onClick:()=>t(n.section),className:"w-10 h-10 flex items-center justify-center rounded cursor-pointer transition-colors relative",style:{color:r?"var(--text-primary)":"var(--text-muted)",background:r?"var(--bg-hover)":"transparent",border:"none"},title:n.label,onMouseEnter:i=>{r||(i.currentTarget.style.color="var(--text-secondary)")},onMouseLeave:i=>{r||(i.currentTarget.style.color="var(--text-muted)")},children:[r&&a.jsx("div",{className:"absolute left-0 top-1.5 bottom-1.5 w-0.5 rounded-r",style:{background:"var(--accent)"}}),n.icon]},n.section)})})})}const et="/api";async function tt(e,t){const n=await fetch(e,t);if(!n.ok){let r;try{r=(await n.json()).detail||n.statusText}catch{r=n.statusText}const i=new Error(`HTTP ${n.status}`);throw i.detail=r,i.status=n.status,i}return n.json()}async function ac(){return tt(`${et}/evaluators`)}async function vs(){return tt(`${et}/eval-sets`)}async function lc(e){return tt(`${et}/eval-sets`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function cc(e,t){return tt(`${et}/eval-sets/${encodeURIComponent(e)}/items`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function uc(e,t){await tt(`${et}/eval-sets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`,{method:"DELETE"})}async function dc(e){return tt(`${et}/eval-sets/${encodeURIComponent(e)}`)}async function pc(e){return tt(`${et}/eval-sets/${encodeURIComponent(e)}/runs`,{method:"POST"})}async function fc(){return tt(`${et}/eval-runs`)}async function Ii(e){return tt(`${et}/eval-runs/${encodeURIComponent(e)}`)}async function Zr(){return tt(`${et}/local-evaluators`)}async function mc(e){return tt(`${et}/local-evaluators`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function hc(e,t){return tt(`${et}/eval-sets/${encodeURIComponent(e)}/evaluators`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({evaluator_refs:t})})}async function gc(e,t){return tt(`${et}/local-evaluators/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}const bc={"uipath-exact-match":e=>({expectedOutput:e}),"uipath-json-similarity":e=>({expectedOutput:e}),"uipath-contains":()=>({searchText:""}),"uipath-llm-judge-output-semantic-similarity":e=>({expectedOutput:e}),"uipath-llm-judge-output-strict-json-similarity":e=>({expectedOutput:e}),"uipath-llm-judge-trajectory-similarity":()=>({expectedAgentBehavior:""}),"uipath-llm-judge-trajectory-simulation":()=>({expectedAgentBehavior:""}),"uipath-tool-call-count":()=>({}),"uipath-tool-call-args":()=>({}),"uipath-tool-call-order":()=>({}),"uipath-tool-call-output":()=>({})};function xc(e,t){if(!e)return{};const n=bc[e.evaluator_type_id];return n?n(t):e.type==="tool"?{}:e.evaluator_type_id.includes("trajectory")?{expectedAgentBehavior:""}:{expectedOutput:t}}function Es(e){return e?e.type==="tool"?!0:e.evaluator_type_id.includes("tool-call"):!1}function yc(e){return e?Es(e)?{label:"tools",color:"var(--warning, #e5a00d)"}:e.evaluator_type_id.includes("trajectory")?{label:"quality",color:"var(--info, #3b82f6)"}:{label:"output",color:"var(--success, #22c55e)"}:{label:"output",color:"var(--success, #22c55e)"}}function vc({run:e,onClose:t}){const n=Ae(E=>E.evalSets),r=Ae(E=>E.setEvalSets),i=Ae(E=>E.incrementEvalSetCount),s=Ae(E=>E.localEvaluators),o=Ae(E=>E.setLocalEvaluators),[l,u]=S.useState(`run-${e.id.slice(0,8)}`),[c,d]=S.useState(new Set),[p,m]=S.useState({}),f=S.useRef(new Set),[g,x]=S.useState(!1),[y,b]=S.useState(null),[k,A]=S.useState(!1),j=Object.values(n),L=S.useMemo(()=>Object.fromEntries(s.map(E=>[E.id,E])),[s]),T=S.useMemo(()=>{const E=new Set;for(const w of c){const M=n[w];M&&M.evaluator_ids.forEach(I=>E.add(I))}return[...E]},[c,n]);S.useEffect(()=>{const E=e.output_data,w=f.current;m(M=>{const I={};for(const D of T)if(w.has(D)&&M[D]!==void 0)I[D]=M[D];else{const N=L[D],_=xc(N,E);I[D]=JSON.stringify(_,null,2)}return I})},[T,L,e.output_data]),S.useEffect(()=>{const E=w=>{w.key==="Escape"&&t()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[t]),S.useEffect(()=>{j.length===0&&vs().then(r).catch(()=>{}),s.length===0&&Zr().then(o).catch(()=>{})},[]);const B=E=>{d(w=>{const M=new Set(w);return M.has(E)?M.delete(E):M.add(E),M})},O=async()=>{var w;if(!l.trim()||c.size===0)return;b(null),x(!0);const E={};for(const M of T){const I=p[M];if(I!==void 0)try{E[M]=JSON.parse(I)}catch{b(`Invalid JSON for evaluator "${((w=L[M])==null?void 0:w.name)??M}"`),x(!1);return}}try{for(const M of c){const I=n[M],D=new Set((I==null?void 0:I.evaluator_ids)??[]),N={};for(const[_,R]of Object.entries(E))D.has(_)&&(N[_]=R);await cc(M,{name:l.trim(),inputs:e.input_data,expected_output:null,evaluation_criterias:N}),i(M)}A(!0),setTimeout(t,3e3)}catch(M){b(M.detail||M.message||"Failed to add item")}finally{x(!1)}};return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(0, 0, 0, 0.5)"},onClick:E=>{E.target===E.currentTarget&&t()},children:a.jsxs("div",{className:"w-full max-w-2xl rounded-lg p-6 shadow-xl max-h-[85vh] flex flex-col",style:{background:"var(--bg-primary)",border:"1px solid var(--border)"},children:[a.jsxs("div",{className:"flex items-center justify-between mb-6",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{background:"var(--accent)"}}),a.jsx("span",{className:"text-sm font-semibold",style:{color:"var(--text-muted)"},children:"Add to Eval Set"})]}),a.jsx("button",{onClick:t,className:"w-7 h-7 flex items-center justify-center rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:E=>{E.currentTarget.style.color="var(--text-primary)"},onMouseLeave:E=>{E.currentTarget.style.color="var(--text-muted)"},"aria-label":"Close",children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0 space-y-4 pr-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Item Name"}),a.jsx("input",{type:"text",value:l,onChange:E=>u(E.target.value),className:"w-full rounded-md px-3 py-2 text-xs",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"}})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Inputs"}),a.jsx("pre",{className:"rounded-md px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words max-h-32 overflow-y-auto",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-secondary)"},children:JSON.stringify(e.input_data,null,2)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Eval Sets"}),j.length===0?a.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:"No eval sets found. Create one first."}):a.jsx("div",{className:"rounded-md border overflow-hidden max-h-40 overflow-y-auto",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:j.map(E=>a.jsxs("label",{className:"flex items-center gap-2.5 px-3 py-2 text-xs cursor-pointer transition-colors",style:{borderBottom:"1px solid var(--border)"},onMouseEnter:w=>{w.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:w=>{w.currentTarget.style.background="transparent"},children:[a.jsx("input",{type:"checkbox",checked:c.has(E.id),onChange:()=>B(E.id),className:"accent-[var(--accent)]"}),a.jsx("span",{className:"flex-1 truncate",style:{color:"var(--text-primary)"},children:E.name}),a.jsxs("span",{className:"text-[10px]",style:{color:"var(--text-muted)"},children:[E.eval_count," items"]})]},E.id))})]}),T.length>0&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Evaluation Criteria"}),a.jsx("div",{className:"space-y-2",children:T.map(E=>{const w=L[E],M=Es(w),I=yc(w);return a.jsxs("div",{className:"rounded-md",style:{border:"1px solid var(--border)",background:"var(--bg-primary)",opacity:M?.6:1},children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",style:{borderBottom:M?"none":"1px solid var(--border)"},children:[a.jsx("span",{className:"text-xs font-medium truncate flex-1",style:{color:"var(--text-primary)"},children:(w==null?void 0:w.name)??E}),a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-medium",style:{color:I.color,background:`color-mix(in srgb, ${I.color} 12%, transparent)`},children:I.label})]}),M?a.jsx("div",{className:"px-3 pb-2",children:a.jsx("span",{className:"text-[10px] italic",style:{color:"var(--text-muted)"},children:"Default criteria — uses evaluator config"})}):a.jsx("div",{className:"px-3 pb-2 pt-1",children:a.jsx("textarea",{value:p[E]??"{}",onChange:D=>{f.current.add(E),m(N=>({...N,[E]:D.target.value}))},rows:8,className:"w-full rounded px-2 py-1.5 text-xs font-mono resize-y",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"}})})]},E)})})]})]}),a.jsxs("div",{className:"mt-4 space-y-3",children:[y&&a.jsx("p",{className:"text-xs px-3 py-2 rounded",style:{color:"var(--error)",background:"color-mix(in srgb, var(--error) 10%, var(--bg-secondary))"},children:y}),k&&a.jsxs("p",{className:"text-xs px-3 py-2 rounded",style:{color:"var(--success)",background:"color-mix(in srgb, var(--success) 10%, var(--bg-secondary))"},children:["Added to ",c.size," eval set",c.size!==1?"s":"","."]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:t,className:"flex-1 py-2 rounded-md text-xs font-semibold cursor-pointer",style:{background:"var(--bg-secondary)",color:"var(--text-secondary)",border:"1px solid var(--border)"},children:"Cancel"}),a.jsx("button",{onClick:O,disabled:!l.trim()||c.size===0||g||k,className:"flex-1 py-2 rounded-md text-[13px] font-semibold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--accent)",color:"var(--bg-primary)",border:"none"},children:g?"Adding...":k?"Added":"Add Item"})]})]})]})})}const Ec={pending:"var(--text-muted)",running:"var(--warning)",suspended:"var(--info)",completed:"var(--success)",failed:"var(--error)"};function kc({run:e,isSelected:t,onClick:n}){var p;const r=Ec[e.status]??"var(--text-muted)",i=((p=e.entrypoint.split("/").pop())==null?void 0:p.slice(0,16))??e.entrypoint,s=e.start_time?new Date(e.start_time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",[o,l]=S.useState(!1),[u,c]=S.useState(!1),d=S.useRef(null);return S.useEffect(()=>{if(!o)return;const m=f=>{d.current&&!d.current.contains(f.target)&&l(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[o]),a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"group relative w-full text-left px-3 py-1.5 flex items-center gap-2 transition-colors cursor-pointer",style:{background:t?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":void 0,borderLeft:t?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:m=>{t||(m.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:m=>{t||(m.currentTarget.style.background="")},onClick:n,children:[a.jsx("span",{className:"shrink-0 w-2 h-2 rounded-full",style:{background:r}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-xs truncate",style:{color:t?"var(--text-primary)":"var(--text-secondary)"},children:i}),a.jsxs("div",{className:"text-[11px] tabular-nums",style:{color:"var(--text-muted)"},children:[s,e.duration?` · ${e.duration}`:""]})]}),e.status==="completed"&&a.jsxs("div",{ref:d,className:"relative shrink-0",children:[a.jsx("button",{onClick:m=>{m.stopPropagation(),l(f=>!f)},className:"opacity-40 group-hover:opacity-100 focus:opacity-100 w-7 h-7 flex items-center justify-center rounded transition-opacity cursor-pointer",style:{color:"var(--text-muted)"},onMouseEnter:m=>{m.currentTarget.style.color="var(--text-primary)",m.currentTarget.style.background="var(--bg-secondary)"},onMouseLeave:m=>{m.currentTarget.style.color="var(--text-muted)",m.currentTarget.style.background=""},"aria-label":"Actions",title:"Actions",children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[a.jsx("circle",{cx:"8",cy:"3",r:"1.5"}),a.jsx("circle",{cx:"8",cy:"8",r:"1.5"}),a.jsx("circle",{cx:"8",cy:"13",r:"1.5"})]})}),o&&a.jsx("div",{className:"absolute right-0 top-full mt-1 z-50 min-w-[140px] rounded-md shadow-lg py-1",style:{background:"var(--bg-primary)",border:"1px solid var(--border)"},children:a.jsx("button",{onClick:m=>{m.stopPropagation(),l(!1),c(!0)},className:"w-full text-left px-3 py-1.5 text-xs cursor-pointer transition-colors",style:{color:"var(--text-secondary)"},onMouseEnter:m=>{m.currentTarget.style.background="var(--bg-hover)",m.currentTarget.style.color="var(--text-primary)"},onMouseLeave:m=>{m.currentTarget.style.background="",m.currentTarget.style.color="var(--text-secondary)"},children:"Add to Eval Set"})})]})]}),u&&a.jsx(vc,{run:e,onClose:()=>c(!1)})]})}function Oi({runs:e,selectedRunId:t,onSelectRun:n,onNewRun:r}){const i=[...e].sort((s,o)=>new Date(o.start_time??0).getTime()-new Date(s.start_time??0).getTime());return a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:r,className:"mx-3 mt-2.5 mb-1 px-3 py-1.5 text-[11px] font-medium rounded border border-[var(--border)] bg-transparent transition-colors cursor-pointer",style:{color:"var(--text-secondary)"},onMouseEnter:s=>{s.currentTarget.style.color="var(--text-primary)",s.currentTarget.style.borderColor="var(--text-muted)"},onMouseLeave:s=>{s.currentTarget.style.color="var(--text-secondary)",s.currentTarget.style.borderColor=""},children:"+ New Run"}),a.jsx("div",{className:"px-3 pt-3 pb-1 text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"History"}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[i.map(s=>a.jsx(kc,{run:s,isSelected:s.id===t,onClick:()=>n(s.id)},s.id)),i.length===0&&a.jsx("p",{className:"text-xs px-3 py-4 text-center",style:{color:"var(--text-muted)"},children:"No runs yet"})]})]})}function ks(){const e=localStorage.getItem("uipath-dev-theme");return e==="light"||e==="dark"?e:"dark"}function ws(e){document.documentElement.setAttribute("data-theme",e),localStorage.setItem("uipath-dev-theme",e)}ws(ks());const _s=Ot(e=>({theme:ks(),toggleTheme:()=>e(t=>{const n=t.theme==="dark"?"light":"dark";return ws(n),{theme:n}})}));function Li(){const{theme:e,toggleTheme:t}=_s(),{enabled:n,status:r,environment:i,tenants:s,uipathUrl:o,setEnvironment:l,startLogin:u,selectTenant:c,logout:d}=zn(),{projectName:p,projectVersion:m,projectAuthors:f}=bs(),[g,x]=S.useState(!1),[y,b]=S.useState(""),k=S.useRef(null),A=S.useRef(null);S.useEffect(()=>{if(!g)return;const N=_=>{k.current&&!k.current.contains(_.target)&&A.current&&!A.current.contains(_.target)&&x(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[g]);const j=r==="authenticated",L=r==="expired",T=r==="pending",B=r==="needs_tenant";let O="UiPath: Disconnected",E=null,w=!0;j?(O=`UiPath: ${o?o.replace(/^https?:\/\/[^/]+\//,""):""}`,E="var(--success)",w=!1):L?(O=`UiPath: ${o?o.replace(/^https?:\/\/[^/]+\//,""):""} (expired)`,E="var(--error)",w=!1):T?O="UiPath: Signing in…":B&&(O="UiPath: Select Tenant");const M=()=>{T||(L?u():x(N=>!N))},I="flex items-center gap-1 px-1.5 rounded transition-colors",D={onMouseEnter:N=>{N.currentTarget.style.background="var(--bg-hover)",N.currentTarget.style.color="var(--text-primary)"},onMouseLeave:N=>{N.currentTarget.style.background="",N.currentTarget.style.color="var(--text-muted)"}};return a.jsxs("div",{className:"h-6 flex items-center justify-end gap-3 px-2 text-xs border-t shrink-0",style:{background:"var(--bg-secondary)",color:"var(--text-muted)",borderColor:"var(--border)",fontSize:"11px"},children:[n&&a.jsxs("div",{className:"relative flex items-center",children:[a.jsxs("div",{ref:A,className:`${I} cursor-pointer`,onClick:M,...D,title:j?o??"":L?"Token expired — click to re-authenticate":T?"Signing in…":B?"Select a tenant":"Click to sign in",children:[T?a.jsxs("svg",{className:"animate-spin",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a.jsx("circle",{cx:"12",cy:"12",r:"10",strokeOpacity:"0.25"}),a.jsx("path",{d:"M12 2a10 10 0 0 1 10 10",strokeLinecap:"round"})]}):E?a.jsx("div",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{background:E}}):w?a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}),a.jsx("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"})]}):null,a.jsx("span",{className:"truncate max-w-[200px]",children:O})]}),g&&a.jsx("div",{ref:k,className:"absolute bottom-full right-0 mb-1 rounded border shadow-lg p-1 min-w-[180px]",style:{background:"var(--bg-secondary)",borderColor:"var(--border)"},children:j||L?a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:()=>{o&&window.open(o,"_blank","noopener,noreferrer"),x(!1)},className:"w-full flex items-center gap-2 px-2 py-2 text-[11px] rounded cursor-pointer transition-colors text-left",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:N=>{N.currentTarget.style.background="var(--bg-hover)",N.currentTarget.style.color="var(--text-primary)"},onMouseLeave:N=>{N.currentTarget.style.background="transparent",N.currentTarget.style.color="var(--text-muted)"},children:[a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),a.jsx("polyline",{points:"15 3 21 3 21 9"}),a.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),"Go to Platform"]}),a.jsxs("button",{onClick:()=>{d(),x(!1)},className:"w-full flex items-center gap-2 px-2 py-2 text-[11px] rounded cursor-pointer transition-colors text-left",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:N=>{N.currentTarget.style.background="var(--bg-hover)",N.currentTarget.style.color="var(--text-primary)"},onMouseLeave:N=>{N.currentTarget.style.background="transparent",N.currentTarget.style.color="var(--text-muted)"},children:[a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),a.jsx("polyline",{points:"16 17 21 12 16 7"}),a.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]}),"Sign Out"]})]}):B?a.jsxs("div",{className:"p-1",children:[a.jsx("label",{className:"block text-[10px] font-medium mb-1",style:{color:"var(--text-muted)"},children:"Tenant"}),a.jsxs("select",{value:y,onChange:N=>b(N.target.value),className:"w-full rounded px-1.5 py-1 text-[10px] mb-1.5 appearance-auto",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:"var(--text-primary)"},children:[a.jsx("option",{value:"",children:"Select…"}),s.map(N=>a.jsx("option",{value:N,children:N},N))]}),a.jsx("button",{onClick:()=>{y&&(c(y),x(!1))},disabled:!y,className:"w-full px-2 py-1 text-[10px] font-medium rounded border border-[var(--border)] bg-transparent cursor-pointer transition-colors disabled:opacity-30 disabled:cursor-not-allowed",style:{color:"var(--text-muted)"},children:"Confirm"})]}):a.jsxs("div",{className:"p-1",children:[a.jsx("label",{className:"block text-[10px] font-medium mb-1",style:{color:"var(--text-muted)"},children:"Environment"}),a.jsxs("select",{value:i,onChange:N=>l(N.target.value),className:"w-full rounded px-1.5 py-0.5 text-[10px] mb-1.5 appearance-auto",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:"var(--text-muted)"},children:[a.jsx("option",{value:"cloud",children:"cloud"}),a.jsx("option",{value:"staging",children:"staging"}),a.jsx("option",{value:"alpha",children:"alpha"})]}),a.jsx("button",{onClick:()=>{u(),x(!1)},className:"w-full px-2 py-1 text-[10px] font-medium rounded border border-[var(--border)] bg-transparent cursor-pointer transition-colors",style:{color:"var(--text-muted)"},onMouseEnter:N=>{N.currentTarget.style.color="var(--text-primary)",N.currentTarget.style.borderColor="var(--text-muted)"},onMouseLeave:N=>{N.currentTarget.style.color="var(--text-muted)",N.currentTarget.style.borderColor="var(--border)"},children:"Sign In"})]})})]}),p&&a.jsxs("span",{className:I,children:["Project: ",p]}),m&&a.jsxs("span",{className:I,children:["Version: v",m]}),f&&a.jsxs("span",{className:I,children:["Author: ",f]}),a.jsxs("a",{href:"https://github.com/UiPath/uipath-dev-python",target:"_blank",rel:"noopener noreferrer",className:`${I} cursor-pointer no-underline`,style:{color:"var(--text-muted)"},...D,title:"View on GitHub",children:[a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z"})}),a.jsx("span",{children:"uipath-dev-python"})]}),a.jsxs("div",{className:`${I} cursor-pointer`,onClick:t,...D,title:`Switch to ${e==="dark"?"light":"dark"} theme`,children:[a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="dark"?a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"5"}),a.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),a.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),a.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),a.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),a.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),a.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),a.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),a.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]}):a.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),a.jsx("span",{children:e==="dark"?"Dark":"Light"})]})]})}function wc(){const{navigate:e}=ot(),t=Ee(c=>c.entrypoints),[n,r]=S.useState(""),[i,s]=S.useState(!0),[o,l]=S.useState(null);S.useEffect(()=>{!n&&t.length>0&&r(t[0])},[t,n]),S.useEffect(()=>{n&&(s(!0),l(null),Xl(n).then(c=>{var p;const d=(p=c.input)==null?void 0:p.properties;s(!!(d!=null&&d.messages))}).catch(c=>{const d=c.detail||{};l(d.error||d.message||`Failed to load entrypoint "${n}"`)}))},[n]);const u=c=>{n&&e(`#/setup/${encodeURIComponent(n)}/${c}`)};return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"w-full max-w-xl px-6",children:[a.jsxs("div",{className:"mb-8 text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2",children:[a.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{background:o?"var(--error)":"var(--accent)"}}),a.jsx("span",{className:"text-sm font-semibold",style:{color:"var(--text-muted)"},children:"New Run"})]}),!o&&a.jsx("p",{className:"text-sm",style:{color:"var(--text-muted)"},children:t.length>1?"Select an entrypoint and choose a mode":"Choose a mode"})]}),t.length>1&&a.jsxs("div",{className:"mb-8",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Entrypoint"}),a.jsx("select",{id:"entrypoint-select",value:n,onChange:c=>r(c.target.value),className:"w-full rounded-md px-3 py-2 text-xs font-mono cursor-pointer appearance-auto",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"},children:t.map(c=>a.jsx("option",{value:c,children:c},c))})]}),o?a.jsxs("div",{className:"rounded-md border overflow-hidden",style:{borderColor:"color-mix(in srgb, var(--error) 25%, var(--border))",background:"var(--bg-secondary)"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{borderBottom:"1px solid color-mix(in srgb, var(--error) 15%, var(--border))",background:"color-mix(in srgb, var(--error) 4%, var(--bg-secondary))"},children:[a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",style:{flexShrink:0},children:a.jsx("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7.25 4.75h1.5v4h-1.5v-4zm.75 6.75a.75.75 0 110-1.5.75.75 0 010 1.5z",fill:"var(--error)"})}),a.jsx("span",{className:"text-[11px] font-medium",style:{color:"var(--error)"},children:"Failed to load entrypoint"})]}),a.jsx("div",{className:"overflow-auto max-h-48 p-3",children:a.jsx("pre",{className:"text-[11px] font-mono whitespace-pre-wrap break-words leading-relaxed m-0",style:{color:"var(--text-muted)"},children:o})})]}):a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsx(ji,{title:"Autonomous",description:"Run the agent end-to-end. Set breakpoints to pause and inspect execution.",icon:a.jsx(_c,{}),color:"var(--success)",onClick:()=>u("run"),disabled:!n}),a.jsx(ji,{title:"Conversational",description:i?"Interactive chat session. Send messages and receive responses in real time.":'Requires a "messages" property in the input schema.',icon:a.jsx(Nc,{}),color:"var(--accent)",onClick:()=>u("chat"),disabled:!n||!i})]})]})})}function ji({title:e,description:t,icon:n,color:r,onClick:i,disabled:s}){return a.jsxs("button",{onClick:i,disabled:s,className:"group flex flex-col items-center text-center p-6 rounded-md border transition-all cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--bg-secondary)",borderColor:"var(--border)"},onMouseEnter:o=>{s||(o.currentTarget.style.borderColor=r,o.currentTarget.style.background=`color-mix(in srgb, ${r} 5%, var(--bg-secondary))`)},onMouseLeave:o=>{o.currentTarget.style.borderColor="var(--border)",o.currentTarget.style.background="var(--bg-secondary)"},children:[a.jsx("div",{className:"mb-4 p-3 rounded-xl transition-colors",style:{background:`color-mix(in srgb, ${r} 10%, var(--bg-primary))`,color:r},children:n}),a.jsx("h3",{className:"text-sm font-semibold mb-1.5",style:{color:"var(--text-primary)"},children:e}),a.jsx("p",{className:"text-xs leading-relaxed",style:{color:"var(--text-muted)"},children:t})]})}function _c(){return a.jsx("svg",{width:"28",height:"28",viewBox:"0 0 26 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M23.832 15.166H22.7487C22.7487 10.9735 19.3579 7.58268 15.1654 7.58268H14.082V6.20685C14.732 5.83852 15.1654 5.13435 15.1654 4.33268C15.1654 3.14102 14.2012 2.16602 12.9987 2.16602C11.7962 2.16602 10.832 3.14102 10.832 4.33268C10.832 5.13435 11.2654 5.83852 11.9154 6.20685V7.58268H10.832C6.63953 7.58268 3.2487 10.9735 3.2487 15.166H2.16536C1.56953 15.166 1.08203 15.6535 1.08203 16.2493V19.4993C1.08203 20.0952 1.56953 20.5827 2.16536 20.5827H3.2487V21.666C3.2487 22.8685 4.2237 23.8327 5.41536 23.8327H20.582C21.7845 23.8327 22.7487 22.8685 22.7487 21.666V20.5827H23.832C24.4279 20.5827 24.9154 20.0952 24.9154 19.4993V16.2493C24.9154 15.6535 24.4279 15.166 23.832 15.166ZM22.7487 18.416H20.582V21.666H5.41536V18.416H3.2487V17.3327H5.41536V15.166C5.41536 12.176 7.84203 9.74935 10.832 9.74935H15.1654C18.1554 9.74935 20.582 12.176 20.582 15.166V17.3327H22.7487V18.416ZM9.20703 14.6243L11.7637 17.181L10.4854 18.4594L9.20703 17.181L7.9287 18.4594L6.65036 17.181L9.20703 14.6243ZM16.7904 14.6243L19.347 17.181L18.0687 18.4594L16.7904 17.181L15.512 18.4594L14.2337 17.181L16.7904 14.6243Z",fill:"currentColor"})})}function Nc(){return a.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 26 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M9.20901 13.541L11.7657 16.0977L10.4873 17.376L9.20901 16.0977L7.93068 17.376L6.65234 16.0977L9.20901 13.541ZM16.7923 13.541L19.349 16.0977L18.0707 17.376L16.7923 16.0977L15.514 17.376L14.2357 16.0977L16.7923 13.541Z",fill:"currentColor"}),a.jsx("path",{d:"M5.25 8.58398H20.75C21.3023 8.58398 21.75 9.0317 21.75 9.58398V23.5293L16.874 21.9043C16.5683 21.8024 16.248 21.751 15.9258 21.751H5.25C4.69782 21.751 4.25018 21.3031 4.25 20.751V9.58398C4.25 9.0317 4.69772 8.58398 5.25 8.58398Z",stroke:"currentColor",strokeWidth:"2"}),a.jsx("ellipse",{cx:"12.9987",cy:"4.33268",rx:"2.16667",ry:"2.16667",fill:"currentColor"}),a.jsx("rect",{x:"11.918",y:"5.41602",width:"2.16667",height:"2.16667",fill:"currentColor"}),a.jsx("path",{d:"M1.08203 14C1.08203 13.4477 1.52975 13 2.08203 13H3.2487V18.4167H2.08203C1.52975 18.4167 1.08203 17.969 1.08203 17.4167V14Z",fill:"currentColor"}),a.jsx("rect",{x:"3.25",y:"15.166",width:"2.16667",height:"1.08333",fill:"currentColor"}),a.jsx("path",{d:"M22.75 13H23.9167C24.4689 13 24.9167 13.4477 24.9167 14V17.4167C24.9167 17.969 24.469 18.4167 23.9167 18.4167H22.75V13Z",fill:"currentColor"}),a.jsx("rect",{x:"20.582",y:"15.166",width:"2.16667",height:"1.08333",fill:"currentColor"})]})}const Sc="modulepreload",Tc=function(e){return"/"+e},Di={},Ns=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let o=function(c){return Promise.all(c.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=o(n.map(c=>{if(c=Tc(c),c in Di)return;Di[c]=!0;const d=c.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${p}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":Sc,d||(m.as="script"),m.crossOrigin="",m.href=c,u&&m.setAttribute("nonce",u),document.head.appendChild(m),d)return new Promise((f,g)=>{m.addEventListener("load",f),m.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${c}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})},Cc={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0};function Ac({data:e}){const t=e.status,n=e.nodeWidth,r=e.label??"Start",i=e.hasBreakpoint,s=e.isPausedHere,o=e.isActiveNode,l=e.isExecutingNode,u=s?"var(--error)":l?"var(--success)":o?"var(--accent)":t==="completed"?"var(--success)":t==="running"?"var(--warning)":"var(--node-border)",c=s?"var(--error)":l?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"px-3 py-1.5 rounded-full text-center text-xs overflow-hidden text-ellipsis whitespace-nowrap cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${u}`,boxShadow:s||o||l?`0 0 4px ${c}`:void 0,animation:s||o||l?`node-pulse-${s?"red":l?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r,children:[i&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),r,a.jsx(gt,{type:"source",position:bt.Bottom,style:Cc})]})}const Mc={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0};function Rc({data:e}){const t=e.status,n=e.nodeWidth,r=e.label??"End",i=e.hasBreakpoint,s=e.isPausedHere,o=e.isActiveNode,l=e.isExecutingNode,u=s?"var(--error)":l?"var(--success)":o?"var(--accent)":t==="completed"?"var(--success)":t==="failed"?"var(--error)":"var(--node-border)",c=s?"var(--error)":l?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"px-3 py-1.5 rounded-full text-center text-xs overflow-hidden text-ellipsis whitespace-nowrap cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${u}`,boxShadow:s||o||l?`0 0 4px ${c}`:void 0,animation:s||o||l?`node-pulse-${s?"red":l?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r,children:[i&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),a.jsx(gt,{type:"target",position:bt.Top,style:Mc}),r]})}const Pi={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0};function Ic({data:e}){const t=e.status,n=e.nodeWidth,r=e.model_name,i=e.label??"Model",s=e.hasBreakpoint,o=e.isPausedHere,l=e.isActiveNode,u=e.isExecutingNode,c=o?"var(--error)":u?"var(--success)":l?"var(--accent)":t==="completed"?"var(--success)":t==="running"?"var(--warning)":t==="failed"?"var(--error)":"var(--node-border)",d=o?"var(--error)":u?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"px-3 py-1.5 rounded-lg text-center text-xs overflow-hidden cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${c}`,boxShadow:o||l||u?`0 0 4px ${d}`:void 0,animation:o||l||u?`node-pulse-${o?"red":u?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r?`${i} +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-elk-CzxJ-xdZ.js","assets/vendor-react-BN_uQvcy.js","assets/ChatPanel-DAnMwTFj.js","assets/vendor-reactflow-BP_V7ttx.js","assets/vendor-reactflow-B5DZHykP.css"])))=>i.map(i=>d[i]); +var Nl=Object.defineProperty;var Sl=(e,t,n)=>t in e?Nl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Rt=(e,t,n)=>Sl(e,typeof t!="symbol"?t+"":t,n);import{W as Tn,a as S,j as a,F as Tl,g as Gr,b as Cl}from"./vendor-react-BN_uQvcy.js";import{H as gt,P as bt,B as Al,M as Ml,u as Rl,a as Il,R as Ol,b as Ll,C as jl,c as Dl,d as Pl}from"./vendor-reactflow-BP_V7ttx.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();const Ci=e=>{let t;const n=new Set,r=(c,d)=>{const p=typeof c=="function"?c(t):c;if(!Object.is(p,t)){const m=t;t=d??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(f=>f(t,m))}},i=()=>t,l={setState:r,getState:i,getInitialState:()=>u,subscribe:c=>(n.add(c),()=>n.delete(c))},u=t=e(r,i,l);return l},Bl=(e=>e?Ci(e):Ci),Fl=e=>e;function zl(e,t=Fl){const n=Tn.useSyncExternalStore(e.subscribe,Tn.useCallback(()=>t(e.getState()),[e,t]),Tn.useCallback(()=>t(e.getInitialState()),[e,t]));return Tn.useDebugValue(n),n}const Ai=e=>{const t=Bl(e),n=r=>zl(t,r);return Object.assign(n,t),n},Ot=(e=>e?Ai(e):Ai),Ee=Ot(e=>({runs:{},selectedRunId:null,traces:{},logs:{},chatMessages:{},entrypoints:[],setRuns:t=>e(n=>{var s;let r=n.breakpoints;for(const o of t)(s=o.breakpoints)!=null&&s.length&&!r[o.id]&&(r={...r,[o.id]:Object.fromEntries(o.breakpoints.map(l=>[l,!0]))});const i={runs:Object.fromEntries(t.map(o=>[o.id,o]))};return r!==n.breakpoints&&(i.breakpoints=r),i}),upsertRun:t=>e(n=>{var i;const r={runs:{...n.runs,[t.id]:t}};if((i=t.breakpoints)!=null&&i.length&&!n.breakpoints[t.id]&&(r.breakpoints={...n.breakpoints,[t.id]:Object.fromEntries(t.breakpoints.map(s=>[s,!0]))}),(t.status==="completed"||t.status==="failed")&&n.activeNodes[t.id]){const{[t.id]:s,...o}=n.activeNodes;r.activeNodes=o}if(t.status!=="suspended"&&n.activeInterrupt[t.id]){const{[t.id]:s,...o}=n.activeInterrupt;r.activeInterrupt=o}return r}),selectRun:t=>e({selectedRunId:t}),addTrace:t=>e(n=>{const r=n.traces[t.run_id]??[],i=r.findIndex(o=>o.span_id===t.span_id),s=i>=0?r.map((o,l)=>l===i?t:o):[...r,t];return{traces:{...n.traces,[t.run_id]:s}}}),setTraces:(t,n)=>e(r=>({traces:{...r.traces,[t]:n}})),addLog:t=>e(n=>{const r=n.logs[t.run_id]??[];return{logs:{...n.logs,[t.run_id]:[...r,t]}}}),setLogs:(t,n)=>e(r=>({logs:{...r.logs,[t]:n}})),addChatEvent:(t,n)=>e(r=>{const i=r.chatMessages[t]??[],s=n.message;if(!s)return r;const o=s.messageId??s.message_id,l=s.role??"assistant",d=(s.contentParts??s.content_parts??[]).filter(x=>{const v=x.mimeType??x.mime_type??"";return v.startsWith("text/")||v==="application/json"}).map(x=>{const v=x.data;return(v==null?void 0:v.inline)??""}).join(` +`).trim(),p=(s.toolCalls??s.tool_calls??[]).map(x=>({name:x.name??"",has_result:!!x.result})),m={message_id:o,role:l,content:d,tool_calls:p.length>0?p:void 0},f=i.findIndex(x=>x.message_id===o);if(f>=0)return{chatMessages:{...r.chatMessages,[t]:i.map((x,v)=>v===f?m:x)}};if(l==="user"){const x=i.findIndex(v=>v.message_id.startsWith("local-")&&v.role==="user"&&v.content===d);if(x>=0)return{chatMessages:{...r.chatMessages,[t]:i.map((v,b)=>b===x?m:v)}}}const h=[...i,m];return{chatMessages:{...r.chatMessages,[t]:h}}}),addLocalChatMessage:(t,n)=>e(r=>{const i=r.chatMessages[t]??[];return{chatMessages:{...r.chatMessages,[t]:[...i,n]}}}),setChatMessages:(t,n)=>e(r=>({chatMessages:{...r.chatMessages,[t]:n}})),setEntrypoints:t=>e({entrypoints:t}),breakpoints:{},toggleBreakpoint:(t,n)=>e(r=>{const i={...r.breakpoints[t]??{}};return i[n]?delete i[n]:i[n]=!0,{breakpoints:{...r.breakpoints,[t]:i}}}),clearBreakpoints:t=>e(n=>{const{[t]:r,...i}=n.breakpoints;return{breakpoints:i}}),activeNodes:{},setActiveNode:(t,n,r)=>e(i=>{const s=i.activeNodes[t]??{executing:{},prev:null};return{activeNodes:{...i.activeNodes,[t]:{executing:{...s.executing,[n]:r??null},prev:s.prev}}}}),removeActiveNode:(t,n)=>e(r=>{const i=r.activeNodes[t];if(!i)return r;const{[n]:s,...o}=i.executing;return{activeNodes:{...r.activeNodes,[t]:{executing:o,prev:n}}}}),resetRunGraphState:t=>e(n=>({stateEvents:{...n.stateEvents,[t]:[]},activeNodes:{...n.activeNodes,[t]:{executing:{},prev:null}}})),stateEvents:{},addStateEvent:(t,n,r,i,s)=>e(o=>{const l=o.stateEvents[t]??[];return{stateEvents:{...o.stateEvents,[t]:[...l,{node_name:n,qualified_node_name:i,phase:s,timestamp:Date.now(),payload:r}]}}}),setStateEvents:(t,n)=>e(r=>({stateEvents:{...r.stateEvents,[t]:n}})),focusedSpan:null,setFocusedSpan:t=>e({focusedSpan:t}),activeInterrupt:{},setActiveInterrupt:(t,n)=>e(r=>({activeInterrupt:{...r.activeInterrupt,[t]:n}})),reloadPending:!1,setReloadPending:t=>e({reloadPending:t}),graphCache:{},setGraphCache:(t,n)=>e(r=>({graphCache:{...r.graphCache,[t]:n}}))})),Vn="/api";async function Ul(e){const t=await fetch(`${Vn}/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({environment:e})});if(!t.ok)throw new Error(`Login failed: ${t.status}`);return t.json()}async function sr(){const e=await fetch(`${Vn}/auth/status`);if(!e.ok)throw new Error(`Status check failed: ${e.status}`);return e.json()}async function $l(e){const t=await fetch(`${Vn}/auth/select-tenant`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenant_name:e})});if(!t.ok)throw new Error(`Tenant selection failed: ${t.status}`);return t.json()}async function Hl(){await fetch(`${Vn}/auth/logout`,{method:"POST"})}const gs="uipath-env",Wl=["cloud","staging","alpha"];function Kl(){const e=localStorage.getItem(gs);return Wl.includes(e)?e:"cloud"}const zn=Ot((e,t)=>({enabled:!0,status:"unauthenticated",environment:Kl(),tenants:[],uipathUrl:null,pollTimer:null,expiryTimer:null,init:async()=>{try{const n=await fetch("/api/config");if(n.ok&&!(await n.json()).auth_enabled){e({enabled:!1});return}const r=await sr();e({status:r.status,tenants:r.tenants??[],uipathUrl:r.uipath_url??null}),r.status==="authenticated"&&t().startExpiryCheck()}catch(n){console.error("Auth init failed",n)}},setEnvironment:n=>{localStorage.setItem(gs,n),e({environment:n})},startLogin:async()=>{const{environment:n}=t();try{const r=await Ul(n);e({status:"pending"}),window.open(r.auth_url,"_blank"),t().pollStatus()}catch(r){console.error("Login failed",r)}},pollStatus:()=>{const{pollTimer:n}=t();if(n)return;const r=setInterval(async()=>{try{const i=await sr();i.status!=="pending"&&(t().stopPolling(),e({status:i.status,tenants:i.tenants??[],uipathUrl:i.uipath_url??null}),i.status==="authenticated"&&t().startExpiryCheck())}catch{}},2e3);e({pollTimer:r})},stopPolling:()=>{const{pollTimer:n}=t();n&&(clearInterval(n),e({pollTimer:null}))},startExpiryCheck:()=>{const{expiryTimer:n}=t();if(n)return;const r=setInterval(async()=>{try{(await sr()).status==="expired"&&(t().stopExpiryCheck(),e({status:"expired"}))}catch{}},3e4);e({expiryTimer:r})},stopExpiryCheck:()=>{const{expiryTimer:n}=t();n&&(clearInterval(n),e({expiryTimer:null}))},selectTenant:async n=>{try{const r=await $l(n);e({status:"authenticated",uipathUrl:r.uipath_url,tenants:[]}),t().startExpiryCheck()}catch(r){console.error("Tenant selection failed",r)}},logout:async()=>{t().stopPolling(),t().stopExpiryCheck();try{await Hl()}catch{}e({status:"unauthenticated",tenants:[],uipathUrl:null})}})),bs=Ot(e=>({projectName:null,projectVersion:null,projectAuthors:null,init:async()=>{try{const t=await fetch("/api/config");if(t.ok){const n=await t.json();e({projectName:n.project_name??null,projectVersion:n.project_version??null,projectAuthors:n.project_authors??null})}}catch{}}}));class Gl{constructor(t){Rt(this,"ws",null);Rt(this,"url");Rt(this,"handlers",new Set);Rt(this,"reconnectTimer",null);Rt(this,"shouldReconnect",!0);Rt(this,"pendingMessages",[]);Rt(this,"activeSubscriptions",new Set);const n=window.location.protocol==="https:"?"wss:":"ws:";this.url=t??`${n}//${window.location.host}/ws`}connect(){var t;((t=this.ws)==null?void 0:t.readyState)!==WebSocket.OPEN&&(this.ws=new WebSocket(this.url),this.ws.onopen=()=>{console.log("[ws] connected");for(const n of this.activeSubscriptions)this.sendRaw(JSON.stringify({type:"subscribe",payload:{run_id:n}}));for(const n of this.pendingMessages)this.sendRaw(n);this.pendingMessages=[]},this.ws.onmessage=n=>{let r;try{r=JSON.parse(n.data)}catch{console.warn("[ws] failed to parse message",n.data);return}this.handlers.forEach(i=>{try{i(r)}catch(s){console.error("[ws] handler error",s)}})},this.ws.onclose=()=>{console.log("[ws] disconnected"),this.shouldReconnect&&(this.reconnectTimer=setTimeout(()=>this.connect(),2e3))},this.ws.onerror=()=>{var n;(n=this.ws)==null||n.close()})}disconnect(){var t;this.shouldReconnect=!1,this.reconnectTimer&&clearTimeout(this.reconnectTimer),(t=this.ws)==null||t.close(),this.ws=null}onMessage(t){return this.handlers.add(t),()=>this.handlers.delete(t)}sendRaw(t){var n;((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(t)}send(t,n){var i;const r=JSON.stringify({type:t,payload:n});((i=this.ws)==null?void 0:i.readyState)===WebSocket.OPEN?this.ws.send(r):this.pendingMessages.push(r)}subscribe(t){this.activeSubscriptions.add(t),this.send("subscribe",{run_id:t})}unsubscribe(t){this.activeSubscriptions.delete(t),this.send("unsubscribe",{run_id:t})}sendChatMessage(t,n){this.send("chat.message",{run_id:t,text:n})}sendInterruptResponse(t,n){this.send("chat.interrupt_response",{run_id:t,data:n})}debugStep(t){this.send("debug.step",{run_id:t})}debugContinue(t){this.send("debug.continue",{run_id:t})}debugStop(t){this.send("debug.stop",{run_id:t})}setBreakpoints(t,n){this.send("debug.set_breakpoints",{run_id:t,breakpoints:n})}sendAgentMessage(t,n,r,i){this.send("agent.message",{text:t,model:n,session_id:r??void 0,skill_ids:i&&i.length>0?i:void 0})}sendAgentStop(t){this.send("agent.stop",{session_id:t})}sendToolApproval(t,n,r){this.send("agent.tool_response",{session_id:t,tool_call_id:n,approved:r})}}const Ae=Ot(e=>({evaluators:[],localEvaluators:[],evalSets:{},evalRuns:{},setEvaluators:t=>e({evaluators:t}),setLocalEvaluators:t=>e({localEvaluators:t}),addLocalEvaluator:t=>e(n=>({localEvaluators:[...n.localEvaluators,t]})),upsertLocalEvaluator:t=>e(n=>({localEvaluators:n.localEvaluators.some(r=>r.id===t.id)?n.localEvaluators.map(r=>r.id===t.id?t:r):[...n.localEvaluators,t]})),setEvalSets:t=>e({evalSets:Object.fromEntries(t.map(n=>[n.id,n]))}),addEvalSet:t=>e(n=>({evalSets:{...n.evalSets,[t.id]:t}})),updateEvalSetEvaluators:(t,n)=>e(r=>{const i=r.evalSets[t];return i?{evalSets:{...r.evalSets,[t]:{...i,evaluator_ids:n}}}:r}),incrementEvalSetCount:(t,n=1)=>e(r=>{const i=r.evalSets[t];return i?{evalSets:{...r.evalSets,[t]:{...i,eval_count:i.eval_count+n}}}:r}),setEvalRuns:t=>e({evalRuns:Object.fromEntries(t.map(n=>[n.id,n]))}),upsertEvalRun:t=>e(n=>({evalRuns:{...n.evalRuns,[t.id]:t}})),updateEvalRunProgress:(t,n,r)=>e(i=>{const s=i.evalRuns[t];return s?{evalRuns:{...i.evalRuns,[t]:{...s,progress_completed:n,progress_total:r,status:"running"}}}:i}),completeEvalRun:(t,n,r)=>e(i=>{const s=i.evalRuns[t];return s?{evalRuns:{...i.evalRuns,[t]:{...s,status:"completed",overall_score:n,evaluator_scores:r,end_time:new Date().toISOString()}}}:i})}));let ql=0;function Ut(){return`agent-msg-${++ql}`}const rt=Ot(e=>({sessionId:null,status:"idle",messages:[],plan:[],models:[],selectedModel:null,modelsLoading:!1,skills:[],selectedSkillIds:[],skillsLoading:!1,setStatus:t=>e({status:t}),addUserMessage:t=>e(n=>({messages:[...n.messages,{id:Ut(),role:"user",content:t,timestamp:Date.now()}]})),appendAssistantText:(t,n)=>e(r=>{const i=[...r.messages],s=i[i.length-1];return s&&s.role==="assistant"&&!s.done?i[i.length-1]={...s,content:s.content+t,done:n}:i.push({id:Ut(),role:"assistant",content:t,timestamp:Date.now(),done:n}),{messages:i}}),setPlan:t=>e(n=>{const r=[...n.messages],i=r.findIndex(o=>o.role==="plan"),s={id:i>=0?r[i].id:Ut(),role:"plan",content:"",timestamp:Date.now(),planItems:t};return i>=0?r[i]=s:r.push(s),{messages:r,plan:t}}),addToolUse:(t,n)=>e(r=>{const i=[...r.messages],s=i[i.length-1],o={tool:t,args:n};return s&&s.role==="tool"&&s.toolCalls?i[i.length-1]={...s,toolCalls:[...s.toolCalls,o]}:i.push({id:Ut(),role:"tool",content:"",timestamp:Date.now(),toolCalls:[o]}),{messages:i}}),addToolResult:(t,n,r)=>e(i=>{const s=[...i.messages];for(let o=s.length-1;o>=0;o--){const l=s[o];if(l.role==="tool"&&l.toolCalls){const u=[...l.toolCalls];for(let c=u.length-1;c>=0;c--)if(u[c].tool===t&&u[c].result===void 0)return u[c]={...u[c],result:n,is_error:r},s[o]={...l,toolCalls:u},{messages:s}}}return{messages:s}}),addToolApprovalRequest:(t,n,r)=>e(i=>{const s=[...i.messages],o={tool:n,args:r,tool_call_id:t,status:"pending"},l=s[s.length-1];return l&&l.role==="tool"&&l.toolCalls?s[s.length-1]={...l,toolCalls:[...l.toolCalls,o]}:s.push({id:Ut(),role:"tool",content:"",timestamp:Date.now(),toolCalls:[o]}),{messages:s}}),resolveToolApproval:(t,n)=>e(r=>{const i=[...r.messages];for(let s=i.length-1;s>=0;s--){const o=i[s];if(o.role==="tool"&&o.toolCalls){const l=[...o.toolCalls];for(let u=l.length-1;u>=0;u--)if(l[u].tool_call_id===t)return l[u]={...l[u],status:n?"approved":"denied"},i[s]={...o,toolCalls:l},{messages:i}}}return{messages:i}}),appendThinking:t=>e(n=>{const r=[...n.messages],i=r[r.length-1];return i&&i.role==="thinking"?r[r.length-1]={...i,content:i.content+t}:r.push({id:Ut(),role:"thinking",content:t,timestamp:Date.now()}),{messages:r}}),addError:t=>e(n=>({status:"error",messages:[...n.messages,{id:Ut(),role:"assistant",content:`Error: ${t}`,timestamp:Date.now(),done:!0}]})),setSessionId:t=>e({sessionId:t}),setModels:t=>e({models:t}),setSelectedModel:t=>e({selectedModel:t}),setModelsLoading:t=>e({modelsLoading:t}),setSkills:t=>e({skills:t}),setSelectedSkillIds:t=>e({selectedSkillIds:t}),toggleSkill:t=>e(n=>({selectedSkillIds:n.selectedSkillIds.includes(t)?n.selectedSkillIds.filter(i=>i!==t):[...n.selectedSkillIds,t]})),setSkillsLoading:t=>e({skillsLoading:t}),clearSession:()=>e({sessionId:null,status:"idle",messages:[],plan:[]})})),Me=Ot(e=>({children:{},expanded:{},selectedFile:null,openTabs:[],fileCache:{},dirty:{},buffers:{},loadingDirs:{},loadingFile:!1,setChildren:(t,n)=>e(r=>({children:{...r.children,[t]:n}})),toggleExpanded:t=>e(n=>({expanded:{...n.expanded,[t]:!n.expanded[t]}})),setSelectedFile:t=>e({selectedFile:t}),openTab:t=>e(n=>({selectedFile:t,openTabs:n.openTabs.includes(t)?n.openTabs:[...n.openTabs,t]})),closeTab:t=>e(n=>{const r=n.openTabs.filter(c=>c!==t);let i=n.selectedFile;if(i===t){const c=n.openTabs.indexOf(t);i=r[Math.min(c,r.length-1)]??null}const{[t]:s,...o}=n.dirty,{[t]:l,...u}=n.buffers;return{openTabs:r,selectedFile:i,dirty:o,buffers:u}}),setFileContent:(t,n)=>e(r=>({fileCache:{...r.fileCache,[t]:n}})),updateBuffer:(t,n)=>e(r=>({buffers:{...r.buffers,[t]:n},dirty:{...r.dirty,[t]:!0}})),markClean:t=>e(n=>{const{[t]:r,...i}=n.dirty,{[t]:s,...o}=n.buffers;return{dirty:i,buffers:o}}),setLoadingDir:(t,n)=>e(r=>({loadingDirs:{...r.loadingDirs,[t]:n}})),setLoadingFile:t=>e({loadingFile:t})})),qr="/api";async function Vr(e,t){const n=await fetch(e,t);if(!n.ok){let r;try{r=(await n.json()).detail||n.statusText}catch{r=n.statusText}const i=new Error(`HTTP ${n.status}`);throw i.detail=r,i.status=n.status,i}return n.json()}async function Yr(e){return Vr(`${qr}/files/tree?path=${encodeURIComponent(e)}`)}async function xs(e){return Vr(`${qr}/files/content?path=${encodeURIComponent(e)}`)}async function Vl(e,t){await Vr(`${qr}/files/content?path=${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})})}let Cn=null;function Xr(){return Cn||(Cn=new Gl,Cn.connect()),Cn}function Yl(){const e=S.useRef(Xr()),{upsertRun:t,addTrace:n,addLog:r,addChatEvent:i,setActiveInterrupt:s,setActiveNode:o,removeActiveNode:l,resetRunGraphState:u,addStateEvent:c,setReloadPending:d}=Ee(),{upsertEvalRun:p,updateEvalRunProgress:m,completeEvalRun:f}=Ae();return S.useEffect(()=>e.current.onMessage(v=>{switch(v.type){case"run.updated":t(v.payload);break;case"trace":n(v.payload);break;case"log":r(v.payload);break;case"chat":{const b=v.payload.run_id;i(b,v.payload);break}case"chat.interrupt":{const b=v.payload.run_id;s(b,v.payload);break}case"state":{const b=v.payload.run_id,E=v.payload.node_name,A=v.payload.qualified_node_name??null,D=v.payload.phase??null,L=v.payload.payload;E==="__start__"&&D==="started"&&u(b),D==="started"?o(b,E,A):D==="completed"&&l(b,E),c(b,E,L,A,D);break}case"reload":d(!0);break;case"files.changed":{const b=v.payload.files,E=new Set(b),A=Me.getState();for(const L of A.openTabs)A.dirty[L]||!E.has(L)||xs(L).then(T=>{var O;const B=Me.getState();B.dirty[L]||((O=B.fileCache[L])==null?void 0:O.content)!==T.content&&B.setFileContent(L,T)}).catch(()=>{});const D=new Set;for(const L of b){const T=L.lastIndexOf("/"),B=T===-1?"":L.substring(0,T);B in A.children&&D.add(B)}for(const L of D)Yr(L).then(T=>Me.getState().setChildren(L,T)).catch(()=>{});break}case"eval_run.created":p(v.payload);break;case"eval_run.progress":{const{run_id:b,completed:E,total:A,item_result:D}=v.payload;m(b,E,A,D);break}case"eval_run.completed":{const{run_id:b,overall_score:E,evaluator_scores:A}=v.payload;f(b,E,A);break}case"agent.status":{const{session_id:b,status:E}=v.payload,A=rt.getState();A.sessionId||A.setSessionId(b),A.setStatus(E);break}case"agent.text":{const{session_id:b,content:E,done:A}=v.payload,D=rt.getState();D.sessionId||D.setSessionId(b),D.appendAssistantText(E,A);break}case"agent.plan":{const{session_id:b,items:E}=v.payload,A=rt.getState();A.sessionId||A.setSessionId(b),A.setPlan(E);break}case"agent.tool_use":{const{session_id:b,tool:E,args:A}=v.payload,D=rt.getState();D.sessionId||D.setSessionId(b),D.addToolUse(E,A);break}case"agent.tool_result":{const{tool:b,result:E,is_error:A}=v.payload;rt.getState().addToolResult(b,E,A);break}case"agent.tool_approval":{const{session_id:b,tool_call_id:E,tool:A,args:D}=v.payload,L=rt.getState();L.sessionId||L.setSessionId(b),L.addToolApprovalRequest(E,A,D);break}case"agent.thinking":{const{content:b}=v.payload;rt.getState().appendThinking(b);break}case"agent.text_delta":{const{session_id:b,delta:E}=v.payload,A=rt.getState();A.sessionId||A.setSessionId(b),A.appendAssistantText(E,!1);break}case"agent.token_usage":break;case"agent.error":{const{message:b}=v.payload;rt.getState().addError(b);break}}}),[t,n,r,i,s,o,l,u,c,d,p,m,f]),e.current}const Lt="/api";async function jt(e,t){const n=await fetch(e,t);if(!n.ok){let r;try{r=(await n.json()).detail||n.statusText}catch{r=n.statusText}const i=new Error(`HTTP ${n.status}`);throw i.detail=r,i.status=n.status,i}return n.json()}async function ys(){return jt(`${Lt}/entrypoints`)}async function Xl(e){return jt(`${Lt}/entrypoints/${encodeURIComponent(e)}/schema`)}async function Zl(e){return jt(`${Lt}/entrypoints/${encodeURIComponent(e)}/mock-input`)}async function Jl(e){return jt(`${Lt}/entrypoints/${encodeURIComponent(e)}/graph`)}async function Mi(e,t,n="run",r=[]){return jt(`${Lt}/runs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrypoint:e,input_data:t,mode:n,breakpoints:r})})}async function Ql(){return jt(`${Lt}/runs`)}async function ar(e){return jt(`${Lt}/runs/${e}`)}async function ec(){return jt(`${Lt}/reload`,{method:"POST"})}function tc(e){const t=e.replace(/^#\/?/,""),n={section:"debug",view:"new",runId:null,tab:"traces",setupEntrypoint:null,setupMode:null,evalCreating:!1,evalSetId:null,evalRunId:null,evalRunItemName:null,evaluatorId:null,evaluatorCreateType:null,evaluatorFilter:null,explorerFile:null};if(!t||t==="new"||t==="debug"||t==="debug/new")return n;const r=t.match(/^(?:debug\/)?setup\/([^/]+)\/(run|chat)$/);if(r)return{...n,view:"setup",setupEntrypoint:decodeURIComponent(r[1]),setupMode:r[2]};const i=t.match(/^(?:debug\/)?runs\/([^/]+)(?:\/(traces|output))?$/);if(i)return{...n,view:"details",runId:i[1],tab:i[2]??"traces"};if(t==="evals/new")return{...n,section:"evals",evalCreating:!0};const s=t.match(/^evals\/runs\/([^/]+?)(?:\/([^/]+))?$/);if(s)return{...n,section:"evals",evalRunId:s[1],evalRunItemName:s[2]?decodeURIComponent(s[2]):null};const o=t.match(/^evals\/sets\/([^/]+)$/);if(o)return{...n,section:"evals",evalSetId:o[1]};if(t==="evals")return{...n,section:"evals"};const l=t.match(/^evaluators\/new(?:\/(deterministic|llm|tool))?$/);if(l)return{...n,section:"evaluators",evaluatorCreateType:l[1]??"any"};const u=t.match(/^evaluators\/category\/(deterministic|llm|tool)$/);if(u)return{...n,section:"evaluators",evaluatorFilter:u[1]};const c=t.match(/^evaluators\/([^/]+)$/);if(c)return{...n,section:"evaluators",evaluatorId:c[1]};if(t==="evaluators")return{...n,section:"evaluators"};const d=t.match(/^explorer\/file\/(.+)$/);return d?{...n,section:"explorer",explorerFile:decodeURIComponent(d[1])}:t==="explorer"?{...n,section:"explorer"}:n}function nc(){return window.location.hash}function rc(e){return window.addEventListener("hashchange",e),()=>window.removeEventListener("hashchange",e)}function st(){const e=S.useSyncExternalStore(rc,nc),t=tc(e),n=S.useCallback(r=>{window.location.hash=r},[]);return{...t,navigate:n}}const Ri="(max-width: 767px)";function ic(){const[e,t]=S.useState(()=>window.matchMedia(Ri).matches);return S.useEffect(()=>{const n=window.matchMedia(Ri),r=i=>t(i.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const oc=[{section:"debug",label:"Developer Console",icon:a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{x:"8",y:"6",width:"8",height:"14",rx:"4"}),a.jsx("path",{d:"M6 10H4"}),a.jsx("path",{d:"M6 18H4"}),a.jsx("path",{d:"M18 10h2"}),a.jsx("path",{d:"M18 18h2"}),a.jsx("path",{d:"M8 14h8"}),a.jsx("path",{d:"M9 6l-1.5-2"}),a.jsx("path",{d:"M15 6l1.5-2"}),a.jsx("path",{d:"M6 14H4"}),a.jsx("path",{d:"M18 14h2"})]})},{section:"evals",label:"Evals",icon:a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M9 3h6"}),a.jsx("path",{d:"M10 3v6.5L5 20a1 1 0 0 0 .9 1.4h12.2a1 1 0 0 0 .9-1.4L14 9.5V3"}),a.jsx("path",{d:"M8.5 14h7"})]})},{section:"evaluators",label:"Evaluators",icon:a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M12 2l7 4v5c0 5.25-3.5 9.74-7 11-3.5-1.26-7-5.75-7-11V6l7-4z"}),a.jsx("path",{d:"M9 12l2 2 4-4"})]})},{section:"explorer",label:"Explorer",icon:a.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",children:a.jsx("path",{d:"M7.5 22.5H17.595C17.07 23.4 16.11 24 15 24H7.5C4.185 24 1.5 21.315 1.5 18V6C1.5 4.89 2.1 3.93 3 3.405V18C3 20.475 5.025 22.5 7.5 22.5ZM21 8.121V18C21 19.6545 19.6545 21 18 21H7.5C5.8455 21 4.5 19.6545 4.5 18V3C4.5 1.3455 5.8455 0 7.5 0H12.879C13.4715 0 14.0505 0.24 14.4705 0.6585L20.3415 6.5295C20.766 6.954 21 7.5195 21 8.121ZM13.5 6.75C13.5 7.164 13.8375 7.5 14.25 7.5H19.1895L13.5 1.8105V6.75ZM19.5 18V9H14.25C13.0095 9 12 7.9905 12 6.75V1.5H7.5C6.672 1.5 6 2.1735 6 3V18C6 18.8265 6.672 19.5 7.5 19.5H18C18.828 19.5 19.5 18.8265 19.5 18Z"})})}];function sc({section:e,onSectionChange:t}){return a.jsx("div",{className:"w-12 flex flex-col items-center shrink-0 border-r",style:{background:"var(--activity-bar-bg)",borderColor:"var(--border)"},children:a.jsx("div",{className:"flex flex-col items-center gap-1 pt-2",children:oc.map(n=>{const r=e===n.section;return a.jsxs("button",{onClick:()=>t(n.section),className:"w-10 h-10 flex items-center justify-center rounded cursor-pointer transition-colors relative",style:{color:r?"var(--text-primary)":"var(--text-muted)",background:r?"var(--bg-hover)":"transparent",border:"none"},title:n.label,onMouseEnter:i=>{r||(i.currentTarget.style.color="var(--text-secondary)")},onMouseLeave:i=>{r||(i.currentTarget.style.color="var(--text-muted)")},children:[r&&a.jsx("div",{className:"absolute left-0 top-1.5 bottom-1.5 w-0.5 rounded-r",style:{background:"var(--accent)"}}),n.icon]},n.section)})})})}const et="/api";async function tt(e,t){const n=await fetch(e,t);if(!n.ok){let r;try{r=(await n.json()).detail||n.statusText}catch{r=n.statusText}const i=new Error(`HTTP ${n.status}`);throw i.detail=r,i.status=n.status,i}return n.json()}async function ac(){return tt(`${et}/evaluators`)}async function vs(){return tt(`${et}/eval-sets`)}async function lc(e){return tt(`${et}/eval-sets`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function cc(e,t){return tt(`${et}/eval-sets/${encodeURIComponent(e)}/items`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function uc(e,t){await tt(`${et}/eval-sets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`,{method:"DELETE"})}async function dc(e){return tt(`${et}/eval-sets/${encodeURIComponent(e)}`)}async function pc(e){return tt(`${et}/eval-sets/${encodeURIComponent(e)}/runs`,{method:"POST"})}async function fc(){return tt(`${et}/eval-runs`)}async function Ii(e){return tt(`${et}/eval-runs/${encodeURIComponent(e)}`)}async function Zr(){return tt(`${et}/local-evaluators`)}async function mc(e){return tt(`${et}/local-evaluators`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function hc(e,t){return tt(`${et}/eval-sets/${encodeURIComponent(e)}/evaluators`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({evaluator_refs:t})})}async function gc(e,t){return tt(`${et}/local-evaluators/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}const bc={"uipath-exact-match":e=>({expectedOutput:e}),"uipath-json-similarity":e=>({expectedOutput:e}),"uipath-contains":()=>({searchText:""}),"uipath-llm-judge-output-semantic-similarity":e=>({expectedOutput:e}),"uipath-llm-judge-output-strict-json-similarity":e=>({expectedOutput:e}),"uipath-llm-judge-trajectory-similarity":()=>({expectedAgentBehavior:""}),"uipath-llm-judge-trajectory-simulation":()=>({expectedAgentBehavior:""}),"uipath-tool-call-count":()=>({}),"uipath-tool-call-args":()=>({}),"uipath-tool-call-order":()=>({}),"uipath-tool-call-output":()=>({})};function xc(e,t){if(!e)return{};const n=bc[e.evaluator_type_id];return n?n(t):e.type==="tool"?{}:e.evaluator_type_id.includes("trajectory")?{expectedAgentBehavior:""}:{expectedOutput:t}}function Es(e){return e?e.type==="tool"?!0:e.evaluator_type_id.includes("tool-call"):!1}function yc(e){return e?Es(e)?{label:"tools",color:"var(--warning, #e5a00d)"}:e.evaluator_type_id.includes("trajectory")?{label:"quality",color:"var(--info, #3b82f6)"}:{label:"output",color:"var(--success, #22c55e)"}:{label:"output",color:"var(--success, #22c55e)"}}function vc({run:e,onClose:t}){const n=Ae(k=>k.evalSets),r=Ae(k=>k.setEvalSets),i=Ae(k=>k.incrementEvalSetCount),s=Ae(k=>k.localEvaluators),o=Ae(k=>k.setLocalEvaluators),[l,u]=S.useState(`run-${e.id.slice(0,8)}`),[c,d]=S.useState(new Set),[p,m]=S.useState({}),f=S.useRef(new Set),[h,x]=S.useState(!1),[v,b]=S.useState(null),[E,A]=S.useState(!1),D=Object.values(n),L=S.useMemo(()=>Object.fromEntries(s.map(k=>[k.id,k])),[s]),T=S.useMemo(()=>{const k=new Set;for(const w of c){const M=n[w];M&&M.evaluator_ids.forEach(I=>k.add(I))}return[...k]},[c,n]);S.useEffect(()=>{const k=e.output_data,w=f.current;m(M=>{const I={};for(const j of T)if(w.has(j)&&M[j]!==void 0)I[j]=M[j];else{const _=L[j],N=xc(_,k);I[j]=JSON.stringify(N,null,2)}return I})},[T,L,e.output_data]),S.useEffect(()=>{const k=w=>{w.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),S.useEffect(()=>{D.length===0&&vs().then(r).catch(()=>{}),s.length===0&&Zr().then(o).catch(()=>{})},[]);const B=k=>{d(w=>{const M=new Set(w);return M.has(k)?M.delete(k):M.add(k),M})},O=async()=>{var w;if(!l.trim()||c.size===0)return;b(null),x(!0);const k={};for(const M of T){const I=p[M];if(I!==void 0)try{k[M]=JSON.parse(I)}catch{b(`Invalid JSON for evaluator "${((w=L[M])==null?void 0:w.name)??M}"`),x(!1);return}}try{for(const M of c){const I=n[M],j=new Set((I==null?void 0:I.evaluator_ids)??[]),_={};for(const[N,R]of Object.entries(k))j.has(N)&&(_[N]=R);await cc(M,{name:l.trim(),inputs:e.input_data,expected_output:null,evaluation_criterias:_}),i(M)}A(!0),setTimeout(t,3e3)}catch(M){b(M.detail||M.message||"Failed to add item")}finally{x(!1)}};return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(0, 0, 0, 0.5)"},onClick:k=>{k.target===k.currentTarget&&t()},children:a.jsxs("div",{className:"w-full max-w-2xl rounded-lg p-6 shadow-xl max-h-[85vh] flex flex-col",style:{background:"var(--bg-primary)",border:"1px solid var(--border)"},children:[a.jsxs("div",{className:"flex items-center justify-between mb-6",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{background:"var(--accent)"}}),a.jsx("span",{className:"text-sm font-semibold",style:{color:"var(--text-muted)"},children:"Add to Eval Set"})]}),a.jsx("button",{onClick:t,className:"w-7 h-7 flex items-center justify-center rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:k=>{k.currentTarget.style.color="var(--text-primary)"},onMouseLeave:k=>{k.currentTarget.style.color="var(--text-muted)"},"aria-label":"Close",children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0 space-y-4 pr-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Item Name"}),a.jsx("input",{type:"text",value:l,onChange:k=>u(k.target.value),className:"w-full rounded-md px-3 py-2 text-xs",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"}})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Inputs"}),a.jsx("pre",{className:"rounded-md px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words max-h-32 overflow-y-auto",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-secondary)"},children:JSON.stringify(e.input_data,null,2)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Eval Sets"}),D.length===0?a.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:"No eval sets found. Create one first."}):a.jsx("div",{className:"rounded-md border overflow-hidden max-h-40 overflow-y-auto",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:D.map(k=>a.jsxs("label",{className:"flex items-center gap-2.5 px-3 py-2 text-xs cursor-pointer transition-colors",style:{borderBottom:"1px solid var(--border)"},onMouseEnter:w=>{w.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:w=>{w.currentTarget.style.background="transparent"},children:[a.jsx("input",{type:"checkbox",checked:c.has(k.id),onChange:()=>B(k.id),className:"accent-[var(--accent)]"}),a.jsx("span",{className:"flex-1 truncate",style:{color:"var(--text-primary)"},children:k.name}),a.jsxs("span",{className:"text-[10px]",style:{color:"var(--text-muted)"},children:[k.eval_count," items"]})]},k.id))})]}),T.length>0&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Evaluation Criteria"}),a.jsx("div",{className:"space-y-2",children:T.map(k=>{const w=L[k],M=Es(w),I=yc(w);return a.jsxs("div",{className:"rounded-md",style:{border:"1px solid var(--border)",background:"var(--bg-primary)",opacity:M?.6:1},children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",style:{borderBottom:M?"none":"1px solid var(--border)"},children:[a.jsx("span",{className:"text-xs font-medium truncate flex-1",style:{color:"var(--text-primary)"},children:(w==null?void 0:w.name)??k}),a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-medium",style:{color:I.color,background:`color-mix(in srgb, ${I.color} 12%, transparent)`},children:I.label})]}),M?a.jsx("div",{className:"px-3 pb-2",children:a.jsx("span",{className:"text-[10px] italic",style:{color:"var(--text-muted)"},children:"Default criteria — uses evaluator config"})}):a.jsx("div",{className:"px-3 pb-2 pt-1",children:a.jsx("textarea",{value:p[k]??"{}",onChange:j=>{f.current.add(k),m(_=>({..._,[k]:j.target.value}))},rows:8,className:"w-full rounded px-2 py-1.5 text-xs font-mono resize-y",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"}})})]},k)})})]})]}),a.jsxs("div",{className:"mt-4 space-y-3",children:[v&&a.jsx("p",{className:"text-xs px-3 py-2 rounded",style:{color:"var(--error)",background:"color-mix(in srgb, var(--error) 10%, var(--bg-secondary))"},children:v}),E&&a.jsxs("p",{className:"text-xs px-3 py-2 rounded",style:{color:"var(--success)",background:"color-mix(in srgb, var(--success) 10%, var(--bg-secondary))"},children:["Added to ",c.size," eval set",c.size!==1?"s":"","."]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:t,className:"flex-1 py-2 rounded-md text-xs font-semibold cursor-pointer",style:{background:"var(--bg-secondary)",color:"var(--text-secondary)",border:"1px solid var(--border)"},children:"Cancel"}),a.jsx("button",{onClick:O,disabled:!l.trim()||c.size===0||h||E,className:"flex-1 py-2 rounded-md text-[13px] font-semibold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--accent)",color:"var(--bg-primary)",border:"none"},children:h?"Adding...":E?"Added":"Add Item"})]})]})]})})}const Ec={pending:"var(--text-muted)",running:"var(--warning)",suspended:"var(--info)",completed:"var(--success)",failed:"var(--error)"};function kc({run:e,isSelected:t,onClick:n}){var p;const r=Ec[e.status]??"var(--text-muted)",i=((p=e.entrypoint.split("/").pop())==null?void 0:p.slice(0,16))??e.entrypoint,s=e.start_time?new Date(e.start_time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"",[o,l]=S.useState(!1),[u,c]=S.useState(!1),d=S.useRef(null);return S.useEffect(()=>{if(!o)return;const m=f=>{d.current&&!d.current.contains(f.target)&&l(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[o]),a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"group relative w-full text-left px-3 py-1.5 flex items-center gap-2 transition-colors cursor-pointer",style:{background:t?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":void 0,borderLeft:t?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:m=>{t||(m.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:m=>{t||(m.currentTarget.style.background="")},onClick:n,children:[a.jsx("span",{className:"shrink-0 w-2 h-2 rounded-full",style:{background:r}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-xs truncate",style:{color:t?"var(--text-primary)":"var(--text-secondary)"},children:i}),a.jsxs("div",{className:"text-[11px] tabular-nums",style:{color:"var(--text-muted)"},children:[s,e.duration?` · ${e.duration}`:""]})]}),e.status==="completed"&&a.jsxs("div",{ref:d,className:"relative shrink-0",children:[a.jsx("button",{onClick:m=>{m.stopPropagation(),l(f=>!f)},className:"opacity-40 group-hover:opacity-100 focus:opacity-100 w-7 h-7 flex items-center justify-center rounded transition-opacity cursor-pointer",style:{color:"var(--text-muted)"},onMouseEnter:m=>{m.currentTarget.style.color="var(--text-primary)",m.currentTarget.style.background="var(--bg-secondary)"},onMouseLeave:m=>{m.currentTarget.style.color="var(--text-muted)",m.currentTarget.style.background=""},"aria-label":"Actions",title:"Actions",children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[a.jsx("circle",{cx:"8",cy:"3",r:"1.5"}),a.jsx("circle",{cx:"8",cy:"8",r:"1.5"}),a.jsx("circle",{cx:"8",cy:"13",r:"1.5"})]})}),o&&a.jsx("div",{className:"absolute right-0 top-full mt-1 z-50 min-w-[140px] rounded-md shadow-lg py-1",style:{background:"var(--bg-primary)",border:"1px solid var(--border)"},children:a.jsx("button",{onClick:m=>{m.stopPropagation(),l(!1),c(!0)},className:"w-full text-left px-3 py-1.5 text-xs cursor-pointer transition-colors",style:{color:"var(--text-secondary)"},onMouseEnter:m=>{m.currentTarget.style.background="var(--bg-hover)",m.currentTarget.style.color="var(--text-primary)"},onMouseLeave:m=>{m.currentTarget.style.background="",m.currentTarget.style.color="var(--text-secondary)"},children:"Add to Eval Set"})})]})]}),u&&a.jsx(vc,{run:e,onClose:()=>c(!1)})]})}function Oi({runs:e,selectedRunId:t,onSelectRun:n,onNewRun:r}){const i=[...e].sort((s,o)=>new Date(o.start_time??0).getTime()-new Date(s.start_time??0).getTime());return a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:r,className:"mx-3 mt-2.5 mb-1 px-3 py-1.5 text-[11px] font-medium rounded border border-[var(--border)] bg-transparent transition-colors cursor-pointer",style:{color:"var(--text-secondary)"},onMouseEnter:s=>{s.currentTarget.style.color="var(--text-primary)",s.currentTarget.style.borderColor="var(--text-muted)"},onMouseLeave:s=>{s.currentTarget.style.color="var(--text-secondary)",s.currentTarget.style.borderColor=""},children:"+ New Run"}),a.jsx("div",{className:"px-3 pt-3 pb-1 text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"History"}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[i.map(s=>a.jsx(kc,{run:s,isSelected:s.id===t,onClick:()=>n(s.id)},s.id)),i.length===0&&a.jsx("p",{className:"text-xs px-3 py-4 text-center",style:{color:"var(--text-muted)"},children:"No runs yet"})]})]})}function ks(){const e=localStorage.getItem("uipath-dev-theme");return e==="light"||e==="dark"?e:"dark"}function ws(e){document.documentElement.setAttribute("data-theme",e),localStorage.setItem("uipath-dev-theme",e)}ws(ks());const _s=Ot(e=>({theme:ks(),toggleTheme:()=>e(t=>{const n=t.theme==="dark"?"light":"dark";return ws(n),{theme:n}})}));function Li(){const{theme:e,toggleTheme:t}=_s(),{enabled:n,status:r,environment:i,tenants:s,uipathUrl:o,setEnvironment:l,startLogin:u,selectTenant:c,logout:d}=zn(),{projectName:p,projectVersion:m,projectAuthors:f}=bs(),[h,x]=S.useState(!1),[v,b]=S.useState(""),E=S.useRef(null),A=S.useRef(null);S.useEffect(()=>{if(!h)return;const _=N=>{E.current&&!E.current.contains(N.target)&&A.current&&!A.current.contains(N.target)&&x(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[h]);const D=r==="authenticated",L=r==="expired",T=r==="pending",B=r==="needs_tenant";let O="UiPath: Disconnected",k=null,w=!0;D?(O=`UiPath: ${o?o.replace(/^https?:\/\/[^/]+\//,""):""}`,k="var(--success)",w=!1):L?(O=`UiPath: ${o?o.replace(/^https?:\/\/[^/]+\//,""):""} (expired)`,k="var(--error)",w=!1):T?O="UiPath: Signing in…":B&&(O="UiPath: Select Tenant");const M=()=>{T||(L?u():x(_=>!_))},I="flex items-center gap-1 px-1.5 rounded transition-colors",j={onMouseEnter:_=>{_.currentTarget.style.background="var(--bg-hover)",_.currentTarget.style.color="var(--text-primary)"},onMouseLeave:_=>{_.currentTarget.style.background="",_.currentTarget.style.color="var(--text-muted)"}};return a.jsxs("div",{className:"h-6 flex items-center justify-end gap-3 px-2 text-xs border-t shrink-0",style:{background:"var(--bg-secondary)",color:"var(--text-muted)",borderColor:"var(--border)",fontSize:"11px"},children:[n&&a.jsxs("div",{className:"relative flex items-center",children:[a.jsxs("div",{ref:A,className:`${I} cursor-pointer`,onClick:M,...j,title:D?o??"":L?"Token expired — click to re-authenticate":T?"Signing in…":B?"Select a tenant":"Click to sign in",children:[T?a.jsxs("svg",{className:"animate-spin",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a.jsx("circle",{cx:"12",cy:"12",r:"10",strokeOpacity:"0.25"}),a.jsx("path",{d:"M12 2a10 10 0 0 1 10 10",strokeLinecap:"round"})]}):k?a.jsx("div",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{background:k}}):w?a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}),a.jsx("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"})]}):null,a.jsx("span",{className:"truncate max-w-[200px]",children:O})]}),h&&a.jsx("div",{ref:E,className:"absolute bottom-full right-0 mb-1 rounded border shadow-lg p-1 min-w-[180px]",style:{background:"var(--bg-secondary)",borderColor:"var(--border)"},children:D||L?a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:()=>{o&&window.open(o,"_blank","noopener,noreferrer"),x(!1)},className:"w-full flex items-center gap-2 px-2 py-2 text-[11px] rounded cursor-pointer transition-colors text-left",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:_=>{_.currentTarget.style.background="var(--bg-hover)",_.currentTarget.style.color="var(--text-primary)"},onMouseLeave:_=>{_.currentTarget.style.background="transparent",_.currentTarget.style.color="var(--text-muted)"},children:[a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),a.jsx("polyline",{points:"15 3 21 3 21 9"}),a.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),"Go to Platform"]}),a.jsxs("button",{onClick:()=>{d(),x(!1)},className:"w-full flex items-center gap-2 px-2 py-2 text-[11px] rounded cursor-pointer transition-colors text-left",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:_=>{_.currentTarget.style.background="var(--bg-hover)",_.currentTarget.style.color="var(--text-primary)"},onMouseLeave:_=>{_.currentTarget.style.background="transparent",_.currentTarget.style.color="var(--text-muted)"},children:[a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),a.jsx("polyline",{points:"16 17 21 12 16 7"}),a.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]}),"Sign Out"]})]}):B?a.jsxs("div",{className:"p-1",children:[a.jsx("label",{className:"block text-[10px] font-medium mb-1",style:{color:"var(--text-muted)"},children:"Tenant"}),a.jsxs("select",{value:v,onChange:_=>b(_.target.value),className:"w-full rounded px-1.5 py-1 text-[10px] mb-1.5 appearance-auto",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:"var(--text-primary)"},children:[a.jsx("option",{value:"",children:"Select…"}),s.map(_=>a.jsx("option",{value:_,children:_},_))]}),a.jsx("button",{onClick:()=>{v&&(c(v),x(!1))},disabled:!v,className:"w-full px-2 py-1 text-[10px] font-medium rounded border border-[var(--border)] bg-transparent cursor-pointer transition-colors disabled:opacity-30 disabled:cursor-not-allowed",style:{color:"var(--text-muted)"},children:"Confirm"})]}):a.jsxs("div",{className:"p-1",children:[a.jsx("label",{className:"block text-[10px] font-medium mb-1",style:{color:"var(--text-muted)"},children:"Environment"}),a.jsxs("select",{value:i,onChange:_=>l(_.target.value),className:"w-full rounded px-1.5 py-0.5 text-[10px] mb-1.5 appearance-auto",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:"var(--text-muted)"},children:[a.jsx("option",{value:"cloud",children:"cloud"}),a.jsx("option",{value:"staging",children:"staging"}),a.jsx("option",{value:"alpha",children:"alpha"})]}),a.jsx("button",{onClick:()=>{u(),x(!1)},className:"w-full px-2 py-1 text-[10px] font-medium rounded border border-[var(--border)] bg-transparent cursor-pointer transition-colors",style:{color:"var(--text-muted)"},onMouseEnter:_=>{_.currentTarget.style.color="var(--text-primary)",_.currentTarget.style.borderColor="var(--text-muted)"},onMouseLeave:_=>{_.currentTarget.style.color="var(--text-muted)",_.currentTarget.style.borderColor="var(--border)"},children:"Sign In"})]})})]}),p&&a.jsxs("span",{className:I,children:["Project: ",p]}),m&&a.jsxs("span",{className:I,children:["Version: v",m]}),f&&a.jsxs("span",{className:I,children:["Author: ",f]}),a.jsxs("a",{href:"https://github.com/UiPath/uipath-dev-python",target:"_blank",rel:"noopener noreferrer",className:`${I} cursor-pointer no-underline`,style:{color:"var(--text-muted)"},...j,title:"View on GitHub",children:[a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z"})}),a.jsx("span",{children:"uipath-dev-python"})]}),a.jsxs("div",{className:`${I} cursor-pointer`,onClick:t,...j,title:`Switch to ${e==="dark"?"light":"dark"} theme`,children:[a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="dark"?a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"5"}),a.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),a.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),a.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),a.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),a.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),a.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),a.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),a.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]}):a.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),a.jsx("span",{children:e==="dark"?"Dark":"Light"})]})]})}function wc(){const{navigate:e}=st(),t=Ee(c=>c.entrypoints),[n,r]=S.useState(""),[i,s]=S.useState(!0),[o,l]=S.useState(null);S.useEffect(()=>{!n&&t.length>0&&r(t[0])},[t,n]),S.useEffect(()=>{n&&(s(!0),l(null),Xl(n).then(c=>{var p;const d=(p=c.input)==null?void 0:p.properties;s(!!(d!=null&&d.messages))}).catch(c=>{const d=c.detail||{};l(d.error||d.message||`Failed to load entrypoint "${n}"`)}))},[n]);const u=c=>{n&&e(`#/setup/${encodeURIComponent(n)}/${c}`)};return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"w-full max-w-xl px-6",children:[a.jsxs("div",{className:"mb-8 text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2",children:[a.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{background:o?"var(--error)":"var(--accent)"}}),a.jsx("span",{className:"text-sm font-semibold",style:{color:"var(--text-muted)"},children:"New Run"})]}),!o&&a.jsx("p",{className:"text-sm",style:{color:"var(--text-muted)"},children:t.length>1?"Select an entrypoint and choose a mode":"Choose a mode"})]}),t.length>1&&a.jsxs("div",{className:"mb-8",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Entrypoint"}),a.jsx("select",{id:"entrypoint-select",value:n,onChange:c=>r(c.target.value),className:"w-full rounded-md px-3 py-2 text-xs font-mono cursor-pointer appearance-auto",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"},children:t.map(c=>a.jsx("option",{value:c,children:c},c))})]}),o?a.jsxs("div",{className:"rounded-md border overflow-hidden",style:{borderColor:"color-mix(in srgb, var(--error) 25%, var(--border))",background:"var(--bg-secondary)"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{borderBottom:"1px solid color-mix(in srgb, var(--error) 15%, var(--border))",background:"color-mix(in srgb, var(--error) 4%, var(--bg-secondary))"},children:[a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",style:{flexShrink:0},children:a.jsx("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7.25 4.75h1.5v4h-1.5v-4zm.75 6.75a.75.75 0 110-1.5.75.75 0 010 1.5z",fill:"var(--error)"})}),a.jsx("span",{className:"text-[11px] font-medium",style:{color:"var(--error)"},children:"Failed to load entrypoint"})]}),a.jsx("div",{className:"overflow-auto max-h-48 p-3",children:a.jsx("pre",{className:"text-[11px] font-mono whitespace-pre-wrap break-words leading-relaxed m-0",style:{color:"var(--text-muted)"},children:o})})]}):a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsx(ji,{title:"Autonomous",description:"Run the agent end-to-end. Set breakpoints to pause and inspect execution.",icon:a.jsx(_c,{}),color:"var(--success)",onClick:()=>u("run"),disabled:!n}),a.jsx(ji,{title:"Conversational",description:i?"Interactive chat session. Send messages and receive responses in real time.":'Requires a "messages" property in the input schema.',icon:a.jsx(Nc,{}),color:"var(--accent)",onClick:()=>u("chat"),disabled:!n||!i})]})]})})}function ji({title:e,description:t,icon:n,color:r,onClick:i,disabled:s}){return a.jsxs("button",{onClick:i,disabled:s,className:"group flex flex-col items-center text-center p-6 rounded-md border transition-all cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--bg-secondary)",borderColor:"var(--border)"},onMouseEnter:o=>{s||(o.currentTarget.style.borderColor=r,o.currentTarget.style.background=`color-mix(in srgb, ${r} 5%, var(--bg-secondary))`)},onMouseLeave:o=>{o.currentTarget.style.borderColor="var(--border)",o.currentTarget.style.background="var(--bg-secondary)"},children:[a.jsx("div",{className:"mb-4 p-3 rounded-xl transition-colors",style:{background:`color-mix(in srgb, ${r} 10%, var(--bg-primary))`,color:r},children:n}),a.jsx("h3",{className:"text-sm font-semibold mb-1.5",style:{color:"var(--text-primary)"},children:e}),a.jsx("p",{className:"text-xs leading-relaxed",style:{color:"var(--text-muted)"},children:t})]})}function _c(){return a.jsx("svg",{width:"28",height:"28",viewBox:"0 0 26 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M23.832 15.166H22.7487C22.7487 10.9735 19.3579 7.58268 15.1654 7.58268H14.082V6.20685C14.732 5.83852 15.1654 5.13435 15.1654 4.33268C15.1654 3.14102 14.2012 2.16602 12.9987 2.16602C11.7962 2.16602 10.832 3.14102 10.832 4.33268C10.832 5.13435 11.2654 5.83852 11.9154 6.20685V7.58268H10.832C6.63953 7.58268 3.2487 10.9735 3.2487 15.166H2.16536C1.56953 15.166 1.08203 15.6535 1.08203 16.2493V19.4993C1.08203 20.0952 1.56953 20.5827 2.16536 20.5827H3.2487V21.666C3.2487 22.8685 4.2237 23.8327 5.41536 23.8327H20.582C21.7845 23.8327 22.7487 22.8685 22.7487 21.666V20.5827H23.832C24.4279 20.5827 24.9154 20.0952 24.9154 19.4993V16.2493C24.9154 15.6535 24.4279 15.166 23.832 15.166ZM22.7487 18.416H20.582V21.666H5.41536V18.416H3.2487V17.3327H5.41536V15.166C5.41536 12.176 7.84203 9.74935 10.832 9.74935H15.1654C18.1554 9.74935 20.582 12.176 20.582 15.166V17.3327H22.7487V18.416ZM9.20703 14.6243L11.7637 17.181L10.4854 18.4594L9.20703 17.181L7.9287 18.4594L6.65036 17.181L9.20703 14.6243ZM16.7904 14.6243L19.347 17.181L18.0687 18.4594L16.7904 17.181L15.512 18.4594L14.2337 17.181L16.7904 14.6243Z",fill:"currentColor"})})}function Nc(){return a.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 26 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("path",{d:"M9.20901 13.541L11.7657 16.0977L10.4873 17.376L9.20901 16.0977L7.93068 17.376L6.65234 16.0977L9.20901 13.541ZM16.7923 13.541L19.349 16.0977L18.0707 17.376L16.7923 16.0977L15.514 17.376L14.2357 16.0977L16.7923 13.541Z",fill:"currentColor"}),a.jsx("path",{d:"M5.25 8.58398H20.75C21.3023 8.58398 21.75 9.0317 21.75 9.58398V23.5293L16.874 21.9043C16.5683 21.8024 16.248 21.751 15.9258 21.751H5.25C4.69782 21.751 4.25018 21.3031 4.25 20.751V9.58398C4.25 9.0317 4.69772 8.58398 5.25 8.58398Z",stroke:"currentColor",strokeWidth:"2"}),a.jsx("ellipse",{cx:"12.9987",cy:"4.33268",rx:"2.16667",ry:"2.16667",fill:"currentColor"}),a.jsx("rect",{x:"11.918",y:"5.41602",width:"2.16667",height:"2.16667",fill:"currentColor"}),a.jsx("path",{d:"M1.08203 14C1.08203 13.4477 1.52975 13 2.08203 13H3.2487V18.4167H2.08203C1.52975 18.4167 1.08203 17.969 1.08203 17.4167V14Z",fill:"currentColor"}),a.jsx("rect",{x:"3.25",y:"15.166",width:"2.16667",height:"1.08333",fill:"currentColor"}),a.jsx("path",{d:"M22.75 13H23.9167C24.4689 13 24.9167 13.4477 24.9167 14V17.4167C24.9167 17.969 24.469 18.4167 23.9167 18.4167H22.75V13Z",fill:"currentColor"}),a.jsx("rect",{x:"20.582",y:"15.166",width:"2.16667",height:"1.08333",fill:"currentColor"})]})}const Sc="modulepreload",Tc=function(e){return"/"+e},Di={},Ns=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let o=function(c){return Promise.all(c.map(d=>Promise.resolve(d).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=o(n.map(c=>{if(c=Tc(c),c in Di)return;Di[c]=!0;const d=c.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${p}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":Sc,d||(m.as="script"),m.crossOrigin="",m.href=c,u&&m.setAttribute("nonce",u),document.head.appendChild(m),d)return new Promise((f,h)=>{m.addEventListener("load",f),m.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${c}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})},Cc={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0};function Ac({data:e}){const t=e.status,n=e.nodeWidth,r=e.label??"Start",i=e.hasBreakpoint,s=e.isPausedHere,o=e.isActiveNode,l=e.isExecutingNode,u=s?"var(--error)":l?"var(--success)":o?"var(--accent)":t==="completed"?"var(--success)":t==="running"?"var(--warning)":"var(--node-border)",c=s?"var(--error)":l?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"px-3 py-1.5 rounded-full text-center text-xs overflow-hidden text-ellipsis whitespace-nowrap cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${u}`,boxShadow:s||o||l?`0 0 4px ${c}`:void 0,animation:s||o||l?`node-pulse-${s?"red":l?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r,children:[i&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),r,a.jsx(gt,{type:"source",position:bt.Bottom,style:Cc})]})}const Mc={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0};function Rc({data:e}){const t=e.status,n=e.nodeWidth,r=e.label??"End",i=e.hasBreakpoint,s=e.isPausedHere,o=e.isActiveNode,l=e.isExecutingNode,u=s?"var(--error)":l?"var(--success)":o?"var(--accent)":t==="completed"?"var(--success)":t==="failed"?"var(--error)":"var(--node-border)",c=s?"var(--error)":l?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"px-3 py-1.5 rounded-full text-center text-xs overflow-hidden text-ellipsis whitespace-nowrap cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${u}`,boxShadow:s||o||l?`0 0 4px ${c}`:void 0,animation:s||o||l?`node-pulse-${s?"red":l?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r,children:[i&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),a.jsx(gt,{type:"target",position:bt.Top,style:Mc}),r]})}const Pi={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0};function Ic({data:e}){const t=e.status,n=e.nodeWidth,r=e.model_name,i=e.label??"Model",s=e.hasBreakpoint,o=e.isPausedHere,l=e.isActiveNode,u=e.isExecutingNode,c=o?"var(--error)":u?"var(--success)":l?"var(--accent)":t==="completed"?"var(--success)":t==="running"?"var(--warning)":t==="failed"?"var(--error)":"var(--node-border)",d=o?"var(--error)":u?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"px-3 py-1.5 rounded-lg text-center text-xs overflow-hidden cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${c}`,boxShadow:o||l||u?`0 0 4px ${d}`:void 0,animation:o||l||u?`node-pulse-${o?"red":u?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r?`${i} ${r}`:i,children:[s&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),a.jsx(gt,{type:"target",position:bt.Top,style:Pi}),a.jsx("div",{style:{color:"var(--info)",fontSize:9,marginBottom:1},children:"model"}),a.jsx("div",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:i}),r&&a.jsx("div",{className:"overflow-hidden text-ellipsis whitespace-nowrap",style:{color:"var(--text-muted)",fontSize:9,marginTop:1},title:r,children:r}),a.jsx(gt,{type:"source",position:bt.Bottom,style:Pi})]})}const Bi={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0},Oc=3;function Lc({data:e}){const t=e.status,n=e.nodeWidth,r=e.tool_names,i=e.tool_count,s=e.label??"Tool",o=e.hasBreakpoint,l=e.isPausedHere,u=e.isActiveNode,c=e.isExecutingNode,d=l?"var(--error)":c?"var(--success)":u?"var(--accent)":t==="completed"?"var(--success)":t==="running"?"var(--warning)":t==="failed"?"var(--error)":"var(--node-border)",p=l?"var(--error)":c?"var(--success)":"var(--accent)",m=(r==null?void 0:r.slice(0,Oc))??[],f=(i??(r==null?void 0:r.length)??0)-m.length;return a.jsxs("div",{className:"px-3 py-1.5 rounded-lg text-center text-xs overflow-hidden cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${d}`,boxShadow:l||u||c?`0 0 4px ${p}`:void 0,animation:l||u||c?`node-pulse-${l?"red":c?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r!=null&&r.length?`${s} ${r.join(` -`)}`:s,children:[o&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),a.jsx(gt,{type:"target",position:bt.Top,style:Bi}),a.jsxs("div",{style:{color:"var(--warning)",fontSize:9,marginBottom:1},children:["tools",i?` (${i})`:""]}),a.jsx("div",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s}),m.length>0&&a.jsxs("div",{style:{marginTop:3,fontSize:9,color:"var(--text-muted)",textAlign:"left"},children:[m.map(g=>a.jsx("div",{className:"truncate",children:g},g)),f>0&&a.jsxs("div",{style:{fontStyle:"italic"},children:["+",f," more"]})]}),a.jsx(gt,{type:"source",position:bt.Bottom,style:Bi})]})}const Fi={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0};function jc({data:e}){const t=e.label??"",n=e.status,r=e.hasBreakpoint,i=e.isPausedHere,s=e.isActiveNode,o=e.isExecutingNode,l=i?"var(--error)":o?"var(--success)":s?"var(--accent)":n==="completed"?"var(--success)":n==="running"?"var(--warning)":n==="failed"?"var(--error)":"var(--bg-tertiary)",u=i?"var(--error)":o?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"relative cursor-pointer",style:{width:"100%",height:"100%",background:"var(--bg-secondary)",border:`1.5px ${i||s||o?"solid":"dashed"} ${l}`,borderRadius:8,boxShadow:i||s||o?`0 0 4px ${u}`:void 0,animation:i||s||o?`node-pulse-${i?"red":o?"green":"accent"} 1.5s ease-in-out infinite`:void 0},children:[r&&a.jsx("div",{className:"absolute",style:{top:4,left:4,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--bg-tertiary)",boxShadow:"0 0 4px var(--error)",zIndex:1}}),a.jsx(gt,{type:"target",position:bt.Top,style:Fi}),a.jsx("div",{style:{padding:"4px 10px",fontSize:10,color:"var(--text-muted)",fontWeight:600,textAlign:"center",borderBottom:`1px solid ${l}`,background:"var(--bg-tertiary)",borderRadius:"8px 8px 0 0"},children:t}),a.jsx(gt,{type:"source",position:bt.Bottom,style:Fi})]})}function Dc({data:e}){const t=e.status,n=e.nodeWidth,r=e.label??"",i=e.hasBreakpoint,s=e.isPausedHere,o=e.isActiveNode,l=e.isExecutingNode,u=s?"var(--error)":l?"var(--success)":o?"var(--accent)":t==="completed"?"var(--success)":t==="running"?"var(--warning)":t==="failed"?"var(--error)":"var(--node-border)",c=s?"var(--error)":l?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"px-3 py-1.5 rounded-lg text-center text-xs overflow-hidden cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${u}`,boxShadow:s||o||l?`0 0 4px ${c}`:void 0,animation:s||o||l?`node-pulse-${s?"red":l?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r,children:[i&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),a.jsx(gt,{type:"target",position:bt.Top}),a.jsx("div",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:r}),a.jsx(gt,{type:"source",position:bt.Bottom})]})}function Pc(e,t=8){if(e.length<2)return"";if(e.length===2)return`M ${e[0].x} ${e[0].y} L ${e[1].x} ${e[1].y}`;let n=`M ${e[0].x} ${e[0].y}`;for(let i=1;i0&&(n+=Math.min(r.length,3)*12+(r.length>3?12:0)+4),e!=null&&e.model_name&&(n+=14),n}let lr=null;async function Wc(){if(!lr){const{default:e}=await Ns(async()=>{const{default:t}=await import("./vendor-elk-CzxJ-xdZ.js").then(n=>n.e);return{default:t}},__vite__mapDeps([0,1]));lr=new e}return lr}const $i={"elk.algorithm":"layered","elk.direction":"DOWN","elk.edgeRouting":"ORTHOGONAL","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.spacing.nodeNode":"25","elk.layered.spacing.nodeNodeBetweenLayers":"50","elk.spacing.edgeNode":"30","elk.spacing.edgeEdge":"15","elk.layered.spacing.edgeNodeBetweenLayers":"25","elk.layered.spacing.edgeEdgeBetweenLayers":"15","elk.portAlignment.default":"CENTER","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES"},Kc="[top=35,left=15,bottom=15,right=15]";function Gc(e){const t=[],n=[];for(const r of e.nodes){const i=r.data,s={id:r.id,width:zi(i),height:Ui(i,r.type)};if(r.data.subgraph){const o=r.data.subgraph;delete s.width,delete s.height,s.layoutOptions={...$i,"elk.padding":Kc},s.children=o.nodes.map(l=>({id:`${r.id}/${l.id}`,width:zi(l.data),height:Ui(l.data,l.type)})),s.edges=o.edges.map(l=>({id:`${r.id}/${l.id}`,sources:[`${r.id}/${l.source}`],targets:[`${r.id}/${l.target}`]}))}t.push(s)}for(const r of e.edges)n.push({id:r.id,sources:[r.source],targets:[r.target]});return{id:"root",layoutOptions:$i,children:t,edges:n}}const Rr={type:Ml.ArrowClosed,width:12,height:12,color:"var(--node-border)"};function Ss(e){return{stroke:"var(--node-border)",strokeWidth:1.5,...e?{strokeDasharray:"6 3"}:{}}}function Hi(e,t,n,r,i){var c;const s=(c=e.sections)==null?void 0:c[0],o=(i==null?void 0:i.x)??0,l=(i==null?void 0:i.y)??0;let u;if(s)u={sourcePoint:{x:s.startPoint.x+o,y:s.startPoint.y+l},targetPoint:{x:s.endPoint.x+o,y:s.endPoint.y+l},bendPoints:(s.bendPoints??[]).map(d=>({x:d.x+o,y:d.y+l}))};else{const d=t.get(e.sources[0]),p=t.get(e.targets[0]);d&&p&&(u={sourcePoint:{x:d.x+d.width/2,y:d.y+d.height},targetPoint:{x:p.x+p.width/2,y:p.y},bendPoints:[]})}return{id:e.id,source:e.sources[0],target:e.targets[0],type:"elk",data:u,style:Ss(r),markerEnd:Rr,...n?{label:n,labelStyle:{fill:"var(--text-muted)",fontSize:10},labelBgStyle:{fill:"var(--bg-primary)",fillOpacity:.8}}:{}}}async function qc(e){var u,c;const t=Gc(e),r=await(await Wc()).layout(t),i=new Map;for(const d of e.nodes)if(i.set(d.id,{type:d.type,data:d.data}),d.data.subgraph)for(const p of d.data.subgraph.nodes)i.set(`${d.id}/${p.id}`,{type:p.type,data:p.data});const s=[],o=[],l=new Map;for(const d of r.children??[]){const p=d.x??0,m=d.y??0;l.set(d.id,{x:p,y:m,width:d.width??0,height:d.height??0});for(const f of d.children??[])l.set(f.id,{x:p+(f.x??0),y:m+(f.y??0),width:f.width??0,height:f.height??0})}for(const d of r.children??[]){const p=i.get(d.id);if((((u=d.children)==null?void 0:u.length)??0)>0){s.push({id:d.id,type:"groupNode",data:{...(p==null?void 0:p.data)??{},nodeWidth:d.width,nodeHeight:d.height},position:{x:d.x??0,y:d.y??0},style:{width:d.width,height:d.height}});for(const x of d.children??[]){const y=i.get(x.id);s.push({id:x.id,type:(y==null?void 0:y.type)??"defaultNode",data:{...(y==null?void 0:y.data)??{},nodeWidth:x.width},position:{x:x.x??0,y:x.y??0},parentNode:d.id,extent:"parent"})}const f=d.x??0,g=d.y??0;for(const x of d.edges??[]){const y=e.nodes.find(k=>k.id===d.id),b=(c=y==null?void 0:y.data.subgraph)==null?void 0:c.edges.find(k=>`${d.id}/${k.id}`===x.id);o.push(Hi(x,l,b==null?void 0:b.label,b==null?void 0:b.conditional,{x:f,y:g}))}}else s.push({id:d.id,type:(p==null?void 0:p.type)??"defaultNode",data:{...(p==null?void 0:p.data)??{},nodeWidth:d.width},position:{x:d.x??0,y:d.y??0}})}for(const d of r.edges??[]){const p=e.edges.find(m=>m.id===d.id);o.push(Hi(d,l,p==null?void 0:p.label,p==null?void 0:p.conditional))}return{nodes:s,edges:o}}function Un({entrypoint:e,runId:t,breakpointNode:n,breakpointNextNodes:r,onBreakpointChange:i}){const[s,o,l]=Rl([]),[u,c,d]=Il([]),[p,m]=S.useState(!0),[f,g]=S.useState(!1),[x,y]=S.useState(0),b=S.useRef(0),k=S.useRef(null),A=Ee(N=>N.breakpoints[t]),j=Ee(N=>N.toggleBreakpoint),L=Ee(N=>N.clearBreakpoints),T=Ee(N=>N.activeNodes[t]),B=Ee(N=>{var _;return(_=N.runs[t])==null?void 0:_.status}),O=S.useCallback((N,_)=>{if(_.type==="startNode"||_.type==="endNode")return;const R=_.type==="groupNode"?_.id:_.id.includes("/")?_.id.split("/").pop():_.id;j(t,R);const W=Ee.getState().breakpoints[t]??{};i==null||i(Object.keys(W))},[t,j,i]),E=A&&Object.keys(A).length>0,w=S.useCallback(()=>{if(E)L(t),i==null||i([]);else{const N=[];for(const R of s){if(R.type==="startNode"||R.type==="endNode"||R.parentNode)continue;const W=R.type==="groupNode"?R.id:R.id.includes("/")?R.id.split("/").pop():R.id;N.push(W)}for(const R of N)A!=null&&A[R]||j(t,R);const _=Ee.getState().breakpoints[t]??{};i==null||i(Object.keys(_))}},[t,E,A,s,L,j,i]);S.useEffect(()=>{o(N=>N.map(_=>{var $;if(_.type==="startNode"||_.type==="endNode")return _;const R=_.type==="groupNode"?_.id:_.id.includes("/")?_.id.split("/").pop():_.id,W=!!(A&&A[R]);return W!==!!(($=_.data)!=null&&$.hasBreakpoint)?{..._,data:{..._.data,hasBreakpoint:W}}:_}))},[A,o]),S.useEffect(()=>{const N=n?new Set(n.split(",").map(_=>_.trim()).filter(Boolean)):null;o(_=>_.map(R=>{var h,F;if(R.type==="startNode"||R.type==="endNode")return R;const W=R.type==="groupNode"?R.id:R.id.includes("/")?R.id.split("/").pop():R.id,$=(h=R.data)==null?void 0:h.label,q=N!=null&&(N.has(W)||$!=null&&N.has($));return q!==!!((F=R.data)!=null&&F.isPausedHere)?{...R,data:{...R.data,isPausedHere:q}}:R}))},[n,x,o]);const M=Ee(N=>N.stateEvents[t]);S.useEffect(()=>{const N=!!n;let _=new Set;const R=new Set,W=new Set,$=new Set,q=new Map,h=new Map;if(M)for(const F of M)F.phase==="started"?h.set(F.node_name,F.qualified_node_name??null):F.phase==="completed"&&h.delete(F.node_name);o(F=>{var v;for(const oe of F)oe.type&&q.set(oe.id,oe.type);const U=oe=>{var K;const ae=[];for(const re of F){const de=re.type==="groupNode"?re.id:re.id.includes("/")?re.id.split("/").pop():re.id,be=(K=re.data)==null?void 0:K.label;(de===oe||be!=null&&be===oe)&&ae.push(re.id)}return ae};if(N&&n){const oe=n.split(",").map(ae=>ae.trim()).filter(Boolean);for(const ae of oe)U(ae).forEach(K=>_.add(K));if(r!=null&&r.length)for(const ae of r)U(ae).forEach(K=>W.add(K));T!=null&&T.prev&&U(T.prev).forEach(ae=>R.add(ae))}else if(h.size>0){const oe=new Map;for(const ae of F){const K=(v=ae.data)==null?void 0:v.label;if(!K)continue;const re=ae.id.includes("/")?ae.id.split("/").pop():ae.id;for(const de of[re,K]){let be=oe.get(de);be||(be=new Set,oe.set(de,be)),be.add(ae.id)}}for(const[ae,K]of h){let re=!1;if(K){const de=K.replace(/:/g,"/");for(const be of F)be.id===de&&(_.add(be.id),re=!0)}if(!re){const de=oe.get(ae);de&&de.forEach(be=>_.add(be))}}}return F}),c(F=>{const U=R.size===0||F.some(v=>_.has(v.target)&&R.has(v.source));return F.map(v=>{var ae,K;let oe;return N?oe=_.has(v.target)&&(R.size===0||!U||R.has(v.source))||_.has(v.source)&&W.has(v.target):(oe=_.has(v.source),!oe&&q.get(v.target)==="endNode"&&_.has(v.target)&&(oe=!0)),oe?(N||$.add(v.target),{...v,style:{stroke:"var(--accent)",strokeWidth:2.5},markerEnd:{...Rr,color:"var(--accent)"},data:{...v.data,highlighted:!0},animated:!0}):(ae=v.data)!=null&&ae.highlighted?{...v,style:Ss((K=v.data)==null?void 0:K.conditional),markerEnd:Rr,data:{...v.data,highlighted:!1},animated:!1}:v})}),o(F=>F.map(U=>{var ae,K,re,de;const v=!N&&_.has(U.id);if(U.type==="startNode"||U.type==="endNode"){const be=$.has(U.id)||!N&&_.has(U.id);return be!==!!((ae=U.data)!=null&&ae.isActiveNode)||v!==!!((K=U.data)!=null&&K.isExecutingNode)?{...U,data:{...U.data,isActiveNode:be,isExecutingNode:v}}:U}const oe=N?W.has(U.id):$.has(U.id);return oe!==!!((re=U.data)!=null&&re.isActiveNode)||v!==!!((de=U.data)!=null&&de.isExecutingNode)?{...U,data:{...U.data,isActiveNode:oe,isExecutingNode:v}}:U}))},[M,T,n,r,B,x,o,c]);const I=Ee(N=>N.graphCache[t]);S.useEffect(()=>{if(!I&&t!=="__setup__")return;const N=I?Promise.resolve(I):Jl(e),_=++b.current;m(!0),g(!1),N.then(async R=>{if(b.current!==_)return;if(!R.nodes.length){g(!0);return}const{nodes:W,edges:$}=await qc(R);if(b.current!==_)return;const q=Ee.getState().breakpoints[t],h=q?W.map(F=>{if(F.type==="startNode"||F.type==="endNode")return F;const U=F.type==="groupNode"?F.id:F.id.includes("/")?F.id.split("/").pop():F.id;return q[U]?{...F,data:{...F.data,hasBreakpoint:!0}}:F}):W;o(h),c($),y(F=>F+1),setTimeout(()=>{var F;(F=k.current)==null||F.fitView({padding:.1,duration:200})},100)}).catch(()=>{b.current===_&&g(!0)}).finally(()=>{b.current===_&&m(!1)})},[e,t,I,o,c]),S.useEffect(()=>{const N=setTimeout(()=>{var _;(_=k.current)==null||_.fitView({padding:.1,duration:200})},100);return()=>clearTimeout(N)},[t]);const D=S.useRef(null);return S.useEffect(()=>{const N=D.current;if(!N)return;const _=new ResizeObserver(()=>{var R;(R=k.current)==null||R.fitView({padding:.1,duration:200})});return _.observe(N),()=>_.disconnect()},[p,f]),S.useEffect(()=>{o(N=>{var v,oe,ae;const _=!!(M!=null&&M.length),R=B==="completed"||B==="failed",W=new Set,$=new Set(N.map(K=>K.id)),q=new Map;for(const K of N){const re=(v=K.data)==null?void 0:v.label;if(!re)continue;const de=K.id.includes("/")?K.id.split("/").pop():K.id;for(const be of[de,re]){let Oe=q.get(be);Oe||(Oe=new Set,q.set(be,Oe)),Oe.add(K.id)}}if(_)for(const K of M){let re=!1;if(K.qualified_node_name){const de=K.qualified_node_name.replace(/:/g,"/");$.has(de)&&(W.add(de),re=!0)}if(!re){const de=q.get(K.node_name);de&&de.forEach(be=>W.add(be))}}const h=new Set;for(const K of N)K.parentNode&&W.has(K.id)&&h.add(K.parentNode);let F;B==="failed"&&W.size===0&&(F=(oe=N.find(K=>!K.parentNode&&K.type!=="startNode"&&K.type!=="endNode"&&K.type!=="groupNode"))==null?void 0:oe.id);let U;if(B==="completed"){const K=(ae=N.find(re=>!re.parentNode&&re.type!=="startNode"&&re.type!=="endNode"&&re.type!=="groupNode"))==null?void 0:ae.id;K&&!W.has(K)&&(U=K)}return N.map(K=>{var de;let re;return K.id===F?re="failed":K.id===U||W.has(K.id)?re="completed":K.type==="startNode"?(!K.parentNode&&_||K.parentNode&&h.has(K.parentNode))&&(re="completed"):K.type==="endNode"?!K.parentNode&&R?re=B==="failed"?"failed":"completed":K.parentNode&&h.has(K.parentNode)&&(re="completed"):K.type==="groupNode"&&h.has(K.id)&&(re="completed"),re!==((de=K.data)==null?void 0:de.status)?{...K,data:{...K.data,status:re}}:K})})},[M,B,x,o]),p?a.jsx("div",{className:"flex items-center justify-center h-full",style:{color:"var(--text-muted)"},children:"Loading graph..."}):f?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4",style:{color:"var(--text-muted)"},children:[a.jsxs("svg",{width:"120",height:"120",viewBox:"0 0 120 120",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"38",y:"10",width:"44",height:"24",rx:"6",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.4"}),a.jsx("line",{x1:"60",y1:"34",x2:"60",y2:"46",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("rect",{x:"12",y:"46",width:"44",height:"24",rx:"6",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("rect",{x:"64",y:"46",width:"44",height:"24",rx:"6",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"60",y1:"46",x2:"34",y2:"46",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"60",y1:"46",x2:"86",y2:"46",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"34",y1:"70",x2:"34",y2:"82",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"86",y1:"70",x2:"86",y2:"82",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"34",y1:"82",x2:"60",y2:"82",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"86",y1:"82",x2:"60",y2:"82",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"60",y1:"82",x2:"60",y2:"86",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("rect",{x:"38",y:"86",width:"44",height:"24",rx:"6",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.4"})]}),a.jsx("span",{className:"text-xs",children:"No graph schema available"})]}):a.jsxs("div",{ref:D,className:"h-full graph-panel",children:[a.jsx("style",{children:` +`)}`:s,children:[o&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),a.jsx(gt,{type:"target",position:bt.Top,style:Bi}),a.jsxs("div",{style:{color:"var(--warning)",fontSize:9,marginBottom:1},children:["tools",i?` (${i})`:""]}),a.jsx("div",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s}),m.length>0&&a.jsxs("div",{style:{marginTop:3,fontSize:9,color:"var(--text-muted)",textAlign:"left"},children:[m.map(h=>a.jsx("div",{className:"truncate",children:h},h)),f>0&&a.jsxs("div",{style:{fontStyle:"italic"},children:["+",f," more"]})]}),a.jsx(gt,{type:"source",position:bt.Bottom,style:Bi})]})}const Fi={opacity:0,width:1,height:1,minWidth:0,minHeight:0,border:"none",padding:0};function jc({data:e}){const t=e.label??"",n=e.status,r=e.hasBreakpoint,i=e.isPausedHere,s=e.isActiveNode,o=e.isExecutingNode,l=i?"var(--error)":o?"var(--success)":s?"var(--accent)":n==="completed"?"var(--success)":n==="running"?"var(--warning)":n==="failed"?"var(--error)":"var(--bg-tertiary)",u=i?"var(--error)":o?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"relative cursor-pointer",style:{width:"100%",height:"100%",background:"var(--bg-secondary)",border:`1.5px ${i||s||o?"solid":"dashed"} ${l}`,borderRadius:8,boxShadow:i||s||o?`0 0 4px ${u}`:void 0,animation:i||s||o?`node-pulse-${i?"red":o?"green":"accent"} 1.5s ease-in-out infinite`:void 0},children:[r&&a.jsx("div",{className:"absolute",style:{top:4,left:4,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--bg-tertiary)",boxShadow:"0 0 4px var(--error)",zIndex:1}}),a.jsx(gt,{type:"target",position:bt.Top,style:Fi}),a.jsx("div",{style:{padding:"4px 10px",fontSize:10,color:"var(--text-muted)",fontWeight:600,textAlign:"center",borderBottom:`1px solid ${l}`,background:"var(--bg-tertiary)",borderRadius:"8px 8px 0 0"},children:t}),a.jsx(gt,{type:"source",position:bt.Bottom,style:Fi})]})}function Dc({data:e}){const t=e.status,n=e.nodeWidth,r=e.label??"",i=e.hasBreakpoint,s=e.isPausedHere,o=e.isActiveNode,l=e.isExecutingNode,u=s?"var(--error)":l?"var(--success)":o?"var(--accent)":t==="completed"?"var(--success)":t==="running"?"var(--warning)":t==="failed"?"var(--error)":"var(--node-border)",c=s?"var(--error)":l?"var(--success)":"var(--accent)";return a.jsxs("div",{className:"px-3 py-1.5 rounded-lg text-center text-xs overflow-hidden cursor-pointer relative",style:{width:n,background:"var(--node-bg)",color:"var(--text-primary)",border:`2px solid ${u}`,boxShadow:s||o||l?`0 0 4px ${c}`:void 0,animation:s||o||l?`node-pulse-${s?"red":l?"green":"accent"} 1.5s ease-in-out infinite`:void 0},title:r,children:[i&&a.jsx("div",{className:"absolute",style:{top:2,left:2,width:12,height:12,borderRadius:"50%",background:"var(--error)",border:"2px solid var(--node-bg)",boxShadow:"0 0 4px var(--error)"}}),a.jsx(gt,{type:"target",position:bt.Top}),a.jsx("div",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:r}),a.jsx(gt,{type:"source",position:bt.Bottom})]})}function Pc(e,t=8){if(e.length<2)return"";if(e.length===2)return`M ${e[0].x} ${e[0].y} L ${e[1].x} ${e[1].y}`;let n=`M ${e[0].x} ${e[0].y}`;for(let i=1;i0&&(n+=Math.min(r.length,3)*12+(r.length>3?12:0)+4),e!=null&&e.model_name&&(n+=14),n}let lr=null;async function Wc(){if(!lr){const{default:e}=await Ns(async()=>{const{default:t}=await import("./vendor-elk-CzxJ-xdZ.js").then(n=>n.e);return{default:t}},__vite__mapDeps([0,1]));lr=new e}return lr}const $i={"elk.algorithm":"layered","elk.direction":"DOWN","elk.edgeRouting":"ORTHOGONAL","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.spacing.nodeNode":"25","elk.layered.spacing.nodeNodeBetweenLayers":"50","elk.spacing.edgeNode":"30","elk.spacing.edgeEdge":"15","elk.layered.spacing.edgeNodeBetweenLayers":"25","elk.layered.spacing.edgeEdgeBetweenLayers":"15","elk.portAlignment.default":"CENTER","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES"},Kc="[top=35,left=15,bottom=15,right=15]";function Gc(e){const t=[],n=[];for(const r of e.nodes){const i=r.data,s={id:r.id,width:zi(i),height:Ui(i,r.type)};if(r.data.subgraph){const o=r.data.subgraph;delete s.width,delete s.height,s.layoutOptions={...$i,"elk.padding":Kc},s.children=o.nodes.map(l=>({id:`${r.id}/${l.id}`,width:zi(l.data),height:Ui(l.data,l.type)})),s.edges=o.edges.map(l=>({id:`${r.id}/${l.id}`,sources:[`${r.id}/${l.source}`],targets:[`${r.id}/${l.target}`]}))}t.push(s)}for(const r of e.edges)n.push({id:r.id,sources:[r.source],targets:[r.target]});return{id:"root",layoutOptions:$i,children:t,edges:n}}const Rr={type:Ml.ArrowClosed,width:12,height:12,color:"var(--node-border)"};function Ss(e){return{stroke:"var(--node-border)",strokeWidth:1.5,...e?{strokeDasharray:"6 3"}:{}}}function Hi(e,t,n,r,i){var c;const s=(c=e.sections)==null?void 0:c[0],o=(i==null?void 0:i.x)??0,l=(i==null?void 0:i.y)??0;let u;if(s)u={sourcePoint:{x:s.startPoint.x+o,y:s.startPoint.y+l},targetPoint:{x:s.endPoint.x+o,y:s.endPoint.y+l},bendPoints:(s.bendPoints??[]).map(d=>({x:d.x+o,y:d.y+l}))};else{const d=t.get(e.sources[0]),p=t.get(e.targets[0]);d&&p&&(u={sourcePoint:{x:d.x+d.width/2,y:d.y+d.height},targetPoint:{x:p.x+p.width/2,y:p.y},bendPoints:[]})}return{id:e.id,source:e.sources[0],target:e.targets[0],type:"elk",data:u,style:Ss(r),markerEnd:Rr,...n?{label:n,labelStyle:{fill:"var(--text-muted)",fontSize:10},labelBgStyle:{fill:"var(--bg-primary)",fillOpacity:.8}}:{}}}async function qc(e){var u,c;const t=Gc(e),r=await(await Wc()).layout(t),i=new Map;for(const d of e.nodes)if(i.set(d.id,{type:d.type,data:d.data}),d.data.subgraph)for(const p of d.data.subgraph.nodes)i.set(`${d.id}/${p.id}`,{type:p.type,data:p.data});const s=[],o=[],l=new Map;for(const d of r.children??[]){const p=d.x??0,m=d.y??0;l.set(d.id,{x:p,y:m,width:d.width??0,height:d.height??0});for(const f of d.children??[])l.set(f.id,{x:p+(f.x??0),y:m+(f.y??0),width:f.width??0,height:f.height??0})}for(const d of r.children??[]){const p=i.get(d.id);if((((u=d.children)==null?void 0:u.length)??0)>0){s.push({id:d.id,type:"groupNode",data:{...(p==null?void 0:p.data)??{},nodeWidth:d.width,nodeHeight:d.height},position:{x:d.x??0,y:d.y??0},style:{width:d.width,height:d.height}});for(const x of d.children??[]){const v=i.get(x.id);s.push({id:x.id,type:(v==null?void 0:v.type)??"defaultNode",data:{...(v==null?void 0:v.data)??{},nodeWidth:x.width},position:{x:x.x??0,y:x.y??0},parentNode:d.id,extent:"parent"})}const f=d.x??0,h=d.y??0;for(const x of d.edges??[]){const v=e.nodes.find(E=>E.id===d.id),b=(c=v==null?void 0:v.data.subgraph)==null?void 0:c.edges.find(E=>`${d.id}/${E.id}`===x.id);o.push(Hi(x,l,b==null?void 0:b.label,b==null?void 0:b.conditional,{x:f,y:h}))}}else s.push({id:d.id,type:(p==null?void 0:p.type)??"defaultNode",data:{...(p==null?void 0:p.data)??{},nodeWidth:d.width},position:{x:d.x??0,y:d.y??0}})}for(const d of r.edges??[]){const p=e.edges.find(m=>m.id===d.id);o.push(Hi(d,l,p==null?void 0:p.label,p==null?void 0:p.conditional))}return{nodes:s,edges:o}}function Un({entrypoint:e,runId:t,breakpointNode:n,breakpointNextNodes:r,onBreakpointChange:i}){const[s,o,l]=Rl([]),[u,c,d]=Il([]),[p,m]=S.useState(!0),[f,h]=S.useState(!1),[x,v]=S.useState(0),b=S.useRef(0),E=S.useRef(null),A=Ee(_=>_.breakpoints[t]),D=Ee(_=>_.toggleBreakpoint),L=Ee(_=>_.clearBreakpoints),T=Ee(_=>_.activeNodes[t]),B=Ee(_=>{var N;return(N=_.runs[t])==null?void 0:N.status}),O=S.useCallback((_,N)=>{if(N.type==="startNode"||N.type==="endNode")return;const R=N.type==="groupNode"?N.id:N.id.includes("/")?N.id.split("/").pop():N.id;D(t,R);const W=Ee.getState().breakpoints[t]??{};i==null||i(Object.keys(W))},[t,D,i]),k=A&&Object.keys(A).length>0,w=S.useCallback(()=>{if(k)L(t),i==null||i([]);else{const _=[];for(const R of s){if(R.type==="startNode"||R.type==="endNode"||R.parentNode)continue;const W=R.type==="groupNode"?R.id:R.id.includes("/")?R.id.split("/").pop():R.id;_.push(W)}for(const R of _)A!=null&&A[R]||D(t,R);const N=Ee.getState().breakpoints[t]??{};i==null||i(Object.keys(N))}},[t,k,A,s,L,D,i]);S.useEffect(()=>{o(_=>_.map(N=>{var $;if(N.type==="startNode"||N.type==="endNode")return N;const R=N.type==="groupNode"?N.id:N.id.includes("/")?N.id.split("/").pop():N.id,W=!!(A&&A[R]);return W!==!!(($=N.data)!=null&&$.hasBreakpoint)?{...N,data:{...N.data,hasBreakpoint:W}}:N}))},[A,o]),S.useEffect(()=>{const _=n?new Set(n.split(",").map(N=>N.trim()).filter(Boolean)):null;o(N=>N.map(R=>{var g,F;if(R.type==="startNode"||R.type==="endNode")return R;const W=R.type==="groupNode"?R.id:R.id.includes("/")?R.id.split("/").pop():R.id,$=(g=R.data)==null?void 0:g.label,V=_!=null&&(_.has(W)||$!=null&&_.has($));return V!==!!((F=R.data)!=null&&F.isPausedHere)?{...R,data:{...R.data,isPausedHere:V}}:R}))},[n,x,o]);const M=Ee(_=>_.stateEvents[t]);S.useEffect(()=>{const _=!!n;let N=new Set;const R=new Set,W=new Set,$=new Set,V=new Map,g=new Map;if(M)for(const F of M)F.phase==="started"?g.set(F.node_name,F.qualified_node_name??null):F.phase==="completed"&&g.delete(F.node_name);o(F=>{var y;for(const Q of F)Q.type&&V.set(Q.id,Q.type);const U=Q=>{var K;const se=[];for(const ie of F){const de=ie.type==="groupNode"?ie.id:ie.id.includes("/")?ie.id.split("/").pop():ie.id,be=(K=ie.data)==null?void 0:K.label;(de===Q||be!=null&&be===Q)&&se.push(ie.id)}return se};if(_&&n){const Q=n.split(",").map(se=>se.trim()).filter(Boolean);for(const se of Q)U(se).forEach(K=>N.add(K));if(r!=null&&r.length)for(const se of r)U(se).forEach(K=>W.add(K));T!=null&&T.prev&&U(T.prev).forEach(se=>R.add(se))}else if(g.size>0){const Q=new Map;for(const se of F){const K=(y=se.data)==null?void 0:y.label;if(!K)continue;const ie=se.id.includes("/")?se.id.split("/").pop():se.id;for(const de of[ie,K]){let be=Q.get(de);be||(be=new Set,Q.set(de,be)),be.add(se.id)}}for(const[se,K]of g){let ie=!1;if(K){const de=K.replace(/:/g,"/");for(const be of F)be.id===de&&(N.add(be.id),ie=!0)}if(!ie){const de=Q.get(se);de&&de.forEach(be=>N.add(be))}}}return F}),c(F=>{const U=R.size===0||F.some(y=>N.has(y.target)&&R.has(y.source));return F.map(y=>{var se,K;let Q;return _?Q=N.has(y.target)&&(R.size===0||!U||R.has(y.source))||N.has(y.source)&&W.has(y.target):(Q=N.has(y.source),!Q&&V.get(y.target)==="endNode"&&N.has(y.target)&&(Q=!0)),Q?(_||$.add(y.target),{...y,style:{stroke:"var(--accent)",strokeWidth:2.5},markerEnd:{...Rr,color:"var(--accent)"},data:{...y.data,highlighted:!0},animated:!0}):(se=y.data)!=null&&se.highlighted?{...y,style:Ss((K=y.data)==null?void 0:K.conditional),markerEnd:Rr,data:{...y.data,highlighted:!1},animated:!1}:y})}),o(F=>F.map(U=>{var se,K,ie,de;const y=!_&&N.has(U.id);if(U.type==="startNode"||U.type==="endNode"){const be=$.has(U.id)||!_&&N.has(U.id);return be!==!!((se=U.data)!=null&&se.isActiveNode)||y!==!!((K=U.data)!=null&&K.isExecutingNode)?{...U,data:{...U.data,isActiveNode:be,isExecutingNode:y}}:U}const Q=_?W.has(U.id):$.has(U.id);return Q!==!!((ie=U.data)!=null&&ie.isActiveNode)||y!==!!((de=U.data)!=null&&de.isExecutingNode)?{...U,data:{...U.data,isActiveNode:Q,isExecutingNode:y}}:U}))},[M,T,n,r,B,x,o,c]);const I=Ee(_=>_.graphCache[t]);S.useEffect(()=>{if(!I&&t!=="__setup__")return;const _=I?Promise.resolve(I):Jl(e),N=++b.current;m(!0),h(!1),_.then(async R=>{if(b.current!==N)return;if(!R.nodes.length){h(!0);return}const{nodes:W,edges:$}=await qc(R);if(b.current!==N)return;const V=Ee.getState().breakpoints[t],g=V?W.map(F=>{if(F.type==="startNode"||F.type==="endNode")return F;const U=F.type==="groupNode"?F.id:F.id.includes("/")?F.id.split("/").pop():F.id;return V[U]?{...F,data:{...F.data,hasBreakpoint:!0}}:F}):W;o(g),c($),v(F=>F+1),setTimeout(()=>{var F;(F=E.current)==null||F.fitView({padding:.1,duration:200})},100)}).catch(()=>{b.current===N&&h(!0)}).finally(()=>{b.current===N&&m(!1)})},[e,t,I,o,c]),S.useEffect(()=>{const _=setTimeout(()=>{var N;(N=E.current)==null||N.fitView({padding:.1,duration:200})},100);return()=>clearTimeout(_)},[t]);const j=S.useRef(null);return S.useEffect(()=>{const _=j.current;if(!_)return;const N=new ResizeObserver(()=>{var R;(R=E.current)==null||R.fitView({padding:.1,duration:200})});return N.observe(_),()=>N.disconnect()},[p,f]),S.useEffect(()=>{o(_=>{var y,Q,se;const N=!!(M!=null&&M.length),R=B==="completed"||B==="failed",W=new Set,$=new Set(_.map(K=>K.id)),V=new Map;for(const K of _){const ie=(y=K.data)==null?void 0:y.label;if(!ie)continue;const de=K.id.includes("/")?K.id.split("/").pop():K.id;for(const be of[de,ie]){let Oe=V.get(be);Oe||(Oe=new Set,V.set(be,Oe)),Oe.add(K.id)}}if(N)for(const K of M){let ie=!1;if(K.qualified_node_name){const de=K.qualified_node_name.replace(/:/g,"/");$.has(de)&&(W.add(de),ie=!0)}if(!ie){const de=V.get(K.node_name);de&&de.forEach(be=>W.add(be))}}const g=new Set;for(const K of _)K.parentNode&&W.has(K.id)&&g.add(K.parentNode);let F;B==="failed"&&W.size===0&&(F=(Q=_.find(K=>!K.parentNode&&K.type!=="startNode"&&K.type!=="endNode"&&K.type!=="groupNode"))==null?void 0:Q.id);let U;if(B==="completed"){const K=(se=_.find(ie=>!ie.parentNode&&ie.type!=="startNode"&&ie.type!=="endNode"&&ie.type!=="groupNode"))==null?void 0:se.id;K&&!W.has(K)&&(U=K)}return _.map(K=>{var de;let ie;return K.id===F?ie="failed":K.id===U||W.has(K.id)?ie="completed":K.type==="startNode"?(!K.parentNode&&N||K.parentNode&&g.has(K.parentNode))&&(ie="completed"):K.type==="endNode"?!K.parentNode&&R?ie=B==="failed"?"failed":"completed":K.parentNode&&g.has(K.parentNode)&&(ie="completed"):K.type==="groupNode"&&g.has(K.id)&&(ie="completed"),ie!==((de=K.data)==null?void 0:de.status)?{...K,data:{...K.data,status:ie}}:K})})},[M,B,x,o]),p?a.jsx("div",{className:"flex items-center justify-center h-full",style:{color:"var(--text-muted)"},children:"Loading graph..."}):f?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4",style:{color:"var(--text-muted)"},children:[a.jsxs("svg",{width:"120",height:"120",viewBox:"0 0 120 120",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"38",y:"10",width:"44",height:"24",rx:"6",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.4"}),a.jsx("line",{x1:"60",y1:"34",x2:"60",y2:"46",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("rect",{x:"12",y:"46",width:"44",height:"24",rx:"6",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("rect",{x:"64",y:"46",width:"44",height:"24",rx:"6",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"60",y1:"46",x2:"34",y2:"46",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"60",y1:"46",x2:"86",y2:"46",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"34",y1:"70",x2:"34",y2:"82",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"86",y1:"70",x2:"86",y2:"82",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"34",y1:"82",x2:"60",y2:"82",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"86",y1:"82",x2:"60",y2:"82",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("line",{x1:"60",y1:"82",x2:"60",y2:"86",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.3"}),a.jsx("rect",{x:"38",y:"86",width:"44",height:"24",rx:"6",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"4 3",opacity:"0.4"})]}),a.jsx("span",{className:"text-xs",children:"No graph schema available"})]}):a.jsxs("div",{ref:j,className:"h-full graph-panel",children:[a.jsx("style",{children:` .graph-panel .react-flow__handle { opacity: 0 !important; width: 0 !important; @@ -37,8 +37,8 @@ ${r.join(` 0%, 100% { box-shadow: 0 0 4px var(--error); } 50% { box-shadow: 0 0 10px var(--error); } } - `}),a.jsxs(Ol,{nodes:s,edges:u,onNodesChange:l,onEdgesChange:d,nodeTypes:Fc,edgeTypes:zc,onInit:N=>{k.current=N},onNodeClick:O,fitView:!0,proOptions:{hideAttribution:!0},nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,children:[a.jsx(Ll,{color:"var(--bg-tertiary)",gap:16}),a.jsx(jl,{showInteractive:!1}),a.jsx(Dl,{position:"top-right",children:a.jsxs("button",{onClick:w,title:E?"Remove all breakpoints":"Set breakpoints on all nodes",style:{background:"var(--bg-secondary)",color:E?"var(--error)":"var(--text-muted)",border:`1px solid ${E?"var(--error)":"var(--node-border)"}`,borderRadius:6,padding:"4px 10px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:[a.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:E?"var(--error)":"var(--node-border)"}}),E?"Clear all":"Break all"]})}),a.jsx(Pl,{nodeColor:N=>{var R;if(N.type==="groupNode")return"var(--bg-tertiary)";const _=(R=N.data)==null?void 0:R.status;return _==="completed"?"var(--success)":_==="running"?"var(--warning)":_==="failed"?"var(--error)":"var(--node-border)"},nodeStrokeWidth:0,style:{background:"var(--bg-secondary)",width:120,height:80}})]})]})}const Ut="__setup__";function Vc({entrypoint:e,mode:t,ws:n,onRunCreated:r,isMobile:i}){const[s,o]=S.useState("{}"),[l,u]=S.useState({}),[c,d]=S.useState(!1),[p,m]=S.useState(!0),[f,g]=S.useState(null),[x,y]=S.useState(""),[b,k]=S.useState(!0),[A,j]=S.useState(()=>{const R=localStorage.getItem("setupTextareaHeight");return R?parseInt(R,10):140}),L=S.useRef(null),[T,B]=S.useState(()=>{const R=localStorage.getItem("setupPanelWidth");return R?parseInt(R,10):380}),O=t==="run";S.useEffect(()=>{m(!0),g(null),Zl(e).then(R=>{u(R.mock_input),o(JSON.stringify(R.mock_input,null,2))}).catch(R=>{console.error("Failed to load mock input:",R);const W=R.detail||{};g(W.message||`Failed to load schema for "${e}"`),o("{}")}).finally(()=>m(!1))},[e]),S.useEffect(()=>{Ee.getState().clearBreakpoints(Ut)},[]);const E=async()=>{let R;try{R=JSON.parse(s)}catch{alert("Invalid JSON input");return}d(!0);try{const W=Ee.getState().breakpoints[Ut]??{},$=Object.keys(W),q=await Mi(e,R,t,$);Ee.getState().clearBreakpoints(Ut),Ee.getState().upsertRun(q),r(q.id)}catch(W){console.error("Failed to create run:",W)}finally{d(!1)}},w=async()=>{const R=x.trim();if(R){d(!0);try{const W=Ee.getState().breakpoints[Ut]??{},$=Object.keys(W),q=await Mi(e,l,"chat",$);Ee.getState().clearBreakpoints(Ut),Ee.getState().upsertRun(q),Ee.getState().addLocalChatMessage(q.id,{message_id:`local-${Date.now()}`,role:"user",content:R}),n.sendChatMessage(q.id,R),r(q.id)}catch(W){console.error("Failed to create chat run:",W)}finally{d(!1)}}};S.useEffect(()=>{try{JSON.parse(s),k(!0)}catch{k(!1)}},[s]);const M=S.useCallback(R=>{R.preventDefault();const W="touches"in R?R.touches[0].clientY:R.clientY,$=A,q=F=>{const U="touches"in F?F.touches[0].clientY:F.clientY,v=Math.max(60,$+(W-U));j(v)},h=()=>{document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",h),document.removeEventListener("touchmove",q),document.removeEventListener("touchend",h),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem("setupTextareaHeight",String(A))};document.body.style.cursor="row-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",q),document.addEventListener("mouseup",h),document.addEventListener("touchmove",q,{passive:!1}),document.addEventListener("touchend",h)},[A]),I=S.useCallback(R=>{R.preventDefault();const W="touches"in R?R.touches[0].clientX:R.clientX,$=T,q=F=>{const U=L.current;if(!U)return;const v="touches"in F?F.touches[0].clientX:F.clientX,oe=U.clientWidth-300,ae=Math.max(280,Math.min(oe,$+(W-v)));B(ae)},h=()=>{document.removeEventListener("mousemove",q),document.removeEventListener("mouseup",h),document.removeEventListener("touchmove",q),document.removeEventListener("touchend",h),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem("setupPanelWidth",String(T))};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",q),document.addEventListener("mouseup",h),document.addEventListener("touchmove",q,{passive:!1}),document.addEventListener("touchend",h)},[T]),D=O?"Autonomous":"Conversational",N=O?"var(--success)":"var(--accent)",_=a.jsxs("div",{className:"shrink-0 flex flex-col",style:i?{background:"var(--bg-primary)"}:{width:T,background:"var(--bg-primary)"},children:[a.jsxs("div",{className:"px-4 text-xs font-semibold border-b flex items-center gap-2 h-10",style:{color:"var(--text-muted)",borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[a.jsx("span",{style:{color:N},children:"●"}),D]}),a.jsxs("div",{className:"flex-1 overflow-y-auto flex flex-col items-center justify-center gap-4 px-6",children:[a.jsx("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",opacity:.5},children:O?a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("polyline",{points:"12 6 12 12 16 14"})]}):a.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),a.jsxs("div",{className:"text-center space-y-1.5",children:[a.jsx("p",{className:"text-sm font-medium",style:{color:"var(--text-secondary)"},children:O?"Ready to execute":"Ready to chat"}),a.jsxs("p",{className:"text-xs leading-relaxed",style:{color:"var(--text-muted)"},children:["Click nodes to set breakpoints",O?a.jsxs(a.Fragment,{children:[",",a.jsx("br",{}),"configure input below, then run"]}):a.jsxs(a.Fragment,{children:[",",a.jsx("br",{}),"then send your first message"]})]})]})]}),O?a.jsxs("div",{className:"flex flex-col",style:{background:"var(--bg-primary)"},children:[!i&&a.jsx("div",{onMouseDown:M,onTouchStart:M,className:"shrink-0 drag-handle-row"}),a.jsxs("div",{className:"px-4 py-3",children:[f?a.jsx("div",{className:"text-xs mb-3 px-3 py-2 rounded",style:{color:"var(--error)",background:"color-mix(in srgb, var(--error) 10%, var(--bg-secondary))"},children:f}):a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:["Input",p&&a.jsx("span",{className:"ml-2 font-normal",children:"Loading..."})]}),a.jsx("textarea",{value:s,onChange:R=>o(R.target.value),spellCheck:!1,className:"w-full rounded-md px-3 py-2 text-xs font-mono leading-relaxed resize-none mb-3",style:{height:i?120:A,background:"var(--bg-secondary)",border:`1px solid ${b?"var(--border)":"#b91c1c"}`,color:"var(--text-primary)"}})]}),a.jsx("button",{onClick:E,disabled:c||p||!!f,className:"w-full py-2 text-sm font-semibold rounded-md border cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2",style:{background:"transparent",borderColor:N,color:N},onMouseEnter:R=>{c||(R.currentTarget.style.background=`color-mix(in srgb, ${N} 10%, transparent)`)},onMouseLeave:R=>{R.currentTarget.style.background="transparent"},children:c?"Starting...":a.jsxs(a.Fragment,{children:[a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:a.jsx("polygon",{points:"5,3 19,12 5,21"})}),"Execute"]})})]})]}):a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-t",style:{borderColor:"var(--border)"},children:[a.jsx("input",{value:x,onChange:R=>y(R.target.value),onKeyDown:R=>{R.key==="Enter"&&!R.shiftKey&&(R.preventDefault(),w())},disabled:c||p,placeholder:c?"Starting...":"Message...",className:"flex-1 bg-transparent text-sm py-1 disabled:opacity-40 placeholder:text-[var(--text-muted)]",style:{color:"var(--text-primary)"}}),a.jsx("button",{onClick:w,disabled:c||p||!x.trim(),className:"text-xs font-semibold px-3 py-1.5 rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed",style:{color:!c&&x.trim()?"var(--accent)":"var(--text-muted)",background:"transparent"},onMouseEnter:R=>{!c&&x.trim()&&(R.currentTarget.style.background="color-mix(in srgb, var(--accent) 10%, transparent)")},onMouseLeave:R=>{R.currentTarget.style.background="transparent"},children:"Send"})]})]});return i?a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsx("div",{className:"shrink-0",style:{height:"40vh"},children:a.jsx(Un,{entrypoint:e,traces:[],runId:Ut})}),a.jsx("div",{className:"flex-1 overflow-y-auto flex flex-col min-h-0",children:_})]}):a.jsxs("div",{ref:L,className:"flex h-full",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx(Un,{entrypoint:e,traces:[],runId:Ut})}),a.jsx("div",{onMouseDown:I,onTouchStart:I,className:"shrink-0 drag-handle-col"}),_]})}const Yc={key:"var(--info)",string:"var(--success)",number:"var(--warning)",boolean:"var(--accent)",null:"var(--accent)",punctuation:"var(--text-muted)"};function Xc(e){const t=[],n=/("(?:[^"\\]|\\.)*")\s*:|("(?:[^"\\]|\\.)*")|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)\b|(true|false)\b|(null)\b|([{}[\]:,])/g;let r=0,i;for(;(i=n.exec(e))!==null;){if(i.index>r&&t.push({type:"punctuation",text:e.slice(r,i.index)}),i[1]!==void 0){t.push({type:"key",text:i[1]});const s=e.indexOf(":",i.index+i[1].length);s!==-1&&(s>i.index+i[1].length&&t.push({type:"punctuation",text:e.slice(i.index+i[1].length,s)}),t.push({type:"punctuation",text:":"}),n.lastIndex=s+1)}else i[2]!==void 0?t.push({type:"string",text:i[2]}):i[3]!==void 0?t.push({type:"number",text:i[3]}):i[4]!==void 0?t.push({type:"boolean",text:i[4]}):i[5]!==void 0?t.push({type:"null",text:i[5]}):i[6]!==void 0&&t.push({type:"punctuation",text:i[6]});r=n.lastIndex}return rXc(e),[e]);return a.jsx("pre",{className:t,style:n,children:r.map((i,s)=>a.jsx("span",{style:{color:Yc[i.type]},children:i.text},s))})}const Zc={started:{color:"var(--info)",label:"Started"},running:{color:"var(--warning)",label:"Running"},completed:{color:"var(--success)",label:"Completed"},failed:{color:"var(--error)",label:"Failed"},error:{color:"var(--error)",label:"Error"}},Jc={color:"var(--text-muted)",label:"Unknown"};function Qc(e){if(typeof e!="string")return null;const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.stringify(JSON.parse(t),null,2)}catch{return null}return null}const Wi=200;function eu(e){if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function tu({value:e}){const[t,n]=S.useState(!1),r=eu(e),i=S.useMemo(()=>Qc(e),[e]),s=i!==null,o=i??r,l=o.length>Wi||o.includes(` -`),u=S.useCallback(()=>n(c=>!c),[]);return l?a.jsxs("div",{children:[t?s?a.jsx(it,{json:o,className:"font-mono text-[11px] whitespace-pre-wrap break-all",style:{}}):a.jsx("pre",{className:"font-mono text-[11px] whitespace-pre-wrap break-all",style:{color:"var(--text-primary)"},children:o}):a.jsxs("span",{className:"font-mono text-[11px] break-all",style:{color:"var(--text-primary)"},children:[o.slice(0,Wi),"..."]}),a.jsx("button",{onClick:u,className:"text-[11px] cursor-pointer ml-1 px-1",style:{color:"var(--info)"},children:t?"[less]":"[more]"})]}):s?a.jsx(it,{json:o,className:"font-mono text-[11px] break-all whitespace-pre-wrap",style:{}}):a.jsx("span",{className:"font-mono text-[11px] break-all",style:{color:"var(--text-primary)"},children:o})}function nu({span:e}){const[t,n]=S.useState(!0),[r,i]=S.useState(!1),[s,o]=S.useState("table"),[l,u]=S.useState(!1),c=Zc[e.status.toLowerCase()]??{...Jc,label:e.status},d=S.useMemo(()=>JSON.stringify(e,null,2),[e]),p=S.useCallback(()=>{navigator.clipboard.writeText(d).then(()=>{u(!0),setTimeout(()=>u(!1),1500)})},[d]),m=Object.entries(e.attributes),f=[{label:"Span",value:e.span_id},...e.trace_id?[{label:"Trace",value:e.trace_id}]:[],{label:"Run",value:e.run_id},...e.parent_span_id?[{label:"Parent",value:e.parent_span_id}]:[]];return a.jsxs("div",{className:"flex flex-col h-full text-xs leading-normal",children:[a.jsxs("div",{className:"px-2 border-b flex items-center gap-1 shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",height:"32px"},children:[a.jsx("button",{onClick:()=>o("table"),className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:s==="table"?"var(--accent)":"var(--text-muted)",background:s==="table"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:g=>{s!=="table"&&(g.currentTarget.style.color="var(--text-primary)")},onMouseLeave:g=>{s!=="table"&&(g.currentTarget.style.color="var(--text-muted)")},children:"Table"}),a.jsx("button",{onClick:()=>o("json"),className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:s==="json"?"var(--accent)":"var(--text-muted)",background:s==="json"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:g=>{s!=="json"&&(g.currentTarget.style.color="var(--text-primary)")},onMouseLeave:g=>{s!=="json"&&(g.currentTarget.style.color="var(--text-muted)")},children:"JSON"}),a.jsxs("span",{className:"ml-auto shrink-0 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-bold uppercase tracking-wider",style:{background:`color-mix(in srgb, ${c.color} 15%, var(--bg-secondary))`,color:c.color},children:[a.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full",style:{background:c.color}}),c.label]})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-0.5 pr-0 pt-0 mr-0.5 mt-0.5",children:s==="table"?a.jsxs(a.Fragment,{children:[m.length>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"px-2 py-1 text-[11px] uppercase font-bold tracking-wider border-b cursor-pointer flex items-center",style:{color:"var(--success)",borderColor:"var(--border)",background:"var(--bg-secondary)"},onClick:()=>n(g=>!g),children:[a.jsxs("span",{className:"flex-1",children:["Attributes (",m.length,")"]}),a.jsx("span",{style:{color:"var(--text-muted)",transform:t?"rotate(0deg)":"rotate(-90deg)"},children:"▾"})]}),t&&m.map(([g,x],y)=>a.jsxs("div",{className:"flex gap-2 px-2 py-1 items-start border-b",style:{borderColor:"var(--border)",background:y%2===0?"var(--bg-primary)":"var(--bg-secondary)"},children:[a.jsx("span",{className:"font-mono font-semibold shrink-0 pt-px truncate text-[11px]",style:{color:"var(--info)",width:"35%"},title:g,children:g}),a.jsx("span",{className:"flex-1 min-w-0",children:a.jsx(tu,{value:x})})]},g))]}),a.jsxs("div",{className:"px-2 py-1 text-[11px] uppercase font-bold tracking-wider border-b cursor-pointer flex items-center",style:{color:"var(--success)",borderColor:"var(--border)",background:"var(--bg-secondary)"},onClick:()=>i(g=>!g),children:[a.jsxs("span",{className:"flex-1",children:["Identifiers (",f.length,")"]}),a.jsx("span",{style:{color:"var(--text-muted)",transform:r?"rotate(0deg)":"rotate(-90deg)"},children:"▾"})]}),r&&f.map((g,x)=>a.jsxs("div",{className:"flex gap-2 px-2 py-1 items-start border-b",style:{borderColor:"var(--border)",background:x%2===0?"var(--bg-primary)":"var(--bg-secondary)"},children:[a.jsx("span",{className:"font-mono font-semibold shrink-0 pt-px truncate text-[11px]",style:{color:"var(--info)",width:"35%"},title:g.label,children:g.label}),a.jsx("span",{className:"flex-1 min-w-0",children:a.jsx("span",{className:"font-mono text-[11px] break-all",style:{color:"var(--text-primary)"},children:g.value})})]},g.label))]}):a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:p,className:"absolute top-1 right-1 z-10 text-[11px] cursor-pointer px-2 py-1 rounded transition-colors",style:{color:l?"var(--success)":"var(--text-muted)",background:"var(--bg-secondary)",border:"1px solid var(--border)"},onMouseEnter:g=>{l||(g.currentTarget.style.color="var(--text-primary)")},onMouseLeave:g=>{g.currentTarget.style.color=l?"var(--success)":"var(--text-muted)"},children:l?"Copied!":"Copy"}),a.jsx(it,{json:d,className:"font-mono text-[11px] whitespace-pre-wrap p-2",style:{}})]})})]})}function ru(e){const t=[];function n(r,i){t.push({span:r.span,depth:i});for(const s of r.children)n(s,i+1)}for(const r of e)n(r,0);return t}function iu({tree:e,selectedSpan:t,onSelect:n}){const r=S.useMemo(()=>ru(e),[e]),{globalStart:i,totalDuration:s}=S.useMemo(()=>{if(r.length===0)return{globalStart:0,totalDuration:1};let o=1/0,l=-1/0;for(const{span:u}of r){const c=new Date(u.timestamp).getTime();o=Math.min(o,c),l=Math.max(l,c+(u.duration_ms??0))}return{globalStart:o,totalDuration:Math.max(l-o,1)}},[r]);return r.length===0?null:a.jsx(a.Fragment,{children:r.map(({span:o,depth:l})=>{var x;const u=new Date(o.timestamp).getTime()-i,c=o.duration_ms??0,d=u/s*100,p=Math.max(c/s*100,.3),m=Ts[o.status.toLowerCase()]??"var(--text-muted)",f=o.span_id===(t==null?void 0:t.span_id),g=(x=o.attributes)==null?void 0:x["openinference.span.kind"];return a.jsxs("button",{"data-span-id":o.span_id,onClick:()=>n(o),className:"w-full text-left text-xs leading-normal py-1 flex items-center transition-colors",style:{background:f?"color-mix(in srgb, var(--accent) 10%, var(--bg-primary))":void 0,borderLeft:f?"2px solid var(--accent)":"2px solid transparent"},onMouseEnter:y=>{f||(y.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:y=>{f||(y.currentTarget.style.background="")},children:[a.jsxs("div",{className:"shrink-0 flex items-center gap-1 overflow-hidden",style:{width:"35%",minWidth:"80px",paddingLeft:`${l*12+4}px`},children:[a.jsx("span",{className:"shrink-0 flex items-center justify-center w-3.5 h-3.5",children:a.jsx(Cs,{kind:g,statusColor:m})}),a.jsx("span",{className:"text-[var(--text-primary)] truncate",children:o.span_name})]}),a.jsx("div",{className:"flex-1 relative h-[14px] mx-1 rounded-sm",style:{background:"var(--bg-secondary)"},children:a.jsx("div",{className:"absolute rounded-sm",style:{left:`${d}%`,width:`${p}%`,top:"2px",bottom:"2px",background:m,opacity:.8,minWidth:"2px"}})}),a.jsx("span",{className:"shrink-0 text-[10px] tabular-nums pr-2",style:{width:"52px",textAlign:"right",color:"var(--text-muted)"},children:As(o.duration_ms)})]},o.span_id)})})}const Ts={started:"var(--info)",running:"var(--warning)",completed:"var(--success)",failed:"var(--error)",error:"var(--error)"};function Cs({kind:e,statusColor:t}){const n=t,r=14,i={width:r,height:r,viewBox:"0 0 16 16",fill:"none",stroke:n,strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};switch(e){case"LLM":return a.jsx("svg",{...i,children:a.jsx("path",{d:"M8 2L9 5L12 4L10 7L14 8L10 9L12 12L9 11L8 14L7 11L4 12L6 9L2 8L6 7L4 4L7 5Z",fill:n,stroke:"none"})});case"TOOL":return a.jsx("svg",{...i,children:a.jsx("path",{d:"M10.5 2.5a3.5 3.5 0 0 0-3.17 4.93L3.5 11.27a1 1 0 0 0 0 1.41l.82.82a1 1 0 0 0 1.41 0l3.84-3.83A3.5 3.5 0 1 0 10.5 2.5z"})});case"AGENT":return a.jsxs("svg",{...i,children:[a.jsx("rect",{x:"3",y:"5",width:"10",height:"8",rx:"2"}),a.jsx("circle",{cx:"6",cy:"9",r:"1",fill:n,stroke:"none"}),a.jsx("circle",{cx:"10",cy:"9",r:"1",fill:n,stroke:"none"}),a.jsx("path",{d:"M8 2v3"}),a.jsx("path",{d:"M6 2h4"})]});case"CHAIN":return a.jsxs("svg",{...i,children:[a.jsx("path",{d:"M6.5 9.5L9.5 6.5"}),a.jsx("path",{d:"M4.5 8.5l-1 1a2 2 0 0 0 2.83 2.83l1-1"}),a.jsx("path",{d:"M11.5 7.5l1-1a2 2 0 0 0-2.83-2.83l-1 1"})]});case"RETRIEVER":return a.jsxs("svg",{...i,children:[a.jsx("circle",{cx:"7",cy:"7",r:"4"}),a.jsx("path",{d:"M10 10l3.5 3.5"})]});case"EMBEDDING":return a.jsxs("svg",{...i,children:[a.jsx("rect",{x:"2",y:"2",width:"4",height:"4",rx:"0.5"}),a.jsx("rect",{x:"10",y:"2",width:"4",height:"4",rx:"0.5"}),a.jsx("rect",{x:"2",y:"10",width:"4",height:"4",rx:"0.5"}),a.jsx("rect",{x:"10",y:"10",width:"4",height:"4",rx:"0.5"})]});default:return a.jsx("span",{className:"shrink-0 w-2 h-2 rounded-full",style:{background:t}})}}function ou(e){const t=new Map(e.map(o=>[o.span_id,o])),n=new Map;for(const o of e)if(o.parent_span_id){const l=n.get(o.parent_span_id)??[];l.push(o),n.set(o.parent_span_id,l)}const r=e.filter(o=>o.parent_span_id===null||!t.has(o.parent_span_id));function i(o){const l=(n.get(o.span_id)??[]).sort((u,c)=>u.timestamp.localeCompare(c.timestamp));return{span:o,children:l.map(i)}}return r.sort((o,l)=>o.timestamp.localeCompare(l.timestamp)).map(i).flatMap(o=>o.span.span_name==="root"?o.children:[o])}function As(e){return e==null?"":e<1e3?`${e.toFixed(0)}ms`:`${(e/1e3).toFixed(2)}s`}function Ms(e){return e.map(t=>{const{span:n}=t;return t.children.length>0?{name:n.span_name,children:Ms(t.children)}:{name:n.span_name}})}function Ir({traces:e}){const[t,n]=S.useState(null),[r,i]=S.useState(new Set),[s,o]=S.useState(()=>{const O=localStorage.getItem("traceTreeSplitWidth");return O?parseFloat(O):50}),[l,u]=S.useState(!1),[c,d]=S.useState(!1),[p,m]=S.useState(()=>localStorage.getItem("traceViewMode")||"tree"),f=ou(e),g=S.useMemo(()=>JSON.stringify(Ms(f),null,2),[e]),x=S.useCallback(()=>{navigator.clipboard.writeText(g).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},[g]),y=Ee(O=>O.focusedSpan),b=Ee(O=>O.setFocusedSpan),[k,A]=S.useState(null),j=S.useRef(null),L=S.useCallback(O=>{i(E=>{const w=new Set(E);return w.has(O)?w.delete(O):w.add(O),w})},[]),T=S.useRef(null);S.useEffect(()=>{const O=f.length>0?f[0].span.span_id:null,E=T.current;if(T.current=O,O&&O!==E)n(f[0].span);else if(t===null)f.length>0&&n(f[0].span);else{const w=e.find(M=>M.span_id===t.span_id);w&&w!==t&&n(w)}},[e]),S.useEffect(()=>{if(!y)return;const E=e.filter(w=>w.span_name===y.name).sort((w,M)=>w.timestamp.localeCompare(M.timestamp))[y.index];if(E){n(E),A(E.span_id);const w=new Map(e.map(M=>[M.span_id,M.parent_span_id]));i(M=>{const I=new Set(M);let D=E.parent_span_id;for(;D;)I.delete(D),D=w.get(D)??null;return I})}b(null)},[y,e,b]),S.useEffect(()=>{if(!k)return;const O=k;A(null),requestAnimationFrame(()=>{const E=j.current,w=E==null?void 0:E.querySelector(`[data-span-id="${O}"]`);E&&w&&w.scrollIntoView({block:"center",behavior:"smooth"})})},[k]),S.useEffect(()=>{if(!l)return;const O=w=>{const M=document.querySelector(".trace-tree-container");if(!M)return;const I=M.getBoundingClientRect(),D=(w.clientX-I.left)/I.width*100,N=Math.max(20,Math.min(80,D));o(N),localStorage.setItem("traceTreeSplitWidth",String(N))},E=()=>{u(!1)};return window.addEventListener("mousemove",O),window.addEventListener("mouseup",E),()=>{window.removeEventListener("mousemove",O),window.removeEventListener("mouseup",E)}},[l]);const B=O=>{O.preventDefault(),u(!0)};return a.jsxs("div",{className:"flex h-full trace-tree-container",style:{cursor:l?"col-resize":void 0},children:[a.jsxs("div",{className:"flex flex-col",style:{width:`${s}%`},children:[e.length>0&&a.jsxs("div",{className:"flex items-center gap-1 px-2 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",height:"32px"},children:[a.jsx("button",{onClick:()=>{m("tree"),localStorage.setItem("traceViewMode","tree")},className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:p==="tree"?"var(--accent)":"var(--text-muted)",background:p==="tree"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:O=>{p!=="tree"&&(O.currentTarget.style.color="var(--text-primary)")},onMouseLeave:O=>{p!=="tree"&&(O.currentTarget.style.color="var(--text-muted)")},children:"Tree"}),a.jsx("button",{onClick:()=>{m("timeline"),localStorage.setItem("traceViewMode","timeline")},className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:p==="timeline"?"var(--accent)":"var(--text-muted)",background:p==="timeline"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:O=>{p!=="timeline"&&(O.currentTarget.style.color="var(--text-primary)")},onMouseLeave:O=>{p!=="timeline"&&(O.currentTarget.style.color="var(--text-muted)")},children:"Timeline"}),a.jsx("button",{onClick:()=>{m("json"),localStorage.setItem("traceViewMode","json")},className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:p==="json"?"var(--accent)":"var(--text-muted)",background:p==="json"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:O=>{p!=="json"&&(O.currentTarget.style.color="var(--text-primary)")},onMouseLeave:O=>{p!=="json"&&(O.currentTarget.style.color="var(--text-muted)")},children:"JSON"})]}),a.jsx("div",{ref:j,className:"overflow-y-auto flex-1 p-0.5 pr-0 pt-0 mr-0.5 mt-0.5",children:f.length===0?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-[var(--text-muted)] text-sm",children:"No traces yet"})}):p==="tree"?f.map((O,E)=>a.jsx(Rs,{node:O,depth:0,selectedId:(t==null?void 0:t.span_id)??null,onSelect:n,isLast:E===f.length-1,collapsedIds:r,toggleExpanded:L},O.span.span_id)):p==="timeline"?a.jsx(iu,{tree:f,selectedSpan:t,onSelect:n}):a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:x,className:"absolute top-1 right-1 z-10 text-[11px] cursor-pointer px-2 py-1 rounded transition-colors",style:{color:c?"var(--success)":"var(--text-muted)",background:"var(--bg-secondary)",border:"1px solid var(--border)"},onMouseEnter:O=>{c||(O.currentTarget.style.color="var(--text-primary)")},onMouseLeave:O=>{O.currentTarget.style.color=c?"var(--success)":"var(--text-muted)"},children:c?"Copied!":"Copy"}),a.jsx(it,{json:g,className:"font-mono text-[11px] whitespace-pre-wrap p-2",style:{}})]})})]}),a.jsx("div",{onMouseDown:B,className:"shrink-0 drag-handle-col",style:l?{background:"var(--accent)"}:void 0}),a.jsx("div",{className:"flex-1 overflow-hidden",children:t?a.jsx(nu,{span:t}):a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-[var(--text-muted)] text-sm",children:"Select a span to view details"})})})]})}function Rs({node:e,depth:t,selectedId:n,onSelect:r,isLast:i,collapsedIds:s,toggleExpanded:o}){var x;const{span:l}=e,u=!s.has(l.span_id),c=Ts[l.status.toLowerCase()]??"var(--text-muted)",d=As(l.duration_ms),p=l.span_id===n,m=e.children.length>0,f=t*20,g=(x=l.attributes)==null?void 0:x["openinference.span.kind"];return a.jsxs("div",{className:"relative",children:[t>0&&a.jsx("div",{className:"absolute top-0 z-10 pointer-events-none",style:{left:`${f-10}px`,width:"1px",height:i?"16px":"100%",background:"var(--border)"}}),a.jsxs("button",{"data-span-id":l.span_id,onClick:()=>r(l),className:"w-full text-left text-xs leading-normal py-1.5 pr-2 flex items-center gap-1.5 transition-colors relative",style:{paddingLeft:`${f+4}px`,background:p?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":void 0,borderLeft:p?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:y=>{p||(y.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:y=>{p||(y.currentTarget.style.background="")},children:[t>0&&a.jsx("div",{className:"absolute z-10 pointer-events-none",style:{left:`${f-10}px`,top:"50%",width:"10px",height:"1px",background:"var(--border)"}}),m?a.jsx("span",{onClick:y=>{y.stopPropagation(),o(l.span_id)},className:"shrink-0 w-5 h-5 flex items-center justify-center cursor-pointer rounded hover:bg-[var(--bg-hover)]",style:{color:"var(--text-muted)"},children:a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",style:{transform:u?"rotate(90deg)":"rotate(0deg)"},children:a.jsx("path",{d:"M3 1.5L7 5L3 8.5",stroke:"currentColor",strokeWidth:"1.5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})}):a.jsx("span",{className:"shrink-0 w-4"}),a.jsx("span",{className:"shrink-0 flex items-center justify-center w-4 h-4",children:a.jsx(Cs,{kind:g,statusColor:c})}),a.jsx("span",{className:"text-[var(--text-primary)] truncate min-w-0 flex-1",children:l.span_name}),d&&a.jsx("span",{className:"text-[var(--text-muted)] shrink-0 ml-auto pl-2 tabular-nums",children:d})]}),u&&e.children.map((y,b)=>a.jsx(Rs,{node:y,depth:t+1,selectedId:n,onSelect:r,isLast:b===e.children.length-1,collapsedIds:s,toggleExpanded:o},y.span.span_id))]})}const su={DEBUG:{color:"var(--text-muted)",bg:"color-mix(in srgb, var(--text-muted) 15%, var(--bg-secondary))",border:"var(--text-muted)"},INFO:{color:"var(--info)",bg:"color-mix(in srgb, var(--info) 15%, var(--bg-secondary))",border:"var(--info)"},WARN:{color:"var(--warning)",bg:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",border:"var(--warning)"},WARNING:{color:"var(--warning)",bg:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",border:"var(--warning)"},ERROR:{color:"var(--error)",bg:"color-mix(in srgb, var(--error) 15%, var(--bg-secondary))",border:"var(--error)"},CRITICAL:{color:"var(--error)",bg:"color-mix(in srgb, var(--error) 15%, var(--bg-secondary))",border:"var(--error)"}},au={color:"var(--text-muted)",bg:"transparent"};function Ki({logs:e}){const t=S.useRef(null),n=S.useRef(null),[r,i]=S.useState(!1);S.useEffect(()=>{var o;(o=n.current)==null||o.scrollIntoView({behavior:"smooth"})},[e.length]);const s=()=>{const o=t.current;o&&i(o.scrollTop>100)};return e.length===0?a.jsx("div",{className:"h-full flex items-center justify-center",children:a.jsx("p",{className:"text-[var(--text-muted)] text-sm",children:"No logs yet"})}):a.jsxs("div",{className:"h-full relative",children:[a.jsxs("div",{ref:t,onScroll:s,className:"h-full overflow-y-auto font-mono text-xs leading-normal",children:[e.map((o,l)=>{const u=new Date(o.timestamp).toLocaleTimeString(void 0,{hour12:!1}),c=o.level.toUpperCase(),d=c.slice(0,4),p=su[c]??au,m=l%2===0;return a.jsxs("div",{className:"flex gap-3 px-3 py-1.5",style:{background:m?"var(--bg-primary)":"var(--bg-secondary)"},children:[a.jsx("span",{className:"text-[var(--text-muted)] shrink-0",children:u}),a.jsx("span",{className:"shrink-0 self-start px-1.5 py-0.5 rounded text-[10px] font-semibold leading-none inline-flex items-center",style:{color:p.color,background:p.bg},children:d}),a.jsx("span",{className:"text-[var(--text-primary)] whitespace-pre-wrap break-all",children:o.message})]},l)}),a.jsx("div",{ref:n})]}),r&&a.jsx("button",{onClick:()=>{var o;return(o=t.current)==null?void 0:o.scrollTo({top:0,behavior:"smooth"})},className:"absolute top-2 right-3 w-6 h-6 flex items-center justify-center rounded-full cursor-pointer transition-opacity opacity-70 hover:opacity-100",style:{background:"var(--bg-tertiary)",color:"var(--text-primary)"},title:"Scroll to top",children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("polyline",{points:"18 15 12 9 6 15"})})})]})}const lu={started:{color:"var(--accent)",label:"started"},updated:{color:"var(--info)",label:"updated"},completed:{color:"var(--success)",label:"completed"},faulted:{color:"var(--error)",label:"faulted"}},Gi={color:"var(--text-muted)",label:""};function An({events:e,runStatus:t}){const n=S.useRef(null),r=S.useRef(!0),[i,s]=S.useState(null),o=()=>{const l=n.current;l&&(r.current=l.scrollHeight-l.scrollTop-l.clientHeight<40)};return S.useEffect(()=>{r.current&&n.current&&(n.current.scrollTop=n.current.scrollHeight)}),e.length===0?a.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:a.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:t==="running"?"Waiting for events...":"No events yet"})}):a.jsx("div",{ref:n,onScroll:o,className:"h-full overflow-y-auto font-mono text-xs leading-normal",children:e.map((l,u)=>{const c=new Date(l.timestamp).toLocaleTimeString(void 0,{hour12:!1}),d=l.payload&&Object.keys(l.payload).length>0,p=i===u,m=l.phase?lu[l.phase]??Gi:Gi;return a.jsxs("div",{children:[a.jsxs("div",{onClick:()=>{d&&s(p?null:u)},className:"flex items-center gap-2 px-3 py-1.5",style:{background:u%2===0?"var(--bg-primary)":"var(--bg-secondary)",cursor:d?"pointer":"default"},children:[a.jsx("span",{className:"shrink-0",style:{color:"var(--text-muted)"},children:c}),a.jsx("span",{className:"shrink-0",style:{color:m.color},children:"●"}),a.jsx("span",{className:"flex-1 truncate",style:{color:"var(--text-primary)"},children:l.node_name}),m.label&&a.jsx("span",{className:"shrink-0 text-[10px]",style:{color:"var(--text-muted)"},children:m.label}),d&&a.jsx("span",{className:"shrink-0 text-[9px] transition-transform",style:{color:"var(--text-muted)",transform:p?"rotate(90deg)":"rotate(0deg)"},children:"▸"})]}),p&&d&&a.jsx("div",{className:"px-3 py-2 border-t border-b",style:{borderColor:"var(--border)",background:"color-mix(in srgb, var(--bg-secondary) 80%, var(--bg-primary))"},children:a.jsx(it,{json:JSON.stringify(l.payload,null,2),className:"text-[11px] font-mono whitespace-pre-wrap break-words"})})]},u)})})}function _t({title:e,copyText:t,trailing:n,children:r}){const[i,s]=S.useState(!1),o=S.useCallback(()=>{t&&navigator.clipboard.writeText(t).then(()=>{s(!0),setTimeout(()=>s(!1),1500)})},[t]);return a.jsxs("div",{className:"overflow-hidden",style:{border:"1px solid var(--border)"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--text-primary)"},children:e}),n,t&&a.jsx("button",{onClick:o,className:`${n?"":"ml-auto "}text-[10px] cursor-pointer px-1.5 py-0.5 rounded transition-colors`,style:{color:i?"var(--success)":"var(--text-muted)",background:"var(--bg-tertiary)",border:"none"},onMouseEnter:l=>{i||(l.currentTarget.style.color="var(--text-primary)")},onMouseLeave:l=>{l.currentTarget.style.color=i?"var(--success)":"var(--text-muted)"},children:i?"Copied":"Copy"})]}),r]})}function qi({runId:e,status:t,ws:n,breakpointNode:r}){const i=t==="suspended",s=o=>{const l=Ee.getState().breakpoints[e]??{};n.setBreakpoints(e,Object.keys(l)),o==="step"?n.debugStep(e):o==="continue"?n.debugContinue(e):n.debugStop(e)};return a.jsxs("div",{className:"flex items-center gap-1 px-4 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"text-[11px] font-semibold mr-1",style:{color:"var(--text-muted)"},children:"Debug"}),a.jsx(cr,{label:"Step",onClick:()=>s("step"),disabled:!i,color:"var(--info)",active:i}),a.jsx(cr,{label:"Continue",onClick:()=>s("continue"),disabled:!i,color:"var(--success)",active:i}),a.jsx(cr,{label:"Stop",onClick:()=>s("stop"),disabled:!i,color:"var(--error)",active:i}),a.jsx("span",{className:"text-[11px] ml-auto truncate",style:{color:i?"var(--accent)":"var(--text-muted)"},children:i?r?`Paused at ${r}`:"Paused":t})]})}function cr({label:e,onClick:t,disabled:n,color:r,active:i}){return a.jsx("button",{onClick:t,disabled:n,className:"px-3 py-1 h-7 text-[11px] font-semibold rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed",style:{color:i?r:"var(--text-muted)",background:i?`color-mix(in srgb, ${r} 10%, transparent)`:"transparent"},onMouseEnter:s=>{n||(s.currentTarget.style.background=`color-mix(in srgb, ${r} 20%, transparent)`)},onMouseLeave:s=>{s.currentTarget.style.background=i?`color-mix(in srgb, ${r} 10%, transparent)`:"transparent"},children:e})}const Vi=S.lazy(()=>Ns(()=>import("./ChatPanel-BcW6Jtpz.js"),__vite__mapDeps([2,1,3,4]))),cu=[],uu=[],du=[],pu=[];function fu({run:e,ws:t,isMobile:n}){const r=e.mode==="chat",[i,s]=S.useState(280),[o,l]=S.useState(()=>{const D=localStorage.getItem("chatPanelWidth");return D?parseInt(D,10):380}),[u,c]=S.useState("primary"),[d,p]=S.useState(r?"primary":"traces"),m=S.useRef(null),f=S.useRef(null),g=S.useRef(!1),x=Ee(D=>D.traces[e.id]||cu),y=Ee(D=>D.logs[e.id]||uu),b=Ee(D=>D.chatMessages[e.id]||du),k=Ee(D=>D.stateEvents[e.id]||pu),A=Ee(D=>D.breakpoints[e.id]);S.useEffect(()=>{t.setBreakpoints(e.id,A?Object.keys(A):[])},[e.id]);const j=S.useCallback(D=>{t.setBreakpoints(e.id,D)},[e.id,t]),L=S.useCallback(D=>{D.preventDefault(),g.current=!0;const N="touches"in D?D.touches[0].clientY:D.clientY,_=i,R=$=>{if(!g.current)return;const q=m.current;if(!q)return;const h="touches"in $?$.touches[0].clientY:$.clientY,F=q.clientHeight-100,U=Math.max(80,Math.min(F,_+(h-N)));s(U)},W=()=>{g.current=!1,document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",W),document.removeEventListener("touchmove",R),document.removeEventListener("touchend",W),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="row-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",W),document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",W)},[i]),T=S.useCallback(D=>{D.preventDefault();const N="touches"in D?D.touches[0].clientX:D.clientX,_=o,R=$=>{const q=f.current;if(!q)return;const h="touches"in $?$.touches[0].clientX:$.clientX,F=q.clientWidth-300,U=Math.max(280,Math.min(F,_+(N-h)));l(U)},W=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",W),document.removeEventListener("touchmove",R),document.removeEventListener("touchend",W),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem("chatPanelWidth",String(o))};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",W),document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",W)},[o]),B=r?"Chat":"Events",O=r?"var(--accent)":"var(--success)",E=D=>D==="primary"?O:D==="events"?"var(--success)":"var(--accent)",w=Ee(D=>D.activeInterrupt[e.id]??null),M=e.status==="running"?a.jsx("span",{className:"ml-auto text-[11px] px-2 py-0.5 rounded-full shrink-0",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--warning)"},children:r?"Thinking...":"Running..."}):r&&e.status==="suspended"&&w?a.jsx("span",{className:"ml-auto text-[11px] px-2 py-0.5 rounded-full shrink-0",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--warning)"},children:"Action Required"}):null;if(n){const D=[{id:"traces",label:"Traces",count:x.length},{id:"primary",label:B},...r?[{id:"events",label:"Events",count:k.length}]:[],{id:"io",label:"I/O"},{id:"logs",label:"Logs",count:y.length}];return a.jsxs("div",{className:"flex flex-col h-full",children:[(e.mode==="debug"||e.status==="suspended"&&!w||A&&Object.keys(A).length>0)&&a.jsx(qi,{runId:e.id,status:e.status,ws:t,breakpointNode:e.breakpoint_node}),a.jsx("div",{className:"shrink-0",style:{height:"40vh"},children:a.jsx(Un,{entrypoint:e.entrypoint,traces:x,runId:e.id,breakpointNode:e.breakpoint_node,breakpointNextNodes:e.breakpoint_next_nodes,onBreakpointChange:j})}),a.jsxs("div",{className:"flex items-center gap-1 px-2 h-10 border-y shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[D.map(N=>a.jsxs("button",{onClick:()=>p(N.id),className:"px-2.5 py-1 h-7 text-xs font-semibold rounded transition-colors cursor-pointer",style:{color:d===N.id?E(N.id):"var(--text-muted)",background:d===N.id?`color-mix(in srgb, ${E(N.id)} 10%, transparent)`:"transparent"},children:[N.label,N.count!==void 0&&N.count>0&&a.jsx("span",{className:"ml-1 font-normal",style:{color:"var(--text-muted)"},children:N.count})]},N.id)),M]}),a.jsxs("div",{className:"flex-1 overflow-hidden",children:[d==="traces"&&a.jsx(Ir,{traces:x}),d==="primary"&&(r?a.jsx(S.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center h-full",style:{color:"var(--text-muted)"},children:a.jsx("span",{className:"text-xs",children:"Loading chat..."})}),children:a.jsx(Vi,{messages:b,runId:e.id,runStatus:e.status,ws:t})}):a.jsx(An,{events:k,runStatus:e.status})),d==="events"&&a.jsx(An,{events:k,runStatus:e.status}),d==="io"&&a.jsx(Yi,{run:e}),d==="logs"&&a.jsx(Ki,{logs:y})]})]})}const I=[{id:"primary",label:B},...r?[{id:"events",label:"Events",count:k.length}]:[],{id:"io",label:"I/O"},{id:"logs",label:"Logs",count:y.length}];return a.jsxs("div",{ref:f,className:"flex h-full",children:[a.jsxs("div",{ref:m,className:"flex flex-col flex-1 min-w-0",children:[(e.mode==="debug"||e.status==="suspended"&&!w||A&&Object.keys(A).length>0)&&a.jsx(qi,{runId:e.id,status:e.status,ws:t,breakpointNode:e.breakpoint_node}),a.jsx("div",{className:"shrink-0 overflow-hidden",style:{height:i},children:a.jsx(Un,{entrypoint:e.entrypoint,traces:x,runId:e.id,breakpointNode:e.breakpoint_node,breakpointNextNodes:e.breakpoint_next_nodes,onBreakpointChange:j})}),a.jsx("div",{onMouseDown:L,onTouchStart:L,className:"shrink-0 drag-handle-row"}),a.jsx("div",{className:"flex-1 overflow-hidden",children:a.jsx(Ir,{traces:x})})]}),a.jsx("div",{onMouseDown:T,onTouchStart:T,className:"shrink-0 drag-handle-col"}),a.jsxs("div",{className:"shrink-0 flex flex-col",style:{width:o,background:"var(--bg-primary)"},children:[a.jsxs("div",{className:"flex items-center gap-1 px-2 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[I.map(D=>a.jsxs("button",{onClick:()=>c(D.id),className:"px-2.5 py-1 h-7 text-xs font-semibold rounded transition-colors cursor-pointer",style:{color:u===D.id?E(D.id):"var(--text-muted)",background:u===D.id?`color-mix(in srgb, ${E(D.id)} 10%, transparent)`:"transparent"},onMouseEnter:N=>{u!==D.id&&(N.currentTarget.style.color="var(--text-primary)")},onMouseLeave:N=>{u!==D.id&&(N.currentTarget.style.color="var(--text-muted)")},children:[D.label,D.count!==void 0&&D.count>0&&a.jsx("span",{className:"ml-1 font-normal",style:{color:"var(--text-muted)"},children:D.count})]},D.id)),M]}),a.jsxs("div",{className:"flex-1 overflow-hidden",children:[u==="primary"&&(r?a.jsx(S.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center h-full",style:{color:"var(--text-muted)"},children:a.jsx("span",{className:"text-xs",children:"Loading chat..."})}),children:a.jsx(Vi,{messages:b,runId:e.id,runStatus:e.status,ws:t})}):a.jsx(An,{events:k,runStatus:e.status})),u==="events"&&a.jsx(An,{events:k,runStatus:e.status}),u==="io"&&a.jsx(Yi,{run:e}),u==="logs"&&a.jsx(Ki,{logs:y})]})]})]})}function Yi({run:e}){return a.jsxs("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:[a.jsx(_t,{title:"Input",copyText:JSON.stringify(e.input_data,null,2),children:a.jsx(it,{json:JSON.stringify(e.input_data,null,2),className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),e.output_data&&a.jsx(_t,{title:"Output",copyText:typeof e.output_data=="string"?e.output_data:JSON.stringify(e.output_data,null,2),children:a.jsx(it,{json:typeof e.output_data=="string"?e.output_data:JSON.stringify(e.output_data,null,2),className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),e.error&&a.jsxs("div",{className:"overflow-hidden",style:{border:"1px solid color-mix(in srgb, var(--error) 40%, var(--border))"},children:[a.jsxs("div",{className:"px-3 py-2 text-xs font-semibold flex items-center gap-2",style:{background:"color-mix(in srgb, var(--error) 15%, var(--bg-secondary))",color:"var(--error)"},children:[a.jsx("span",{children:"Error"}),a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono",style:{background:"color-mix(in srgb, var(--error) 20%, var(--bg-secondary))"},children:e.error.code}),a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono",style:{background:"color-mix(in srgb, var(--error) 20%, var(--bg-secondary))"},children:e.error.category})]}),a.jsxs("div",{className:"px-3 py-2 text-xs leading-normal",children:[a.jsx("div",{className:"font-semibold mb-2",style:{color:"var(--text-primary)"},children:e.error.title}),a.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] max-w-prose",style:{color:"var(--text-secondary)"},children:e.error.detail})]})]})]})}function Xi(){const{reloadPending:e,setReloadPending:t,setEntrypoints:n}=Ee(),[r,i]=S.useState(!1);if(!e)return null;const s=async()=>{i(!0);try{await ec();const o=await ys();n(o.map(l=>l.name)),t(!1)}catch(o){console.error("Reload failed:",o)}finally{i(!1)}};return a.jsxs("div",{className:"fixed top-4 left-1/2 -translate-x-1/2 z-50 flex items-center justify-between px-5 py-2.5 rounded-lg shadow-lg min-w-[400px]",style:{background:"var(--bg-secondary)",border:"1px solid var(--bg-tertiary)"},children:[a.jsx("span",{className:"text-sm",style:{color:"var(--text-secondary)"},children:"Files changed, reload to apply"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:s,disabled:r,className:"px-3 py-1 text-sm font-medium rounded cursor-pointer",style:{background:"var(--accent)",color:"#fff",opacity:r?.6:1},children:r?"Reloading...":"Reload"}),a.jsx("button",{onClick:()=>t(!1),className:"text-sm cursor-pointer px-1",style:{color:"var(--text-muted)",background:"none",border:"none"},children:"✕"})]})]})}let mu=0;const Zi=Ot(e=>({toasts:[],addToast:(t,n)=>{const r=String(++mu);e(s=>({toasts:[...s.toasts,{id:r,type:t,message:n}]})),setTimeout(()=>{e(s=>({toasts:s.toasts.filter(o=>o.id!==r)}))},t==="error"?8e3:5e3)},removeToast:t=>{e(n=>({toasts:n.toasts.filter(r=>r.id!==t)}))}})),Ji={success:{color:"var(--success)",bg:"color-mix(in srgb, var(--success) 10%, var(--bg-elevated))",border:"color-mix(in srgb, var(--success) 30%, var(--border))"},error:{color:"var(--error)",bg:"color-mix(in srgb, var(--error) 10%, var(--bg-elevated))",border:"color-mix(in srgb, var(--error) 30%, var(--border))"},info:{color:"var(--info)",bg:"color-mix(in srgb, var(--info) 10%, var(--bg-elevated))",border:"color-mix(in srgb, var(--info) 30%, var(--border))"}};function Qi(){const e=Zi(n=>n.toasts),t=Zi(n=>n.removeToast);return e.length===0?null:a.jsx("div",{className:"fixed bottom-8 right-4 z-[100] flex flex-col gap-2 pointer-events-none",children:e.map(n=>{const r=Ji[n.type]??Ji.info;return a.jsxs("div",{className:"pointer-events-auto flex items-center gap-2 px-4 py-2.5 rounded-lg shadow-lg text-xs font-medium max-w-xs animate-[slideIn_0.2s_ease-out]",style:{background:r.bg,border:`1px solid ${r.border}`,color:r.color},children:[a.jsx("span",{className:"flex-1",children:n.message}),a.jsx("button",{onClick:()=>t(n.id),className:"shrink-0 w-5 h-5 flex items-center justify-center rounded cursor-pointer transition-opacity opacity-60 hover:opacity-100",style:{color:r.color,background:"transparent",border:"none"},"aria-label":"Dismiss",children:a.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[a.jsx("line",{x1:"1",y1:"1",x2:"9",y2:"9"}),a.jsx("line",{x1:"9",y1:"1",x2:"1",y2:"9"})]})})]},n.id)})})}function hu(e){return e===null?"-":`${Math.round(e*100)}%`}function gu(e){if(e===null)return"var(--text-muted)";const t=e*100;return t>=80?"var(--success)":t>=50?"var(--warning)":"var(--error)"}const eo={pending:{color:"var(--text-muted)",label:"Pending"},running:{color:"var(--info)",label:"Running"},completed:{color:"var(--success)",label:"Completed"},failed:{color:"var(--error)",label:"Failed"}};function to(){const e=Ae(l=>l.evalSets),t=Ae(l=>l.evalRuns),{evalSetId:n,evalRunId:r,navigate:i}=ot(),s=Object.values(e),o=Object.values(t).sort((l,u)=>new Date(u.start_time??0).getTime()-new Date(l.start_time??0).getTime());return a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[a.jsx("button",{onClick:()=>i("#/evals/new"),className:"w-[calc(100%-24px)] mx-3 mt-2.5 mb-1 px-3 py-1.5 text-[11px] text-center font-medium rounded border border-[var(--border)] bg-transparent transition-colors cursor-pointer",style:{color:"var(--text-secondary)"},onMouseEnter:l=>{l.currentTarget.style.color="var(--text-primary)",l.currentTarget.style.borderColor="var(--text-muted)"},onMouseLeave:l=>{l.currentTarget.style.color="var(--text-secondary)",l.currentTarget.style.borderColor=""},children:"+ New Eval Set"}),a.jsx("div",{className:"px-3 pt-3 pb-1 text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"Eval Sets"}),s.map(l=>{const u=n===l.id;return a.jsxs("button",{onClick:()=>i(`#/evals/sets/${l.id}`),className:"w-full text-left px-3 py-1.5 text-xs cursor-pointer transition-colors",style:{background:u?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:u?"var(--text-primary)":"var(--text-secondary)",borderLeft:u?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:c=>{u||(c.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:c=>{u||(c.currentTarget.style.background="transparent")},children:[a.jsx("div",{className:"truncate font-medium",children:l.name}),a.jsxs("div",{className:"text-[11px] mt-0.5",style:{color:"var(--text-muted)"},children:[l.eval_count," items · ",l.evaluator_ids.length," evaluator",l.evaluator_ids.length!==1?"s":""]})]},l.id)}),s.length===0&&a.jsx("p",{className:"text-[11px] px-3 py-2",style:{color:"var(--text-muted)"},children:"No eval sets yet"}),a.jsx("div",{className:"px-3 pt-4 pb-1 text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"History"}),o.map(l=>{const u=r===l.id,c=eo[l.status]??eo.pending;return a.jsx("button",{onClick:()=>i(`#/evals/runs/${l.id}`),className:"w-full text-left px-3 py-1.5 text-xs cursor-pointer transition-colors",style:{background:u?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:u?"var(--text-primary)":"var(--text-secondary)",borderLeft:u?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:d=>{u||(d.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:d=>{u||(d.currentTarget.style.background="transparent")},children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:c.color}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"truncate font-medium",children:l.eval_set_name}),a.jsx("div",{className:"text-[11px] mt-0.5",style:{color:"var(--text-muted)"},children:l.start_time?new Date(l.start_time).toLocaleString():c.label})]}),a.jsx("span",{className:"font-mono shrink-0",style:{color:gu(l.overall_score)},children:hu(l.overall_score)})]})},l.id)}),o.length===0&&a.jsx("p",{className:"text-[11px] px-3 py-2",style:{color:"var(--text-muted)"},children:"No eval runs yet"})]})}function no(e,t=60){const n=typeof e=="string"?e:JSON.stringify(e);return!n||n==="null"?"-":n.length>t?n.slice(0,t)+"...":n}function bu({evalSetId:e}){const[t,n]=S.useState(null),[r,i]=S.useState(!0),[s,o]=S.useState(null),[l,u]=S.useState(!1),[c,d]=S.useState("io"),p=Ae(h=>h.evaluators),m=Ae(h=>h.localEvaluators),f=Ae(h=>h.updateEvalSetEvaluators),g=Ae(h=>h.incrementEvalSetCount),x=Ae(h=>h.upsertEvalRun),{navigate:y}=ot(),[b,k]=S.useState(!1),[A,j]=S.useState(new Set),[L,T]=S.useState(!1),B=S.useRef(null),[O,E]=S.useState(()=>{const h=localStorage.getItem("evalSetSidebarWidth");return h?parseInt(h,10):320}),[w,M]=S.useState(!1),I=S.useRef(null);S.useEffect(()=>{localStorage.setItem("evalSetSidebarWidth",String(O))},[O]),S.useEffect(()=>{i(!0),o(null),dc(e).then(h=>{n(h),h.items.length>0&&o(h.items[0].name)}).catch(console.error).finally(()=>i(!1))},[e]);const D=async()=>{u(!0);try{const h=await pc(e);x(h),y(`#/evals/runs/${h.id}`)}catch(h){console.error(h)}finally{u(!1)}},N=async h=>{if(t)try{await uc(e,h),n(F=>{if(!F)return F;const U=F.items.filter(v=>v.name!==h);return{...F,items:U,eval_count:U.length}}),g(e,-1),s===h&&o(null)}catch(F){console.error(F)}},_=S.useCallback(()=>{t&&j(new Set(t.evaluator_ids)),k(!0)},[t]),R=h=>{j(F=>{const U=new Set(F);return U.has(h)?U.delete(h):U.add(h),U})},W=async()=>{if(t){T(!0);try{const h=await hc(e,Array.from(A));n(h),f(e,h.evaluator_ids),k(!1)}catch(h){console.error(h)}finally{T(!1)}}};S.useEffect(()=>{if(!b)return;const h=F=>{B.current&&!B.current.contains(F.target)&&k(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[b]);const $=S.useCallback(h=>{h.preventDefault(),M(!0);const F="touches"in h?h.touches[0].clientX:h.clientX,U=O,v=ae=>{const K=I.current;if(!K)return;const re="touches"in ae?ae.touches[0].clientX:ae.clientX,de=K.clientWidth-300,be=Math.max(280,Math.min(de,U+(F-re)));E(be)},oe=()=>{M(!1),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",oe),document.removeEventListener("touchmove",v),document.removeEventListener("touchend",oe),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",v),document.addEventListener("mouseup",oe),document.addEventListener("touchmove",v,{passive:!1}),document.addEventListener("touchend",oe)},[O]);if(r)return a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-sm",children:"Loading..."});if(!t)return a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)]",children:"Eval set not found"});const q=t.items.find(h=>h.name===s)??null;return a.jsxs("div",{ref:I,className:"flex h-full",children:[a.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[a.jsxs("div",{className:"px-4 h-10 border-b shrink-0 flex items-center gap-4",style:{borderColor:"var(--border)"},children:[a.jsx("h1",{className:"text-base font-semibold",style:{color:"var(--text-primary)"},children:t.name}),a.jsxs("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:[t.eval_count," items"]}),a.jsxs("div",{className:"flex gap-1 items-center ml-auto relative",children:[a.jsx("button",{onClick:_,className:"w-7 h-7 flex items-center justify-center rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:h=>{h.currentTarget.style.color="var(--text-primary)",h.currentTarget.style.background="var(--bg-secondary)"},onMouseLeave:h=>{h.currentTarget.style.color="var(--text-muted)",h.currentTarget.style.background="transparent"},title:"Edit evaluators","aria-label":"Edit evaluators",children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"}),a.jsx("path",{d:"m15 5 4 4"})]})}),t.evaluator_ids.map(h=>{const F=p.find(U=>U.id===h);return a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[11px] font-medium",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:(F==null?void 0:F.name)??h},h)}),b&&a.jsxs("div",{ref:B,className:"absolute top-full right-0 mt-1 z-50 rounded-md border shadow-lg",style:{background:"var(--bg-primary)",borderColor:"var(--border)",minWidth:220},children:[a.jsx("div",{className:"px-3 py-2 border-b text-[10px] uppercase tracking-wide font-semibold",style:{color:"var(--text-muted)",borderColor:"var(--border)"},children:"Evaluators"}),a.jsx("div",{className:"max-h-48 overflow-y-auto",children:m.length===0?a.jsx("div",{className:"px-3 py-3 text-xs",style:{color:"var(--text-muted)"},children:"No evaluators available"}):m.map(h=>a.jsxs("label",{className:"flex items-center gap-2 px-3 py-1.5 text-xs cursor-pointer transition-colors",style:{borderBottom:"1px solid var(--border)"},onMouseEnter:F=>{F.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:F=>{F.currentTarget.style.background="transparent"},children:[a.jsx("input",{type:"checkbox",checked:A.has(h.id),onChange:()=>R(h.id),className:"accent-[var(--accent)]"}),a.jsx("span",{className:"flex-1 truncate",style:{color:"var(--text-primary)"},children:h.name})]},h.id))}),a.jsx("div",{className:"px-3 py-2 border-t flex justify-end",style:{borderColor:"var(--border)"},children:a.jsx("button",{onClick:W,disabled:L,className:"px-3 py-1 text-[11px] font-semibold rounded cursor-pointer transition-colors disabled:opacity-50",style:{background:"var(--accent)",color:"var(--bg-primary)",border:"none"},onMouseEnter:h=>{h.currentTarget.style.background="var(--accent-hover)"},onMouseLeave:h=>{h.currentTarget.style.background="var(--accent)"},children:L?"Saving...":"Update"})})]})]}),a.jsxs("button",{onClick:D,disabled:l,className:"ml-2 px-3 py-1 h-7 text-xs font-semibold rounded border flex items-center gap-1.5 cursor-pointer transition-colors disabled:opacity-30 disabled:cursor-not-allowed",style:{color:"var(--success)",borderColor:"var(--success)",background:"transparent"},onMouseEnter:h=>{l||(h.currentTarget.style.background="color-mix(in srgb, var(--success) 10%, transparent)")},onMouseLeave:h=>{h.currentTarget.style.background="transparent"},title:"Run eval set","aria-label":"Run eval set",children:[a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:a.jsx("polygon",{points:"5,3 19,12 5,21"})}),l?"Running...":"Run"]})]}),a.jsxs("div",{className:"flex items-center px-3 h-7 text-[11px] font-semibold shrink-0 border-b",style:{color:"var(--text-muted)",background:"var(--bg-secondary)",borderColor:"var(--border)"},children:[a.jsx("span",{className:"w-56 shrink-0",children:"Name"}),a.jsx("span",{className:"flex-1 min-w-0",children:"Input"}),a.jsx("span",{className:"w-32 shrink-0 pl-2",children:"Expected Behavior"}),a.jsx("span",{className:"w-32 shrink-0 pl-2",children:"Expected Output"}),a.jsx("span",{className:"w-32 shrink-0 pl-2",children:"Simulation Instr."}),a.jsx("span",{className:"w-8 shrink-0"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[t.items.map(h=>{const F=h.name===s;return a.jsxs("button",{onClick:()=>o(F?null:h.name),className:"group w-full text-left px-3 py-1.5 flex items-center text-xs border-b transition-colors cursor-pointer",style:{borderColor:"var(--border)",background:F?"color-mix(in srgb, var(--accent) 10%, var(--bg-primary))":void 0,borderLeft:F?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:U=>{F||(U.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:U=>{F||(U.currentTarget.style.background="")},children:[a.jsx("span",{className:"w-56 shrink-0 truncate",style:{color:"var(--text-primary)"},children:h.name}),a.jsx("span",{className:"flex-1 min-w-0 truncate font-mono text-[11px]",style:{color:"var(--text-muted)"},children:no(h.inputs)}),a.jsx("span",{className:"w-32 shrink-0 truncate pl-2 text-[11px]",style:{color:"var(--text-muted)"},children:h.expected_behavior||"-"}),a.jsx("span",{className:"w-32 shrink-0 truncate pl-2 font-mono text-[11px]",style:{color:"var(--text-muted)"},children:no(h.expected_output,40)}),a.jsx("span",{className:"w-32 shrink-0 truncate pl-2 text-[11px]",style:{color:"var(--text-muted)"},children:h.simulation_instructions||"-"}),a.jsx("span",{role:"button",tabIndex:0,className:"w-8 shrink-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",onClick:U=>{U.stopPropagation(),N(h.name)},onKeyDown:U=>{U.key==="Enter"&&(U.stopPropagation(),N(h.name))},style:{color:"var(--text-muted)"},onMouseEnter:U=>{U.currentTarget.style.color="var(--error)"},onMouseLeave:U=>{U.currentTarget.style.color="var(--text-muted)"},title:"Delete item",children:a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},h.name)}),t.items.length===0&&a.jsx("div",{className:"flex items-center justify-center py-8 text-[var(--text-muted)] text-xs",children:"No items in this eval set"})]})]}),a.jsx("div",{onMouseDown:$,onTouchStart:$,className:`shrink-0 drag-handle-col${w?"":" transition-all"}`,style:{width:q?3:0,opacity:q?1:0}}),a.jsxs("div",{className:`shrink-0 flex flex-col overflow-hidden${w?"":" transition-[width] duration-200 ease-in-out"}`,style:{width:q?O:0,background:"var(--bg-primary)"},children:[a.jsx("div",{className:"flex items-center gap-1 px-2 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",minWidth:O},children:["io","evaluators"].map(h=>{const F=c===h,U=h==="io"?"I/O":"Evaluators";return a.jsx("button",{onClick:()=>d(h),className:"px-2.5 py-1 h-7 text-xs font-semibold rounded inline-flex items-center cursor-pointer transition-colors",style:{color:F?"var(--accent)":"var(--text-muted)",background:F?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent",border:"none"},children:U},h)})}),a.jsx("div",{className:"flex-1 overflow-hidden",style:{minWidth:O},children:q?c==="io"?a.jsx(xu,{item:q}):a.jsx(yu,{item:q,evaluators:p}):null})]})]})}function xu({item:e}){const t=JSON.stringify(e.inputs,null,2),n=e.expected_output!=null?typeof e.expected_output=="string"?e.expected_output:JSON.stringify(e.expected_output,null,2):null;return a.jsxs("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:[a.jsx(_t,{title:"Input",copyText:t,children:a.jsx(it,{json:t,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),e.expected_behavior&&a.jsx(_t,{title:"Expected Behavior",copyText:e.expected_behavior,children:a.jsx("div",{className:"px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap",style:{color:"var(--text-secondary)"},children:e.expected_behavior})}),n&&a.jsx(_t,{title:"Expected Output",copyText:n,children:a.jsx(it,{json:n,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),e.simulation_instructions&&a.jsx(_t,{title:"Simulation Instructions",copyText:e.simulation_instructions,children:a.jsx("div",{className:"px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap",style:{color:"var(--text-secondary)"},children:e.simulation_instructions})})]})}function yu({item:e,evaluators:t}){return a.jsx("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:e.evaluator_ids.length>0?a.jsx(a.Fragment,{children:e.evaluator_ids.map(n=>{var s;const r=t.find(o=>o.id===n),i=(s=e.evaluation_criterias)==null?void 0:s[n];return a.jsxs("div",{className:"overflow-hidden",style:{border:"1px solid var(--border)"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--text-primary)"},children:(r==null?void 0:r.name)??n}),a.jsx("span",{className:"ml-auto text-[10px]",style:{color:"var(--text-muted)"},children:i?"Custom criteria":"Default criteria"})]}),i&&a.jsx("pre",{className:"px-3 py-2 border-t text-[11px] font-mono overflow-x-auto max-h-32 whitespace-pre-wrap break-words",style:{borderColor:"var(--border)",color:"var(--text-secondary)"},children:JSON.stringify(i,null,2)})]},n)})}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:"No evaluators configured for this item"})})}function en(e){return e===null?"-":`${Math.round(e*100)}%`}function wt(e){if(e===null)return"var(--text-muted)";const t=e*100;return t>=80?"var(--success)":t>=50?"var(--warning)":"var(--error)"}function vu(e,t){if(!e)return"-";const n=new Date(e).getTime(),r=t?new Date(t).getTime():Date.now(),i=Math.round((r-n)/1e3);return i<60?`${i}s`:`${Math.floor(i/60)}m ${i%60}s`}function ro(e){return e.replace(/\s*Evaluator$/i,"")}const io={pending:{color:"var(--text-muted)",bg:"var(--bg-tertiary)",label:"Pending"},running:{color:"var(--info)",bg:"rgba(59,130,246,0.1)",label:"Running"},completed:{color:"var(--success)",bg:"rgba(34,197,94,0.1)",label:"Completed"},failed:{color:"var(--error)",bg:"rgba(239,68,68,0.1)",label:"Failed"}};function Eu({evalRunId:e,itemName:t}){const[n,r]=S.useState(null),[i,s]=S.useState(!0),{navigate:o}=ot(),l=t??null,[u,c]=S.useState(220),d=S.useRef(null),p=S.useRef(!1),[m,f]=S.useState(()=>{const M=localStorage.getItem("evalSidebarWidth");return M?parseInt(M,10):320}),[g,x]=S.useState(!1),y=S.useRef(null);S.useEffect(()=>{localStorage.setItem("evalSidebarWidth",String(m))},[m]);const b=Ae(M=>M.evalRuns[e]),k=Ae(M=>M.evaluators);S.useEffect(()=>{s(!0),Ii(e).then(M=>{if(r(M),!t){const I=M.results.find(D=>D.status==="completed")??M.results[0];I&&o(`#/evals/runs/${e}/${encodeURIComponent(I.name)}`)}}).catch(console.error).finally(()=>s(!1))},[e]),S.useEffect(()=>{((b==null?void 0:b.status)==="completed"||(b==null?void 0:b.status)==="failed")&&Ii(e).then(r).catch(console.error)},[b==null?void 0:b.status,e]),S.useEffect(()=>{if(t||!(n!=null&&n.results))return;const M=n.results.find(I=>I.status==="completed")??n.results[0];M&&o(`#/evals/runs/${e}/${encodeURIComponent(M.name)}`)},[n==null?void 0:n.results]);const A=S.useCallback(M=>{M.preventDefault(),p.current=!0;const I="touches"in M?M.touches[0].clientY:M.clientY,D=u,N=R=>{if(!p.current)return;const W=d.current;if(!W)return;const $="touches"in R?R.touches[0].clientY:R.clientY,q=W.clientHeight-100,h=Math.max(80,Math.min(q,D+($-I)));c(h)},_=()=>{p.current=!1,document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",_),document.removeEventListener("touchmove",N),document.removeEventListener("touchend",_),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="row-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",N),document.addEventListener("mouseup",_),document.addEventListener("touchmove",N,{passive:!1}),document.addEventListener("touchend",_)},[u]),j=S.useCallback(M=>{M.preventDefault(),x(!0);const I="touches"in M?M.touches[0].clientX:M.clientX,D=m,N=R=>{const W=y.current;if(!W)return;const $="touches"in R?R.touches[0].clientX:R.clientX,q=W.clientWidth-300,h=Math.max(280,Math.min(q,D+(I-$)));f(h)},_=()=>{x(!1),document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",_),document.removeEventListener("touchmove",N),document.removeEventListener("touchend",_),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",N),document.addEventListener("mouseup",_),document.addEventListener("touchmove",N,{passive:!1}),document.addEventListener("touchend",_)},[m]);if(i)return a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-sm",children:"Loading..."});if(!n)return a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)]",children:"Eval run not found"});const L=b??n,T=io[L.status]??io.pending,B=L.status==="running",O=Object.keys(L.evaluator_scores??{}),E=n.results.find(M=>M.name===l)??null,w=((E==null?void 0:E.traces)??[]).map(M=>({...M,run_id:""}));return a.jsxs("div",{ref:y,className:"flex h-full",children:[a.jsxs("div",{ref:d,className:"flex flex-col flex-1 min-w-0",children:[a.jsxs("div",{className:"px-4 h-10 border-b shrink-0 flex items-center gap-4",style:{borderColor:"var(--border)"},children:[a.jsx("h1",{className:"text-base font-semibold truncate min-w-0",style:{color:"var(--text-primary)"},children:L.eval_set_name}),a.jsx("span",{className:"px-2 py-0.5 rounded text-[11px] font-semibold uppercase tracking-wide",style:{color:T.color,background:T.bg},children:T.label}),a.jsx("span",{className:"text-sm font-bold font-mono",style:{color:wt(L.overall_score)},children:en(L.overall_score)}),a.jsx("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:vu(L.start_time,L.end_time)}),B&&a.jsxs("div",{className:"flex items-center gap-2 max-w-[160px]",children:[a.jsx("div",{className:"flex-1 h-2 rounded-full overflow-hidden",style:{background:"var(--bg-tertiary)"},children:a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${L.progress_total>0?L.progress_completed/L.progress_total*100:0}%`,background:"var(--info)"}})}),a.jsxs("span",{className:"text-[11px] shrink-0",style:{color:"var(--text-muted)"},children:[L.progress_completed,"/",L.progress_total]})]}),O.length>0&&a.jsx("div",{className:"flex gap-3 ml-auto",children:O.map(M=>{const I=k.find(N=>N.id===M),D=L.evaluator_scores[M];return a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:ro((I==null?void 0:I.name)??M)}),a.jsx("div",{className:"w-12 h-2 rounded-full overflow-hidden",style:{background:"var(--bg-tertiary)"},children:a.jsx("div",{className:"h-full rounded-full",style:{width:`${D*100}%`,background:wt(D)}})}),a.jsx("span",{className:"text-[11px] font-mono",style:{color:wt(D)},children:en(D)})]},M)})})]}),a.jsxs("div",{className:"shrink-0 overflow-hidden flex flex-col",style:{height:u},children:[a.jsxs("div",{className:"flex items-center px-3 h-7 text-[11px] font-semibold shrink-0 border-b",style:{color:"var(--text-muted)",background:"var(--bg-secondary)",borderColor:"var(--border)"},children:[a.jsx("span",{className:"w-5 shrink-0"}),a.jsx("span",{className:"flex-1 min-w-0",children:"Name"}),a.jsx("span",{className:"w-14 shrink-0 text-right",children:"Score"}),O.map(M=>{const I=k.find(D=>D.id===M);return a.jsx("span",{className:"w-36 shrink-0 text-right truncate pl-2",title:(I==null?void 0:I.name)??M,children:ro((I==null?void 0:I.name)??M)},M)}),a.jsx("span",{className:"w-14 shrink-0 text-right",children:"Time"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.results.map(M=>{const I=M.status==="pending",D=M.status==="failed",N=M.name===l;return a.jsxs("button",{onClick:()=>{o(N?`#/evals/runs/${e}`:`#/evals/runs/${e}/${encodeURIComponent(M.name)}`)},className:"w-full text-left px-3 py-1.5 flex items-center text-xs border-b transition-colors cursor-pointer",style:{borderColor:"var(--border)",background:N?"color-mix(in srgb, var(--accent) 10%, var(--bg-primary))":void 0,borderLeft:N?"2px solid var(--accent)":"2px solid transparent",opacity:I?.5:1},onMouseEnter:_=>{N||(_.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:_=>{N||(_.currentTarget.style.background="")},children:[a.jsx("span",{className:"w-5 shrink-0 flex justify-center",children:a.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:I?"var(--text-muted)":D?"var(--error)":M.overall_score>=.8?"var(--success)":M.overall_score>=.5?"var(--warning)":"var(--error)"}})}),a.jsx("span",{className:"flex-1 min-w-0 truncate",style:{color:"var(--text-primary)"},children:M.name}),a.jsx("span",{className:"w-14 shrink-0 text-right font-mono font-semibold",style:{color:wt(I?null:M.overall_score)},children:I?"-":en(M.overall_score)}),O.map(_=>a.jsx("span",{className:"w-36 shrink-0 text-right font-mono pl-2",style:{color:wt(I?null:M.scores[_]??null)},children:I?"-":en(M.scores[_]??null)},_)),a.jsx("span",{className:"w-14 shrink-0 text-right",style:{color:"var(--text-muted)"},children:M.duration_ms!==null?`${(M.duration_ms/1e3).toFixed(1)}s`:"-"})]},M.name)}),n.results.length===0&&a.jsx("div",{className:"flex items-center justify-center py-8 text-[var(--text-muted)] text-xs",children:B?"Waiting for results...":"No results"})]})]}),a.jsx("div",{onMouseDown:A,onTouchStart:A,className:"shrink-0 drag-handle-row"}),a.jsx("div",{className:"flex-1 overflow-hidden",children:E&&w.length>0?a.jsx(Ir,{traces:w}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:(E==null?void 0:E.status)==="pending"?"Pending...":"No traces available"})})]}),a.jsx("div",{onMouseDown:j,onTouchStart:j,className:`shrink-0 drag-handle-col${g?"":" transition-all"}`,style:{width:E?3:0,opacity:E?1:0}}),a.jsx(wu,{width:m,item:E,evaluators:k,isRunning:B,isDragging:g})]})}const ku=[{id:"score",label:"Score"},{id:"io",label:"I/O"},{id:"logs",label:"Logs"}];function wu({width:e,item:t,evaluators:n,isRunning:r,isDragging:i}){const[s,o]=S.useState("score"),l=!!t;return a.jsxs("div",{className:`shrink-0 flex flex-col overflow-hidden${i?"":" transition-[width] duration-200 ease-in-out"}`,style:{width:l?e:0,background:"var(--bg-primary)"},children:[a.jsxs("div",{className:"flex items-center gap-1 px-2 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",minWidth:e},children:[ku.map(u=>a.jsx("button",{onClick:()=>o(u.id),className:"px-2.5 py-1 h-7 text-xs font-semibold rounded transition-colors cursor-pointer",style:{color:s===u.id?"var(--accent)":"var(--text-muted)",background:s===u.id?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent",border:"none"},onMouseEnter:c=>{s!==u.id&&(c.currentTarget.style.color="var(--text-primary)")},onMouseLeave:c=>{s!==u.id&&(c.currentTarget.style.color="var(--text-muted)")},children:u.label},u.id)),r&&a.jsx("span",{className:"ml-auto text-[11px] px-2 py-0.5 rounded-full shrink-0",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--warning)"},children:"Running..."})]}),a.jsx("div",{className:"flex-1 overflow-y-auto",style:{minWidth:e},children:t?t.status==="pending"?a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:"Pending..."}):a.jsxs(a.Fragment,{children:[t.status==="failed"&&a.jsxs("div",{className:"mx-2 mt-2 px-3 py-2 rounded text-xs",style:{background:"rgba(239,68,68,0.1)",color:"var(--error)"},children:[a.jsxs("div",{className:"flex items-center gap-2 font-semibold",children:[a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:[a.jsx("circle",{cx:"8",cy:"8",r:"7",stroke:"currentColor",strokeWidth:"1.5"}),a.jsx("path",{d:"M8 4.5v4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),a.jsx("circle",{cx:"8",cy:"11",r:"0.75",fill:"currentColor"})]}),a.jsx("span",{children:"Evaluator error"})]}),t.error&&a.jsx("div",{className:"mt-1 pl-[22px] text-[11px] opacity-80 break-words",style:{color:"var(--text-secondary)"},children:t.error})]}),s==="score"?a.jsx(_u,{item:t,evaluators:n}):s==="io"?a.jsx(Nu,{item:t}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:"Logs coming soon"})]}):null})]})}function _u({item:e,evaluators:t}){const n=Object.keys(e.scores);return a.jsxs("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:[a.jsx("div",{className:"overflow-hidden",style:{border:"1px solid var(--border)"},children:a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"truncate text-[11px] font-semibold",style:{color:"var(--text-primary)"},children:"Overall"}),a.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[a.jsx("div",{className:"w-24 h-2.5 rounded-full overflow-hidden",style:{background:"var(--bg-tertiary)"},children:a.jsx("div",{className:"h-full rounded-full",style:{width:`${e.overall_score*100}%`,background:wt(e.overall_score)}})}),a.jsx("span",{className:"text-xs font-mono font-bold shrink-0 w-10 text-right",style:{color:wt(e.overall_score)},children:en(e.overall_score)})]})]})}),e.status==="failed"&&n.length===0&&a.jsx("div",{className:"px-3 py-3 text-xs text-center",style:{color:"var(--text-muted)"},children:"All evaluators failed — no scores available"}),n.map(r=>{const i=t.find(l=>l.id===r),s=e.scores[r],o=e.justifications[r];return a.jsxs("div",{className:"overflow-hidden",style:{border:"1px solid var(--border)"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"truncate text-[11px] font-semibold",style:{color:"var(--text-primary)"},title:(i==null?void 0:i.name)??r,children:(i==null?void 0:i.name)??r}),a.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[a.jsx("div",{className:"w-24 h-2.5 rounded-full overflow-hidden",style:{background:"var(--bg-tertiary)"},children:a.jsx("div",{className:"h-full rounded-full",style:{width:`${s*100}%`,background:wt(s)}})}),a.jsx("span",{className:"text-xs font-mono font-bold shrink-0 w-10 text-right",style:{color:wt(s)},children:en(s)})]})]}),o&&a.jsx(Tu,{text:o})]},r)})]})}function Nu({item:e}){const t=JSON.stringify(e.inputs,null,2),n=typeof e.output=="string"?e.output:JSON.stringify(e.output,null,2),r=e.expected_output!=null?typeof e.expected_output=="string"?e.expected_output:JSON.stringify(e.expected_output,null,2):null;return a.jsxs("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:[a.jsx(_t,{title:"Input",copyText:t,children:a.jsx(it,{json:t,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),r&&a.jsx(_t,{title:"Expected Output",copyText:r,children:a.jsx(it,{json:r,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),a.jsx(_t,{title:"Output",copyText:n,trailing:e.duration_ms!==null?a.jsxs("span",{className:"ml-auto text-[10px]",style:{color:"var(--text-muted)"},children:[(e.duration_ms/1e3).toFixed(2),"s"]}):void 0,children:a.jsx(it,{json:n,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})})]})}function Su(e){var i;const t=e.match(/expected="(.+?)"\s+actual="(.+?)"(.*)/s);if(!t)return null;const n={},r=((i=t[3])==null?void 0:i.trim())??"";if(r)for(const s of r.match(/(\w+)=([\S]+)/g)??[]){const o=s.indexOf("=");n[s.slice(0,o)]=s.slice(o+1)}return{expected:t[1],actual:t[2],meta:n}}function oo(e){try{const t=e.replace(/'/g,'"').replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null"),n=JSON.parse(t);return JSON.stringify(n,null,2)}catch{return e}}function Tu({text:e}){const t=Su(e);if(!t)return a.jsx("div",{className:"px-3 py-2 border-t",style:{borderColor:"var(--border)"},children:a.jsx("div",{className:"text-xs leading-relaxed",style:{color:"var(--text-secondary)"},children:e})});const n=oo(t.expected),r=oo(t.actual),i=n===r;return a.jsxs("div",{className:"border-t",style:{borderColor:"var(--border)"},children:[a.jsxs("div",{className:"grid grid-cols-2 gap-0",children:[a.jsxs("div",{className:"px-3 py-2 border-r",style:{borderColor:"var(--border)"},children:[a.jsx("div",{className:"text-[10px] font-semibold mb-1",style:{color:"var(--text-muted)"},children:"Expected"}),a.jsx("pre",{className:"text-[11px] font-mono whitespace-pre-wrap break-words",style:{color:"var(--text-secondary)"},children:n})]}),a.jsxs("div",{className:"px-3 py-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[a.jsx("span",{className:"text-[10px] font-semibold",style:{color:"var(--text-muted)"},children:"Actual"}),a.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:i?"var(--success)":"var(--error)"}})]}),a.jsx("pre",{className:"text-[11px] font-mono whitespace-pre-wrap break-words",style:{color:i?"var(--success)":"var(--error)"},children:r})]})]}),Object.keys(t.meta).length>0&&a.jsx("div",{className:"px-3 py-1.5 border-t flex items-center gap-3",style:{borderColor:"var(--border)"},children:Object.entries(t.meta).map(([s,o])=>a.jsxs("span",{className:"text-[10px]",style:{color:"var(--text-muted)"},children:[a.jsx("span",{className:"font-medium",children:s.replace(/_/g," ")})," ",a.jsx("span",{className:"font-mono",children:o})]},s))})]})}const so={deterministic:"var(--success)",llm:"#a78bfa",tool:"var(--info)"};function ao(){const e=Ae(f=>f.localEvaluators),t=Ae(f=>f.addEvalSet),{navigate:n}=ot(),[r,i]=S.useState(""),[s,o]=S.useState(new Set),[l,u]=S.useState(null),[c,d]=S.useState(!1),p=f=>{o(g=>{const x=new Set(g);return x.has(f)?x.delete(f):x.add(f),x})},m=async()=>{if(r.trim()){u(null),d(!0);try{const f=await lc({name:r.trim(),evaluator_refs:Array.from(s)});t(f),n(`#/evals/sets/${f.id}`)}catch(f){u(f.detail||f.message||"Failed to create eval set")}finally{d(!1)}}};return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"w-full max-w-xl px-6",children:[a.jsxs("div",{className:"mb-8 text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2",children:[a.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{background:"var(--accent)"}}),a.jsx("span",{className:"text-sm font-semibold",style:{color:"var(--text-muted)"},children:"New Eval Set"})]}),a.jsx("p",{className:"text-sm",style:{color:"var(--text-muted)"},children:"Create an evaluation set with a name and evaluators"})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Name"}),a.jsx("input",{type:"text",value:r,onChange:f=>i(f.target.value),placeholder:"e.g. Basic QA Tests",className:"w-full rounded-md px-3 py-2 text-xs",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"},onKeyDown:f=>{f.key==="Enter"&&r.trim()&&m()}})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Evaluators"}),e.length===0?a.jsxs("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:["No evaluators configured."," ",a.jsx("button",{onClick:()=>n("#/evaluators/new"),className:"underline cursor-pointer",style:{color:"var(--accent)",background:"none",border:"none",padding:0,font:"inherit"},children:"Create one first"})]}):a.jsx("div",{className:"rounded-md border overflow-hidden",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:e.map(f=>a.jsxs("label",{className:"flex items-center gap-2.5 px-3 py-2 text-xs cursor-pointer transition-colors",style:{borderBottom:"1px solid var(--border)"},onMouseEnter:g=>{g.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:g=>{g.currentTarget.style.background="transparent"},children:[a.jsx("input",{type:"checkbox",checked:s.has(f.id),onChange:()=>p(f.id),className:"accent-[var(--accent)]"}),a.jsx("span",{className:"flex-1 truncate",style:{color:"var(--text-primary)"},children:f.name}),a.jsx("span",{className:"text-[11px] font-medium px-1.5 py-0.5 rounded",style:{background:`color-mix(in srgb, ${so[f.type]??"var(--text-muted)"} 15%, transparent)`,color:so[f.type]??"var(--text-muted)"},children:f.type})]},f.id))})]}),l&&a.jsx("p",{className:"text-xs mb-4 px-3 py-2 rounded",style:{color:"var(--error)",background:"color-mix(in srgb, var(--error) 10%, var(--bg-secondary))"},children:l}),a.jsx("button",{onClick:m,disabled:!r.trim()||c,className:"w-full py-2 rounded-md text-[13px] font-semibold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--accent)",color:"var(--bg-primary)",border:"none"},children:c?"Creating...":"Create Eval Set"})]})})}const Cu=[{type:"deterministic",label:"Deterministic",badgeColor:"var(--success)"},{type:"llm",label:"LLM Judge",badgeColor:"#a78bfa"},{type:"tool",label:"Tool-Based",badgeColor:"var(--info)"}];function lo(){const e=Ae(s=>s.localEvaluators),{evaluatorFilter:t,evaluatorCreateType:n,navigate:r}=ot(),i=!t&&!n;return a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("#/evaluators/new"),className:"mx-3 mt-2.5 mb-1 px-3 py-1.5 text-[11px] font-medium rounded border border-[var(--border)] bg-transparent transition-colors cursor-pointer",style:{color:"var(--text-secondary)"},onMouseEnter:s=>{s.currentTarget.style.color="var(--text-primary)",s.currentTarget.style.borderColor="var(--text-muted)"},onMouseLeave:s=>{s.currentTarget.style.color="var(--text-secondary)",s.currentTarget.style.borderColor=""},children:"+ New Evaluator"}),a.jsx("div",{className:"px-3 pt-3 pb-1 text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"Categories"}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[a.jsxs("button",{onClick:()=>r("#/evaluators"),className:"w-full text-left px-3 py-2 text-xs flex items-center gap-2 cursor-pointer transition-colors",style:{background:i?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:i?"var(--text-primary)":"var(--text-secondary)",borderLeft:i?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:s=>{i||(s.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:s=>{i||(s.currentTarget.style.background="transparent")},children:[a.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:"var(--text-muted)"}}),a.jsx("span",{className:"flex-1 truncate",children:"All"}),e.length>0&&a.jsx("span",{className:"text-[10px] px-1.5 rounded-full",style:{background:"var(--bg-tertiary)",color:"var(--text-muted)"},children:e.length})]}),Cu.map(s=>{const o=e.filter(u=>u.type===s.type).length,l=t===s.type;return a.jsxs("button",{onClick:()=>r(l?"#/evaluators":`#/evaluators/category/${s.type}`),className:"w-full text-left px-3 py-2 text-xs flex items-center gap-2 cursor-pointer transition-colors",style:{background:l?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:l?"var(--text-primary)":"var(--text-secondary)",borderLeft:l?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:u=>{l||(u.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:u=>{l||(u.currentTarget.style.background="transparent")},children:[a.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:s.badgeColor}}),a.jsx("span",{className:"flex-1 truncate",children:s.label}),o>0&&a.jsx("span",{className:"text-[10px] px-1.5 rounded-full",style:{background:"var(--bg-tertiary)",color:"var(--text-muted)"},children:o})]},s.type)})]})]})}const co={deterministic:{label:"Deterministic",color:"var(--success)",bg:"rgba(34,197,94,0.1)"},llm:{label:"LLM Judge",color:"#a78bfa",bg:"rgba(167,139,250,0.1)"},tool:{label:"Tool-Based",color:"var(--info)",bg:"rgba(59,130,246,0.1)"}},Or={deterministic:"Deterministic",llm:"LLM Judge",tool:"Tool-Based"},pn={deterministic:[{id:"uipath-exact-match",name:"Exact Match"},{id:"uipath-contains",name:"Contains"},{id:"uipath-json-similarity",name:"JSON Similarity"}],llm:[{id:"uipath-llm-judge-output-semantic-similarity",name:"LLM Judge Output"},{id:"uipath-llm-judge-output-strict-json-similarity",name:"LLM Judge Strict JSON"},{id:"uipath-llm-judge-trajectory-similarity",name:"LLM Judge Trajectory"},{id:"uipath-llm-judge-trajectory-simulation",name:"LLM Judge Trajectory Simulation"}],tool:[{id:"uipath-tool-call-order",name:"Tool Call Order"},{id:"uipath-tool-call-args",name:"Tool Call Args"},{id:"uipath-tool-call-count",name:"Tool Call Count"},{id:"uipath-tool-call-output",name:"Tool Call Output"}]};function Is(e){return e.includes("trajectory")?{targetOutputKey:!1,prompt:!0}:e.includes("llm-judge")?{targetOutputKey:!0,prompt:!0}:e.includes("tool-call-output")?{targetOutputKey:!0,prompt:!1}:e.includes("exact-match")||e.includes("contains")||e.includes("json-similarity")?{targetOutputKey:!0,prompt:!1}:{targetOutputKey:!1,prompt:!1}}const ur={"uipath-exact-match":{description:"Checks whether the agent output exactly matches the expected output.",prompt:""},"uipath-contains":{description:"Checks whether the agent output contains the expected substring.",prompt:""},"uipath-json-similarity":{description:"Compares JSON structures for semantic similarity, ignoring key ordering and whitespace.",prompt:""},"uipath-llm-judge-output-semantic-similarity":{description:"Uses an LLM to score semantic similarity between the agent's actual output and the expected output, accounting for synonyms, paraphrases, and equivalent expressions.",prompt:`As an expert evaluator, analyze the semantic similarity between the expected and actual outputs and determine a score from 0 to 100. Focus on comparing meaning and contextual equivalence of corresponding fields, accounting for alternative valid expressions, synonyms, and reasonable variations in language while maintaining high standards for accuracy and completeness. Provide your score with a brief justification. + `}),a.jsxs(Ol,{nodes:s,edges:u,onNodesChange:l,onEdgesChange:d,nodeTypes:Fc,edgeTypes:zc,onInit:_=>{E.current=_},onNodeClick:O,fitView:!0,proOptions:{hideAttribution:!0},nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,children:[a.jsx(Ll,{color:"var(--bg-tertiary)",gap:16}),a.jsx(jl,{showInteractive:!1}),a.jsx(Dl,{position:"top-right",children:a.jsxs("button",{onClick:w,title:k?"Remove all breakpoints":"Set breakpoints on all nodes",style:{background:"var(--bg-secondary)",color:k?"var(--error)":"var(--text-muted)",border:`1px solid ${k?"var(--error)":"var(--node-border)"}`,borderRadius:6,padding:"4px 10px",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:[a.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:k?"var(--error)":"var(--node-border)"}}),k?"Clear all":"Break all"]})}),a.jsx(Pl,{nodeColor:_=>{var R;if(_.type==="groupNode")return"var(--bg-tertiary)";const N=(R=_.data)==null?void 0:R.status;return N==="completed"?"var(--success)":N==="running"?"var(--warning)":N==="failed"?"var(--error)":"var(--node-border)"},nodeStrokeWidth:0,style:{background:"var(--bg-secondary)",width:120,height:80}})]})]})}const $t="__setup__";function Vc({entrypoint:e,mode:t,ws:n,onRunCreated:r,isMobile:i}){const[s,o]=S.useState("{}"),[l,u]=S.useState({}),[c,d]=S.useState(!1),[p,m]=S.useState(!0),[f,h]=S.useState(null),[x,v]=S.useState(""),[b,E]=S.useState(!0),[A,D]=S.useState(()=>{const R=localStorage.getItem("setupTextareaHeight");return R?parseInt(R,10):140}),L=S.useRef(null),[T,B]=S.useState(()=>{const R=localStorage.getItem("setupPanelWidth");return R?parseInt(R,10):380}),O=t==="run";S.useEffect(()=>{m(!0),h(null),Zl(e).then(R=>{u(R.mock_input),o(JSON.stringify(R.mock_input,null,2))}).catch(R=>{console.error("Failed to load mock input:",R);const W=R.detail||{};h(W.message||`Failed to load schema for "${e}"`),o("{}")}).finally(()=>m(!1))},[e]),S.useEffect(()=>{Ee.getState().clearBreakpoints($t)},[]);const k=async()=>{let R;try{R=JSON.parse(s)}catch{alert("Invalid JSON input");return}d(!0);try{const W=Ee.getState().breakpoints[$t]??{},$=Object.keys(W),V=await Mi(e,R,t,$);Ee.getState().clearBreakpoints($t),Ee.getState().upsertRun(V),r(V.id)}catch(W){console.error("Failed to create run:",W)}finally{d(!1)}},w=async()=>{const R=x.trim();if(R){d(!0);try{const W=Ee.getState().breakpoints[$t]??{},$=Object.keys(W),V=await Mi(e,l,"chat",$);Ee.getState().clearBreakpoints($t),Ee.getState().upsertRun(V),Ee.getState().addLocalChatMessage(V.id,{message_id:`local-${Date.now()}`,role:"user",content:R}),n.sendChatMessage(V.id,R),r(V.id)}catch(W){console.error("Failed to create chat run:",W)}finally{d(!1)}}};S.useEffect(()=>{try{JSON.parse(s),E(!0)}catch{E(!1)}},[s]);const M=S.useCallback(R=>{R.preventDefault();const W="touches"in R?R.touches[0].clientY:R.clientY,$=A,V=F=>{const U="touches"in F?F.touches[0].clientY:F.clientY,y=Math.max(60,$+(W-U));D(y)},g=()=>{document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",g),document.removeEventListener("touchmove",V),document.removeEventListener("touchend",g),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem("setupTextareaHeight",String(A))};document.body.style.cursor="row-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",V),document.addEventListener("mouseup",g),document.addEventListener("touchmove",V,{passive:!1}),document.addEventListener("touchend",g)},[A]),I=S.useCallback(R=>{R.preventDefault();const W="touches"in R?R.touches[0].clientX:R.clientX,$=T,V=F=>{const U=L.current;if(!U)return;const y="touches"in F?F.touches[0].clientX:F.clientX,Q=U.clientWidth-300,se=Math.max(280,Math.min(Q,$+(W-y)));B(se)},g=()=>{document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",g),document.removeEventListener("touchmove",V),document.removeEventListener("touchend",g),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem("setupPanelWidth",String(T))};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",V),document.addEventListener("mouseup",g),document.addEventListener("touchmove",V,{passive:!1}),document.addEventListener("touchend",g)},[T]),j=O?"Autonomous":"Conversational",_=O?"var(--success)":"var(--accent)",N=a.jsxs("div",{className:"shrink-0 flex flex-col",style:i?{background:"var(--bg-primary)"}:{width:T,background:"var(--bg-primary)"},children:[a.jsxs("div",{className:"px-4 text-xs font-semibold border-b flex items-center gap-2 h-10",style:{color:"var(--text-muted)",borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[a.jsx("span",{style:{color:_},children:"●"}),j]}),a.jsxs("div",{className:"flex-1 overflow-y-auto flex flex-col items-center justify-center gap-4 px-6",children:[a.jsx("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",opacity:.5},children:O?a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("polyline",{points:"12 6 12 12 16 14"})]}):a.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),a.jsxs("div",{className:"text-center space-y-1.5",children:[a.jsx("p",{className:"text-sm font-medium",style:{color:"var(--text-secondary)"},children:O?"Ready to execute":"Ready to chat"}),a.jsxs("p",{className:"text-xs leading-relaxed",style:{color:"var(--text-muted)"},children:["Click nodes to set breakpoints",O?a.jsxs(a.Fragment,{children:[",",a.jsx("br",{}),"configure input below, then run"]}):a.jsxs(a.Fragment,{children:[",",a.jsx("br",{}),"then send your first message"]})]})]})]}),O?a.jsxs("div",{className:"flex flex-col",style:{background:"var(--bg-primary)"},children:[!i&&a.jsx("div",{onMouseDown:M,onTouchStart:M,className:"shrink-0 drag-handle-row"}),a.jsxs("div",{className:"px-4 py-3",children:[f?a.jsx("div",{className:"text-xs mb-3 px-3 py-2 rounded",style:{color:"var(--error)",background:"color-mix(in srgb, var(--error) 10%, var(--bg-secondary))"},children:f}):a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:["Input",p&&a.jsx("span",{className:"ml-2 font-normal",children:"Loading..."})]}),a.jsx("textarea",{value:s,onChange:R=>o(R.target.value),spellCheck:!1,className:"w-full rounded-md px-3 py-2 text-xs font-mono leading-relaxed resize-none mb-3",style:{height:i?120:A,background:"var(--bg-secondary)",border:`1px solid ${b?"var(--border)":"#b91c1c"}`,color:"var(--text-primary)"}})]}),a.jsx("button",{onClick:k,disabled:c||p||!!f,className:"w-full py-2 text-sm font-semibold rounded-md border cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2",style:{background:"transparent",borderColor:_,color:_},onMouseEnter:R=>{c||(R.currentTarget.style.background=`color-mix(in srgb, ${_} 10%, transparent)`)},onMouseLeave:R=>{R.currentTarget.style.background="transparent"},children:c?"Starting...":a.jsxs(a.Fragment,{children:[a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:a.jsx("polygon",{points:"5,3 19,12 5,21"})}),"Execute"]})})]})]}):a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-t",style:{borderColor:"var(--border)"},children:[a.jsx("input",{value:x,onChange:R=>v(R.target.value),onKeyDown:R=>{R.key==="Enter"&&!R.shiftKey&&(R.preventDefault(),w())},disabled:c||p,placeholder:c?"Starting...":"Message...",className:"flex-1 bg-transparent text-sm py-1 disabled:opacity-40 placeholder:text-[var(--text-muted)]",style:{color:"var(--text-primary)"}}),a.jsx("button",{onClick:w,disabled:c||p||!x.trim(),className:"text-xs font-semibold px-3 py-1.5 rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed",style:{color:!c&&x.trim()?"var(--accent)":"var(--text-muted)",background:"transparent"},onMouseEnter:R=>{!c&&x.trim()&&(R.currentTarget.style.background="color-mix(in srgb, var(--accent) 10%, transparent)")},onMouseLeave:R=>{R.currentTarget.style.background="transparent"},children:"Send"})]})]});return i?a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsx("div",{className:"shrink-0",style:{height:"40vh"},children:a.jsx(Un,{entrypoint:e,traces:[],runId:$t})}),a.jsx("div",{className:"flex-1 overflow-y-auto flex flex-col min-h-0",children:N})]}):a.jsxs("div",{ref:L,className:"flex h-full",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx(Un,{entrypoint:e,traces:[],runId:$t})}),a.jsx("div",{onMouseDown:I,onTouchStart:I,className:"shrink-0 drag-handle-col"}),N]})}const Yc={key:"var(--info)",string:"var(--success)",number:"var(--warning)",boolean:"var(--accent)",null:"var(--accent)",punctuation:"var(--text-muted)"};function Xc(e){const t=[],n=/("(?:[^"\\]|\\.)*")\s*:|("(?:[^"\\]|\\.)*")|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)\b|(true|false)\b|(null)\b|([{}[\]:,])/g;let r=0,i;for(;(i=n.exec(e))!==null;){if(i.index>r&&t.push({type:"punctuation",text:e.slice(r,i.index)}),i[1]!==void 0){t.push({type:"key",text:i[1]});const s=e.indexOf(":",i.index+i[1].length);s!==-1&&(s>i.index+i[1].length&&t.push({type:"punctuation",text:e.slice(i.index+i[1].length,s)}),t.push({type:"punctuation",text:":"}),n.lastIndex=s+1)}else i[2]!==void 0?t.push({type:"string",text:i[2]}):i[3]!==void 0?t.push({type:"number",text:i[3]}):i[4]!==void 0?t.push({type:"boolean",text:i[4]}):i[5]!==void 0?t.push({type:"null",text:i[5]}):i[6]!==void 0&&t.push({type:"punctuation",text:i[6]});r=n.lastIndex}return rXc(e),[e]);return a.jsx("pre",{className:t,style:n,children:r.map((i,s)=>a.jsx("span",{style:{color:Yc[i.type]},children:i.text},s))})}const Zc={started:{color:"var(--info)",label:"Started"},running:{color:"var(--warning)",label:"Running"},completed:{color:"var(--success)",label:"Completed"},failed:{color:"var(--error)",label:"Failed"},error:{color:"var(--error)",label:"Error"}},Jc={color:"var(--text-muted)",label:"Unknown"};function Qc(e){if(typeof e!="string")return null;const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.stringify(JSON.parse(t),null,2)}catch{return null}return null}const Wi=200;function eu(e){if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function tu({value:e}){const[t,n]=S.useState(!1),r=eu(e),i=S.useMemo(()=>Qc(e),[e]),s=i!==null,o=i??r,l=o.length>Wi||o.includes(` +`),u=S.useCallback(()=>n(c=>!c),[]);return l?a.jsxs("div",{children:[t?s?a.jsx(ot,{json:o,className:"font-mono text-[11px] whitespace-pre-wrap break-all",style:{}}):a.jsx("pre",{className:"font-mono text-[11px] whitespace-pre-wrap break-all",style:{color:"var(--text-primary)"},children:o}):a.jsxs("span",{className:"font-mono text-[11px] break-all",style:{color:"var(--text-primary)"},children:[o.slice(0,Wi),"..."]}),a.jsx("button",{onClick:u,className:"text-[11px] cursor-pointer ml-1 px-1",style:{color:"var(--info)"},children:t?"[less]":"[more]"})]}):s?a.jsx(ot,{json:o,className:"font-mono text-[11px] break-all whitespace-pre-wrap",style:{}}):a.jsx("span",{className:"font-mono text-[11px] break-all",style:{color:"var(--text-primary)"},children:o})}function nu({span:e}){const[t,n]=S.useState(!0),[r,i]=S.useState(!1),[s,o]=S.useState("table"),[l,u]=S.useState(!1),c=Zc[e.status.toLowerCase()]??{...Jc,label:e.status},d=S.useMemo(()=>JSON.stringify(e,null,2),[e]),p=S.useCallback(()=>{navigator.clipboard.writeText(d).then(()=>{u(!0),setTimeout(()=>u(!1),1500)})},[d]),m=Object.entries(e.attributes),f=[{label:"Span",value:e.span_id},...e.trace_id?[{label:"Trace",value:e.trace_id}]:[],{label:"Run",value:e.run_id},...e.parent_span_id?[{label:"Parent",value:e.parent_span_id}]:[]];return a.jsxs("div",{className:"flex flex-col h-full text-xs leading-normal",children:[a.jsxs("div",{className:"px-2 border-b flex items-center gap-1 shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",height:"32px"},children:[a.jsx("button",{onClick:()=>o("table"),className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:s==="table"?"var(--accent)":"var(--text-muted)",background:s==="table"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:h=>{s!=="table"&&(h.currentTarget.style.color="var(--text-primary)")},onMouseLeave:h=>{s!=="table"&&(h.currentTarget.style.color="var(--text-muted)")},children:"Table"}),a.jsx("button",{onClick:()=>o("json"),className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:s==="json"?"var(--accent)":"var(--text-muted)",background:s==="json"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:h=>{s!=="json"&&(h.currentTarget.style.color="var(--text-primary)")},onMouseLeave:h=>{s!=="json"&&(h.currentTarget.style.color="var(--text-muted)")},children:"JSON"}),a.jsxs("span",{className:"ml-auto shrink-0 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-bold uppercase tracking-wider",style:{background:`color-mix(in srgb, ${c.color} 15%, var(--bg-secondary))`,color:c.color},children:[a.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full",style:{background:c.color}}),c.label]})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-0.5 pr-0 pt-0 mr-0.5 mt-0.5",children:s==="table"?a.jsxs(a.Fragment,{children:[m.length>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"px-2 py-1 text-[11px] uppercase font-bold tracking-wider border-b cursor-pointer flex items-center",style:{color:"var(--success)",borderColor:"var(--border)",background:"var(--bg-secondary)"},onClick:()=>n(h=>!h),children:[a.jsxs("span",{className:"flex-1",children:["Attributes (",m.length,")"]}),a.jsx("span",{style:{color:"var(--text-muted)",transform:t?"rotate(0deg)":"rotate(-90deg)"},children:"▾"})]}),t&&m.map(([h,x],v)=>a.jsxs("div",{className:"flex gap-2 px-2 py-1 items-start border-b",style:{borderColor:"var(--border)",background:v%2===0?"var(--bg-primary)":"var(--bg-secondary)"},children:[a.jsx("span",{className:"font-mono font-semibold shrink-0 pt-px truncate text-[11px]",style:{color:"var(--info)",width:"35%"},title:h,children:h}),a.jsx("span",{className:"flex-1 min-w-0",children:a.jsx(tu,{value:x})})]},h))]}),a.jsxs("div",{className:"px-2 py-1 text-[11px] uppercase font-bold tracking-wider border-b cursor-pointer flex items-center",style:{color:"var(--success)",borderColor:"var(--border)",background:"var(--bg-secondary)"},onClick:()=>i(h=>!h),children:[a.jsxs("span",{className:"flex-1",children:["Identifiers (",f.length,")"]}),a.jsx("span",{style:{color:"var(--text-muted)",transform:r?"rotate(0deg)":"rotate(-90deg)"},children:"▾"})]}),r&&f.map((h,x)=>a.jsxs("div",{className:"flex gap-2 px-2 py-1 items-start border-b",style:{borderColor:"var(--border)",background:x%2===0?"var(--bg-primary)":"var(--bg-secondary)"},children:[a.jsx("span",{className:"font-mono font-semibold shrink-0 pt-px truncate text-[11px]",style:{color:"var(--info)",width:"35%"},title:h.label,children:h.label}),a.jsx("span",{className:"flex-1 min-w-0",children:a.jsx("span",{className:"font-mono text-[11px] break-all",style:{color:"var(--text-primary)"},children:h.value})})]},h.label))]}):a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:p,className:"absolute top-1 right-1 z-10 text-[11px] cursor-pointer px-2 py-1 rounded transition-colors",style:{color:l?"var(--success)":"var(--text-muted)",background:"var(--bg-secondary)",border:"1px solid var(--border)"},onMouseEnter:h=>{l||(h.currentTarget.style.color="var(--text-primary)")},onMouseLeave:h=>{h.currentTarget.style.color=l?"var(--success)":"var(--text-muted)"},children:l?"Copied!":"Copy"}),a.jsx(ot,{json:d,className:"font-mono text-[11px] whitespace-pre-wrap p-2",style:{}})]})})]})}function ru(e){const t=[];function n(r,i){t.push({span:r.span,depth:i});for(const s of r.children)n(s,i+1)}for(const r of e)n(r,0);return t}function iu({tree:e,selectedSpan:t,onSelect:n}){const r=S.useMemo(()=>ru(e),[e]),{globalStart:i,totalDuration:s}=S.useMemo(()=>{if(r.length===0)return{globalStart:0,totalDuration:1};let o=1/0,l=-1/0;for(const{span:u}of r){const c=new Date(u.timestamp).getTime();o=Math.min(o,c),l=Math.max(l,c+(u.duration_ms??0))}return{globalStart:o,totalDuration:Math.max(l-o,1)}},[r]);return r.length===0?null:a.jsx(a.Fragment,{children:r.map(({span:o,depth:l})=>{var x;const u=new Date(o.timestamp).getTime()-i,c=o.duration_ms??0,d=u/s*100,p=Math.max(c/s*100,.3),m=Ts[o.status.toLowerCase()]??"var(--text-muted)",f=o.span_id===(t==null?void 0:t.span_id),h=(x=o.attributes)==null?void 0:x["openinference.span.kind"];return a.jsxs("button",{"data-span-id":o.span_id,onClick:()=>n(o),className:"w-full text-left text-xs leading-normal py-1 flex items-center transition-colors",style:{background:f?"color-mix(in srgb, var(--accent) 10%, var(--bg-primary))":void 0,borderLeft:f?"2px solid var(--accent)":"2px solid transparent"},onMouseEnter:v=>{f||(v.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:v=>{f||(v.currentTarget.style.background="")},children:[a.jsxs("div",{className:"shrink-0 flex items-center gap-1 overflow-hidden",style:{width:"35%",minWidth:"80px",paddingLeft:`${l*12+4}px`},children:[a.jsx("span",{className:"shrink-0 flex items-center justify-center w-3.5 h-3.5",children:a.jsx(Cs,{kind:h,statusColor:m})}),a.jsx("span",{className:"text-[var(--text-primary)] truncate",children:o.span_name})]}),a.jsx("div",{className:"flex-1 relative h-[14px] mx-1 rounded-sm",style:{background:"var(--bg-secondary)"},children:a.jsx("div",{className:"absolute rounded-sm",style:{left:`${d}%`,width:`${p}%`,top:"2px",bottom:"2px",background:m,opacity:.8,minWidth:"2px"}})}),a.jsx("span",{className:"shrink-0 text-[10px] tabular-nums pr-2",style:{width:"52px",textAlign:"right",color:"var(--text-muted)"},children:As(o.duration_ms)})]},o.span_id)})})}const Ts={started:"var(--info)",running:"var(--warning)",completed:"var(--success)",failed:"var(--error)",error:"var(--error)"};function Cs({kind:e,statusColor:t}){const n=t,r=14,i={width:r,height:r,viewBox:"0 0 16 16",fill:"none",stroke:n,strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};switch(e){case"LLM":return a.jsx("svg",{...i,children:a.jsx("path",{d:"M8 2L9 5L12 4L10 7L14 8L10 9L12 12L9 11L8 14L7 11L4 12L6 9L2 8L6 7L4 4L7 5Z",fill:n,stroke:"none"})});case"TOOL":return a.jsx("svg",{...i,children:a.jsx("path",{d:"M10.5 2.5a3.5 3.5 0 0 0-3.17 4.93L3.5 11.27a1 1 0 0 0 0 1.41l.82.82a1 1 0 0 0 1.41 0l3.84-3.83A3.5 3.5 0 1 0 10.5 2.5z"})});case"AGENT":return a.jsxs("svg",{...i,children:[a.jsx("rect",{x:"3",y:"5",width:"10",height:"8",rx:"2"}),a.jsx("circle",{cx:"6",cy:"9",r:"1",fill:n,stroke:"none"}),a.jsx("circle",{cx:"10",cy:"9",r:"1",fill:n,stroke:"none"}),a.jsx("path",{d:"M8 2v3"}),a.jsx("path",{d:"M6 2h4"})]});case"CHAIN":return a.jsxs("svg",{...i,children:[a.jsx("path",{d:"M6.5 9.5L9.5 6.5"}),a.jsx("path",{d:"M4.5 8.5l-1 1a2 2 0 0 0 2.83 2.83l1-1"}),a.jsx("path",{d:"M11.5 7.5l1-1a2 2 0 0 0-2.83-2.83l-1 1"})]});case"RETRIEVER":return a.jsxs("svg",{...i,children:[a.jsx("circle",{cx:"7",cy:"7",r:"4"}),a.jsx("path",{d:"M10 10l3.5 3.5"})]});case"EMBEDDING":return a.jsxs("svg",{...i,children:[a.jsx("rect",{x:"2",y:"2",width:"4",height:"4",rx:"0.5"}),a.jsx("rect",{x:"10",y:"2",width:"4",height:"4",rx:"0.5"}),a.jsx("rect",{x:"2",y:"10",width:"4",height:"4",rx:"0.5"}),a.jsx("rect",{x:"10",y:"10",width:"4",height:"4",rx:"0.5"})]});default:return a.jsx("span",{className:"shrink-0 w-2 h-2 rounded-full",style:{background:t}})}}function ou(e){const t=new Map(e.map(o=>[o.span_id,o])),n=new Map;for(const o of e)if(o.parent_span_id){const l=n.get(o.parent_span_id)??[];l.push(o),n.set(o.parent_span_id,l)}const r=e.filter(o=>o.parent_span_id===null||!t.has(o.parent_span_id));function i(o){const l=(n.get(o.span_id)??[]).sort((u,c)=>u.timestamp.localeCompare(c.timestamp));return{span:o,children:l.map(i)}}return r.sort((o,l)=>o.timestamp.localeCompare(l.timestamp)).map(i).flatMap(o=>o.span.span_name==="root"?o.children:[o])}function As(e){return e==null?"":e<1e3?`${e.toFixed(0)}ms`:`${(e/1e3).toFixed(2)}s`}function Ms(e){return e.map(t=>{const{span:n}=t;return t.children.length>0?{name:n.span_name,children:Ms(t.children)}:{name:n.span_name}})}function Ir({traces:e}){const[t,n]=S.useState(null),[r,i]=S.useState(new Set),[s,o]=S.useState(()=>{const O=localStorage.getItem("traceTreeSplitWidth");return O?parseFloat(O):50}),[l,u]=S.useState(!1),[c,d]=S.useState(!1),[p,m]=S.useState(()=>localStorage.getItem("traceViewMode")||"tree"),f=ou(e),h=S.useMemo(()=>JSON.stringify(Ms(f),null,2),[e]),x=S.useCallback(()=>{navigator.clipboard.writeText(h).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},[h]),v=Ee(O=>O.focusedSpan),b=Ee(O=>O.setFocusedSpan),[E,A]=S.useState(null),D=S.useRef(null),L=S.useCallback(O=>{i(k=>{const w=new Set(k);return w.has(O)?w.delete(O):w.add(O),w})},[]),T=S.useRef(null);S.useEffect(()=>{const O=f.length>0?f[0].span.span_id:null,k=T.current;if(T.current=O,O&&O!==k)n(f[0].span);else if(t===null)f.length>0&&n(f[0].span);else{const w=e.find(M=>M.span_id===t.span_id);w&&w!==t&&n(w)}},[e]),S.useEffect(()=>{if(!v)return;const k=e.filter(w=>w.span_name===v.name).sort((w,M)=>w.timestamp.localeCompare(M.timestamp))[v.index];if(k){n(k),A(k.span_id);const w=new Map(e.map(M=>[M.span_id,M.parent_span_id]));i(M=>{const I=new Set(M);let j=k.parent_span_id;for(;j;)I.delete(j),j=w.get(j)??null;return I})}b(null)},[v,e,b]),S.useEffect(()=>{if(!E)return;const O=E;A(null),requestAnimationFrame(()=>{const k=D.current,w=k==null?void 0:k.querySelector(`[data-span-id="${O}"]`);k&&w&&w.scrollIntoView({block:"center",behavior:"smooth"})})},[E]),S.useEffect(()=>{if(!l)return;const O=w=>{const M=document.querySelector(".trace-tree-container");if(!M)return;const I=M.getBoundingClientRect(),j=(w.clientX-I.left)/I.width*100,_=Math.max(20,Math.min(80,j));o(_),localStorage.setItem("traceTreeSplitWidth",String(_))},k=()=>{u(!1)};return window.addEventListener("mousemove",O),window.addEventListener("mouseup",k),()=>{window.removeEventListener("mousemove",O),window.removeEventListener("mouseup",k)}},[l]);const B=O=>{O.preventDefault(),u(!0)};return a.jsxs("div",{className:"flex h-full trace-tree-container",style:{cursor:l?"col-resize":void 0},children:[a.jsxs("div",{className:"flex flex-col",style:{width:`${s}%`},children:[e.length>0&&a.jsxs("div",{className:"flex items-center gap-1 px-2 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",height:"32px"},children:[a.jsx("button",{onClick:()=>{m("tree"),localStorage.setItem("traceViewMode","tree")},className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:p==="tree"?"var(--accent)":"var(--text-muted)",background:p==="tree"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:O=>{p!=="tree"&&(O.currentTarget.style.color="var(--text-primary)")},onMouseLeave:O=>{p!=="tree"&&(O.currentTarget.style.color="var(--text-muted)")},children:"Tree"}),a.jsx("button",{onClick:()=>{m("timeline"),localStorage.setItem("traceViewMode","timeline")},className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:p==="timeline"?"var(--accent)":"var(--text-muted)",background:p==="timeline"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:O=>{p!=="timeline"&&(O.currentTarget.style.color="var(--text-primary)")},onMouseLeave:O=>{p!=="timeline"&&(O.currentTarget.style.color="var(--text-muted)")},children:"Timeline"}),a.jsx("button",{onClick:()=>{m("json"),localStorage.setItem("traceViewMode","json")},className:"px-2.5 h-6 text-[11px] font-semibold rounded transition-colors cursor-pointer inline-flex items-center",style:{color:p==="json"?"var(--accent)":"var(--text-muted)",background:p==="json"?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent"},onMouseEnter:O=>{p!=="json"&&(O.currentTarget.style.color="var(--text-primary)")},onMouseLeave:O=>{p!=="json"&&(O.currentTarget.style.color="var(--text-muted)")},children:"JSON"})]}),a.jsx("div",{ref:D,className:"overflow-y-auto flex-1 p-0.5 pr-0 pt-0 mr-0.5 mt-0.5",children:f.length===0?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-[var(--text-muted)] text-sm",children:"No traces yet"})}):p==="tree"?f.map((O,k)=>a.jsx(Rs,{node:O,depth:0,selectedId:(t==null?void 0:t.span_id)??null,onSelect:n,isLast:k===f.length-1,collapsedIds:r,toggleExpanded:L},O.span.span_id)):p==="timeline"?a.jsx(iu,{tree:f,selectedSpan:t,onSelect:n}):a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:x,className:"absolute top-1 right-1 z-10 text-[11px] cursor-pointer px-2 py-1 rounded transition-colors",style:{color:c?"var(--success)":"var(--text-muted)",background:"var(--bg-secondary)",border:"1px solid var(--border)"},onMouseEnter:O=>{c||(O.currentTarget.style.color="var(--text-primary)")},onMouseLeave:O=>{O.currentTarget.style.color=c?"var(--success)":"var(--text-muted)"},children:c?"Copied!":"Copy"}),a.jsx(ot,{json:h,className:"font-mono text-[11px] whitespace-pre-wrap p-2",style:{}})]})})]}),a.jsx("div",{onMouseDown:B,className:"shrink-0 drag-handle-col",style:l?{background:"var(--accent)"}:void 0}),a.jsx("div",{className:"flex-1 overflow-hidden",children:t?a.jsx(nu,{span:t}):a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-[var(--text-muted)] text-sm",children:"Select a span to view details"})})})]})}function Rs({node:e,depth:t,selectedId:n,onSelect:r,isLast:i,collapsedIds:s,toggleExpanded:o}){var x;const{span:l}=e,u=!s.has(l.span_id),c=Ts[l.status.toLowerCase()]??"var(--text-muted)",d=As(l.duration_ms),p=l.span_id===n,m=e.children.length>0,f=t*20,h=(x=l.attributes)==null?void 0:x["openinference.span.kind"];return a.jsxs("div",{className:"relative",children:[t>0&&a.jsx("div",{className:"absolute top-0 z-10 pointer-events-none",style:{left:`${f-10}px`,width:"1px",height:i?"16px":"100%",background:"var(--border)"}}),a.jsxs("button",{"data-span-id":l.span_id,onClick:()=>r(l),className:"w-full text-left text-xs leading-normal py-1.5 pr-2 flex items-center gap-1.5 transition-colors relative",style:{paddingLeft:`${f+4}px`,background:p?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":void 0,borderLeft:p?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:v=>{p||(v.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:v=>{p||(v.currentTarget.style.background="")},children:[t>0&&a.jsx("div",{className:"absolute z-10 pointer-events-none",style:{left:`${f-10}px`,top:"50%",width:"10px",height:"1px",background:"var(--border)"}}),m?a.jsx("span",{onClick:v=>{v.stopPropagation(),o(l.span_id)},className:"shrink-0 w-5 h-5 flex items-center justify-center cursor-pointer rounded hover:bg-[var(--bg-hover)]",style:{color:"var(--text-muted)"},children:a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",style:{transform:u?"rotate(90deg)":"rotate(0deg)"},children:a.jsx("path",{d:"M3 1.5L7 5L3 8.5",stroke:"currentColor",strokeWidth:"1.5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})}):a.jsx("span",{className:"shrink-0 w-4"}),a.jsx("span",{className:"shrink-0 flex items-center justify-center w-4 h-4",children:a.jsx(Cs,{kind:h,statusColor:c})}),a.jsx("span",{className:"text-[var(--text-primary)] truncate min-w-0 flex-1",children:l.span_name}),d&&a.jsx("span",{className:"text-[var(--text-muted)] shrink-0 ml-auto pl-2 tabular-nums",children:d})]}),u&&e.children.map((v,b)=>a.jsx(Rs,{node:v,depth:t+1,selectedId:n,onSelect:r,isLast:b===e.children.length-1,collapsedIds:s,toggleExpanded:o},v.span.span_id))]})}const su={DEBUG:{color:"var(--text-muted)",bg:"color-mix(in srgb, var(--text-muted) 15%, var(--bg-secondary))",border:"var(--text-muted)"},INFO:{color:"var(--info)",bg:"color-mix(in srgb, var(--info) 15%, var(--bg-secondary))",border:"var(--info)"},WARN:{color:"var(--warning)",bg:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",border:"var(--warning)"},WARNING:{color:"var(--warning)",bg:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",border:"var(--warning)"},ERROR:{color:"var(--error)",bg:"color-mix(in srgb, var(--error) 15%, var(--bg-secondary))",border:"var(--error)"},CRITICAL:{color:"var(--error)",bg:"color-mix(in srgb, var(--error) 15%, var(--bg-secondary))",border:"var(--error)"}},au={color:"var(--text-muted)",bg:"transparent"};function Ki({logs:e}){const t=S.useRef(null),n=S.useRef(null),[r,i]=S.useState(!1);S.useEffect(()=>{var o;(o=n.current)==null||o.scrollIntoView({behavior:"smooth"})},[e.length]);const s=()=>{const o=t.current;o&&i(o.scrollTop>100)};return e.length===0?a.jsx("div",{className:"h-full flex items-center justify-center",children:a.jsx("p",{className:"text-[var(--text-muted)] text-sm",children:"No logs yet"})}):a.jsxs("div",{className:"h-full relative",children:[a.jsxs("div",{ref:t,onScroll:s,className:"h-full overflow-y-auto font-mono text-xs leading-normal",children:[e.map((o,l)=>{const u=new Date(o.timestamp).toLocaleTimeString(void 0,{hour12:!1}),c=o.level.toUpperCase(),d=c.slice(0,4),p=su[c]??au,m=l%2===0;return a.jsxs("div",{className:"flex gap-3 px-3 py-1.5",style:{background:m?"var(--bg-primary)":"var(--bg-secondary)"},children:[a.jsx("span",{className:"text-[var(--text-muted)] shrink-0",children:u}),a.jsx("span",{className:"shrink-0 self-start px-1.5 py-0.5 rounded text-[10px] font-semibold leading-none inline-flex items-center",style:{color:p.color,background:p.bg},children:d}),a.jsx("span",{className:"text-[var(--text-primary)] whitespace-pre-wrap break-all",children:o.message})]},l)}),a.jsx("div",{ref:n})]}),r&&a.jsx("button",{onClick:()=>{var o;return(o=t.current)==null?void 0:o.scrollTo({top:0,behavior:"smooth"})},className:"absolute top-2 right-3 w-6 h-6 flex items-center justify-center rounded-full cursor-pointer transition-opacity opacity-70 hover:opacity-100",style:{background:"var(--bg-tertiary)",color:"var(--text-primary)"},title:"Scroll to top",children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("polyline",{points:"18 15 12 9 6 15"})})})]})}const lu={started:{color:"var(--accent)",label:"started"},updated:{color:"var(--info)",label:"updated"},completed:{color:"var(--success)",label:"completed"},faulted:{color:"var(--error)",label:"faulted"}},Gi={color:"var(--text-muted)",label:""};function An({events:e,runStatus:t}){const n=S.useRef(null),r=S.useRef(!0),[i,s]=S.useState(null),o=()=>{const l=n.current;l&&(r.current=l.scrollHeight-l.scrollTop-l.clientHeight<40)};return S.useEffect(()=>{r.current&&n.current&&(n.current.scrollTop=n.current.scrollHeight)}),e.length===0?a.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:a.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:t==="running"?"Waiting for events...":"No events yet"})}):a.jsx("div",{ref:n,onScroll:o,className:"h-full overflow-y-auto font-mono text-xs leading-normal",children:e.map((l,u)=>{const c=new Date(l.timestamp).toLocaleTimeString(void 0,{hour12:!1}),d=l.payload&&Object.keys(l.payload).length>0,p=i===u,m=l.phase?lu[l.phase]??Gi:Gi;return a.jsxs("div",{children:[a.jsxs("div",{onClick:()=>{d&&s(p?null:u)},className:"flex items-center gap-2 px-3 py-1.5",style:{background:u%2===0?"var(--bg-primary)":"var(--bg-secondary)",cursor:d?"pointer":"default"},children:[a.jsx("span",{className:"shrink-0",style:{color:"var(--text-muted)"},children:c}),a.jsx("span",{className:"shrink-0",style:{color:m.color},children:"●"}),a.jsx("span",{className:"flex-1 truncate",style:{color:"var(--text-primary)"},children:l.node_name}),m.label&&a.jsx("span",{className:"shrink-0 text-[10px]",style:{color:"var(--text-muted)"},children:m.label}),d&&a.jsx("span",{className:"shrink-0 text-[9px] transition-transform",style:{color:"var(--text-muted)",transform:p?"rotate(90deg)":"rotate(0deg)"},children:"▸"})]}),p&&d&&a.jsx("div",{className:"px-3 py-2 border-t border-b",style:{borderColor:"var(--border)",background:"color-mix(in srgb, var(--bg-secondary) 80%, var(--bg-primary))"},children:a.jsx(ot,{json:JSON.stringify(l.payload,null,2),className:"text-[11px] font-mono whitespace-pre-wrap break-words"})})]},u)})})}function _t({title:e,copyText:t,trailing:n,children:r}){const[i,s]=S.useState(!1),o=S.useCallback(()=>{t&&navigator.clipboard.writeText(t).then(()=>{s(!0),setTimeout(()=>s(!1),1500)})},[t]);return a.jsxs("div",{className:"overflow-hidden",style:{border:"1px solid var(--border)"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--text-primary)"},children:e}),n,t&&a.jsx("button",{onClick:o,className:`${n?"":"ml-auto "}text-[10px] cursor-pointer px-1.5 py-0.5 rounded transition-colors`,style:{color:i?"var(--success)":"var(--text-muted)",background:"var(--bg-tertiary)",border:"none"},onMouseEnter:l=>{i||(l.currentTarget.style.color="var(--text-primary)")},onMouseLeave:l=>{l.currentTarget.style.color=i?"var(--success)":"var(--text-muted)"},children:i?"Copied":"Copy"})]}),r]})}function qi({runId:e,status:t,ws:n,breakpointNode:r}){const i=t==="suspended",s=o=>{const l=Ee.getState().breakpoints[e]??{};n.setBreakpoints(e,Object.keys(l)),o==="step"?n.debugStep(e):o==="continue"?n.debugContinue(e):n.debugStop(e)};return a.jsxs("div",{className:"flex items-center gap-1 px-4 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"text-[11px] font-semibold mr-1",style:{color:"var(--text-muted)"},children:"Debug"}),a.jsx(cr,{label:"Step",onClick:()=>s("step"),disabled:!i,color:"var(--info)",active:i}),a.jsx(cr,{label:"Continue",onClick:()=>s("continue"),disabled:!i,color:"var(--success)",active:i}),a.jsx(cr,{label:"Stop",onClick:()=>s("stop"),disabled:!i,color:"var(--error)",active:i}),a.jsx("span",{className:"text-[11px] ml-auto truncate",style:{color:i?"var(--accent)":"var(--text-muted)"},children:i?r?`Paused at ${r}`:"Paused":t})]})}function cr({label:e,onClick:t,disabled:n,color:r,active:i}){return a.jsx("button",{onClick:t,disabled:n,className:"px-3 py-1 h-7 text-[11px] font-semibold rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed",style:{color:i?r:"var(--text-muted)",background:i?`color-mix(in srgb, ${r} 10%, transparent)`:"transparent"},onMouseEnter:s=>{n||(s.currentTarget.style.background=`color-mix(in srgb, ${r} 20%, transparent)`)},onMouseLeave:s=>{s.currentTarget.style.background=i?`color-mix(in srgb, ${r} 10%, transparent)`:"transparent"},children:e})}const Vi=S.lazy(()=>Ns(()=>import("./ChatPanel-DAnMwTFj.js"),__vite__mapDeps([2,1,3,4]))),cu=[],uu=[],du=[],pu=[];function fu({run:e,ws:t,isMobile:n}){const r=e.mode==="chat",[i,s]=S.useState(280),[o,l]=S.useState(()=>{const j=localStorage.getItem("chatPanelWidth");return j?parseInt(j,10):380}),[u,c]=S.useState("primary"),[d,p]=S.useState(r?"primary":"traces"),m=S.useRef(null),f=S.useRef(null),h=S.useRef(!1),x=Ee(j=>j.traces[e.id]||cu),v=Ee(j=>j.logs[e.id]||uu),b=Ee(j=>j.chatMessages[e.id]||du),E=Ee(j=>j.stateEvents[e.id]||pu),A=Ee(j=>j.breakpoints[e.id]);S.useEffect(()=>{t.setBreakpoints(e.id,A?Object.keys(A):[])},[e.id]);const D=S.useCallback(j=>{t.setBreakpoints(e.id,j)},[e.id,t]),L=S.useCallback(j=>{j.preventDefault(),h.current=!0;const _="touches"in j?j.touches[0].clientY:j.clientY,N=i,R=$=>{if(!h.current)return;const V=m.current;if(!V)return;const g="touches"in $?$.touches[0].clientY:$.clientY,F=V.clientHeight-100,U=Math.max(80,Math.min(F,N+(g-_)));s(U)},W=()=>{h.current=!1,document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",W),document.removeEventListener("touchmove",R),document.removeEventListener("touchend",W),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="row-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",W),document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",W)},[i]),T=S.useCallback(j=>{j.preventDefault();const _="touches"in j?j.touches[0].clientX:j.clientX,N=o,R=$=>{const V=f.current;if(!V)return;const g="touches"in $?$.touches[0].clientX:$.clientX,F=V.clientWidth-300,U=Math.max(280,Math.min(F,N+(_-g)));l(U)},W=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",W),document.removeEventListener("touchmove",R),document.removeEventListener("touchend",W),document.body.style.cursor="",document.body.style.userSelect="",localStorage.setItem("chatPanelWidth",String(o))};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",W),document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",W)},[o]),B=r?"Chat":"Events",O=r?"var(--accent)":"var(--success)",k=j=>j==="primary"?O:j==="events"?"var(--success)":"var(--accent)",w=Ee(j=>j.activeInterrupt[e.id]??null),M=e.status==="running"?a.jsx("span",{className:"ml-auto text-[11px] px-2 py-0.5 rounded-full shrink-0",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--warning)"},children:r?"Thinking...":"Running..."}):r&&e.status==="suspended"&&w?a.jsx("span",{className:"ml-auto text-[11px] px-2 py-0.5 rounded-full shrink-0",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--warning)"},children:"Action Required"}):null;if(n){const j=[{id:"traces",label:"Traces",count:x.length},{id:"primary",label:B},...r?[{id:"events",label:"Events",count:E.length}]:[],{id:"io",label:"I/O"},{id:"logs",label:"Logs",count:v.length}];return a.jsxs("div",{className:"flex flex-col h-full",children:[(e.mode==="debug"||e.status==="suspended"&&!w||A&&Object.keys(A).length>0)&&a.jsx(qi,{runId:e.id,status:e.status,ws:t,breakpointNode:e.breakpoint_node}),a.jsx("div",{className:"shrink-0",style:{height:"40vh"},children:a.jsx(Un,{entrypoint:e.entrypoint,traces:x,runId:e.id,breakpointNode:e.breakpoint_node,breakpointNextNodes:e.breakpoint_next_nodes,onBreakpointChange:D})}),a.jsxs("div",{className:"flex items-center gap-1 px-2 h-10 border-y shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[j.map(_=>a.jsxs("button",{onClick:()=>p(_.id),className:"px-2.5 py-1 h-7 text-xs font-semibold rounded transition-colors cursor-pointer",style:{color:d===_.id?k(_.id):"var(--text-muted)",background:d===_.id?`color-mix(in srgb, ${k(_.id)} 10%, transparent)`:"transparent"},children:[_.label,_.count!==void 0&&_.count>0&&a.jsx("span",{className:"ml-1 font-normal",style:{color:"var(--text-muted)"},children:_.count})]},_.id)),M]}),a.jsxs("div",{className:"flex-1 overflow-hidden",children:[d==="traces"&&a.jsx(Ir,{traces:x}),d==="primary"&&(r?a.jsx(S.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center h-full",style:{color:"var(--text-muted)"},children:a.jsx("span",{className:"text-xs",children:"Loading chat..."})}),children:a.jsx(Vi,{messages:b,runId:e.id,runStatus:e.status,ws:t})}):a.jsx(An,{events:E,runStatus:e.status})),d==="events"&&a.jsx(An,{events:E,runStatus:e.status}),d==="io"&&a.jsx(Yi,{run:e}),d==="logs"&&a.jsx(Ki,{logs:v})]})]})}const I=[{id:"primary",label:B},...r?[{id:"events",label:"Events",count:E.length}]:[],{id:"io",label:"I/O"},{id:"logs",label:"Logs",count:v.length}];return a.jsxs("div",{ref:f,className:"flex h-full",children:[a.jsxs("div",{ref:m,className:"flex flex-col flex-1 min-w-0",children:[(e.mode==="debug"||e.status==="suspended"&&!w||A&&Object.keys(A).length>0)&&a.jsx(qi,{runId:e.id,status:e.status,ws:t,breakpointNode:e.breakpoint_node}),a.jsx("div",{className:"shrink-0 overflow-hidden",style:{height:i},children:a.jsx(Un,{entrypoint:e.entrypoint,traces:x,runId:e.id,breakpointNode:e.breakpoint_node,breakpointNextNodes:e.breakpoint_next_nodes,onBreakpointChange:D})}),a.jsx("div",{onMouseDown:L,onTouchStart:L,className:"shrink-0 drag-handle-row"}),a.jsx("div",{className:"flex-1 overflow-hidden",children:a.jsx(Ir,{traces:x})})]}),a.jsx("div",{onMouseDown:T,onTouchStart:T,className:"shrink-0 drag-handle-col"}),a.jsxs("div",{className:"shrink-0 flex flex-col",style:{width:o,background:"var(--bg-primary)"},children:[a.jsxs("div",{className:"flex items-center gap-1 px-2 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[I.map(j=>a.jsxs("button",{onClick:()=>c(j.id),className:"px-2.5 py-1 h-7 text-xs font-semibold rounded transition-colors cursor-pointer",style:{color:u===j.id?k(j.id):"var(--text-muted)",background:u===j.id?`color-mix(in srgb, ${k(j.id)} 10%, transparent)`:"transparent"},onMouseEnter:_=>{u!==j.id&&(_.currentTarget.style.color="var(--text-primary)")},onMouseLeave:_=>{u!==j.id&&(_.currentTarget.style.color="var(--text-muted)")},children:[j.label,j.count!==void 0&&j.count>0&&a.jsx("span",{className:"ml-1 font-normal",style:{color:"var(--text-muted)"},children:j.count})]},j.id)),M]}),a.jsxs("div",{className:"flex-1 overflow-hidden",children:[u==="primary"&&(r?a.jsx(S.Suspense,{fallback:a.jsx("div",{className:"flex items-center justify-center h-full",style:{color:"var(--text-muted)"},children:a.jsx("span",{className:"text-xs",children:"Loading chat..."})}),children:a.jsx(Vi,{messages:b,runId:e.id,runStatus:e.status,ws:t})}):a.jsx(An,{events:E,runStatus:e.status})),u==="events"&&a.jsx(An,{events:E,runStatus:e.status}),u==="io"&&a.jsx(Yi,{run:e}),u==="logs"&&a.jsx(Ki,{logs:v})]})]})]})}function Yi({run:e}){return a.jsxs("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:[a.jsx(_t,{title:"Input",copyText:JSON.stringify(e.input_data,null,2),children:a.jsx(ot,{json:JSON.stringify(e.input_data,null,2),className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),e.output_data&&a.jsx(_t,{title:"Output",copyText:typeof e.output_data=="string"?e.output_data:JSON.stringify(e.output_data,null,2),children:a.jsx(ot,{json:typeof e.output_data=="string"?e.output_data:JSON.stringify(e.output_data,null,2),className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),e.error&&a.jsxs("div",{className:"overflow-hidden",style:{border:"1px solid color-mix(in srgb, var(--error) 40%, var(--border))"},children:[a.jsxs("div",{className:"px-3 py-2 text-xs font-semibold flex items-center gap-2",style:{background:"color-mix(in srgb, var(--error) 15%, var(--bg-secondary))",color:"var(--error)"},children:[a.jsx("span",{children:"Error"}),a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono",style:{background:"color-mix(in srgb, var(--error) 20%, var(--bg-secondary))"},children:e.error.code}),a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono",style:{background:"color-mix(in srgb, var(--error) 20%, var(--bg-secondary))"},children:e.error.category})]}),a.jsxs("div",{className:"px-3 py-2 text-xs leading-normal",children:[a.jsx("div",{className:"font-semibold mb-2",style:{color:"var(--text-primary)"},children:e.error.title}),a.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11px] max-w-prose",style:{color:"var(--text-secondary)"},children:e.error.detail})]})]})]})}function Xi(){const{reloadPending:e,setReloadPending:t,setEntrypoints:n}=Ee(),[r,i]=S.useState(!1);if(!e)return null;const s=async()=>{i(!0);try{await ec();const o=await ys();n(o.map(l=>l.name)),t(!1)}catch(o){console.error("Reload failed:",o)}finally{i(!1)}};return a.jsxs("div",{className:"fixed top-4 left-1/2 -translate-x-1/2 z-50 flex items-center justify-between px-5 py-2.5 rounded-lg shadow-lg min-w-[400px]",style:{background:"var(--bg-secondary)",border:"1px solid var(--bg-tertiary)"},children:[a.jsx("span",{className:"text-sm",style:{color:"var(--text-secondary)"},children:"Files changed, reload to apply"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:s,disabled:r,className:"px-3 py-1 text-sm font-medium rounded cursor-pointer",style:{background:"var(--accent)",color:"#fff",opacity:r?.6:1},children:r?"Reloading...":"Reload"}),a.jsx("button",{onClick:()=>t(!1),className:"text-sm cursor-pointer px-1",style:{color:"var(--text-muted)",background:"none",border:"none"},children:"✕"})]})]})}let mu=0;const Zi=Ot(e=>({toasts:[],addToast:(t,n)=>{const r=String(++mu);e(s=>({toasts:[...s.toasts,{id:r,type:t,message:n}]})),setTimeout(()=>{e(s=>({toasts:s.toasts.filter(o=>o.id!==r)}))},t==="error"?8e3:5e3)},removeToast:t=>{e(n=>({toasts:n.toasts.filter(r=>r.id!==t)}))}})),Ji={success:{color:"var(--success)",bg:"color-mix(in srgb, var(--success) 10%, var(--bg-elevated))",border:"color-mix(in srgb, var(--success) 30%, var(--border))"},error:{color:"var(--error)",bg:"color-mix(in srgb, var(--error) 10%, var(--bg-elevated))",border:"color-mix(in srgb, var(--error) 30%, var(--border))"},info:{color:"var(--info)",bg:"color-mix(in srgb, var(--info) 10%, var(--bg-elevated))",border:"color-mix(in srgb, var(--info) 30%, var(--border))"}};function Qi(){const e=Zi(n=>n.toasts),t=Zi(n=>n.removeToast);return e.length===0?null:a.jsx("div",{className:"fixed bottom-8 right-4 z-[100] flex flex-col gap-2 pointer-events-none",children:e.map(n=>{const r=Ji[n.type]??Ji.info;return a.jsxs("div",{className:"pointer-events-auto flex items-center gap-2 px-4 py-2.5 rounded-lg shadow-lg text-xs font-medium max-w-xs animate-[slideIn_0.2s_ease-out]",style:{background:r.bg,border:`1px solid ${r.border}`,color:r.color},children:[a.jsx("span",{className:"flex-1",children:n.message}),a.jsx("button",{onClick:()=>t(n.id),className:"shrink-0 w-5 h-5 flex items-center justify-center rounded cursor-pointer transition-opacity opacity-60 hover:opacity-100",style:{color:r.color,background:"transparent",border:"none"},"aria-label":"Dismiss",children:a.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[a.jsx("line",{x1:"1",y1:"1",x2:"9",y2:"9"}),a.jsx("line",{x1:"9",y1:"1",x2:"1",y2:"9"})]})})]},n.id)})})}function hu(e){return e===null?"-":`${Math.round(e*100)}%`}function gu(e){if(e===null)return"var(--text-muted)";const t=e*100;return t>=80?"var(--success)":t>=50?"var(--warning)":"var(--error)"}const eo={pending:{color:"var(--text-muted)",label:"Pending"},running:{color:"var(--info)",label:"Running"},completed:{color:"var(--success)",label:"Completed"},failed:{color:"var(--error)",label:"Failed"}};function to(){const e=Ae(l=>l.evalSets),t=Ae(l=>l.evalRuns),{evalSetId:n,evalRunId:r,navigate:i}=st(),s=Object.values(e),o=Object.values(t).sort((l,u)=>new Date(u.start_time??0).getTime()-new Date(l.start_time??0).getTime());return a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[a.jsx("button",{onClick:()=>i("#/evals/new"),className:"w-[calc(100%-24px)] mx-3 mt-2.5 mb-1 px-3 py-1.5 text-[11px] text-center font-medium rounded border border-[var(--border)] bg-transparent transition-colors cursor-pointer",style:{color:"var(--text-secondary)"},onMouseEnter:l=>{l.currentTarget.style.color="var(--text-primary)",l.currentTarget.style.borderColor="var(--text-muted)"},onMouseLeave:l=>{l.currentTarget.style.color="var(--text-secondary)",l.currentTarget.style.borderColor=""},children:"+ New Eval Set"}),a.jsx("div",{className:"px-3 pt-3 pb-1 text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"Eval Sets"}),s.map(l=>{const u=n===l.id;return a.jsxs("button",{onClick:()=>i(`#/evals/sets/${l.id}`),className:"w-full text-left px-3 py-1.5 text-xs cursor-pointer transition-colors",style:{background:u?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:u?"var(--text-primary)":"var(--text-secondary)",borderLeft:u?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:c=>{u||(c.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:c=>{u||(c.currentTarget.style.background="transparent")},children:[a.jsx("div",{className:"truncate font-medium",children:l.name}),a.jsxs("div",{className:"text-[11px] mt-0.5",style:{color:"var(--text-muted)"},children:[l.eval_count," items · ",l.evaluator_ids.length," evaluator",l.evaluator_ids.length!==1?"s":""]})]},l.id)}),s.length===0&&a.jsx("p",{className:"text-[11px] px-3 py-2",style:{color:"var(--text-muted)"},children:"No eval sets yet"}),a.jsx("div",{className:"px-3 pt-4 pb-1 text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"History"}),o.map(l=>{const u=r===l.id,c=eo[l.status]??eo.pending;return a.jsx("button",{onClick:()=>i(`#/evals/runs/${l.id}`),className:"w-full text-left px-3 py-1.5 text-xs cursor-pointer transition-colors",style:{background:u?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:u?"var(--text-primary)":"var(--text-secondary)",borderLeft:u?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:d=>{u||(d.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:d=>{u||(d.currentTarget.style.background="transparent")},children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:c.color}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"truncate font-medium",children:l.eval_set_name}),a.jsx("div",{className:"text-[11px] mt-0.5",style:{color:"var(--text-muted)"},children:l.start_time?new Date(l.start_time).toLocaleString():c.label})]}),a.jsx("span",{className:"font-mono shrink-0",style:{color:gu(l.overall_score)},children:hu(l.overall_score)})]})},l.id)}),o.length===0&&a.jsx("p",{className:"text-[11px] px-3 py-2",style:{color:"var(--text-muted)"},children:"No eval runs yet"})]})}function no(e,t=60){const n=typeof e=="string"?e:JSON.stringify(e);return!n||n==="null"?"-":n.length>t?n.slice(0,t)+"...":n}function bu({evalSetId:e}){const[t,n]=S.useState(null),[r,i]=S.useState(!0),[s,o]=S.useState(null),[l,u]=S.useState(!1),[c,d]=S.useState("io"),p=Ae(g=>g.evaluators),m=Ae(g=>g.localEvaluators),f=Ae(g=>g.updateEvalSetEvaluators),h=Ae(g=>g.incrementEvalSetCount),x=Ae(g=>g.upsertEvalRun),{navigate:v}=st(),[b,E]=S.useState(!1),[A,D]=S.useState(new Set),[L,T]=S.useState(!1),B=S.useRef(null),[O,k]=S.useState(()=>{const g=localStorage.getItem("evalSetSidebarWidth");return g?parseInt(g,10):320}),[w,M]=S.useState(!1),I=S.useRef(null);S.useEffect(()=>{localStorage.setItem("evalSetSidebarWidth",String(O))},[O]),S.useEffect(()=>{i(!0),o(null),dc(e).then(g=>{n(g),g.items.length>0&&o(g.items[0].name)}).catch(console.error).finally(()=>i(!1))},[e]);const j=async()=>{u(!0);try{const g=await pc(e);x(g),v(`#/evals/runs/${g.id}`)}catch(g){console.error(g)}finally{u(!1)}},_=async g=>{if(t)try{await uc(e,g),n(F=>{if(!F)return F;const U=F.items.filter(y=>y.name!==g);return{...F,items:U,eval_count:U.length}}),h(e,-1),s===g&&o(null)}catch(F){console.error(F)}},N=S.useCallback(()=>{t&&D(new Set(t.evaluator_ids)),E(!0)},[t]),R=g=>{D(F=>{const U=new Set(F);return U.has(g)?U.delete(g):U.add(g),U})},W=async()=>{if(t){T(!0);try{const g=await hc(e,Array.from(A));n(g),f(e,g.evaluator_ids),E(!1)}catch(g){console.error(g)}finally{T(!1)}}};S.useEffect(()=>{if(!b)return;const g=F=>{B.current&&!B.current.contains(F.target)&&E(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[b]);const $=S.useCallback(g=>{g.preventDefault(),M(!0);const F="touches"in g?g.touches[0].clientX:g.clientX,U=O,y=se=>{const K=I.current;if(!K)return;const ie="touches"in se?se.touches[0].clientX:se.clientX,de=K.clientWidth-300,be=Math.max(280,Math.min(de,U+(F-ie)));k(be)},Q=()=>{M(!1),document.removeEventListener("mousemove",y),document.removeEventListener("mouseup",Q),document.removeEventListener("touchmove",y),document.removeEventListener("touchend",Q),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",y),document.addEventListener("mouseup",Q),document.addEventListener("touchmove",y,{passive:!1}),document.addEventListener("touchend",Q)},[O]);if(r)return a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-sm",children:"Loading..."});if(!t)return a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)]",children:"Eval set not found"});const V=t.items.find(g=>g.name===s)??null;return a.jsxs("div",{ref:I,className:"flex h-full",children:[a.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[a.jsxs("div",{className:"px-4 h-10 border-b shrink-0 flex items-center gap-4",style:{borderColor:"var(--border)"},children:[a.jsx("h1",{className:"text-base font-semibold",style:{color:"var(--text-primary)"},children:t.name}),a.jsxs("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:[t.eval_count," items"]}),a.jsxs("div",{className:"flex gap-1 items-center ml-auto relative",children:[a.jsx("button",{onClick:N,className:"w-7 h-7 flex items-center justify-center rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:g=>{g.currentTarget.style.color="var(--text-primary)",g.currentTarget.style.background="var(--bg-secondary)"},onMouseLeave:g=>{g.currentTarget.style.color="var(--text-muted)",g.currentTarget.style.background="transparent"},title:"Edit evaluators","aria-label":"Edit evaluators",children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"}),a.jsx("path",{d:"m15 5 4 4"})]})}),t.evaluator_ids.map(g=>{const F=p.find(U=>U.id===g);return a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[11px] font-medium",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:(F==null?void 0:F.name)??g},g)}),b&&a.jsxs("div",{ref:B,className:"absolute top-full right-0 mt-1 z-50 rounded-md border shadow-lg",style:{background:"var(--bg-primary)",borderColor:"var(--border)",minWidth:220},children:[a.jsx("div",{className:"px-3 py-2 border-b text-[10px] uppercase tracking-wide font-semibold",style:{color:"var(--text-muted)",borderColor:"var(--border)"},children:"Evaluators"}),a.jsx("div",{className:"max-h-48 overflow-y-auto",children:m.length===0?a.jsx("div",{className:"px-3 py-3 text-xs",style:{color:"var(--text-muted)"},children:"No evaluators available"}):m.map(g=>a.jsxs("label",{className:"flex items-center gap-2 px-3 py-1.5 text-xs cursor-pointer transition-colors",style:{borderBottom:"1px solid var(--border)"},onMouseEnter:F=>{F.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:F=>{F.currentTarget.style.background="transparent"},children:[a.jsx("input",{type:"checkbox",checked:A.has(g.id),onChange:()=>R(g.id),className:"accent-[var(--accent)]"}),a.jsx("span",{className:"flex-1 truncate",style:{color:"var(--text-primary)"},children:g.name})]},g.id))}),a.jsx("div",{className:"px-3 py-2 border-t flex justify-end",style:{borderColor:"var(--border)"},children:a.jsx("button",{onClick:W,disabled:L,className:"px-3 py-1 text-[11px] font-semibold rounded cursor-pointer transition-colors disabled:opacity-50",style:{background:"var(--accent)",color:"var(--bg-primary)",border:"none"},onMouseEnter:g=>{g.currentTarget.style.background="var(--accent-hover)"},onMouseLeave:g=>{g.currentTarget.style.background="var(--accent)"},children:L?"Saving...":"Update"})})]})]}),a.jsxs("button",{onClick:j,disabled:l,className:"ml-2 px-3 py-1 h-7 text-xs font-semibold rounded border flex items-center gap-1.5 cursor-pointer transition-colors disabled:opacity-30 disabled:cursor-not-allowed",style:{color:"var(--success)",borderColor:"var(--success)",background:"transparent"},onMouseEnter:g=>{l||(g.currentTarget.style.background="color-mix(in srgb, var(--success) 10%, transparent)")},onMouseLeave:g=>{g.currentTarget.style.background="transparent"},title:"Run eval set","aria-label":"Run eval set",children:[a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:a.jsx("polygon",{points:"5,3 19,12 5,21"})}),l?"Running...":"Run"]})]}),a.jsxs("div",{className:"flex items-center px-3 h-7 text-[11px] font-semibold shrink-0 border-b",style:{color:"var(--text-muted)",background:"var(--bg-secondary)",borderColor:"var(--border)"},children:[a.jsx("span",{className:"w-56 shrink-0",children:"Name"}),a.jsx("span",{className:"flex-1 min-w-0",children:"Input"}),a.jsx("span",{className:"w-32 shrink-0 pl-2",children:"Expected Behavior"}),a.jsx("span",{className:"w-32 shrink-0 pl-2",children:"Expected Output"}),a.jsx("span",{className:"w-32 shrink-0 pl-2",children:"Simulation Instr."}),a.jsx("span",{className:"w-8 shrink-0"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[t.items.map(g=>{const F=g.name===s;return a.jsxs("button",{onClick:()=>o(F?null:g.name),className:"group w-full text-left px-3 py-1.5 flex items-center text-xs border-b transition-colors cursor-pointer",style:{borderColor:"var(--border)",background:F?"color-mix(in srgb, var(--accent) 10%, var(--bg-primary))":void 0,borderLeft:F?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:U=>{F||(U.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:U=>{F||(U.currentTarget.style.background="")},children:[a.jsx("span",{className:"w-56 shrink-0 truncate",style:{color:"var(--text-primary)"},children:g.name}),a.jsx("span",{className:"flex-1 min-w-0 truncate font-mono text-[11px]",style:{color:"var(--text-muted)"},children:no(g.inputs)}),a.jsx("span",{className:"w-32 shrink-0 truncate pl-2 text-[11px]",style:{color:"var(--text-muted)"},children:g.expected_behavior||"-"}),a.jsx("span",{className:"w-32 shrink-0 truncate pl-2 font-mono text-[11px]",style:{color:"var(--text-muted)"},children:no(g.expected_output,40)}),a.jsx("span",{className:"w-32 shrink-0 truncate pl-2 text-[11px]",style:{color:"var(--text-muted)"},children:g.simulation_instructions||"-"}),a.jsx("span",{role:"button",tabIndex:0,className:"w-8 shrink-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",onClick:U=>{U.stopPropagation(),_(g.name)},onKeyDown:U=>{U.key==="Enter"&&(U.stopPropagation(),_(g.name))},style:{color:"var(--text-muted)"},onMouseEnter:U=>{U.currentTarget.style.color="var(--error)"},onMouseLeave:U=>{U.currentTarget.style.color="var(--text-muted)"},title:"Delete item",children:a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},g.name)}),t.items.length===0&&a.jsx("div",{className:"flex items-center justify-center py-8 text-[var(--text-muted)] text-xs",children:"No items in this eval set"})]})]}),a.jsx("div",{onMouseDown:$,onTouchStart:$,className:`shrink-0 drag-handle-col${w?"":" transition-all"}`,style:{width:V?3:0,opacity:V?1:0}}),a.jsxs("div",{className:`shrink-0 flex flex-col overflow-hidden${w?"":" transition-[width] duration-200 ease-in-out"}`,style:{width:V?O:0,background:"var(--bg-primary)"},children:[a.jsx("div",{className:"flex items-center gap-1 px-2 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",minWidth:O},children:["io","evaluators"].map(g=>{const F=c===g,U=g==="io"?"I/O":"Evaluators";return a.jsx("button",{onClick:()=>d(g),className:"px-2.5 py-1 h-7 text-xs font-semibold rounded inline-flex items-center cursor-pointer transition-colors",style:{color:F?"var(--accent)":"var(--text-muted)",background:F?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent",border:"none"},children:U},g)})}),a.jsx("div",{className:"flex-1 overflow-hidden",style:{minWidth:O},children:V?c==="io"?a.jsx(xu,{item:V}):a.jsx(yu,{item:V,evaluators:p}):null})]})]})}function xu({item:e}){const t=JSON.stringify(e.inputs,null,2),n=e.expected_output!=null?typeof e.expected_output=="string"?e.expected_output:JSON.stringify(e.expected_output,null,2):null;return a.jsxs("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:[a.jsx(_t,{title:"Input",copyText:t,children:a.jsx(ot,{json:t,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),e.expected_behavior&&a.jsx(_t,{title:"Expected Behavior",copyText:e.expected_behavior,children:a.jsx("div",{className:"px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap",style:{color:"var(--text-secondary)"},children:e.expected_behavior})}),n&&a.jsx(_t,{title:"Expected Output",copyText:n,children:a.jsx(ot,{json:n,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),e.simulation_instructions&&a.jsx(_t,{title:"Simulation Instructions",copyText:e.simulation_instructions,children:a.jsx("div",{className:"px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap",style:{color:"var(--text-secondary)"},children:e.simulation_instructions})})]})}function yu({item:e,evaluators:t}){return a.jsx("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:e.evaluator_ids.length>0?a.jsx(a.Fragment,{children:e.evaluator_ids.map(n=>{var s;const r=t.find(o=>o.id===n),i=(s=e.evaluation_criterias)==null?void 0:s[n];return a.jsxs("div",{className:"overflow-hidden",style:{border:"1px solid var(--border)"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--text-primary)"},children:(r==null?void 0:r.name)??n}),a.jsx("span",{className:"ml-auto text-[10px]",style:{color:"var(--text-muted)"},children:i?"Custom criteria":"Default criteria"})]}),i&&a.jsx("pre",{className:"px-3 py-2 border-t text-[11px] font-mono overflow-x-auto max-h-32 whitespace-pre-wrap break-words",style:{borderColor:"var(--border)",color:"var(--text-secondary)"},children:JSON.stringify(i,null,2)})]},n)})}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:"No evaluators configured for this item"})})}function en(e){return e===null?"-":`${Math.round(e*100)}%`}function wt(e){if(e===null)return"var(--text-muted)";const t=e*100;return t>=80?"var(--success)":t>=50?"var(--warning)":"var(--error)"}function vu(e,t){if(!e)return"-";const n=new Date(e).getTime(),r=t?new Date(t).getTime():Date.now(),i=Math.round((r-n)/1e3);return i<60?`${i}s`:`${Math.floor(i/60)}m ${i%60}s`}function ro(e){return e.replace(/\s*Evaluator$/i,"")}const io={pending:{color:"var(--text-muted)",bg:"var(--bg-tertiary)",label:"Pending"},running:{color:"var(--info)",bg:"rgba(59,130,246,0.1)",label:"Running"},completed:{color:"var(--success)",bg:"rgba(34,197,94,0.1)",label:"Completed"},failed:{color:"var(--error)",bg:"rgba(239,68,68,0.1)",label:"Failed"}};function Eu({evalRunId:e,itemName:t}){const[n,r]=S.useState(null),[i,s]=S.useState(!0),{navigate:o}=st(),l=t??null,[u,c]=S.useState(220),d=S.useRef(null),p=S.useRef(!1),[m,f]=S.useState(()=>{const M=localStorage.getItem("evalSidebarWidth");return M?parseInt(M,10):320}),[h,x]=S.useState(!1),v=S.useRef(null);S.useEffect(()=>{localStorage.setItem("evalSidebarWidth",String(m))},[m]);const b=Ae(M=>M.evalRuns[e]),E=Ae(M=>M.evaluators);S.useEffect(()=>{s(!0),Ii(e).then(M=>{if(r(M),!t){const I=M.results.find(j=>j.status==="completed")??M.results[0];I&&o(`#/evals/runs/${e}/${encodeURIComponent(I.name)}`)}}).catch(console.error).finally(()=>s(!1))},[e]),S.useEffect(()=>{((b==null?void 0:b.status)==="completed"||(b==null?void 0:b.status)==="failed")&&Ii(e).then(r).catch(console.error)},[b==null?void 0:b.status,e]),S.useEffect(()=>{if(t||!(n!=null&&n.results))return;const M=n.results.find(I=>I.status==="completed")??n.results[0];M&&o(`#/evals/runs/${e}/${encodeURIComponent(M.name)}`)},[n==null?void 0:n.results]);const A=S.useCallback(M=>{M.preventDefault(),p.current=!0;const I="touches"in M?M.touches[0].clientY:M.clientY,j=u,_=R=>{if(!p.current)return;const W=d.current;if(!W)return;const $="touches"in R?R.touches[0].clientY:R.clientY,V=W.clientHeight-100,g=Math.max(80,Math.min(V,j+($-I)));c(g)},N=()=>{p.current=!1,document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",N),document.removeEventListener("touchmove",_),document.removeEventListener("touchend",N),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="row-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",_),document.addEventListener("mouseup",N),document.addEventListener("touchmove",_,{passive:!1}),document.addEventListener("touchend",N)},[u]),D=S.useCallback(M=>{M.preventDefault(),x(!0);const I="touches"in M?M.touches[0].clientX:M.clientX,j=m,_=R=>{const W=v.current;if(!W)return;const $="touches"in R?R.touches[0].clientX:R.clientX,V=W.clientWidth-300,g=Math.max(280,Math.min(V,j+(I-$)));f(g)},N=()=>{x(!1),document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",N),document.removeEventListener("touchmove",_),document.removeEventListener("touchend",N),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",_),document.addEventListener("mouseup",N),document.addEventListener("touchmove",_,{passive:!1}),document.addEventListener("touchend",N)},[m]);if(i)return a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-sm",children:"Loading..."});if(!n)return a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)]",children:"Eval run not found"});const L=b??n,T=io[L.status]??io.pending,B=L.status==="running",O=Object.keys(L.evaluator_scores??{}),k=n.results.find(M=>M.name===l)??null,w=((k==null?void 0:k.traces)??[]).map(M=>({...M,run_id:""}));return a.jsxs("div",{ref:v,className:"flex h-full",children:[a.jsxs("div",{ref:d,className:"flex flex-col flex-1 min-w-0",children:[a.jsxs("div",{className:"px-4 h-10 border-b shrink-0 flex items-center gap-4",style:{borderColor:"var(--border)"},children:[a.jsx("h1",{className:"text-base font-semibold truncate min-w-0",style:{color:"var(--text-primary)"},children:L.eval_set_name}),a.jsx("span",{className:"px-2 py-0.5 rounded text-[11px] font-semibold uppercase tracking-wide",style:{color:T.color,background:T.bg},children:T.label}),a.jsx("span",{className:"text-sm font-bold font-mono",style:{color:wt(L.overall_score)},children:en(L.overall_score)}),a.jsx("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:vu(L.start_time,L.end_time)}),B&&a.jsxs("div",{className:"flex items-center gap-2 max-w-[160px]",children:[a.jsx("div",{className:"flex-1 h-2 rounded-full overflow-hidden",style:{background:"var(--bg-tertiary)"},children:a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${L.progress_total>0?L.progress_completed/L.progress_total*100:0}%`,background:"var(--info)"}})}),a.jsxs("span",{className:"text-[11px] shrink-0",style:{color:"var(--text-muted)"},children:[L.progress_completed,"/",L.progress_total]})]}),O.length>0&&a.jsx("div",{className:"flex gap-3 ml-auto",children:O.map(M=>{const I=E.find(_=>_.id===M),j=L.evaluator_scores[M];return a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:ro((I==null?void 0:I.name)??M)}),a.jsx("div",{className:"w-12 h-2 rounded-full overflow-hidden",style:{background:"var(--bg-tertiary)"},children:a.jsx("div",{className:"h-full rounded-full",style:{width:`${j*100}%`,background:wt(j)}})}),a.jsx("span",{className:"text-[11px] font-mono",style:{color:wt(j)},children:en(j)})]},M)})})]}),a.jsxs("div",{className:"shrink-0 overflow-hidden flex flex-col",style:{height:u},children:[a.jsxs("div",{className:"flex items-center px-3 h-7 text-[11px] font-semibold shrink-0 border-b",style:{color:"var(--text-muted)",background:"var(--bg-secondary)",borderColor:"var(--border)"},children:[a.jsx("span",{className:"w-5 shrink-0"}),a.jsx("span",{className:"flex-1 min-w-0",children:"Name"}),a.jsx("span",{className:"w-14 shrink-0 text-right",children:"Score"}),O.map(M=>{const I=E.find(j=>j.id===M);return a.jsx("span",{className:"w-36 shrink-0 text-right truncate pl-2",title:(I==null?void 0:I.name)??M,children:ro((I==null?void 0:I.name)??M)},M)}),a.jsx("span",{className:"w-14 shrink-0 text-right",children:"Time"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.results.map(M=>{const I=M.status==="pending",j=M.status==="failed",_=M.name===l;return a.jsxs("button",{onClick:()=>{o(_?`#/evals/runs/${e}`:`#/evals/runs/${e}/${encodeURIComponent(M.name)}`)},className:"w-full text-left px-3 py-1.5 flex items-center text-xs border-b transition-colors cursor-pointer",style:{borderColor:"var(--border)",background:_?"color-mix(in srgb, var(--accent) 10%, var(--bg-primary))":void 0,borderLeft:_?"2px solid var(--accent)":"2px solid transparent",opacity:I?.5:1},onMouseEnter:N=>{_||(N.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:N=>{_||(N.currentTarget.style.background="")},children:[a.jsx("span",{className:"w-5 shrink-0 flex justify-center",children:a.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:I?"var(--text-muted)":j?"var(--error)":M.overall_score>=.8?"var(--success)":M.overall_score>=.5?"var(--warning)":"var(--error)"}})}),a.jsx("span",{className:"flex-1 min-w-0 truncate",style:{color:"var(--text-primary)"},children:M.name}),a.jsx("span",{className:"w-14 shrink-0 text-right font-mono font-semibold",style:{color:wt(I?null:M.overall_score)},children:I?"-":en(M.overall_score)}),O.map(N=>a.jsx("span",{className:"w-36 shrink-0 text-right font-mono pl-2",style:{color:wt(I?null:M.scores[N]??null)},children:I?"-":en(M.scores[N]??null)},N)),a.jsx("span",{className:"w-14 shrink-0 text-right",style:{color:"var(--text-muted)"},children:M.duration_ms!==null?`${(M.duration_ms/1e3).toFixed(1)}s`:"-"})]},M.name)}),n.results.length===0&&a.jsx("div",{className:"flex items-center justify-center py-8 text-[var(--text-muted)] text-xs",children:B?"Waiting for results...":"No results"})]})]}),a.jsx("div",{onMouseDown:A,onTouchStart:A,className:"shrink-0 drag-handle-row"}),a.jsx("div",{className:"flex-1 overflow-hidden",children:k&&w.length>0?a.jsx(Ir,{traces:w}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:(k==null?void 0:k.status)==="pending"?"Pending...":"No traces available"})})]}),a.jsx("div",{onMouseDown:D,onTouchStart:D,className:`shrink-0 drag-handle-col${h?"":" transition-all"}`,style:{width:k?3:0,opacity:k?1:0}}),a.jsx(wu,{width:m,item:k,evaluators:E,isRunning:B,isDragging:h})]})}const ku=[{id:"score",label:"Score"},{id:"io",label:"I/O"},{id:"logs",label:"Logs"}];function wu({width:e,item:t,evaluators:n,isRunning:r,isDragging:i}){const[s,o]=S.useState("score"),l=!!t;return a.jsxs("div",{className:`shrink-0 flex flex-col overflow-hidden${i?"":" transition-[width] duration-200 ease-in-out"}`,style:{width:l?e:0,background:"var(--bg-primary)"},children:[a.jsxs("div",{className:"flex items-center gap-1 px-2 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",minWidth:e},children:[ku.map(u=>a.jsx("button",{onClick:()=>o(u.id),className:"px-2.5 py-1 h-7 text-xs font-semibold rounded transition-colors cursor-pointer",style:{color:s===u.id?"var(--accent)":"var(--text-muted)",background:s===u.id?"color-mix(in srgb, var(--accent) 10%, transparent)":"transparent",border:"none"},onMouseEnter:c=>{s!==u.id&&(c.currentTarget.style.color="var(--text-primary)")},onMouseLeave:c=>{s!==u.id&&(c.currentTarget.style.color="var(--text-muted)")},children:u.label},u.id)),r&&a.jsx("span",{className:"ml-auto text-[11px] px-2 py-0.5 rounded-full shrink-0",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--warning)"},children:"Running..."})]}),a.jsx("div",{className:"flex-1 overflow-y-auto",style:{minWidth:e},children:t?t.status==="pending"?a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:"Pending..."}):a.jsxs(a.Fragment,{children:[t.status==="failed"&&a.jsxs("div",{className:"mx-2 mt-2 px-3 py-2 rounded text-xs",style:{background:"rgba(239,68,68,0.1)",color:"var(--error)"},children:[a.jsxs("div",{className:"flex items-center gap-2 font-semibold",children:[a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:[a.jsx("circle",{cx:"8",cy:"8",r:"7",stroke:"currentColor",strokeWidth:"1.5"}),a.jsx("path",{d:"M8 4.5v4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),a.jsx("circle",{cx:"8",cy:"11",r:"0.75",fill:"currentColor"})]}),a.jsx("span",{children:"Evaluator error"})]}),t.error&&a.jsx("div",{className:"mt-1 pl-[22px] text-[11px] opacity-80 break-words",style:{color:"var(--text-secondary)"},children:t.error})]}),s==="score"?a.jsx(_u,{item:t,evaluators:n}):s==="io"?a.jsx(Nu,{item:t}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:"Logs coming soon"})]}):null})]})}function _u({item:e,evaluators:t}){const n=Object.keys(e.scores);return a.jsxs("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:[a.jsx("div",{className:"overflow-hidden",style:{border:"1px solid var(--border)"},children:a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"truncate text-[11px] font-semibold",style:{color:"var(--text-primary)"},children:"Overall"}),a.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[a.jsx("div",{className:"w-24 h-2.5 rounded-full overflow-hidden",style:{background:"var(--bg-tertiary)"},children:a.jsx("div",{className:"h-full rounded-full",style:{width:`${e.overall_score*100}%`,background:wt(e.overall_score)}})}),a.jsx("span",{className:"text-xs font-mono font-bold shrink-0 w-10 text-right",style:{color:wt(e.overall_score)},children:en(e.overall_score)})]})]})}),e.status==="failed"&&n.length===0&&a.jsx("div",{className:"px-3 py-3 text-xs text-center",style:{color:"var(--text-muted)"},children:"All evaluators failed — no scores available"}),n.map(r=>{const i=t.find(l=>l.id===r),s=e.scores[r],o=e.justifications[r];return a.jsxs("div",{className:"overflow-hidden",style:{border:"1px solid var(--border)"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"var(--bg-secondary)"},children:[a.jsx("span",{className:"truncate text-[11px] font-semibold",style:{color:"var(--text-primary)"},title:(i==null?void 0:i.name)??r,children:(i==null?void 0:i.name)??r}),a.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[a.jsx("div",{className:"w-24 h-2.5 rounded-full overflow-hidden",style:{background:"var(--bg-tertiary)"},children:a.jsx("div",{className:"h-full rounded-full",style:{width:`${s*100}%`,background:wt(s)}})}),a.jsx("span",{className:"text-xs font-mono font-bold shrink-0 w-10 text-right",style:{color:wt(s)},children:en(s)})]})]}),o&&a.jsx(Tu,{text:o})]},r)})]})}function Nu({item:e}){const t=JSON.stringify(e.inputs,null,2),n=typeof e.output=="string"?e.output:JSON.stringify(e.output,null,2),r=e.expected_output!=null?typeof e.expected_output=="string"?e.expected_output:JSON.stringify(e.expected_output,null,2):null;return a.jsxs("div",{className:"p-2 overflow-y-auto h-full space-y-1.5",children:[a.jsx(_t,{title:"Input",copyText:t,children:a.jsx(ot,{json:t,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),r&&a.jsx(_t,{title:"Expected Output",copyText:r,children:a.jsx(ot,{json:r,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})}),a.jsx(_t,{title:"Output",copyText:n,trailing:e.duration_ms!==null?a.jsxs("span",{className:"ml-auto text-[10px]",style:{color:"var(--text-muted)"},children:[(e.duration_ms/1e3).toFixed(2),"s"]}):void 0,children:a.jsx(ot,{json:n,className:"px-3 py-2 text-xs font-mono whitespace-pre-wrap break-words"})})]})}function Su(e){var i;const t=e.match(/expected="(.+?)"\s+actual="(.+?)"(.*)/s);if(!t)return null;const n={},r=((i=t[3])==null?void 0:i.trim())??"";if(r)for(const s of r.match(/(\w+)=([\S]+)/g)??[]){const o=s.indexOf("=");n[s.slice(0,o)]=s.slice(o+1)}return{expected:t[1],actual:t[2],meta:n}}function oo(e){try{const t=e.replace(/'/g,'"').replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null"),n=JSON.parse(t);return JSON.stringify(n,null,2)}catch{return e}}function Tu({text:e}){const t=Su(e);if(!t)return a.jsx("div",{className:"px-3 py-2 border-t",style:{borderColor:"var(--border)"},children:a.jsx("div",{className:"text-xs leading-relaxed",style:{color:"var(--text-secondary)"},children:e})});const n=oo(t.expected),r=oo(t.actual),i=n===r;return a.jsxs("div",{className:"border-t",style:{borderColor:"var(--border)"},children:[a.jsxs("div",{className:"grid grid-cols-2 gap-0",children:[a.jsxs("div",{className:"px-3 py-2 border-r",style:{borderColor:"var(--border)"},children:[a.jsx("div",{className:"text-[10px] font-semibold mb-1",style:{color:"var(--text-muted)"},children:"Expected"}),a.jsx("pre",{className:"text-[11px] font-mono whitespace-pre-wrap break-words",style:{color:"var(--text-secondary)"},children:n})]}),a.jsxs("div",{className:"px-3 py-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[a.jsx("span",{className:"text-[10px] font-semibold",style:{color:"var(--text-muted)"},children:"Actual"}),a.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:i?"var(--success)":"var(--error)"}})]}),a.jsx("pre",{className:"text-[11px] font-mono whitespace-pre-wrap break-words",style:{color:i?"var(--success)":"var(--error)"},children:r})]})]}),Object.keys(t.meta).length>0&&a.jsx("div",{className:"px-3 py-1.5 border-t flex items-center gap-3",style:{borderColor:"var(--border)"},children:Object.entries(t.meta).map(([s,o])=>a.jsxs("span",{className:"text-[10px]",style:{color:"var(--text-muted)"},children:[a.jsx("span",{className:"font-medium",children:s.replace(/_/g," ")})," ",a.jsx("span",{className:"font-mono",children:o})]},s))})]})}const so={deterministic:"var(--success)",llm:"#a78bfa",tool:"var(--info)"};function ao(){const e=Ae(f=>f.localEvaluators),t=Ae(f=>f.addEvalSet),{navigate:n}=st(),[r,i]=S.useState(""),[s,o]=S.useState(new Set),[l,u]=S.useState(null),[c,d]=S.useState(!1),p=f=>{o(h=>{const x=new Set(h);return x.has(f)?x.delete(f):x.add(f),x})},m=async()=>{if(r.trim()){u(null),d(!0);try{const f=await lc({name:r.trim(),evaluator_refs:Array.from(s)});t(f),n(`#/evals/sets/${f.id}`)}catch(f){u(f.detail||f.message||"Failed to create eval set")}finally{d(!1)}}};return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"w-full max-w-xl px-6",children:[a.jsxs("div",{className:"mb-8 text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2",children:[a.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{background:"var(--accent)"}}),a.jsx("span",{className:"text-sm font-semibold",style:{color:"var(--text-muted)"},children:"New Eval Set"})]}),a.jsx("p",{className:"text-sm",style:{color:"var(--text-muted)"},children:"Create an evaluation set with a name and evaluators"})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Name"}),a.jsx("input",{type:"text",value:r,onChange:f=>i(f.target.value),placeholder:"e.g. Basic QA Tests",className:"w-full rounded-md px-3 py-2 text-xs",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"},onKeyDown:f=>{f.key==="Enter"&&r.trim()&&m()}})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Evaluators"}),e.length===0?a.jsxs("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:["No evaluators configured."," ",a.jsx("button",{onClick:()=>n("#/evaluators/new"),className:"underline cursor-pointer",style:{color:"var(--accent)",background:"none",border:"none",padding:0,font:"inherit"},children:"Create one first"})]}):a.jsx("div",{className:"rounded-md border overflow-hidden",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:e.map(f=>a.jsxs("label",{className:"flex items-center gap-2.5 px-3 py-2 text-xs cursor-pointer transition-colors",style:{borderBottom:"1px solid var(--border)"},onMouseEnter:h=>{h.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:h=>{h.currentTarget.style.background="transparent"},children:[a.jsx("input",{type:"checkbox",checked:s.has(f.id),onChange:()=>p(f.id),className:"accent-[var(--accent)]"}),a.jsx("span",{className:"flex-1 truncate",style:{color:"var(--text-primary)"},children:f.name}),a.jsx("span",{className:"text-[11px] font-medium px-1.5 py-0.5 rounded",style:{background:`color-mix(in srgb, ${so[f.type]??"var(--text-muted)"} 15%, transparent)`,color:so[f.type]??"var(--text-muted)"},children:f.type})]},f.id))})]}),l&&a.jsx("p",{className:"text-xs mb-4 px-3 py-2 rounded",style:{color:"var(--error)",background:"color-mix(in srgb, var(--error) 10%, var(--bg-secondary))"},children:l}),a.jsx("button",{onClick:m,disabled:!r.trim()||c,className:"w-full py-2 rounded-md text-[13px] font-semibold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--accent)",color:"var(--bg-primary)",border:"none"},children:c?"Creating...":"Create Eval Set"})]})})}const Cu=[{type:"deterministic",label:"Deterministic",badgeColor:"var(--success)"},{type:"llm",label:"LLM Judge",badgeColor:"#a78bfa"},{type:"tool",label:"Tool-Based",badgeColor:"var(--info)"}];function lo(){const e=Ae(s=>s.localEvaluators),{evaluatorFilter:t,evaluatorCreateType:n,navigate:r}=st(),i=!t&&!n;return a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("#/evaluators/new"),className:"mx-3 mt-2.5 mb-1 px-3 py-1.5 text-[11px] font-medium rounded border border-[var(--border)] bg-transparent transition-colors cursor-pointer",style:{color:"var(--text-secondary)"},onMouseEnter:s=>{s.currentTarget.style.color="var(--text-primary)",s.currentTarget.style.borderColor="var(--text-muted)"},onMouseLeave:s=>{s.currentTarget.style.color="var(--text-secondary)",s.currentTarget.style.borderColor=""},children:"+ New Evaluator"}),a.jsx("div",{className:"px-3 pt-3 pb-1 text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"Categories"}),a.jsxs("div",{className:"flex-1 overflow-y-auto",children:[a.jsxs("button",{onClick:()=>r("#/evaluators"),className:"w-full text-left px-3 py-2 text-xs flex items-center gap-2 cursor-pointer transition-colors",style:{background:i?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:i?"var(--text-primary)":"var(--text-secondary)",borderLeft:i?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:s=>{i||(s.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:s=>{i||(s.currentTarget.style.background="transparent")},children:[a.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:"var(--text-muted)"}}),a.jsx("span",{className:"flex-1 truncate",children:"All"}),e.length>0&&a.jsx("span",{className:"text-[10px] px-1.5 rounded-full",style:{background:"var(--bg-tertiary)",color:"var(--text-muted)"},children:e.length})]}),Cu.map(s=>{const o=e.filter(u=>u.type===s.type).length,l=t===s.type;return a.jsxs("button",{onClick:()=>r(l?"#/evaluators":`#/evaluators/category/${s.type}`),className:"w-full text-left px-3 py-2 text-xs flex items-center gap-2 cursor-pointer transition-colors",style:{background:l?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:l?"var(--text-primary)":"var(--text-secondary)",borderLeft:l?"3px solid var(--accent)":"3px solid transparent"},onMouseEnter:u=>{l||(u.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:u=>{l||(u.currentTarget.style.background="transparent")},children:[a.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:s.badgeColor}}),a.jsx("span",{className:"flex-1 truncate",children:s.label}),o>0&&a.jsx("span",{className:"text-[10px] px-1.5 rounded-full",style:{background:"var(--bg-tertiary)",color:"var(--text-muted)"},children:o})]},s.type)})]})]})}const co={deterministic:{label:"Deterministic",color:"var(--success)",bg:"rgba(34,197,94,0.1)"},llm:{label:"LLM Judge",color:"#a78bfa",bg:"rgba(167,139,250,0.1)"},tool:{label:"Tool-Based",color:"var(--info)",bg:"rgba(59,130,246,0.1)"}},Or={deterministic:"Deterministic",llm:"LLM Judge",tool:"Tool-Based"},pn={deterministic:[{id:"uipath-exact-match",name:"Exact Match"},{id:"uipath-contains",name:"Contains"},{id:"uipath-json-similarity",name:"JSON Similarity"}],llm:[{id:"uipath-llm-judge-output-semantic-similarity",name:"LLM Judge Output"},{id:"uipath-llm-judge-output-strict-json-similarity",name:"LLM Judge Strict JSON"},{id:"uipath-llm-judge-trajectory-similarity",name:"LLM Judge Trajectory"},{id:"uipath-llm-judge-trajectory-simulation",name:"LLM Judge Trajectory Simulation"}],tool:[{id:"uipath-tool-call-order",name:"Tool Call Order"},{id:"uipath-tool-call-args",name:"Tool Call Args"},{id:"uipath-tool-call-count",name:"Tool Call Count"},{id:"uipath-tool-call-output",name:"Tool Call Output"}]};function Is(e){return e.includes("trajectory")?{targetOutputKey:!1,prompt:!0}:e.includes("llm-judge")?{targetOutputKey:!0,prompt:!0}:e.includes("tool-call-output")?{targetOutputKey:!0,prompt:!1}:e.includes("exact-match")||e.includes("contains")||e.includes("json-similarity")?{targetOutputKey:!0,prompt:!1}:{targetOutputKey:!1,prompt:!1}}const ur={"uipath-exact-match":{description:"Checks whether the agent output exactly matches the expected output.",prompt:""},"uipath-contains":{description:"Checks whether the agent output contains the expected substring.",prompt:""},"uipath-json-similarity":{description:"Compares JSON structures for semantic similarity, ignoring key ordering and whitespace.",prompt:""},"uipath-llm-judge-output-semantic-similarity":{description:"Uses an LLM to score semantic similarity between the agent's actual output and the expected output, accounting for synonyms, paraphrases, and equivalent expressions.",prompt:`As an expert evaluator, analyze the semantic similarity between the expected and actual outputs and determine a score from 0 to 100. Focus on comparing meaning and contextual equivalence of corresponding fields, accounting for alternative valid expressions, synonyms, and reasonable variations in language while maintaining high standards for accuracy and completeness. Provide your score with a brief justification. ---- ExpectedOutput: {{ExpectedOutput}} @@ -68,27 +68,27 @@ ExpectedAgentBehavior: {{ExpectedAgentBehavior}} ---- AgentRunHistory: -{{AgentRunHistory}}`},"uipath-tool-call-order":{description:"Validates that the agent called tools in the expected sequence.",prompt:""},"uipath-tool-call-args":{description:"Checks whether the agent called tools with the expected arguments.",prompt:""},"uipath-tool-call-count":{description:"Validates that the agent made the expected number of tool calls.",prompt:""},"uipath-tool-call-output":{description:"Validates the output returned by the agent's tool calls.",prompt:""}};function Au(e){for(const[t,n]of Object.entries(pn))if(n.some(r=>r.id===e))return t;return"deterministic"}function Mu({evaluatorId:e,evaluatorFilter:t}){const n=Ae(k=>k.localEvaluators),r=Ae(k=>k.setLocalEvaluators),i=Ae(k=>k.upsertLocalEvaluator),s=Ae(k=>k.evaluators),{navigate:o}=ot(),l=e?n.find(k=>k.id===e)??null:null,u=!!l,c=t?n.filter(k=>k.type===t):n,[d,p]=S.useState(()=>{const k=localStorage.getItem("evaluatorSidebarWidth");return k?parseInt(k,10):320}),[m,f]=S.useState(!1),g=S.useRef(null);S.useEffect(()=>{localStorage.setItem("evaluatorSidebarWidth",String(d))},[d]),S.useEffect(()=>{Zr().then(r).catch(console.error)},[r]);const x=S.useCallback(k=>{k.preventDefault(),f(!0);const A="touches"in k?k.touches[0].clientX:k.clientX,j=d,L=B=>{const O=g.current;if(!O)return;const E="touches"in B?B.touches[0].clientX:B.clientX,w=O.clientWidth-300,M=Math.max(280,Math.min(w,j+(A-E)));p(M)},T=()=>{f(!1),document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",T),document.removeEventListener("touchmove",L),document.removeEventListener("touchend",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",T),document.addEventListener("touchmove",L,{passive:!1}),document.addEventListener("touchend",T)},[d]),y=k=>{i(k)},b=()=>{o("#/evaluators")};return a.jsxs("div",{ref:g,className:"flex h-full",children:[a.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[a.jsxs("div",{className:"px-4 h-10 border-b shrink-0 flex items-center gap-4",style:{borderColor:"var(--border)"},children:[a.jsx("h1",{className:"text-base font-semibold",style:{color:"var(--text-primary)"},children:"Evaluators"}),a.jsxs("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:[c.length,t?` / ${n.length}`:""," configured"]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:c.length===0?a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:n.length===0?"No evaluators configured yet.":"No evaluators in this category."}):a.jsx("div",{className:"grid gap-3",style:{gridTemplateColumns:"repeat(auto-fill, minmax(320px, 1fr))"},children:c.map(k=>a.jsx(Ru,{evaluator:k,evaluators:s,selected:k.id===e,onClick:()=>o(k.id===e?"#/evaluators":`#/evaluators/${encodeURIComponent(k.id)}`)},k.id))})})]}),a.jsx("div",{onMouseDown:x,onTouchStart:x,className:`shrink-0 drag-handle-col${m?"":" transition-all"}`,style:{width:u?3:0,opacity:u?1:0}}),a.jsxs("div",{className:`shrink-0 flex flex-col overflow-hidden${m?"":" transition-[width] duration-200 ease-in-out"}`,style:{width:u?d:0,background:"var(--bg-primary)"},children:[a.jsxs("div",{className:"flex items-center gap-1 px-2 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",minWidth:d},children:[a.jsx("span",{className:"px-2 py-0.5 h-7 text-xs font-semibold rounded inline-flex items-center",style:{color:"var(--accent)",background:"color-mix(in srgb, var(--accent) 10%, transparent)"},children:"Edit Evaluator"}),a.jsx("button",{onClick:b,"aria-label":"Close editor",className:"ml-auto w-7 h-7 flex items-center justify-center rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:k=>{k.currentTarget.style.color="var(--text-primary)"},onMouseLeave:k=>{k.currentTarget.style.color="var(--text-muted)"},children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),a.jsx("div",{className:"flex-1 overflow-hidden",style:{minWidth:d},children:l&&a.jsx(Iu,{evaluator:l,onUpdated:y})})]})]})}function Ru({evaluator:e,evaluators:t,selected:n,onClick:r}){const i=co[e.type]??co.deterministic,s=t.find(l=>l.id===e.evaluator_type_id),o=e.evaluator_type_id.startsWith("file://");return a.jsxs("div",{className:"rounded-md p-4 flex flex-col cursor-pointer transition-colors",style:{border:n?"1px solid var(--accent)":"1px solid var(--border)",background:n?"color-mix(in srgb, var(--accent) 5%, var(--card-bg))":"var(--card-bg)"},onClick:r,onMouseEnter:l=>{n||(l.currentTarget.style.borderColor="var(--text-muted)")},onMouseLeave:l=>{n||(l.currentTarget.style.borderColor="var(--border)")},children:[a.jsx("div",{className:"text-sm font-semibold",style:{color:"var(--text-primary)"},children:e.name}),e.description&&a.jsx("div",{className:"text-xs leading-relaxed mt-2",style:{color:"var(--text-secondary)"},children:e.description}),a.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-auto pt-3",children:[a.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-medium",style:{color:i.color,background:i.bg},children:["Category: ",i.label]}),a.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-medium",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:["Type: ",o?"Custom":(s==null?void 0:s.name)??e.evaluator_type_id]}),a.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-medium font-mono",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:["Target: ",e.target_output_key||"*"]})]})]})}function Iu({evaluator:e,onUpdated:t}){var L,T;const n=Au(e.evaluator_type_id),r=pn[n]??[],[i,s]=S.useState(e.description),[o,l]=S.useState(e.evaluator_type_id),[u,c]=S.useState(((L=e.config)==null?void 0:L.targetOutputKey)??"*"),[d,p]=S.useState(((T=e.config)==null?void 0:T.prompt)??""),[m,f]=S.useState(!1),[g,x]=S.useState(null),[y,b]=S.useState(!1);S.useEffect(()=>{var B,O;s(e.description),l(e.evaluator_type_id),c(((B=e.config)==null?void 0:B.targetOutputKey)??"*"),p(((O=e.config)==null?void 0:O.prompt)??""),x(null),b(!1)},[e.id]);const k=Is(o),A=async()=>{f(!0),x(null),b(!1);try{const B={};k.targetOutputKey&&(B.targetOutputKey=u),k.prompt&&d.trim()&&(B.prompt=d);const O=await gc(e.id,{description:i.trim(),evaluator_type_id:o,config:B});t(O),b(!0),setTimeout(()=>b(!1),2e3)}catch(B){const O=B==null?void 0:B.detail;x(O??"Failed to update evaluator")}finally{f(!1)}},j={background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)"};return a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"p-4 overflow-y-auto flex-1 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Name"}),a.jsx("div",{className:"px-3 py-2 rounded-lg text-xs",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:e.name})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Category"}),a.jsx("div",{className:"px-3 py-2 rounded-lg text-xs",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:Or[n]??n})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Type"}),a.jsx("select",{value:o,onChange:B=>l(B.target.value),className:"w-full px-3 py-2 rounded-lg text-xs outline-none cursor-pointer",style:j,children:r.map(B=>a.jsx("option",{value:B.id,children:B.name},B.id))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Description"}),a.jsx("textarea",{value:i,onChange:B=>s(B.target.value),placeholder:"What does this evaluator check?",rows:4,className:"w-full px-3 py-2 rounded-lg text-xs leading-relaxed outline-none resize-y",style:j})]}),k.targetOutputKey&&a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Target Output Key"}),a.jsx("input",{type:"text",value:u,onChange:B=>c(B.target.value),placeholder:"*",className:"w-full px-3 py-2 rounded-lg text-xs outline-none",style:j}),a.jsx("div",{className:"text-[11px] mt-0.5",style:{color:"var(--text-muted)"},children:"Use * for entire output or a specific key name"})]}),k.prompt&&a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Prompt"}),a.jsx("textarea",{value:d,onChange:B=>p(B.target.value),placeholder:"Evaluation prompt for the LLM judge...",rows:8,className:"w-full px-3 py-2 rounded-lg text-xs font-mono leading-relaxed outline-none resize-y",style:j})]})]}),a.jsxs("div",{className:"shrink-0 p-4 space-y-2",children:[g&&a.jsx("div",{className:"text-xs px-3 py-2 rounded-lg",style:{background:"rgba(239,68,68,0.1)",color:"var(--error)"},children:g}),y&&a.jsx("div",{className:"text-xs px-3 py-2 rounded-lg",style:{background:"rgba(34,197,94,0.1)",color:"var(--success)"},children:"Saved successfully"}),a.jsx("button",{onClick:A,disabled:m,className:"w-full py-2.5 text-xs font-semibold rounded-md border cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed transition-colors",style:{background:"transparent",borderColor:"var(--accent)",color:"var(--accent)"},onMouseEnter:B=>{B.currentTarget.style.background="color-mix(in srgb, var(--accent) 15%, transparent)"},onMouseLeave:B=>{B.currentTarget.style.background="transparent"},children:m?"Saving...":"Save Changes"})]})]})}const Ou=["deterministic","llm","tool"];function Lu({category:e}){var N;const t=Ae(_=>_.addLocalEvaluator),{navigate:n}=ot(),r=e!=="any",[i,s]=S.useState(r?e:"deterministic"),o=pn[i]??[],[l,u]=S.useState(""),[c,d]=S.useState(""),[p,m]=S.useState(((N=o[0])==null?void 0:N.id)??""),[f,g]=S.useState("*"),[x,y]=S.useState(""),[b,k]=S.useState(!1),[A,j]=S.useState(null),[L,T]=S.useState(!1),[B,O]=S.useState(!1);S.useEffect(()=>{var q;const _=r?e:"deterministic";s(_);const W=((q=(pn[_]??[])[0])==null?void 0:q.id)??"",$=ur[W];u(""),d(($==null?void 0:$.description)??""),m(W),g("*"),y(($==null?void 0:$.prompt)??""),j(null),T(!1),O(!1)},[e,r]);const E=_=>{var q;s(_);const W=((q=(pn[_]??[])[0])==null?void 0:q.id)??"",$=ur[W];m(W),L||d(($==null?void 0:$.description)??""),B||y(($==null?void 0:$.prompt)??"")},w=_=>{m(_);const R=ur[_];R&&(L||d(R.description),B||y(R.prompt))},M=Is(p),I=async()=>{if(!l.trim()){j("Name is required");return}k(!0),j(null);try{const _={};M.targetOutputKey&&(_.targetOutputKey=f),M.prompt&&x.trim()&&(_.prompt=x);const R=await mc({name:l.trim(),description:c.trim(),evaluator_type_id:p,config:_});t(R),n("#/evaluators")}catch(_){const R=_==null?void 0:_.detail;j(R??"Failed to create evaluator")}finally{k(!1)}},D={background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"};return a.jsx("div",{className:"h-full overflow-y-auto",children:a.jsx("div",{className:"flex items-center justify-center min-h-full py-8",children:a.jsxs("div",{className:"w-full max-w-xl px-6",children:[a.jsxs("div",{className:"mb-8 text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2",children:[a.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{background:"var(--accent)"}}),a.jsx("span",{className:"text-sm font-semibold",style:{color:"var(--text-muted)"},children:"New Evaluator"})]}),a.jsx("p",{className:"text-sm",style:{color:"var(--text-muted)"},children:"Create an evaluator to score agent outputs"})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Name"}),a.jsx("input",{type:"text",value:l,onChange:_=>u(_.target.value),placeholder:"e.g. MyEvaluator",className:"w-full rounded-md px-3 py-2 text-xs",style:D,onKeyDown:_=>{_.key==="Enter"&&l.trim()&&I()}})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Category"}),r?a.jsx("div",{className:"px-3 py-2 rounded-md text-xs",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:Or[i]??i}):a.jsx("select",{value:i,onChange:_=>E(_.target.value),className:"w-full rounded-md px-3 py-2 text-xs cursor-pointer appearance-auto",style:D,children:Ou.map(_=>a.jsx("option",{value:_,children:Or[_]},_))})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Type"}),a.jsx("select",{value:p,onChange:_=>w(_.target.value),className:"w-full rounded-md px-3 py-2 text-xs cursor-pointer appearance-auto",style:D,children:o.map(_=>a.jsx("option",{value:_.id,children:_.name},_.id))})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Description"}),a.jsx("textarea",{value:c,onChange:_=>{d(_.target.value),T(!0)},placeholder:"What does this evaluator check?",rows:3,className:"w-full rounded-md px-3 py-2 text-xs leading-relaxed resize-y",style:D})]}),M.targetOutputKey&&a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Target Output Key"}),a.jsx("input",{type:"text",value:f,onChange:_=>g(_.target.value),placeholder:"*",className:"w-full rounded-md px-3 py-2 text-xs",style:D}),a.jsx("div",{className:"text-xs mt-1",style:{color:"var(--text-muted)"},children:"Use * for entire output or a specific key name"})]}),M.prompt&&a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Prompt"}),a.jsx("textarea",{value:x,onChange:_=>{y(_.target.value),O(!0)},placeholder:"Evaluation prompt for the LLM judge...",rows:6,className:"w-full rounded-md px-3 py-2 text-xs font-mono leading-relaxed resize-y",style:D})]}),A&&a.jsx("p",{className:"text-xs mb-4 px-3 py-2 rounded",style:{color:"var(--error)",background:"color-mix(in srgb, var(--error) 10%, var(--bg-secondary))"},children:A}),a.jsx("button",{onClick:I,disabled:b||!l.trim(),className:"w-full py-2 rounded-md text-[13px] font-semibold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--accent)",color:"var(--bg-primary)",border:"none"},children:b?"Creating...":"Create Evaluator"})]})})})}function Os({path:e,name:t,type:n,depth:r}){const i=Me(b=>b.children[e]),s=Me(b=>!!b.expanded[e]),o=Me(b=>!!b.loadingDirs[e]),l=Me(b=>!!b.dirty[e]),u=Me(b=>b.selectedFile),{setChildren:c,toggleExpanded:d,setLoadingDir:p,openTab:m}=Me(),{navigate:f}=ot(),g=n==="directory",x=!g&&u===e,y=S.useCallback(()=>{g?(!i&&!o&&(p(e,!0),Yr(e).then(b=>c(e,b)).catch(console.error).finally(()=>p(e,!1))),d(e)):(m(e),f(`#/explorer/file/${encodeURIComponent(e)}`))},[g,i,o,e,c,d,p,m,f]);return a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:y,className:"w-full text-left flex items-center gap-1 py-[3px] text-[13px] cursor-pointer transition-colors group",style:{paddingLeft:`${12+r*16}px`,paddingRight:"8px",background:x?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:x?"var(--text-primary)":"var(--text-secondary)",border:"none"},onMouseEnter:b=>{x||(b.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:b=>{x||(b.currentTarget.style.background="transparent")},children:[a.jsx("span",{className:"w-3 shrink-0 flex items-center justify-center",style:{color:"var(--text-muted)"},children:g&&a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:s?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s"},children:a.jsx("path",{d:"M3 1.5L7 5L3 8.5z"})})}),a.jsx("span",{className:"shrink-0",style:{color:g?"var(--accent)":"var(--text-muted)"},children:g?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})}):a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),a.jsx("span",{className:"truncate flex-1",children:t}),l&&a.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:"var(--accent)"}}),o&&a.jsx("span",{className:"text-[10px] shrink-0",style:{color:"var(--text-muted)"},children:"..."})]}),g&&s&&i&&i.map(b=>a.jsx(Os,{path:b.path,name:b.name,type:b.type,depth:r+1},b.path))]})}function uo(){const e=Me(n=>n.children[""]),{setChildren:t}=Me();return S.useEffect(()=>{e||Yr("").then(n=>t("",n)).catch(console.error)},[e,t]),a.jsx("div",{className:"flex-1 overflow-y-auto py-1",children:e?e.map(n=>a.jsx(Os,{path:n.path,name:n.name,type:n.type,depth:0},n.path)):a.jsx("p",{className:"text-[11px] px-3 py-2",style:{color:"var(--text-muted)"},children:"Loading..."})})}const ju=e=>{e.editor.defineTheme("uipath-dark",{base:"vs-dark",inherit:!0,rules:[{token:"comment",foreground:"64748b",fontStyle:"italic"},{token:"keyword",foreground:"c084fc"},{token:"string",foreground:"86efac"},{token:"number",foreground:"fcd34d"},{token:"type",foreground:"7dd3fc"}],colors:{"editor.background":"#0f172a","editor.foreground":"#cbd5e1","editor.lineHighlightBackground":"#1e293b","editor.selectionBackground":"#334155","editor.inactiveSelectionBackground":"#263348","editorLineNumber.foreground":"#64748b","editorLineNumber.activeForeground":"#94a3b8","editorCursor.foreground":"#fa4616","editorIndentGuide.background":"#334155","editorIndentGuide.activeBackground":"#64748b","editorWidget.background":"#1e293b","editorWidget.border":"#334155","editorSuggestWidget.background":"#1e293b","editorSuggestWidget.border":"#334155","editorSuggestWidget.selectedBackground":"#263348","editorHoverWidget.background":"#1e293b","editorHoverWidget.border":"#334155","scrollbarSlider.background":"#33415580","scrollbarSlider.hoverBackground":"#33415599","scrollbarSlider.activeBackground":"#334155cc"}}),e.editor.defineTheme("uipath-light",{base:"vs",inherit:!0,rules:[{token:"comment",foreground:"94a3b8",fontStyle:"italic"},{token:"keyword",foreground:"7c3aed"},{token:"string",foreground:"16a34a"},{token:"number",foreground:"d97706"},{token:"type",foreground:"0284c7"}],colors:{"editor.background":"#f8fafc","editor.foreground":"#0f172a","editor.lineHighlightBackground":"#f1f5f9","editor.selectionBackground":"#e2e8f0","editor.inactiveSelectionBackground":"#f1f5f9","editorLineNumber.foreground":"#94a3b8","editorLineNumber.activeForeground":"#475569","editorCursor.foreground":"#fa4616","editorIndentGuide.background":"#e2e8f0","editorIndentGuide.activeBackground":"#94a3b8","editorWidget.background":"#ffffff","editorWidget.border":"#e2e8f0","editorSuggestWidget.background":"#ffffff","editorSuggestWidget.border":"#e2e8f0","editorSuggestWidget.selectedBackground":"#f1f5f9","editorHoverWidget.background":"#ffffff","editorHoverWidget.border":"#e2e8f0","scrollbarSlider.background":"#d1d5db80","scrollbarSlider.hoverBackground":"#d1d5db99","scrollbarSlider.activeBackground":"#d1d5dbcc"}})};function po(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Du(e){const t=e.replace(/\\/g,"/").split("/");return t[t.length-1]||e}function Pu(){const e=Me(E=>E.openTabs),n=Me(E=>E.selectedFile),r=Me(E=>n?E.fileCache[n]:void 0),i=Me(E=>n?!!E.dirty[n]:!1),s=Me(E=>n?E.buffers[n]:void 0),o=Me(E=>E.loadingFile),l=Me(E=>E.dirty),{setFileContent:u,updateBuffer:c,markClean:d,setLoadingFile:p,openTab:m,closeTab:f}=Me(),{navigate:g}=ot(),x=_s(E=>E.theme),y=S.useRef(null),{explorerFile:b}=ot();S.useEffect(()=>{b&&m(b)},[b,m]),S.useEffect(()=>{n&&(Me.getState().fileCache[n]||(p(!0),xs(n).then(E=>u(n,E)).catch(console.error).finally(()=>p(!1))))},[n,u,p]);const k=S.useCallback(()=>{if(!n)return;const E=Me.getState().fileCache[n],M=Me.getState().buffers[n]??(E==null?void 0:E.content);M!=null&&Vl(n,M).then(()=>{d(n),u(n,{...E,content:M})}).catch(console.error)},[n,d,u]);S.useEffect(()=>{const E=w=>{(w.ctrlKey||w.metaKey)&&w.key==="s"&&(w.preventDefault(),k())};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[k]);const A=E=>{y.current=E},j=S.useCallback(E=>{E!==void 0&&n&&c(n,E)},[n,c]),L=S.useCallback(E=>{m(E),g(`#/explorer/file/${encodeURIComponent(E)}`)},[m,g]),T=S.useCallback((E,w)=>{E.stopPropagation();const M=Me.getState(),I=M.openTabs.filter(D=>D!==w);if(f(w),M.selectedFile===w){const D=M.openTabs.indexOf(w),N=I[Math.min(D,I.length-1)];g(N?`#/explorer/file/${encodeURIComponent(N)}`:"#/explorer")}},[f,g]),B=S.useCallback((E,w)=>{E.button===1&&T(E,w)},[T]),O=e.length>0&&a.jsx("div",{className:"h-10 flex items-end overflow-x-auto shrink-0",style:{background:"var(--bg-secondary)",borderBottom:"1px solid var(--border)"},children:e.map(E=>{const w=E===n,M=!!l[E];return a.jsxs("button",{onClick:()=>L(E),onMouseDown:I=>B(I,E),className:"h-full flex items-center gap-1.5 px-3 text-[12px] shrink-0 cursor-pointer transition-colors relative",style:{background:w?"var(--bg-primary)":"transparent",color:w?"var(--text-primary)":"var(--text-secondary)",border:"none",borderBottom:w?"2px solid var(--accent)":"2px solid transparent",maxWidth:"180px"},onMouseEnter:I=>{w||(I.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:I=>{w||(I.currentTarget.style.background="transparent")},children:[a.jsx("span",{className:"truncate",children:Du(E)}),M?a.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:"var(--accent)"},title:"Unsaved changes"}):a.jsx("span",{className:"w-4 h-4 flex items-center justify-center rounded shrink-0 transition-colors",style:{color:"var(--text-muted)"},onClick:I=>T(I,E),onMouseEnter:I=>{I.currentTarget.style.background="var(--bg-hover)",I.currentTarget.style.color="var(--text-primary)"},onMouseLeave:I=>{I.currentTarget.style.background="transparent",I.currentTarget.style.color="var(--text-muted)"},children:a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:a.jsx("path",{d:"M8 8.707l3.646 3.647.708-.707L8.707 8l3.647-3.646-.707-.708L8 7.293 4.354 3.646l-.708.708L7.293 8l-3.647 3.646.708.708L8 8.707z"})})})]},E)})});return n?o&&!r?a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsx("div",{className:"flex-1 flex items-center justify-center",style:{color:"var(--text-muted)"},children:a.jsx("div",{className:"text-sm",children:"Loading file..."})})]}):!r&&!o?a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsx("div",{className:"flex-1 flex items-center justify-center",style:{color:"var(--text-muted)"},children:a.jsx("div",{className:"text-sm",children:"Failed to load file"})})]}):r?r.binary?a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsx("div",{className:"h-8 flex items-center px-3 gap-2 text-xs shrink-0 border-b",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:a.jsx("span",{style:{color:"var(--text-muted)"},children:po(r.size)})}),a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-3",style:{color:"var(--text-muted)"},children:[a.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("polyline",{points:"14 2 14 8 20 8"}),a.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]}),a.jsx("span",{className:"text-sm",children:"Binary file — preview not available"})]})]}):a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsxs("div",{className:"h-8 flex items-center px-3 gap-2 text-xs shrink-0 border-b",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[r.language&&a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px]",style:{background:"var(--bg-hover)",color:"var(--text-muted)"},children:r.language}),a.jsx("span",{style:{color:"var(--text-muted)"},children:po(r.size)}),a.jsx("div",{className:"flex-1"}),i&&a.jsx("span",{className:"text-[10px] font-medium",style:{color:"var(--accent)"},children:"Modified"}),a.jsx("button",{onClick:k,className:"px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors",style:{background:i?"var(--accent)":"var(--bg-hover)",color:i?"white":"var(--text-muted)",border:"none"},children:"Save"})]}),a.jsx("div",{className:"flex-1 overflow-hidden",children:a.jsx(Tl,{language:r.language??"plaintext",theme:x==="dark"?"uipath-dark":"uipath-light",value:s??r.content??"",onChange:j,beforeMount:ju,onMount:A,options:{minimap:{enabled:!1},fontSize:13,lineNumbersMinChars:4,scrollBeyondLastLine:!1,wordWrap:"on",automaticLayout:!0,tabSize:2,renderWhitespace:"selection"}},n)})]}):null:a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsx("div",{className:"flex-1 flex items-center justify-center",style:{color:"var(--text-muted)"},children:"Select a file to view"})]})}const Ls="/api";async function Bu(){const e=await fetch(`${Ls}/agent/models`);if(!e.ok){if(e.status===401)return[];throw new Error(`HTTP ${e.status}`)}return e.json()}async function Fu(){const e=await fetch(`${Ls}/agent/skills`);if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}function zu(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Uu=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,$u=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Hu={};function fo(e,t){return(Hu.jsx?$u:Uu).test(e)}const Wu=/[ \t\n\f\r]/g;function Ku(e){return typeof e=="object"?e.type==="text"?mo(e.value):!1:mo(e)}function mo(e){return e.replace(Wu,"")===""}class xn{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}xn.prototype.normal={};xn.prototype.property={};xn.prototype.space=void 0;function js(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new xn(n,r,t)}function Lr(e){return e.toLowerCase()}class Ye{constructor(t,n){this.attribute=n,this.property=t}}Ye.prototype.attribute="";Ye.prototype.booleanish=!1;Ye.prototype.boolean=!1;Ye.prototype.commaOrSpaceSeparated=!1;Ye.prototype.commaSeparated=!1;Ye.prototype.defined=!1;Ye.prototype.mustUseProperty=!1;Ye.prototype.number=!1;Ye.prototype.overloadedBoolean=!1;Ye.prototype.property="";Ye.prototype.spaceSeparated=!1;Ye.prototype.space=void 0;let Gu=0;const pe=Wt(),Pe=Wt(),jr=Wt(),G=Wt(),Ce=Wt(),tn=Wt(),Je=Wt();function Wt(){return 2**++Gu}const Dr=Object.freeze(Object.defineProperty({__proto__:null,boolean:pe,booleanish:Pe,commaOrSpaceSeparated:Je,commaSeparated:tn,number:G,overloadedBoolean:jr,spaceSeparated:Ce},Symbol.toStringTag,{value:"Module"})),dr=Object.keys(Dr);class Jr extends Ye{constructor(t,n,r,i){let s=-1;if(super(t,n),ho(this,"space",i),typeof r=="number")for(;++s4&&n.slice(0,4)==="data"&&Zu.test(t)){if(t.charAt(4)==="-"){const s=t.slice(5).replace(go,ed);r="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=t.slice(4);if(!go.test(s)){let o=s.replace(Xu,Qu);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}i=Jr}return new i(r,t)}function Qu(e){return"-"+e.toLowerCase()}function ed(e){return e.charAt(1).toUpperCase()}const td=js([Ds,qu,Fs,zs,Us],"html"),Qr=js([Ds,Vu,Fs,zs,Us],"svg");function nd(e){return e.join(" ").trim()}var Yt={},pr,bo;function rd(){if(bo)return pr;bo=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,l=/^\s+|\s+$/g,u=` -`,c="/",d="*",p="",m="comment",f="declaration";function g(y,b){if(typeof y!="string")throw new TypeError("First argument must be a string");if(!y)return[];b=b||{};var k=1,A=1;function j(N){var _=N.match(t);_&&(k+=_.length);var R=N.lastIndexOf(u);A=~R?N.length-R:A+N.length}function L(){var N={line:k,column:A};return function(_){return _.position=new T(N),E(),_}}function T(N){this.start=N,this.end={line:k,column:A},this.source=b.source}T.prototype.content=y;function B(N){var _=new Error(b.source+":"+k+":"+A+": "+N);if(_.reason=N,_.filename=b.source,_.line=k,_.column=A,_.source=y,!b.silent)throw _}function O(N){var _=N.exec(y);if(_){var R=_[0];return j(R),y=y.slice(R.length),_}}function E(){O(n)}function w(N){var _;for(N=N||[];_=M();)_!==!1&&N.push(_);return N}function M(){var N=L();if(!(c!=y.charAt(0)||d!=y.charAt(1))){for(var _=2;p!=y.charAt(_)&&(d!=y.charAt(_)||c!=y.charAt(_+1));)++_;if(_+=2,p===y.charAt(_-1))return B("End of comment missing");var R=y.slice(2,_-2);return A+=2,j(R),y=y.slice(_),A+=2,N({type:m,comment:R})}}function I(){var N=L(),_=O(r);if(_){if(M(),!O(i))return B("property missing ':'");var R=O(s),W=N({type:f,property:x(_[0].replace(e,p)),value:R?x(R[0].replace(e,p)):p});return O(o),W}}function D(){var N=[];w(N);for(var _;_=I();)_!==!1&&(N.push(_),w(N));return N}return E(),D()}function x(y){return y?y.replace(l,p):p}return pr=g,pr}var xo;function id(){if(xo)return Yt;xo=1;var e=Yt&&Yt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.default=n;const t=e(rd());function n(r,i){let s=null;if(!r||typeof r!="string")return s;const o=(0,t.default)(r),l=typeof i=="function";return o.forEach(u=>{if(u.type!=="declaration")return;const{property:c,value:d}=u;l?i(c,d,u):d&&(s=s||{},s[c]=d)}),s}return Yt}var an={},yo;function od(){if(yo)return an;yo=1,Object.defineProperty(an,"__esModule",{value:!0}),an.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,s=function(c){return!c||n.test(c)||e.test(c)},o=function(c,d){return d.toUpperCase()},l=function(c,d){return"".concat(d,"-")},u=function(c,d){return d===void 0&&(d={}),s(c)?c:(c=c.toLowerCase(),d.reactCompat?c=c.replace(i,l):c=c.replace(r,l),c.replace(t,o))};return an.camelCase=u,an}var ln,vo;function sd(){if(vo)return ln;vo=1;var e=ln&&ln.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(id()),n=od();function r(i,s){var o={};return!i||typeof i!="string"||(0,t.default)(i,function(l,u){l&&u&&(o[(0,n.camelCase)(l,s)]=u)}),o}return r.default=r,ln=r,ln}var ad=sd();const ld=Gr(ad),$s=Hs("end"),ei=Hs("start");function Hs(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function cd(e){const t=ei(e),n=$s(e);if(t&&n)return{start:t,end:n}}function fn(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Eo(e.position):"start"in e||"end"in e?Eo(e):"line"in e||"column"in e?Pr(e):""}function Pr(e){return ko(e&&e.line)+":"+ko(e&&e.column)}function Eo(e){return Pr(e&&e.start)+"-"+Pr(e&&e.end)}function ko(e){return e&&typeof e=="number"?e:1}class He extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",s={},o=!1;if(n&&("line"in n&&"column"in n?s={place:n}:"start"in n&&"end"in n?s={place:n}:"type"in n?s={ancestors:[n],place:n.position}:s={...n}),typeof t=="string"?i=t:!s.cause&&t&&(o=!0,i=t.message,s.cause=t),!s.ruleId&&!s.source&&typeof r=="string"){const u=r.indexOf(":");u===-1?s.ruleId=r:(s.source=r.slice(0,u),s.ruleId=r.slice(u+1))}if(!s.place&&s.ancestors&&s.ancestors){const u=s.ancestors[s.ancestors.length-1];u&&(s.place=u.position)}const l=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=l?l.line:void 0,this.name=fn(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=o&&s.cause&&typeof s.cause.stack=="string"?s.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}He.prototype.file="";He.prototype.name="";He.prototype.reason="";He.prototype.message="";He.prototype.stack="";He.prototype.column=void 0;He.prototype.line=void 0;He.prototype.ancestors=void 0;He.prototype.cause=void 0;He.prototype.fatal=void 0;He.prototype.place=void 0;He.prototype.ruleId=void 0;He.prototype.source=void 0;const ti={}.hasOwnProperty,ud=new Map,dd=/[A-Z]/g,pd=new Set(["table","tbody","thead","tfoot","tr"]),fd=new Set(["td","th"]),Ws="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function md(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=kd(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=Ed(n,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Qr:td,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},s=Ks(i,e,void 0);return s&&typeof s!="string"?s:i.create(e,i.Fragment,{children:s||void 0},void 0)}function Ks(e,t,n){if(t.type==="element")return hd(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return gd(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return xd(e,t,n);if(t.type==="mdxjsEsm")return bd(e,t);if(t.type==="root")return yd(e,t,n);if(t.type==="text")return vd(e,t)}function hd(e,t,n){const r=e.schema;let i=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=Qr,e.schema=i),e.ancestors.push(t);const s=qs(e,t.tagName,!1),o=wd(e,t);let l=ri(e,t);return pd.has(t.tagName)&&(l=l.filter(function(u){return typeof u=="string"?!Ku(u):!0})),Gs(e,o,s,t),ni(o,l),e.ancestors.pop(),e.schema=r,e.create(t,s,o,n)}function gd(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}gn(e,t.position)}function bd(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);gn(e,t.position)}function xd(e,t,n){const r=e.schema;let i=r;t.name==="svg"&&r.space==="html"&&(i=Qr,e.schema=i),e.ancestors.push(t);const s=t.name===null?e.Fragment:qs(e,t.name,!0),o=_d(e,t),l=ri(e,t);return Gs(e,o,s,t),ni(o,l),e.ancestors.pop(),e.schema=r,e.create(t,s,o,n)}function yd(e,t,n){const r={};return ni(r,ri(e,t)),e.create(t,e.Fragment,r,n)}function vd(e,t){return t.value}function Gs(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function ni(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Ed(e,t,n){return r;function r(i,s,o,l){const c=Array.isArray(o.children)?n:t;return l?c(s,o,l):c(s,o)}}function kd(e,t){return n;function n(r,i,s,o){const l=Array.isArray(s.children),u=ei(r);return t(i,s,o,l,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function wd(e,t){const n={};let r,i;for(i in t.properties)if(i!=="children"&&ti.call(t.properties,i)){const s=Nd(e,i,t.properties[i]);if(s){const[o,l]=s;e.tableCellAlignToStyle&&o==="align"&&typeof l=="string"&&fd.has(t.tagName)?r=l:n[o]=l}}if(r){const s=n.style||(n.style={});s[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function _d(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const s=r.data.estree.body[0];s.type;const o=s.expression;o.type;const l=o.properties[0];l.type,Object.assign(n,e.evaluater.evaluateExpression(l.argument))}else gn(e,t.position);else{const i=r.name;let s;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const l=r.value.data.estree.body[0];l.type,s=e.evaluater.evaluateExpression(l.expression)}else gn(e,t.position);else s=r.value===null?!0:r.value;n[i]=s}return n}function ri(e,t){const n=[];let r=-1;const i=e.passKeys?new Map:ud;for(;++ri?0:i+t:t=t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);s0?(Qe(e,e.length,0,t),e):t}const No={}.hasOwnProperty;function Ys(e){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function ut(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const qe=Dt(/[A-Za-z]/),$e=Dt(/[\dA-Za-z]/),Ld=Dt(/[#-'*+\--9=?A-Z^-~]/);function $n(e){return e!==null&&(e<32||e===127)}const Br=Dt(/\d/),jd=Dt(/[\dA-Fa-f]/),Dd=Dt(/[!-/:-@[-`{-~]/);function ie(e){return e!==null&&e<-2}function Ne(e){return e!==null&&(e<0||e===32)}function ge(e){return e===-2||e===-1||e===32}const Yn=Dt(new RegExp("\\p{P}|\\p{S}","u")),Ht=Dt(/\s/);function Dt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function on(e){const t=[];let n=-1,r=0,i=0;for(;++n55295&&s<57344){const l=e.charCodeAt(n+1);s<56320&&l>56319&&l<57344?(o=String.fromCharCode(s,l),i=1):o="�"}else o=String.fromCharCode(s);o&&(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,o=""),i&&(n+=i,i=0)}return t.join("")+e.slice(r)}function ve(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let s=0;return o;function o(u){return ge(u)?(e.enter(n),l(u)):t(u)}function l(u){return ge(u)&&s++o))return;const B=t.events.length;let O=B,E,w;for(;O--;)if(t.events[O][0]==="exit"&&t.events[O][1].type==="chunkFlow"){if(E){w=t.events[O][1].end;break}E=!0}for(b(r),T=B;TA;){const L=n[j];t.containerState=L[1],L[0].exit.call(t,e)}n.length=A}function k(){i.write([null]),s=void 0,i=void 0,t.containerState._closeFlow=void 0}}function Ud(e,t,n){return ve(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function nn(e){if(e===null||Ne(e)||Ht(e))return 1;if(Yn(e))return 2}function Xn(e,t,n){const r=[];let i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const p={...e[r][1].end},m={...e[n][1].start};To(p,-u),To(m,u),o={type:u>1?"strongSequence":"emphasisSequence",start:p,end:{...e[r][1].end}},l={type:u>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:m},s={type:u>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},i={type:u>1?"strong":"emphasis",start:{...o.start},end:{...l.end}},e[r][1].end={...o.start},e[n][1].start={...l.end},c=[],e[r][1].end.offset-e[r][1].start.offset&&(c=rt(c,[["enter",e[r][1],t],["exit",e[r][1],t]])),c=rt(c,[["enter",i,t],["enter",o,t],["exit",o,t],["enter",s,t]]),c=rt(c,Xn(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),c=rt(c,[["exit",s,t],["enter",l,t],["exit",l,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,c=rt(c,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,Qe(e,r-1,n-r+3,c),n=r+c.length-d-2;break}}for(n=-1;++n0&&ge(T)?ve(e,k,"linePrefix",s+1)(T):k(T)}function k(T){return T===null||ie(T)?e.check(Co,x,j)(T):(e.enter("codeFlowValue"),A(T))}function A(T){return T===null||ie(T)?(e.exit("codeFlowValue"),k(T)):(e.consume(T),A)}function j(T){return e.exit("codeFenced"),t(T)}function L(T,B,O){let E=0;return w;function w(_){return T.enter("lineEnding"),T.consume(_),T.exit("lineEnding"),M}function M(_){return T.enter("codeFencedFence"),ge(_)?ve(T,I,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):I(_)}function I(_){return _===l?(T.enter("codeFencedFenceSequence"),D(_)):O(_)}function D(_){return _===l?(E++,T.consume(_),D):E>=o?(T.exit("codeFencedFenceSequence"),ge(_)?ve(T,N,"whitespace")(_):N(_)):O(_)}function N(_){return _===null||ie(_)?(T.exit("codeFencedFence"),B(_)):O(_)}}}function Qd(e,t,n){const r=this;return i;function i(o){return o===null?n(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s)}function s(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}const mr={name:"codeIndented",tokenize:tp},ep={partial:!0,tokenize:np};function tp(e,t,n){const r=this;return i;function i(c){return e.enter("codeIndented"),ve(e,s,"linePrefix",5)(c)}function s(c){const d=r.events[r.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?o(c):n(c)}function o(c){return c===null?u(c):ie(c)?e.attempt(ep,o,u)(c):(e.enter("codeFlowValue"),l(c))}function l(c){return c===null||ie(c)?(e.exit("codeFlowValue"),o(c)):(e.consume(c),l)}function u(c){return e.exit("codeIndented"),t(c)}}function np(e,t,n){const r=this;return i;function i(o){return r.parser.lazy[r.now().line]?n(o):ie(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):ve(e,s,"linePrefix",5)(o)}function s(o){const l=r.events[r.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(o):ie(o)?i(o):n(o)}}const rp={name:"codeText",previous:op,resolve:ip,tokenize:sp};function ip(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const i=n||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&cn(this.left,r),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),cn(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),cn(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(o):e.interrupt(r.parser.constructs.flow,n,t)(o)}}function ta(e,t,n,r,i,s,o,l,u){const c=u||Number.POSITIVE_INFINITY;let d=0;return p;function p(b){return b===60?(e.enter(r),e.enter(i),e.enter(s),e.consume(b),e.exit(s),m):b===null||b===32||b===41||$n(b)?n(b):(e.enter(r),e.enter(o),e.enter(l),e.enter("chunkString",{contentType:"string"}),x(b))}function m(b){return b===62?(e.enter(s),e.consume(b),e.exit(s),e.exit(i),e.exit(r),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),f(b))}function f(b){return b===62?(e.exit("chunkString"),e.exit(l),m(b)):b===null||b===60||ie(b)?n(b):(e.consume(b),b===92?g:f)}function g(b){return b===60||b===62||b===92?(e.consume(b),f):f(b)}function x(b){return!d&&(b===null||b===41||Ne(b))?(e.exit("chunkString"),e.exit(l),e.exit(o),e.exit(r),t(b)):d999||f===null||f===91||f===93&&!u||f===94&&!l&&"_hiddenFootnoteSupport"in o.parser.constructs?n(f):f===93?(e.exit(s),e.enter(i),e.consume(f),e.exit(i),e.exit(r),t):ie(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),p(f))}function p(f){return f===null||f===91||f===93||ie(f)||l++>999?(e.exit("chunkString"),d(f)):(e.consume(f),u||(u=!ge(f)),f===92?m:p)}function m(f){return f===91||f===92||f===93?(e.consume(f),l++,p):p(f)}}function ra(e,t,n,r,i,s){let o;return l;function l(m){return m===34||m===39||m===40?(e.enter(r),e.enter(i),e.consume(m),e.exit(i),o=m===40?41:m,u):n(m)}function u(m){return m===o?(e.enter(i),e.consume(m),e.exit(i),e.exit(r),t):(e.enter(s),c(m))}function c(m){return m===o?(e.exit(s),u(o)):m===null?n(m):ie(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),ve(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===o||m===null||ie(m)?(e.exit("chunkString"),c(m)):(e.consume(m),m===92?p:d)}function p(m){return m===o||m===92?(e.consume(m),d):d(m)}}function mn(e,t){let n;return r;function r(i){return ie(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r):ge(i)?ve(e,r,n?"linePrefix":"lineSuffix")(i):t(i)}}const mp={name:"definition",tokenize:gp},hp={partial:!0,tokenize:bp};function gp(e,t,n){const r=this;let i;return s;function s(f){return e.enter("definition"),o(f)}function o(f){return na.call(r,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function l(f){return i=ut(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),u):n(f)}function u(f){return Ne(f)?mn(e,c)(f):c(f)}function c(f){return ta(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function d(f){return e.attempt(hp,p,p)(f)}function p(f){return ge(f)?ve(e,m,"whitespace")(f):m(f)}function m(f){return f===null||ie(f)?(e.exit("definition"),r.parser.defined.push(i),t(f)):n(f)}}function bp(e,t,n){return r;function r(l){return Ne(l)?mn(e,i)(l):n(l)}function i(l){return ra(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function s(l){return ge(l)?ve(e,o,"whitespace")(l):o(l)}function o(l){return l===null||ie(l)?t(l):n(l)}}const xp={name:"hardBreakEscape",tokenize:yp};function yp(e,t,n){return r;function r(s){return e.enter("hardBreakEscape"),e.consume(s),i}function i(s){return ie(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}const vp={name:"headingAtx",resolve:Ep,tokenize:kp};function Ep(e,t){let n=e.length-2,r=3,i,s;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},s={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},Qe(e,r,n-r+1,[["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t]])),e}function kp(e,t,n){let r=0;return i;function i(d){return e.enter("atxHeading"),s(d)}function s(d){return e.enter("atxHeadingSequence"),o(d)}function o(d){return d===35&&r++<6?(e.consume(d),o):d===null||Ne(d)?(e.exit("atxHeadingSequence"),l(d)):n(d)}function l(d){return d===35?(e.enter("atxHeadingSequence"),u(d)):d===null||ie(d)?(e.exit("atxHeading"),t(d)):ge(d)?ve(e,l,"whitespace")(d):(e.enter("atxHeadingText"),c(d))}function u(d){return d===35?(e.consume(d),u):(e.exit("atxHeadingSequence"),l(d))}function c(d){return d===null||d===35||Ne(d)?(e.exit("atxHeadingText"),l(d)):(e.consume(d),c)}}const wp=["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","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Mo=["pre","script","style","textarea"],_p={concrete:!0,name:"htmlFlow",resolveTo:Tp,tokenize:Cp},Np={partial:!0,tokenize:Mp},Sp={partial:!0,tokenize:Ap};function Tp(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Cp(e,t,n){const r=this;let i,s,o,l,u;return c;function c(v){return d(v)}function d(v){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(v),p}function p(v){return v===33?(e.consume(v),m):v===47?(e.consume(v),s=!0,x):v===63?(e.consume(v),i=3,r.interrupt?t:h):qe(v)?(e.consume(v),o=String.fromCharCode(v),y):n(v)}function m(v){return v===45?(e.consume(v),i=2,f):v===91?(e.consume(v),i=5,l=0,g):qe(v)?(e.consume(v),i=4,r.interrupt?t:h):n(v)}function f(v){return v===45?(e.consume(v),r.interrupt?t:h):n(v)}function g(v){const oe="CDATA[";return v===oe.charCodeAt(l++)?(e.consume(v),l===oe.length?r.interrupt?t:I:g):n(v)}function x(v){return qe(v)?(e.consume(v),o=String.fromCharCode(v),y):n(v)}function y(v){if(v===null||v===47||v===62||Ne(v)){const oe=v===47,ae=o.toLowerCase();return!oe&&!s&&Mo.includes(ae)?(i=1,r.interrupt?t(v):I(v)):wp.includes(o.toLowerCase())?(i=6,oe?(e.consume(v),b):r.interrupt?t(v):I(v)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(v):s?k(v):A(v))}return v===45||$e(v)?(e.consume(v),o+=String.fromCharCode(v),y):n(v)}function b(v){return v===62?(e.consume(v),r.interrupt?t:I):n(v)}function k(v){return ge(v)?(e.consume(v),k):w(v)}function A(v){return v===47?(e.consume(v),w):v===58||v===95||qe(v)?(e.consume(v),j):ge(v)?(e.consume(v),A):w(v)}function j(v){return v===45||v===46||v===58||v===95||$e(v)?(e.consume(v),j):L(v)}function L(v){return v===61?(e.consume(v),T):ge(v)?(e.consume(v),L):A(v)}function T(v){return v===null||v===60||v===61||v===62||v===96?n(v):v===34||v===39?(e.consume(v),u=v,B):ge(v)?(e.consume(v),T):O(v)}function B(v){return v===u?(e.consume(v),u=null,E):v===null||ie(v)?n(v):(e.consume(v),B)}function O(v){return v===null||v===34||v===39||v===47||v===60||v===61||v===62||v===96||Ne(v)?L(v):(e.consume(v),O)}function E(v){return v===47||v===62||ge(v)?A(v):n(v)}function w(v){return v===62?(e.consume(v),M):n(v)}function M(v){return v===null||ie(v)?I(v):ge(v)?(e.consume(v),M):n(v)}function I(v){return v===45&&i===2?(e.consume(v),R):v===60&&i===1?(e.consume(v),W):v===62&&i===4?(e.consume(v),F):v===63&&i===3?(e.consume(v),h):v===93&&i===5?(e.consume(v),q):ie(v)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Np,U,D)(v)):v===null||ie(v)?(e.exit("htmlFlowData"),D(v)):(e.consume(v),I)}function D(v){return e.check(Sp,N,U)(v)}function N(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),_}function _(v){return v===null||ie(v)?D(v):(e.enter("htmlFlowData"),I(v))}function R(v){return v===45?(e.consume(v),h):I(v)}function W(v){return v===47?(e.consume(v),o="",$):I(v)}function $(v){if(v===62){const oe=o.toLowerCase();return Mo.includes(oe)?(e.consume(v),F):I(v)}return qe(v)&&o.length<8?(e.consume(v),o+=String.fromCharCode(v),$):I(v)}function q(v){return v===93?(e.consume(v),h):I(v)}function h(v){return v===62?(e.consume(v),F):v===45&&i===2?(e.consume(v),h):I(v)}function F(v){return v===null||ie(v)?(e.exit("htmlFlowData"),U(v)):(e.consume(v),F)}function U(v){return e.exit("htmlFlow"),t(v)}}function Ap(e,t,n){const r=this;return i;function i(o){return ie(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s):n(o)}function s(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function Mp(e,t,n){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(yn,t,n)}}const Rp={name:"htmlText",tokenize:Ip};function Ip(e,t,n){const r=this;let i,s,o;return l;function l(h){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(h),u}function u(h){return h===33?(e.consume(h),c):h===47?(e.consume(h),L):h===63?(e.consume(h),A):qe(h)?(e.consume(h),O):n(h)}function c(h){return h===45?(e.consume(h),d):h===91?(e.consume(h),s=0,g):qe(h)?(e.consume(h),k):n(h)}function d(h){return h===45?(e.consume(h),f):n(h)}function p(h){return h===null?n(h):h===45?(e.consume(h),m):ie(h)?(o=p,W(h)):(e.consume(h),p)}function m(h){return h===45?(e.consume(h),f):p(h)}function f(h){return h===62?R(h):h===45?m(h):p(h)}function g(h){const F="CDATA[";return h===F.charCodeAt(s++)?(e.consume(h),s===F.length?x:g):n(h)}function x(h){return h===null?n(h):h===93?(e.consume(h),y):ie(h)?(o=x,W(h)):(e.consume(h),x)}function y(h){return h===93?(e.consume(h),b):x(h)}function b(h){return h===62?R(h):h===93?(e.consume(h),b):x(h)}function k(h){return h===null||h===62?R(h):ie(h)?(o=k,W(h)):(e.consume(h),k)}function A(h){return h===null?n(h):h===63?(e.consume(h),j):ie(h)?(o=A,W(h)):(e.consume(h),A)}function j(h){return h===62?R(h):A(h)}function L(h){return qe(h)?(e.consume(h),T):n(h)}function T(h){return h===45||$e(h)?(e.consume(h),T):B(h)}function B(h){return ie(h)?(o=B,W(h)):ge(h)?(e.consume(h),B):R(h)}function O(h){return h===45||$e(h)?(e.consume(h),O):h===47||h===62||Ne(h)?E(h):n(h)}function E(h){return h===47?(e.consume(h),R):h===58||h===95||qe(h)?(e.consume(h),w):ie(h)?(o=E,W(h)):ge(h)?(e.consume(h),E):R(h)}function w(h){return h===45||h===46||h===58||h===95||$e(h)?(e.consume(h),w):M(h)}function M(h){return h===61?(e.consume(h),I):ie(h)?(o=M,W(h)):ge(h)?(e.consume(h),M):E(h)}function I(h){return h===null||h===60||h===61||h===62||h===96?n(h):h===34||h===39?(e.consume(h),i=h,D):ie(h)?(o=I,W(h)):ge(h)?(e.consume(h),I):(e.consume(h),N)}function D(h){return h===i?(e.consume(h),i=void 0,_):h===null?n(h):ie(h)?(o=D,W(h)):(e.consume(h),D)}function N(h){return h===null||h===34||h===39||h===60||h===61||h===96?n(h):h===47||h===62||Ne(h)?E(h):(e.consume(h),N)}function _(h){return h===47||h===62||Ne(h)?E(h):n(h)}function R(h){return h===62?(e.consume(h),e.exit("htmlTextData"),e.exit("htmlText"),t):n(h)}function W(h){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),$}function $(h){return ge(h)?ve(e,q,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h):q(h)}function q(h){return e.enter("htmlTextData"),o(h)}}const si={name:"labelEnd",resolveAll:Dp,resolveTo:Pp,tokenize:Bp},Op={tokenize:Fp},Lp={tokenize:zp},jp={tokenize:Up};function Dp(e){let t=-1;const n=[];for(;++t=3&&(c===null||ie(c))?(e.exit("thematicBreak"),t(c)):n(c)}function u(c){return c===i?(e.consume(c),r++,u):(e.exit("thematicBreakSequence"),ge(c)?ve(e,l,"whitespace")(c):l(c))}}const Ve={continuation:{tokenize:Zp},exit:Qp,name:"list",tokenize:Xp},Vp={partial:!0,tokenize:ef},Yp={partial:!0,tokenize:Jp};function Xp(e,t,n){const r=this,i=r.events[r.events.length-1];let s=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,o=0;return l;function l(f){const g=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:Br(f)){if(r.containerState.type||(r.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Fn,n,c)(f):c(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(f)}return n(f)}function u(f){return Br(f)&&++o<10?(e.consume(f),u):(!r.interrupt||o<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),c(f)):n(f)}function c(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(yn,r.interrupt?n:d,e.attempt(Vp,m,p))}function d(f){return r.containerState.initialBlankLine=!0,s++,m(f)}function p(f){return ge(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),m):n(f)}function m(f){return r.containerState.size=s+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function Zp(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(yn,i,s);function i(l){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,ve(e,t,"listItemIndent",r.containerState.size+1)(l)}function s(l){return r.containerState.furtherBlankLines||!ge(l)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(l)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Yp,t,o)(l))}function o(l){return r.containerState._closeFlow=!0,r.interrupt=void 0,ve(e,e.attempt(Ve,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function Jp(e,t,n){const r=this;return ve(e,i,"listItemIndent",r.containerState.size+1);function i(s){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?t(s):n(s)}}function Qp(e){e.exit(this.containerState.type)}function ef(e,t,n){const r=this;return ve(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(s){const o=r.events[r.events.length-1];return!ge(s)&&o&&o[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}const Ro={name:"setextUnderline",resolveTo:tf,tokenize:nf};function tf(e,t){let n=e.length,r,i,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);const o={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",s?(e.splice(i,0,["enter",o,t]),e.splice(s+1,0,["exit",e[r][1],t]),e[r][1].end={...e[s][1].end}):e[r][1]=o,e.push(["exit",o,t]),e}function nf(e,t,n){const r=this;let i;return s;function s(c){let d=r.events.length,p;for(;d--;)if(r.events[d][1].type!=="lineEnding"&&r.events[d][1].type!=="linePrefix"&&r.events[d][1].type!=="content"){p=r.events[d][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||p)?(e.enter("setextHeadingLine"),i=c,o(c)):n(c)}function o(c){return e.enter("setextHeadingLineSequence"),l(c)}function l(c){return c===i?(e.consume(c),l):(e.exit("setextHeadingLineSequence"),ge(c)?ve(e,u,"lineSuffix")(c):u(c))}function u(c){return c===null||ie(c)?(e.exit("setextHeadingLine"),t(c)):n(c)}}const rf={tokenize:of};function of(e){const t=this,n=e.attempt(yn,r,e.attempt(this.parser.constructs.flowInitial,i,ve(e,e.attempt(this.parser.constructs.flow,i,e.attempt(cp,i)),"linePrefix")));return n;function r(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const sf={resolveAll:oa()},af=ia("string"),lf=ia("text");function ia(e){return{resolveAll:oa(e==="text"?cf:void 0),tokenize:t};function t(n){const r=this,i=this.parser.constructs[e],s=n.attempt(i,o,l);return o;function o(d){return c(d)?s(d):l(d)}function l(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),u}function u(d){return c(d)?(n.exit("data"),s(d)):(n.consume(d),u)}function c(d){if(d===null)return!0;const p=i[d];let m=-1;if(p)for(;++m-1){const l=o[0];typeof l=="string"?o[0]=l.slice(r):o.shift()}s>0&&o.push(e[i].slice(0,s))}return o}function kf(e,t){let n=-1;const r=[];let i;for(;++nr.id===e))return t;return"deterministic"}function Mu({evaluatorId:e,evaluatorFilter:t}){const n=Ae(E=>E.localEvaluators),r=Ae(E=>E.setLocalEvaluators),i=Ae(E=>E.upsertLocalEvaluator),s=Ae(E=>E.evaluators),{navigate:o}=st(),l=e?n.find(E=>E.id===e)??null:null,u=!!l,c=t?n.filter(E=>E.type===t):n,[d,p]=S.useState(()=>{const E=localStorage.getItem("evaluatorSidebarWidth");return E?parseInt(E,10):320}),[m,f]=S.useState(!1),h=S.useRef(null);S.useEffect(()=>{localStorage.setItem("evaluatorSidebarWidth",String(d))},[d]),S.useEffect(()=>{Zr().then(r).catch(console.error)},[r]);const x=S.useCallback(E=>{E.preventDefault(),f(!0);const A="touches"in E?E.touches[0].clientX:E.clientX,D=d,L=B=>{const O=h.current;if(!O)return;const k="touches"in B?B.touches[0].clientX:B.clientX,w=O.clientWidth-300,M=Math.max(280,Math.min(w,D+(A-k)));p(M)},T=()=>{f(!1),document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",T),document.removeEventListener("touchmove",L),document.removeEventListener("touchend",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",T),document.addEventListener("touchmove",L,{passive:!1}),document.addEventListener("touchend",T)},[d]),v=E=>{i(E)},b=()=>{o("#/evaluators")};return a.jsxs("div",{ref:h,className:"flex h-full",children:[a.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[a.jsxs("div",{className:"px-4 h-10 border-b shrink-0 flex items-center gap-4",style:{borderColor:"var(--border)"},children:[a.jsx("h1",{className:"text-base font-semibold",style:{color:"var(--text-primary)"},children:"Evaluators"}),a.jsxs("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:[c.length,t?` / ${n.length}`:""," configured"]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:c.length===0?a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)] text-xs",children:n.length===0?"No evaluators configured yet.":"No evaluators in this category."}):a.jsx("div",{className:"grid gap-3",style:{gridTemplateColumns:"repeat(auto-fill, minmax(320px, 1fr))"},children:c.map(E=>a.jsx(Ru,{evaluator:E,evaluators:s,selected:E.id===e,onClick:()=>o(E.id===e?"#/evaluators":`#/evaluators/${encodeURIComponent(E.id)}`)},E.id))})})]}),a.jsx("div",{onMouseDown:x,onTouchStart:x,className:`shrink-0 drag-handle-col${m?"":" transition-all"}`,style:{width:u?3:0,opacity:u?1:0}}),a.jsxs("div",{className:`shrink-0 flex flex-col overflow-hidden${m?"":" transition-[width] duration-200 ease-in-out"}`,style:{width:u?d:0,background:"var(--bg-primary)"},children:[a.jsxs("div",{className:"flex items-center gap-1 px-2 h-10 border-b shrink-0",style:{borderColor:"var(--border)",background:"var(--bg-secondary)",minWidth:d},children:[a.jsx("span",{className:"px-2 py-0.5 h-7 text-xs font-semibold rounded inline-flex items-center",style:{color:"var(--accent)",background:"color-mix(in srgb, var(--accent) 10%, transparent)"},children:"Edit Evaluator"}),a.jsx("button",{onClick:b,"aria-label":"Close editor",className:"ml-auto w-7 h-7 flex items-center justify-center rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)",background:"transparent",border:"none"},onMouseEnter:E=>{E.currentTarget.style.color="var(--text-primary)"},onMouseLeave:E=>{E.currentTarget.style.color="var(--text-muted)"},children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),a.jsx("div",{className:"flex-1 overflow-hidden",style:{minWidth:d},children:l&&a.jsx(Iu,{evaluator:l,onUpdated:v})})]})]})}function Ru({evaluator:e,evaluators:t,selected:n,onClick:r}){const i=co[e.type]??co.deterministic,s=t.find(l=>l.id===e.evaluator_type_id),o=e.evaluator_type_id.startsWith("file://");return a.jsxs("div",{className:"rounded-md p-4 flex flex-col cursor-pointer transition-colors",style:{border:n?"1px solid var(--accent)":"1px solid var(--border)",background:n?"color-mix(in srgb, var(--accent) 5%, var(--card-bg))":"var(--card-bg)"},onClick:r,onMouseEnter:l=>{n||(l.currentTarget.style.borderColor="var(--text-muted)")},onMouseLeave:l=>{n||(l.currentTarget.style.borderColor="var(--border)")},children:[a.jsx("div",{className:"text-sm font-semibold",style:{color:"var(--text-primary)"},children:e.name}),e.description&&a.jsx("div",{className:"text-xs leading-relaxed mt-2",style:{color:"var(--text-secondary)"},children:e.description}),a.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-auto pt-3",children:[a.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-medium",style:{color:i.color,background:i.bg},children:["Category: ",i.label]}),a.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-medium",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:["Type: ",o?"Custom":(s==null?void 0:s.name)??e.evaluator_type_id]}),a.jsxs("span",{className:"px-2 py-0.5 rounded text-[10px] font-medium font-mono",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:["Target: ",e.target_output_key||"*"]})]})]})}function Iu({evaluator:e,onUpdated:t}){var L,T;const n=Au(e.evaluator_type_id),r=pn[n]??[],[i,s]=S.useState(e.description),[o,l]=S.useState(e.evaluator_type_id),[u,c]=S.useState(((L=e.config)==null?void 0:L.targetOutputKey)??"*"),[d,p]=S.useState(((T=e.config)==null?void 0:T.prompt)??""),[m,f]=S.useState(!1),[h,x]=S.useState(null),[v,b]=S.useState(!1);S.useEffect(()=>{var B,O;s(e.description),l(e.evaluator_type_id),c(((B=e.config)==null?void 0:B.targetOutputKey)??"*"),p(((O=e.config)==null?void 0:O.prompt)??""),x(null),b(!1)},[e.id]);const E=Is(o),A=async()=>{f(!0),x(null),b(!1);try{const B={};E.targetOutputKey&&(B.targetOutputKey=u),E.prompt&&d.trim()&&(B.prompt=d);const O=await gc(e.id,{description:i.trim(),evaluator_type_id:o,config:B});t(O),b(!0),setTimeout(()=>b(!1),2e3)}catch(B){const O=B==null?void 0:B.detail;x(O??"Failed to update evaluator")}finally{f(!1)}},D={background:"var(--bg-secondary)",color:"var(--text-primary)",border:"1px solid var(--border)"};return a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"p-4 overflow-y-auto flex-1 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Name"}),a.jsx("div",{className:"px-3 py-2 rounded-lg text-xs",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:e.name})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Category"}),a.jsx("div",{className:"px-3 py-2 rounded-lg text-xs",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:Or[n]??n})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Type"}),a.jsx("select",{value:o,onChange:B=>l(B.target.value),className:"w-full px-3 py-2 rounded-lg text-xs outline-none cursor-pointer",style:D,children:r.map(B=>a.jsx("option",{value:B.id,children:B.name},B.id))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Description"}),a.jsx("textarea",{value:i,onChange:B=>s(B.target.value),placeholder:"What does this evaluator check?",rows:4,className:"w-full px-3 py-2 rounded-lg text-xs leading-relaxed outline-none resize-y",style:D})]}),E.targetOutputKey&&a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Target Output Key"}),a.jsx("input",{type:"text",value:u,onChange:B=>c(B.target.value),placeholder:"*",className:"w-full px-3 py-2 rounded-lg text-xs outline-none",style:D}),a.jsx("div",{className:"text-[11px] mt-0.5",style:{color:"var(--text-muted)"},children:"Use * for entire output or a specific key name"})]}),E.prompt&&a.jsxs("div",{children:[a.jsx("label",{className:"text-[11px] font-medium block mb-1",style:{color:"var(--text-muted)"},children:"Prompt"}),a.jsx("textarea",{value:d,onChange:B=>p(B.target.value),placeholder:"Evaluation prompt for the LLM judge...",rows:8,className:"w-full px-3 py-2 rounded-lg text-xs font-mono leading-relaxed outline-none resize-y",style:D})]})]}),a.jsxs("div",{className:"shrink-0 p-4 space-y-2",children:[h&&a.jsx("div",{className:"text-xs px-3 py-2 rounded-lg",style:{background:"rgba(239,68,68,0.1)",color:"var(--error)"},children:h}),v&&a.jsx("div",{className:"text-xs px-3 py-2 rounded-lg",style:{background:"rgba(34,197,94,0.1)",color:"var(--success)"},children:"Saved successfully"}),a.jsx("button",{onClick:A,disabled:m,className:"w-full py-2.5 text-xs font-semibold rounded-md border cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed transition-colors",style:{background:"transparent",borderColor:"var(--accent)",color:"var(--accent)"},onMouseEnter:B=>{B.currentTarget.style.background="color-mix(in srgb, var(--accent) 15%, transparent)"},onMouseLeave:B=>{B.currentTarget.style.background="transparent"},children:m?"Saving...":"Save Changes"})]})]})}const Ou=["deterministic","llm","tool"];function Lu({category:e}){var _;const t=Ae(N=>N.addLocalEvaluator),{navigate:n}=st(),r=e!=="any",[i,s]=S.useState(r?e:"deterministic"),o=pn[i]??[],[l,u]=S.useState(""),[c,d]=S.useState(""),[p,m]=S.useState(((_=o[0])==null?void 0:_.id)??""),[f,h]=S.useState("*"),[x,v]=S.useState(""),[b,E]=S.useState(!1),[A,D]=S.useState(null),[L,T]=S.useState(!1),[B,O]=S.useState(!1);S.useEffect(()=>{var V;const N=r?e:"deterministic";s(N);const W=((V=(pn[N]??[])[0])==null?void 0:V.id)??"",$=ur[W];u(""),d(($==null?void 0:$.description)??""),m(W),h("*"),v(($==null?void 0:$.prompt)??""),D(null),T(!1),O(!1)},[e,r]);const k=N=>{var V;s(N);const W=((V=(pn[N]??[])[0])==null?void 0:V.id)??"",$=ur[W];m(W),L||d(($==null?void 0:$.description)??""),B||v(($==null?void 0:$.prompt)??"")},w=N=>{m(N);const R=ur[N];R&&(L||d(R.description),B||v(R.prompt))},M=Is(p),I=async()=>{if(!l.trim()){D("Name is required");return}E(!0),D(null);try{const N={};M.targetOutputKey&&(N.targetOutputKey=f),M.prompt&&x.trim()&&(N.prompt=x);const R=await mc({name:l.trim(),description:c.trim(),evaluator_type_id:p,config:N});t(R),n("#/evaluators")}catch(N){const R=N==null?void 0:N.detail;D(R??"Failed to create evaluator")}finally{E(!1)}},j={background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"};return a.jsx("div",{className:"h-full overflow-y-auto",children:a.jsx("div",{className:"flex items-center justify-center min-h-full py-8",children:a.jsxs("div",{className:"w-full max-w-xl px-6",children:[a.jsxs("div",{className:"mb-8 text-center",children:[a.jsxs("div",{className:"flex items-center justify-center gap-2 mb-2",children:[a.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{background:"var(--accent)"}}),a.jsx("span",{className:"text-sm font-semibold",style:{color:"var(--text-muted)"},children:"New Evaluator"})]}),a.jsx("p",{className:"text-sm",style:{color:"var(--text-muted)"},children:"Create an evaluator to score agent outputs"})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Name"}),a.jsx("input",{type:"text",value:l,onChange:N=>u(N.target.value),placeholder:"e.g. MyEvaluator",className:"w-full rounded-md px-3 py-2 text-xs",style:j,onKeyDown:N=>{N.key==="Enter"&&l.trim()&&I()}})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Category"}),r?a.jsx("div",{className:"px-3 py-2 rounded-md text-xs",style:{background:"var(--bg-tertiary)",color:"var(--text-secondary)"},children:Or[i]??i}):a.jsx("select",{value:i,onChange:N=>k(N.target.value),className:"w-full rounded-md px-3 py-2 text-xs cursor-pointer appearance-auto",style:j,children:Ou.map(N=>a.jsx("option",{value:N,children:Or[N]},N))})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Type"}),a.jsx("select",{value:p,onChange:N=>w(N.target.value),className:"w-full rounded-md px-3 py-2 text-xs cursor-pointer appearance-auto",style:j,children:o.map(N=>a.jsx("option",{value:N.id,children:N.name},N.id))})]}),a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Description"}),a.jsx("textarea",{value:c,onChange:N=>{d(N.target.value),T(!0)},placeholder:"What does this evaluator check?",rows:3,className:"w-full rounded-md px-3 py-2 text-xs leading-relaxed resize-y",style:j})]}),M.targetOutputKey&&a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Target Output Key"}),a.jsx("input",{type:"text",value:f,onChange:N=>h(N.target.value),placeholder:"*",className:"w-full rounded-md px-3 py-2 text-xs",style:j}),a.jsx("div",{className:"text-xs mt-1",style:{color:"var(--text-muted)"},children:"Use * for entire output or a specific key name"})]}),M.prompt&&a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-[11px] font-medium mb-1.5",style:{color:"var(--text-muted)"},children:"Prompt"}),a.jsx("textarea",{value:x,onChange:N=>{v(N.target.value),O(!0)},placeholder:"Evaluation prompt for the LLM judge...",rows:6,className:"w-full rounded-md px-3 py-2 text-xs font-mono leading-relaxed resize-y",style:j})]}),A&&a.jsx("p",{className:"text-xs mb-4 px-3 py-2 rounded",style:{color:"var(--error)",background:"color-mix(in srgb, var(--error) 10%, var(--bg-secondary))"},children:A}),a.jsx("button",{onClick:I,disabled:b||!l.trim(),className:"w-full py-2 rounded-md text-[13px] font-semibold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--accent)",color:"var(--bg-primary)",border:"none"},children:b?"Creating...":"Create Evaluator"})]})})})}function Os({path:e,name:t,type:n,depth:r}){const i=Me(b=>b.children[e]),s=Me(b=>!!b.expanded[e]),o=Me(b=>!!b.loadingDirs[e]),l=Me(b=>!!b.dirty[e]),u=Me(b=>b.selectedFile),{setChildren:c,toggleExpanded:d,setLoadingDir:p,openTab:m}=Me(),{navigate:f}=st(),h=n==="directory",x=!h&&u===e,v=S.useCallback(()=>{h?(!i&&!o&&(p(e,!0),Yr(e).then(b=>c(e,b)).catch(console.error).finally(()=>p(e,!1))),d(e)):(m(e),f(`#/explorer/file/${encodeURIComponent(e)}`))},[h,i,o,e,c,d,p,m,f]);return a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:v,className:"w-full text-left flex items-center gap-1 py-[3px] text-[13px] cursor-pointer transition-colors group",style:{paddingLeft:`${12+r*16}px`,paddingRight:"8px",background:x?"color-mix(in srgb, var(--accent) 15%, var(--bg-primary))":"transparent",color:x?"var(--text-primary)":"var(--text-secondary)",border:"none"},onMouseEnter:b=>{x||(b.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:b=>{x||(b.currentTarget.style.background="transparent")},children:[a.jsx("span",{className:"w-3 shrink-0 flex items-center justify-center",style:{color:"var(--text-muted)"},children:h&&a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:s?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s"},children:a.jsx("path",{d:"M3 1.5L7 5L3 8.5z"})})}),a.jsx("span",{className:"shrink-0",style:{color:h?"var(--accent)":"var(--text-muted)"},children:h?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})}):a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),a.jsx("span",{className:"truncate flex-1",children:t}),l&&a.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:"var(--accent)"}}),o&&a.jsx("span",{className:"text-[10px] shrink-0",style:{color:"var(--text-muted)"},children:"..."})]}),h&&s&&i&&i.map(b=>a.jsx(Os,{path:b.path,name:b.name,type:b.type,depth:r+1},b.path))]})}function uo(){const e=Me(n=>n.children[""]),{setChildren:t}=Me();return S.useEffect(()=>{e||Yr("").then(n=>t("",n)).catch(console.error)},[e,t]),a.jsx("div",{className:"flex-1 overflow-y-auto py-1",children:e?e.map(n=>a.jsx(Os,{path:n.path,name:n.name,type:n.type,depth:0},n.path)):a.jsx("p",{className:"text-[11px] px-3 py-2",style:{color:"var(--text-muted)"},children:"Loading..."})})}const ju=e=>{e.editor.defineTheme("uipath-dark",{base:"vs-dark",inherit:!0,rules:[{token:"comment",foreground:"64748b",fontStyle:"italic"},{token:"keyword",foreground:"c084fc"},{token:"string",foreground:"86efac"},{token:"number",foreground:"fcd34d"},{token:"type",foreground:"7dd3fc"}],colors:{"editor.background":"#0f172a","editor.foreground":"#cbd5e1","editor.lineHighlightBackground":"#1e293b","editor.selectionBackground":"#334155","editor.inactiveSelectionBackground":"#263348","editorLineNumber.foreground":"#64748b","editorLineNumber.activeForeground":"#94a3b8","editorCursor.foreground":"#fa4616","editorIndentGuide.background":"#334155","editorIndentGuide.activeBackground":"#64748b","editorWidget.background":"#1e293b","editorWidget.border":"#334155","editorSuggestWidget.background":"#1e293b","editorSuggestWidget.border":"#334155","editorSuggestWidget.selectedBackground":"#263348","editorHoverWidget.background":"#1e293b","editorHoverWidget.border":"#334155","scrollbarSlider.background":"#33415580","scrollbarSlider.hoverBackground":"#33415599","scrollbarSlider.activeBackground":"#334155cc"}}),e.editor.defineTheme("uipath-light",{base:"vs",inherit:!0,rules:[{token:"comment",foreground:"94a3b8",fontStyle:"italic"},{token:"keyword",foreground:"7c3aed"},{token:"string",foreground:"16a34a"},{token:"number",foreground:"d97706"},{token:"type",foreground:"0284c7"}],colors:{"editor.background":"#f8fafc","editor.foreground":"#0f172a","editor.lineHighlightBackground":"#f1f5f9","editor.selectionBackground":"#e2e8f0","editor.inactiveSelectionBackground":"#f1f5f9","editorLineNumber.foreground":"#94a3b8","editorLineNumber.activeForeground":"#475569","editorCursor.foreground":"#fa4616","editorIndentGuide.background":"#e2e8f0","editorIndentGuide.activeBackground":"#94a3b8","editorWidget.background":"#ffffff","editorWidget.border":"#e2e8f0","editorSuggestWidget.background":"#ffffff","editorSuggestWidget.border":"#e2e8f0","editorSuggestWidget.selectedBackground":"#f1f5f9","editorHoverWidget.background":"#ffffff","editorHoverWidget.border":"#e2e8f0","scrollbarSlider.background":"#d1d5db80","scrollbarSlider.hoverBackground":"#d1d5db99","scrollbarSlider.activeBackground":"#d1d5dbcc"}})};function po(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Du(e){const t=e.replace(/\\/g,"/").split("/");return t[t.length-1]||e}function Pu(){const e=Me(k=>k.openTabs),n=Me(k=>k.selectedFile),r=Me(k=>n?k.fileCache[n]:void 0),i=Me(k=>n?!!k.dirty[n]:!1),s=Me(k=>n?k.buffers[n]:void 0),o=Me(k=>k.loadingFile),l=Me(k=>k.dirty),{setFileContent:u,updateBuffer:c,markClean:d,setLoadingFile:p,openTab:m,closeTab:f}=Me(),{navigate:h}=st(),x=_s(k=>k.theme),v=S.useRef(null),{explorerFile:b}=st();S.useEffect(()=>{b&&m(b)},[b,m]),S.useEffect(()=>{n&&(Me.getState().fileCache[n]||(p(!0),xs(n).then(k=>u(n,k)).catch(console.error).finally(()=>p(!1))))},[n,u,p]);const E=S.useCallback(()=>{if(!n)return;const k=Me.getState().fileCache[n],M=Me.getState().buffers[n]??(k==null?void 0:k.content);M!=null&&Vl(n,M).then(()=>{d(n),u(n,{...k,content:M})}).catch(console.error)},[n,d,u]);S.useEffect(()=>{const k=w=>{(w.ctrlKey||w.metaKey)&&w.key==="s"&&(w.preventDefault(),E())};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[E]);const A=k=>{v.current=k},D=S.useCallback(k=>{k!==void 0&&n&&c(n,k)},[n,c]),L=S.useCallback(k=>{m(k),h(`#/explorer/file/${encodeURIComponent(k)}`)},[m,h]),T=S.useCallback((k,w)=>{k.stopPropagation();const M=Me.getState(),I=M.openTabs.filter(j=>j!==w);if(f(w),M.selectedFile===w){const j=M.openTabs.indexOf(w),_=I[Math.min(j,I.length-1)];h(_?`#/explorer/file/${encodeURIComponent(_)}`:"#/explorer")}},[f,h]),B=S.useCallback((k,w)=>{k.button===1&&T(k,w)},[T]),O=e.length>0&&a.jsx("div",{className:"h-10 flex items-end overflow-x-auto shrink-0",style:{background:"var(--bg-secondary)",borderBottom:"1px solid var(--border)"},children:e.map(k=>{const w=k===n,M=!!l[k];return a.jsxs("button",{onClick:()=>L(k),onMouseDown:I=>B(I,k),className:"h-full flex items-center gap-1.5 px-3 text-[12px] shrink-0 cursor-pointer transition-colors relative",style:{background:w?"var(--bg-primary)":"transparent",color:w?"var(--text-primary)":"var(--text-secondary)",border:"none",borderBottom:w?"2px solid var(--accent)":"2px solid transparent",maxWidth:"180px"},onMouseEnter:I=>{w||(I.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:I=>{w||(I.currentTarget.style.background="transparent")},children:[a.jsx("span",{className:"truncate",children:Du(k)}),M?a.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{background:"var(--accent)"},title:"Unsaved changes"}):a.jsx("span",{className:"w-4 h-4 flex items-center justify-center rounded shrink-0 transition-colors",style:{color:"var(--text-muted)"},onClick:I=>T(I,k),onMouseEnter:I=>{I.currentTarget.style.background="var(--bg-hover)",I.currentTarget.style.color="var(--text-primary)"},onMouseLeave:I=>{I.currentTarget.style.background="transparent",I.currentTarget.style.color="var(--text-muted)"},children:a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:a.jsx("path",{d:"M8 8.707l3.646 3.647.708-.707L8.707 8l3.647-3.646-.707-.708L8 7.293 4.354 3.646l-.708.708L7.293 8l-3.647 3.646.708.708L8 8.707z"})})})]},k)})});return n?o&&!r?a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsx("div",{className:"flex-1 flex items-center justify-center",style:{color:"var(--text-muted)"},children:a.jsx("div",{className:"text-sm",children:"Loading file..."})})]}):!r&&!o?a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsx("div",{className:"flex-1 flex items-center justify-center",style:{color:"var(--text-muted)"},children:a.jsx("div",{className:"text-sm",children:"Failed to load file"})})]}):r?r.binary?a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsx("div",{className:"h-8 flex items-center px-3 gap-2 text-xs shrink-0 border-b",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:a.jsx("span",{style:{color:"var(--text-muted)"},children:po(r.size)})}),a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-3",style:{color:"var(--text-muted)"},children:[a.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("polyline",{points:"14 2 14 8 20 8"}),a.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]}),a.jsx("span",{className:"text-sm",children:"Binary file — preview not available"})]})]}):a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsxs("div",{className:"h-8 flex items-center px-3 gap-2 text-xs shrink-0 border-b",style:{borderColor:"var(--border)",background:"var(--bg-secondary)"},children:[r.language&&a.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px]",style:{background:"var(--bg-hover)",color:"var(--text-muted)"},children:r.language}),a.jsx("span",{style:{color:"var(--text-muted)"},children:po(r.size)}),a.jsx("div",{className:"flex-1"}),i&&a.jsx("span",{className:"text-[10px] font-medium",style:{color:"var(--accent)"},children:"Modified"}),a.jsx("button",{onClick:E,className:"px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors",style:{background:i?"var(--accent)":"var(--bg-hover)",color:i?"white":"var(--text-muted)",border:"none"},children:"Save"})]}),a.jsx("div",{className:"flex-1 overflow-hidden",children:a.jsx(Tl,{language:r.language??"plaintext",theme:x==="dark"?"uipath-dark":"uipath-light",value:s??r.content??"",onChange:D,beforeMount:ju,onMount:A,options:{minimap:{enabled:!1},fontSize:13,lineNumbersMinChars:4,scrollBeyondLastLine:!1,wordWrap:"on",automaticLayout:!0,tabSize:2,renderWhitespace:"selection"}},n)})]}):null:a.jsxs("div",{className:"flex flex-col h-full",children:[O,a.jsx("div",{className:"flex-1 flex items-center justify-center",style:{color:"var(--text-muted)"},children:"Select a file to view"})]})}const Ls="/api";async function Bu(){const e=await fetch(`${Ls}/agent/models`);if(!e.ok){if(e.status===401)return[];throw new Error(`HTTP ${e.status}`)}return e.json()}async function Fu(){const e=await fetch(`${Ls}/agent/skills`);if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}function zu(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const Uu=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,$u=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Hu={};function fo(e,t){return(Hu.jsx?$u:Uu).test(e)}const Wu=/[ \t\n\f\r]/g;function Ku(e){return typeof e=="object"?e.type==="text"?mo(e.value):!1:mo(e)}function mo(e){return e.replace(Wu,"")===""}class xn{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}xn.prototype.normal={};xn.prototype.property={};xn.prototype.space=void 0;function js(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new xn(n,r,t)}function Lr(e){return e.toLowerCase()}class Ye{constructor(t,n){this.attribute=n,this.property=t}}Ye.prototype.attribute="";Ye.prototype.booleanish=!1;Ye.prototype.boolean=!1;Ye.prototype.commaOrSpaceSeparated=!1;Ye.prototype.commaSeparated=!1;Ye.prototype.defined=!1;Ye.prototype.mustUseProperty=!1;Ye.prototype.number=!1;Ye.prototype.overloadedBoolean=!1;Ye.prototype.property="";Ye.prototype.spaceSeparated=!1;Ye.prototype.space=void 0;let Gu=0;const pe=Kt(),Pe=Kt(),jr=Kt(),G=Kt(),Ce=Kt(),tn=Kt(),Je=Kt();function Kt(){return 2**++Gu}const Dr=Object.freeze(Object.defineProperty({__proto__:null,boolean:pe,booleanish:Pe,commaOrSpaceSeparated:Je,commaSeparated:tn,number:G,overloadedBoolean:jr,spaceSeparated:Ce},Symbol.toStringTag,{value:"Module"})),dr=Object.keys(Dr);class Jr extends Ye{constructor(t,n,r,i){let s=-1;if(super(t,n),ho(this,"space",i),typeof r=="number")for(;++s4&&n.slice(0,4)==="data"&&Zu.test(t)){if(t.charAt(4)==="-"){const s=t.slice(5).replace(go,ed);r="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=t.slice(4);if(!go.test(s)){let o=s.replace(Xu,Qu);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}i=Jr}return new i(r,t)}function Qu(e){return"-"+e.toLowerCase()}function ed(e){return e.charAt(1).toUpperCase()}const td=js([Ds,qu,Fs,zs,Us],"html"),Qr=js([Ds,Vu,Fs,zs,Us],"svg");function nd(e){return e.join(" ").trim()}var Yt={},pr,bo;function rd(){if(bo)return pr;bo=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,l=/^\s+|\s+$/g,u=` +`,c="/",d="*",p="",m="comment",f="declaration";function h(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var E=1,A=1;function D(_){var N=_.match(t);N&&(E+=N.length);var R=_.lastIndexOf(u);A=~R?_.length-R:A+_.length}function L(){var _={line:E,column:A};return function(N){return N.position=new T(_),k(),N}}function T(_){this.start=_,this.end={line:E,column:A},this.source=b.source}T.prototype.content=v;function B(_){var N=new Error(b.source+":"+E+":"+A+": "+_);if(N.reason=_,N.filename=b.source,N.line=E,N.column=A,N.source=v,!b.silent)throw N}function O(_){var N=_.exec(v);if(N){var R=N[0];return D(R),v=v.slice(R.length),N}}function k(){O(n)}function w(_){var N;for(_=_||[];N=M();)N!==!1&&_.push(N);return _}function M(){var _=L();if(!(c!=v.charAt(0)||d!=v.charAt(1))){for(var N=2;p!=v.charAt(N)&&(d!=v.charAt(N)||c!=v.charAt(N+1));)++N;if(N+=2,p===v.charAt(N-1))return B("End of comment missing");var R=v.slice(2,N-2);return A+=2,D(R),v=v.slice(N),A+=2,_({type:m,comment:R})}}function I(){var _=L(),N=O(r);if(N){if(M(),!O(i))return B("property missing ':'");var R=O(s),W=_({type:f,property:x(N[0].replace(e,p)),value:R?x(R[0].replace(e,p)):p});return O(o),W}}function j(){var _=[];w(_);for(var N;N=I();)N!==!1&&(_.push(N),w(_));return _}return k(),j()}function x(v){return v?v.replace(l,p):p}return pr=h,pr}var xo;function id(){if(xo)return Yt;xo=1;var e=Yt&&Yt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.default=n;const t=e(rd());function n(r,i){let s=null;if(!r||typeof r!="string")return s;const o=(0,t.default)(r),l=typeof i=="function";return o.forEach(u=>{if(u.type!=="declaration")return;const{property:c,value:d}=u;l?i(c,d,u):d&&(s=s||{},s[c]=d)}),s}return Yt}var an={},yo;function od(){if(yo)return an;yo=1,Object.defineProperty(an,"__esModule",{value:!0}),an.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,s=function(c){return!c||n.test(c)||e.test(c)},o=function(c,d){return d.toUpperCase()},l=function(c,d){return"".concat(d,"-")},u=function(c,d){return d===void 0&&(d={}),s(c)?c:(c=c.toLowerCase(),d.reactCompat?c=c.replace(i,l):c=c.replace(r,l),c.replace(t,o))};return an.camelCase=u,an}var ln,vo;function sd(){if(vo)return ln;vo=1;var e=ln&&ln.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(id()),n=od();function r(i,s){var o={};return!i||typeof i!="string"||(0,t.default)(i,function(l,u){l&&u&&(o[(0,n.camelCase)(l,s)]=u)}),o}return r.default=r,ln=r,ln}var ad=sd();const ld=Gr(ad),$s=Hs("end"),ei=Hs("start");function Hs(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function cd(e){const t=ei(e),n=$s(e);if(t&&n)return{start:t,end:n}}function fn(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Eo(e.position):"start"in e||"end"in e?Eo(e):"line"in e||"column"in e?Pr(e):""}function Pr(e){return ko(e&&e.line)+":"+ko(e&&e.column)}function Eo(e){return Pr(e&&e.start)+"-"+Pr(e&&e.end)}function ko(e){return e&&typeof e=="number"?e:1}class He extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",s={},o=!1;if(n&&("line"in n&&"column"in n?s={place:n}:"start"in n&&"end"in n?s={place:n}:"type"in n?s={ancestors:[n],place:n.position}:s={...n}),typeof t=="string"?i=t:!s.cause&&t&&(o=!0,i=t.message,s.cause=t),!s.ruleId&&!s.source&&typeof r=="string"){const u=r.indexOf(":");u===-1?s.ruleId=r:(s.source=r.slice(0,u),s.ruleId=r.slice(u+1))}if(!s.place&&s.ancestors&&s.ancestors){const u=s.ancestors[s.ancestors.length-1];u&&(s.place=u.position)}const l=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=l?l.line:void 0,this.name=fn(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=o&&s.cause&&typeof s.cause.stack=="string"?s.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}He.prototype.file="";He.prototype.name="";He.prototype.reason="";He.prototype.message="";He.prototype.stack="";He.prototype.column=void 0;He.prototype.line=void 0;He.prototype.ancestors=void 0;He.prototype.cause=void 0;He.prototype.fatal=void 0;He.prototype.place=void 0;He.prototype.ruleId=void 0;He.prototype.source=void 0;const ti={}.hasOwnProperty,ud=new Map,dd=/[A-Z]/g,pd=new Set(["table","tbody","thead","tfoot","tr"]),fd=new Set(["td","th"]),Ws="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function md(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=kd(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=Ed(n,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Qr:td,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},s=Ks(i,e,void 0);return s&&typeof s!="string"?s:i.create(e,i.Fragment,{children:s||void 0},void 0)}function Ks(e,t,n){if(t.type==="element")return hd(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return gd(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return xd(e,t,n);if(t.type==="mdxjsEsm")return bd(e,t);if(t.type==="root")return yd(e,t,n);if(t.type==="text")return vd(e,t)}function hd(e,t,n){const r=e.schema;let i=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=Qr,e.schema=i),e.ancestors.push(t);const s=qs(e,t.tagName,!1),o=wd(e,t);let l=ri(e,t);return pd.has(t.tagName)&&(l=l.filter(function(u){return typeof u=="string"?!Ku(u):!0})),Gs(e,o,s,t),ni(o,l),e.ancestors.pop(),e.schema=r,e.create(t,s,o,n)}function gd(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}gn(e,t.position)}function bd(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);gn(e,t.position)}function xd(e,t,n){const r=e.schema;let i=r;t.name==="svg"&&r.space==="html"&&(i=Qr,e.schema=i),e.ancestors.push(t);const s=t.name===null?e.Fragment:qs(e,t.name,!0),o=_d(e,t),l=ri(e,t);return Gs(e,o,s,t),ni(o,l),e.ancestors.pop(),e.schema=r,e.create(t,s,o,n)}function yd(e,t,n){const r={};return ni(r,ri(e,t)),e.create(t,e.Fragment,r,n)}function vd(e,t){return t.value}function Gs(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function ni(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Ed(e,t,n){return r;function r(i,s,o,l){const c=Array.isArray(o.children)?n:t;return l?c(s,o,l):c(s,o)}}function kd(e,t){return n;function n(r,i,s,o){const l=Array.isArray(s.children),u=ei(r);return t(i,s,o,l,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function wd(e,t){const n={};let r,i;for(i in t.properties)if(i!=="children"&&ti.call(t.properties,i)){const s=Nd(e,i,t.properties[i]);if(s){const[o,l]=s;e.tableCellAlignToStyle&&o==="align"&&typeof l=="string"&&fd.has(t.tagName)?r=l:n[o]=l}}if(r){const s=n.style||(n.style={});s[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function _d(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const s=r.data.estree.body[0];s.type;const o=s.expression;o.type;const l=o.properties[0];l.type,Object.assign(n,e.evaluater.evaluateExpression(l.argument))}else gn(e,t.position);else{const i=r.name;let s;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const l=r.value.data.estree.body[0];l.type,s=e.evaluater.evaluateExpression(l.expression)}else gn(e,t.position);else s=r.value===null?!0:r.value;n[i]=s}return n}function ri(e,t){const n=[];let r=-1;const i=e.passKeys?new Map:ud;for(;++ri?0:i+t:t=t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);s0?(Qe(e,e.length,0,t),e):t}const No={}.hasOwnProperty;function Ys(e){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function dt(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const qe=Dt(/[A-Za-z]/),$e=Dt(/[\dA-Za-z]/),Ld=Dt(/[#-'*+\--9=?A-Z^-~]/);function $n(e){return e!==null&&(e<32||e===127)}const Br=Dt(/\d/),jd=Dt(/[\dA-Fa-f]/),Dd=Dt(/[!-/:-@[-`{-~]/);function oe(e){return e!==null&&e<-2}function Ne(e){return e!==null&&(e<0||e===32)}function ge(e){return e===-2||e===-1||e===32}const Yn=Dt(new RegExp("\\p{P}|\\p{S}","u")),Wt=Dt(/\s/);function Dt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function on(e){const t=[];let n=-1,r=0,i=0;for(;++n55295&&s<57344){const l=e.charCodeAt(n+1);s<56320&&l>56319&&l<57344?(o=String.fromCharCode(s,l),i=1):o="�"}else o=String.fromCharCode(s);o&&(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,o=""),i&&(n+=i,i=0)}return t.join("")+e.slice(r)}function ve(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let s=0;return o;function o(u){return ge(u)?(e.enter(n),l(u)):t(u)}function l(u){return ge(u)&&s++o))return;const B=t.events.length;let O=B,k,w;for(;O--;)if(t.events[O][0]==="exit"&&t.events[O][1].type==="chunkFlow"){if(k){w=t.events[O][1].end;break}k=!0}for(b(r),T=B;TA;){const L=n[D];t.containerState=L[1],L[0].exit.call(t,e)}n.length=A}function E(){i.write([null]),s=void 0,i=void 0,t.containerState._closeFlow=void 0}}function Ud(e,t,n){return ve(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function nn(e){if(e===null||Ne(e)||Wt(e))return 1;if(Yn(e))return 2}function Xn(e,t,n){const r=[];let i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const p={...e[r][1].end},m={...e[n][1].start};To(p,-u),To(m,u),o={type:u>1?"strongSequence":"emphasisSequence",start:p,end:{...e[r][1].end}},l={type:u>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:m},s={type:u>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},i={type:u>1?"strong":"emphasis",start:{...o.start},end:{...l.end}},e[r][1].end={...o.start},e[n][1].start={...l.end},c=[],e[r][1].end.offset-e[r][1].start.offset&&(c=it(c,[["enter",e[r][1],t],["exit",e[r][1],t]])),c=it(c,[["enter",i,t],["enter",o,t],["exit",o,t],["enter",s,t]]),c=it(c,Xn(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),c=it(c,[["exit",s,t],["enter",l,t],["exit",l,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,c=it(c,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,Qe(e,r-1,n-r+3,c),n=r+c.length-d-2;break}}for(n=-1;++n0&&ge(T)?ve(e,E,"linePrefix",s+1)(T):E(T)}function E(T){return T===null||oe(T)?e.check(Co,x,D)(T):(e.enter("codeFlowValue"),A(T))}function A(T){return T===null||oe(T)?(e.exit("codeFlowValue"),E(T)):(e.consume(T),A)}function D(T){return e.exit("codeFenced"),t(T)}function L(T,B,O){let k=0;return w;function w(N){return T.enter("lineEnding"),T.consume(N),T.exit("lineEnding"),M}function M(N){return T.enter("codeFencedFence"),ge(N)?ve(T,I,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):I(N)}function I(N){return N===l?(T.enter("codeFencedFenceSequence"),j(N)):O(N)}function j(N){return N===l?(k++,T.consume(N),j):k>=o?(T.exit("codeFencedFenceSequence"),ge(N)?ve(T,_,"whitespace")(N):_(N)):O(N)}function _(N){return N===null||oe(N)?(T.exit("codeFencedFence"),B(N)):O(N)}}}function Qd(e,t,n){const r=this;return i;function i(o){return o===null?n(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s)}function s(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}const mr={name:"codeIndented",tokenize:tp},ep={partial:!0,tokenize:np};function tp(e,t,n){const r=this;return i;function i(c){return e.enter("codeIndented"),ve(e,s,"linePrefix",5)(c)}function s(c){const d=r.events[r.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?o(c):n(c)}function o(c){return c===null?u(c):oe(c)?e.attempt(ep,o,u)(c):(e.enter("codeFlowValue"),l(c))}function l(c){return c===null||oe(c)?(e.exit("codeFlowValue"),o(c)):(e.consume(c),l)}function u(c){return e.exit("codeIndented"),t(c)}}function np(e,t,n){const r=this;return i;function i(o){return r.parser.lazy[r.now().line]?n(o):oe(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):ve(e,s,"linePrefix",5)(o)}function s(o){const l=r.events[r.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(o):oe(o)?i(o):n(o)}}const rp={name:"codeText",previous:op,resolve:ip,tokenize:sp};function ip(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const i=n||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&cn(this.left,r),s.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),cn(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),cn(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(o):e.interrupt(r.parser.constructs.flow,n,t)(o)}}function ta(e,t,n,r,i,s,o,l,u){const c=u||Number.POSITIVE_INFINITY;let d=0;return p;function p(b){return b===60?(e.enter(r),e.enter(i),e.enter(s),e.consume(b),e.exit(s),m):b===null||b===32||b===41||$n(b)?n(b):(e.enter(r),e.enter(o),e.enter(l),e.enter("chunkString",{contentType:"string"}),x(b))}function m(b){return b===62?(e.enter(s),e.consume(b),e.exit(s),e.exit(i),e.exit(r),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),f(b))}function f(b){return b===62?(e.exit("chunkString"),e.exit(l),m(b)):b===null||b===60||oe(b)?n(b):(e.consume(b),b===92?h:f)}function h(b){return b===60||b===62||b===92?(e.consume(b),f):f(b)}function x(b){return!d&&(b===null||b===41||Ne(b))?(e.exit("chunkString"),e.exit(l),e.exit(o),e.exit(r),t(b)):d999||f===null||f===91||f===93&&!u||f===94&&!l&&"_hiddenFootnoteSupport"in o.parser.constructs?n(f):f===93?(e.exit(s),e.enter(i),e.consume(f),e.exit(i),e.exit(r),t):oe(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),p(f))}function p(f){return f===null||f===91||f===93||oe(f)||l++>999?(e.exit("chunkString"),d(f)):(e.consume(f),u||(u=!ge(f)),f===92?m:p)}function m(f){return f===91||f===92||f===93?(e.consume(f),l++,p):p(f)}}function ra(e,t,n,r,i,s){let o;return l;function l(m){return m===34||m===39||m===40?(e.enter(r),e.enter(i),e.consume(m),e.exit(i),o=m===40?41:m,u):n(m)}function u(m){return m===o?(e.enter(i),e.consume(m),e.exit(i),e.exit(r),t):(e.enter(s),c(m))}function c(m){return m===o?(e.exit(s),u(o)):m===null?n(m):oe(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),ve(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===o||m===null||oe(m)?(e.exit("chunkString"),c(m)):(e.consume(m),m===92?p:d)}function p(m){return m===o||m===92?(e.consume(m),d):d(m)}}function mn(e,t){let n;return r;function r(i){return oe(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r):ge(i)?ve(e,r,n?"linePrefix":"lineSuffix")(i):t(i)}}const mp={name:"definition",tokenize:gp},hp={partial:!0,tokenize:bp};function gp(e,t,n){const r=this;let i;return s;function s(f){return e.enter("definition"),o(f)}function o(f){return na.call(r,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function l(f){return i=dt(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),u):n(f)}function u(f){return Ne(f)?mn(e,c)(f):c(f)}function c(f){return ta(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function d(f){return e.attempt(hp,p,p)(f)}function p(f){return ge(f)?ve(e,m,"whitespace")(f):m(f)}function m(f){return f===null||oe(f)?(e.exit("definition"),r.parser.defined.push(i),t(f)):n(f)}}function bp(e,t,n){return r;function r(l){return Ne(l)?mn(e,i)(l):n(l)}function i(l){return ra(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function s(l){return ge(l)?ve(e,o,"whitespace")(l):o(l)}function o(l){return l===null||oe(l)?t(l):n(l)}}const xp={name:"hardBreakEscape",tokenize:yp};function yp(e,t,n){return r;function r(s){return e.enter("hardBreakEscape"),e.consume(s),i}function i(s){return oe(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}const vp={name:"headingAtx",resolve:Ep,tokenize:kp};function Ep(e,t){let n=e.length-2,r=3,i,s;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},s={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},Qe(e,r,n-r+1,[["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t]])),e}function kp(e,t,n){let r=0;return i;function i(d){return e.enter("atxHeading"),s(d)}function s(d){return e.enter("atxHeadingSequence"),o(d)}function o(d){return d===35&&r++<6?(e.consume(d),o):d===null||Ne(d)?(e.exit("atxHeadingSequence"),l(d)):n(d)}function l(d){return d===35?(e.enter("atxHeadingSequence"),u(d)):d===null||oe(d)?(e.exit("atxHeading"),t(d)):ge(d)?ve(e,l,"whitespace")(d):(e.enter("atxHeadingText"),c(d))}function u(d){return d===35?(e.consume(d),u):(e.exit("atxHeadingSequence"),l(d))}function c(d){return d===null||d===35||Ne(d)?(e.exit("atxHeadingText"),l(d)):(e.consume(d),c)}}const wp=["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","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Mo=["pre","script","style","textarea"],_p={concrete:!0,name:"htmlFlow",resolveTo:Tp,tokenize:Cp},Np={partial:!0,tokenize:Mp},Sp={partial:!0,tokenize:Ap};function Tp(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Cp(e,t,n){const r=this;let i,s,o,l,u;return c;function c(y){return d(y)}function d(y){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(y),p}function p(y){return y===33?(e.consume(y),m):y===47?(e.consume(y),s=!0,x):y===63?(e.consume(y),i=3,r.interrupt?t:g):qe(y)?(e.consume(y),o=String.fromCharCode(y),v):n(y)}function m(y){return y===45?(e.consume(y),i=2,f):y===91?(e.consume(y),i=5,l=0,h):qe(y)?(e.consume(y),i=4,r.interrupt?t:g):n(y)}function f(y){return y===45?(e.consume(y),r.interrupt?t:g):n(y)}function h(y){const Q="CDATA[";return y===Q.charCodeAt(l++)?(e.consume(y),l===Q.length?r.interrupt?t:I:h):n(y)}function x(y){return qe(y)?(e.consume(y),o=String.fromCharCode(y),v):n(y)}function v(y){if(y===null||y===47||y===62||Ne(y)){const Q=y===47,se=o.toLowerCase();return!Q&&!s&&Mo.includes(se)?(i=1,r.interrupt?t(y):I(y)):wp.includes(o.toLowerCase())?(i=6,Q?(e.consume(y),b):r.interrupt?t(y):I(y)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(y):s?E(y):A(y))}return y===45||$e(y)?(e.consume(y),o+=String.fromCharCode(y),v):n(y)}function b(y){return y===62?(e.consume(y),r.interrupt?t:I):n(y)}function E(y){return ge(y)?(e.consume(y),E):w(y)}function A(y){return y===47?(e.consume(y),w):y===58||y===95||qe(y)?(e.consume(y),D):ge(y)?(e.consume(y),A):w(y)}function D(y){return y===45||y===46||y===58||y===95||$e(y)?(e.consume(y),D):L(y)}function L(y){return y===61?(e.consume(y),T):ge(y)?(e.consume(y),L):A(y)}function T(y){return y===null||y===60||y===61||y===62||y===96?n(y):y===34||y===39?(e.consume(y),u=y,B):ge(y)?(e.consume(y),T):O(y)}function B(y){return y===u?(e.consume(y),u=null,k):y===null||oe(y)?n(y):(e.consume(y),B)}function O(y){return y===null||y===34||y===39||y===47||y===60||y===61||y===62||y===96||Ne(y)?L(y):(e.consume(y),O)}function k(y){return y===47||y===62||ge(y)?A(y):n(y)}function w(y){return y===62?(e.consume(y),M):n(y)}function M(y){return y===null||oe(y)?I(y):ge(y)?(e.consume(y),M):n(y)}function I(y){return y===45&&i===2?(e.consume(y),R):y===60&&i===1?(e.consume(y),W):y===62&&i===4?(e.consume(y),F):y===63&&i===3?(e.consume(y),g):y===93&&i===5?(e.consume(y),V):oe(y)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Np,U,j)(y)):y===null||oe(y)?(e.exit("htmlFlowData"),j(y)):(e.consume(y),I)}function j(y){return e.check(Sp,_,U)(y)}function _(y){return e.enter("lineEnding"),e.consume(y),e.exit("lineEnding"),N}function N(y){return y===null||oe(y)?j(y):(e.enter("htmlFlowData"),I(y))}function R(y){return y===45?(e.consume(y),g):I(y)}function W(y){return y===47?(e.consume(y),o="",$):I(y)}function $(y){if(y===62){const Q=o.toLowerCase();return Mo.includes(Q)?(e.consume(y),F):I(y)}return qe(y)&&o.length<8?(e.consume(y),o+=String.fromCharCode(y),$):I(y)}function V(y){return y===93?(e.consume(y),g):I(y)}function g(y){return y===62?(e.consume(y),F):y===45&&i===2?(e.consume(y),g):I(y)}function F(y){return y===null||oe(y)?(e.exit("htmlFlowData"),U(y)):(e.consume(y),F)}function U(y){return e.exit("htmlFlow"),t(y)}}function Ap(e,t,n){const r=this;return i;function i(o){return oe(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),s):n(o)}function s(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function Mp(e,t,n){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(yn,t,n)}}const Rp={name:"htmlText",tokenize:Ip};function Ip(e,t,n){const r=this;let i,s,o;return l;function l(g){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(g),u}function u(g){return g===33?(e.consume(g),c):g===47?(e.consume(g),L):g===63?(e.consume(g),A):qe(g)?(e.consume(g),O):n(g)}function c(g){return g===45?(e.consume(g),d):g===91?(e.consume(g),s=0,h):qe(g)?(e.consume(g),E):n(g)}function d(g){return g===45?(e.consume(g),f):n(g)}function p(g){return g===null?n(g):g===45?(e.consume(g),m):oe(g)?(o=p,W(g)):(e.consume(g),p)}function m(g){return g===45?(e.consume(g),f):p(g)}function f(g){return g===62?R(g):g===45?m(g):p(g)}function h(g){const F="CDATA[";return g===F.charCodeAt(s++)?(e.consume(g),s===F.length?x:h):n(g)}function x(g){return g===null?n(g):g===93?(e.consume(g),v):oe(g)?(o=x,W(g)):(e.consume(g),x)}function v(g){return g===93?(e.consume(g),b):x(g)}function b(g){return g===62?R(g):g===93?(e.consume(g),b):x(g)}function E(g){return g===null||g===62?R(g):oe(g)?(o=E,W(g)):(e.consume(g),E)}function A(g){return g===null?n(g):g===63?(e.consume(g),D):oe(g)?(o=A,W(g)):(e.consume(g),A)}function D(g){return g===62?R(g):A(g)}function L(g){return qe(g)?(e.consume(g),T):n(g)}function T(g){return g===45||$e(g)?(e.consume(g),T):B(g)}function B(g){return oe(g)?(o=B,W(g)):ge(g)?(e.consume(g),B):R(g)}function O(g){return g===45||$e(g)?(e.consume(g),O):g===47||g===62||Ne(g)?k(g):n(g)}function k(g){return g===47?(e.consume(g),R):g===58||g===95||qe(g)?(e.consume(g),w):oe(g)?(o=k,W(g)):ge(g)?(e.consume(g),k):R(g)}function w(g){return g===45||g===46||g===58||g===95||$e(g)?(e.consume(g),w):M(g)}function M(g){return g===61?(e.consume(g),I):oe(g)?(o=M,W(g)):ge(g)?(e.consume(g),M):k(g)}function I(g){return g===null||g===60||g===61||g===62||g===96?n(g):g===34||g===39?(e.consume(g),i=g,j):oe(g)?(o=I,W(g)):ge(g)?(e.consume(g),I):(e.consume(g),_)}function j(g){return g===i?(e.consume(g),i=void 0,N):g===null?n(g):oe(g)?(o=j,W(g)):(e.consume(g),j)}function _(g){return g===null||g===34||g===39||g===60||g===61||g===96?n(g):g===47||g===62||Ne(g)?k(g):(e.consume(g),_)}function N(g){return g===47||g===62||Ne(g)?k(g):n(g)}function R(g){return g===62?(e.consume(g),e.exit("htmlTextData"),e.exit("htmlText"),t):n(g)}function W(g){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),$}function $(g){return ge(g)?ve(e,V,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(g):V(g)}function V(g){return e.enter("htmlTextData"),o(g)}}const si={name:"labelEnd",resolveAll:Dp,resolveTo:Pp,tokenize:Bp},Op={tokenize:Fp},Lp={tokenize:zp},jp={tokenize:Up};function Dp(e){let t=-1;const n=[];for(;++t=3&&(c===null||oe(c))?(e.exit("thematicBreak"),t(c)):n(c)}function u(c){return c===i?(e.consume(c),r++,u):(e.exit("thematicBreakSequence"),ge(c)?ve(e,l,"whitespace")(c):l(c))}}const Ve={continuation:{tokenize:Zp},exit:Qp,name:"list",tokenize:Xp},Vp={partial:!0,tokenize:ef},Yp={partial:!0,tokenize:Jp};function Xp(e,t,n){const r=this,i=r.events[r.events.length-1];let s=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,o=0;return l;function l(f){const h=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(h==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:Br(f)){if(r.containerState.type||(r.containerState.type=h,e.enter(h,{_container:!0})),h==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(Fn,n,c)(f):c(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(f)}return n(f)}function u(f){return Br(f)&&++o<10?(e.consume(f),u):(!r.interrupt||o<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),c(f)):n(f)}function c(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(yn,r.interrupt?n:d,e.attempt(Vp,m,p))}function d(f){return r.containerState.initialBlankLine=!0,s++,m(f)}function p(f){return ge(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),m):n(f)}function m(f){return r.containerState.size=s+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function Zp(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(yn,i,s);function i(l){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,ve(e,t,"listItemIndent",r.containerState.size+1)(l)}function s(l){return r.containerState.furtherBlankLines||!ge(l)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(l)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Yp,t,o)(l))}function o(l){return r.containerState._closeFlow=!0,r.interrupt=void 0,ve(e,e.attempt(Ve,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function Jp(e,t,n){const r=this;return ve(e,i,"listItemIndent",r.containerState.size+1);function i(s){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?t(s):n(s)}}function Qp(e){e.exit(this.containerState.type)}function ef(e,t,n){const r=this;return ve(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(s){const o=r.events[r.events.length-1];return!ge(s)&&o&&o[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}const Ro={name:"setextUnderline",resolveTo:tf,tokenize:nf};function tf(e,t){let n=e.length,r,i,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);const o={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type="setextHeadingText",s?(e.splice(i,0,["enter",o,t]),e.splice(s+1,0,["exit",e[r][1],t]),e[r][1].end={...e[s][1].end}):e[r][1]=o,e.push(["exit",o,t]),e}function nf(e,t,n){const r=this;let i;return s;function s(c){let d=r.events.length,p;for(;d--;)if(r.events[d][1].type!=="lineEnding"&&r.events[d][1].type!=="linePrefix"&&r.events[d][1].type!=="content"){p=r.events[d][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||p)?(e.enter("setextHeadingLine"),i=c,o(c)):n(c)}function o(c){return e.enter("setextHeadingLineSequence"),l(c)}function l(c){return c===i?(e.consume(c),l):(e.exit("setextHeadingLineSequence"),ge(c)?ve(e,u,"lineSuffix")(c):u(c))}function u(c){return c===null||oe(c)?(e.exit("setextHeadingLine"),t(c)):n(c)}}const rf={tokenize:of};function of(e){const t=this,n=e.attempt(yn,r,e.attempt(this.parser.constructs.flowInitial,i,ve(e,e.attempt(this.parser.constructs.flow,i,e.attempt(cp,i)),"linePrefix")));return n;function r(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const sf={resolveAll:oa()},af=ia("string"),lf=ia("text");function ia(e){return{resolveAll:oa(e==="text"?cf:void 0),tokenize:t};function t(n){const r=this,i=this.parser.constructs[e],s=n.attempt(i,o,l);return o;function o(d){return c(d)?s(d):l(d)}function l(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),u}function u(d){return c(d)?(n.exit("data"),s(d)):(n.consume(d),u)}function c(d){if(d===null)return!0;const p=i[d];let m=-1;if(p)for(;++m-1){const l=o[0];typeof l=="string"?o[0]=l.slice(r):o.shift()}s>0&&o.push(e[i].slice(0,s))}return o}function kf(e,t){let n=-1;const r=[];let i;for(;++n0){const We=Q.tokenStack[Q.tokenStack.length-1];(We[1]||Oo).call(Q,void 0,We[0])}for(H.position={start:It(P.length>0?P[0][1].start:{line:1,column:1,offset:0}),end:It(P.length>0?P[P.length-2][1].end:{line:1,column:1,offset:0})},ke=-1;++ke0){const We=ee.tokenStack[ee.tokenStack.length-1];(We[1]||Oo).call(ee,void 0,We[0])}for(H.position={start:It(P.length>0?P[0][1].start:{line:1,column:1,offset:0}),end:It(P.length>0?P[P.length-2][1].end:{line:1,column:1,offset:0})},ke=-1;++ke0&&(r.className=["language-"+i[0]]);let s={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(s.data={meta:t.meta}),e.patch(t,s),s=e.applyData(t,s),s={type:"element",tagName:"pre",properties:{},children:[s]},e.patch(t,s),s}function Df(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Pf(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Bf(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),i=on(r.toLowerCase()),s=e.footnoteOrder.indexOf(r);let o,l=e.footnoteCounts.get(r);l===void 0?(l=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=s+1,l+=1,e.footnoteCounts.set(r,l);const u={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+i,id:n+"fnref-"+i+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(o)}]};e.patch(t,u);const c={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(t,c),e.applyData(t,c)}function Ff(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function zf(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function la(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const i=e.all(t),s=i[0];s&&s.type==="text"?s.value="["+s.value:i.unshift({type:"text",value:"["});const o=i[i.length-1];return o&&o.type==="text"?o.value+=r:i.push({type:"text",value:r}),i}function Uf(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return la(e,t);const i={src:on(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function $f(e,t){const n={src:on(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function Hf(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function Wf(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return la(e,t);const i={href:on(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function Kf(e,t){const n={href:on(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Gf(e,t,n){const r=e.all(t),i=n?qf(n):ca(t),s={},o=[];if(typeof t.checked=="boolean"){const d=r[0];let p;d&&d.type==="element"&&d.tagName==="p"?p=d:(p={type:"element",tagName:"p",properties:{},children:[]},r.unshift(p)),p.children.length>0&&p.children.unshift({type:"text",value:" "}),p.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let l=-1;for(;++l1}function Vf(e,t){const n={},r=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++i0){const o={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},l=ei(t.children[1]),u=$s(t.children[t.children.length-1]);l&&u&&(o.position={start:l,end:u}),i.push(o)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,s),e.applyData(t,s)}function Qf(e,t,n){const r=n?n.children:void 0,s=(r?r.indexOf(t):1)===0?"th":"td",o=n&&n.type==="table"?n.align:void 0,l=o?o.length:t.children.length;let u=-1;const c=[];for(;++u0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return s.push(Do(t.slice(i),i>0,!1)),s.join("")}function Do(e,t,n){let r=0,i=e.length;if(t){let s=e.codePointAt(r);for(;s===Lo||s===jo;)r++,s=e.codePointAt(r)}if(n){let s=e.codePointAt(i-1);for(;s===Lo||s===jo;)i--,s=e.codePointAt(i-1)}return i>r?e.slice(r,i):""}function nm(e,t){const n={type:"text",value:tm(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function rm(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const im={blockquote:Of,break:Lf,code:jf,delete:Df,emphasis:Pf,footnoteReference:Bf,heading:Ff,html:zf,imageReference:Uf,image:$f,inlineCode:Hf,linkReference:Wf,link:Kf,listItem:Gf,list:Vf,paragraph:Yf,root:Xf,strong:Zf,table:Jf,tableCell:em,tableRow:Qf,text:nm,thematicBreak:rm,toml:Mn,yaml:Mn,definition:Mn,footnoteDefinition:Mn};function Mn(){}const ua=-1,Zn=0,hn=1,Hn=2,ai=3,li=4,ci=5,ui=6,da=7,pa=8,Po=typeof self=="object"?self:globalThis,om=(e,t)=>{const n=(i,s)=>(e.set(s,i),i),r=i=>{if(e.has(i))return e.get(i);const[s,o]=t[i];switch(s){case Zn:case ua:return n(o,i);case hn:{const l=n([],i);for(const u of o)l.push(r(u));return l}case Hn:{const l=n({},i);for(const[u,c]of o)l[r(u)]=r(c);return l}case ai:return n(new Date(o),i);case li:{const{source:l,flags:u}=o;return n(new RegExp(l,u),i)}case ci:{const l=n(new Map,i);for(const[u,c]of o)l.set(r(u),r(c));return l}case ui:{const l=n(new Set,i);for(const u of o)l.add(r(u));return l}case da:{const{name:l,message:u}=o;return n(new Po[l](u),i)}case pa:return n(BigInt(o),i);case"BigInt":return n(Object(BigInt(o)),i);case"ArrayBuffer":return n(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:l}=new Uint8Array(o);return n(new DataView(l),o)}}return n(new Po[s](o),i)};return r},Bo=e=>om(new Map,e)(0),Xt="",{toString:sm}={},{keys:am}=Object,un=e=>{const t=typeof e;if(t!=="object"||!e)return[Zn,t];const n=sm.call(e).slice(8,-1);switch(n){case"Array":return[hn,Xt];case"Object":return[Hn,Xt];case"Date":return[ai,Xt];case"RegExp":return[li,Xt];case"Map":return[ci,Xt];case"Set":return[ui,Xt];case"DataView":return[hn,n]}return n.includes("Array")?[hn,n]:n.includes("Error")?[da,n]:[Hn,n]},Rn=([e,t])=>e===Zn&&(t==="function"||t==="symbol"),lm=(e,t,n,r)=>{const i=(o,l)=>{const u=r.push(o)-1;return n.set(l,u),u},s=o=>{if(n.has(o))return n.get(o);let[l,u]=un(o);switch(l){case Zn:{let d=o;switch(u){case"bigint":l=pa,d=o.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);d=null;break;case"undefined":return i([ua],o)}return i([l,d],o)}case hn:{if(u){let m=o;return u==="DataView"?m=new Uint8Array(o.buffer):u==="ArrayBuffer"&&(m=new Uint8Array(o)),i([u,[...m]],o)}const d=[],p=i([l,d],o);for(const m of o)d.push(s(m));return p}case Hn:{if(u)switch(u){case"BigInt":return i([u,o.toString()],o);case"Boolean":case"Number":case"String":return i([u,o.valueOf()],o)}if(t&&"toJSON"in o)return s(o.toJSON());const d=[],p=i([l,d],o);for(const m of am(o))(e||!Rn(un(o[m])))&&d.push([s(m),s(o[m])]);return p}case ai:return i([l,o.toISOString()],o);case li:{const{source:d,flags:p}=o;return i([l,{source:d,flags:p}],o)}case ci:{const d=[],p=i([l,d],o);for(const[m,f]of o)(e||!(Rn(un(m))||Rn(un(f))))&&d.push([s(m),s(f)]);return p}case ui:{const d=[],p=i([l,d],o);for(const m of o)(e||!Rn(un(m)))&&d.push(s(m));return p}}const{message:c}=o;return i([l,{name:u,message:c}],o)};return s},Fo=(e,{json:t,lossy:n}={})=>{const r=[];return lm(!(t||n),!!t,new Map,r)(e),r},Wn=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Bo(Fo(e,t)):structuredClone(e):(e,t)=>Bo(Fo(e,t));function cm(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function um(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function dm(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||cm,r=e.options.footnoteBackLabel||um,i=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",o=e.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let u=-1;for(;++u0&&g.push({type:"text",value:" "});let k=typeof n=="string"?n:n(u,f);typeof k=="string"&&(k={type:"text",value:k}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(u,f),className:["data-footnote-backref"]},children:Array.isArray(k)?k:[k]})}const y=d[d.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const k=y.children[y.children.length-1];k&&k.type==="text"?k.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...g)}else d.push(...g);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:e.wrap(d,!0)};e.patch(c,b),l.push(b)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:{...Wn(o),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:` +`});const c={type:"element",tagName:"li",properties:s,children:o};return e.patch(t,c),e.applyData(t,c)}function qf(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r1}function Vf(e,t){const n={},r=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++i0){const o={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},l=ei(t.children[1]),u=$s(t.children[t.children.length-1]);l&&u&&(o.position={start:l,end:u}),i.push(o)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,s),e.applyData(t,s)}function Qf(e,t,n){const r=n?n.children:void 0,s=(r?r.indexOf(t):1)===0?"th":"td",o=n&&n.type==="table"?n.align:void 0,l=o?o.length:t.children.length;let u=-1;const c=[];for(;++u0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return s.push(Do(t.slice(i),i>0,!1)),s.join("")}function Do(e,t,n){let r=0,i=e.length;if(t){let s=e.codePointAt(r);for(;s===Lo||s===jo;)r++,s=e.codePointAt(r)}if(n){let s=e.codePointAt(i-1);for(;s===Lo||s===jo;)i--,s=e.codePointAt(i-1)}return i>r?e.slice(r,i):""}function nm(e,t){const n={type:"text",value:tm(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function rm(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const im={blockquote:Of,break:Lf,code:jf,delete:Df,emphasis:Pf,footnoteReference:Bf,heading:Ff,html:zf,imageReference:Uf,image:$f,inlineCode:Hf,linkReference:Wf,link:Kf,listItem:Gf,list:Vf,paragraph:Yf,root:Xf,strong:Zf,table:Jf,tableCell:em,tableRow:Qf,text:nm,thematicBreak:rm,toml:Mn,yaml:Mn,definition:Mn,footnoteDefinition:Mn};function Mn(){}const ua=-1,Zn=0,hn=1,Hn=2,ai=3,li=4,ci=5,ui=6,da=7,pa=8,Po=typeof self=="object"?self:globalThis,om=(e,t)=>{const n=(i,s)=>(e.set(s,i),i),r=i=>{if(e.has(i))return e.get(i);const[s,o]=t[i];switch(s){case Zn:case ua:return n(o,i);case hn:{const l=n([],i);for(const u of o)l.push(r(u));return l}case Hn:{const l=n({},i);for(const[u,c]of o)l[r(u)]=r(c);return l}case ai:return n(new Date(o),i);case li:{const{source:l,flags:u}=o;return n(new RegExp(l,u),i)}case ci:{const l=n(new Map,i);for(const[u,c]of o)l.set(r(u),r(c));return l}case ui:{const l=n(new Set,i);for(const u of o)l.add(r(u));return l}case da:{const{name:l,message:u}=o;return n(new Po[l](u),i)}case pa:return n(BigInt(o),i);case"BigInt":return n(Object(BigInt(o)),i);case"ArrayBuffer":return n(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:l}=new Uint8Array(o);return n(new DataView(l),o)}}return n(new Po[s](o),i)};return r},Bo=e=>om(new Map,e)(0),Xt="",{toString:sm}={},{keys:am}=Object,un=e=>{const t=typeof e;if(t!=="object"||!e)return[Zn,t];const n=sm.call(e).slice(8,-1);switch(n){case"Array":return[hn,Xt];case"Object":return[Hn,Xt];case"Date":return[ai,Xt];case"RegExp":return[li,Xt];case"Map":return[ci,Xt];case"Set":return[ui,Xt];case"DataView":return[hn,n]}return n.includes("Array")?[hn,n]:n.includes("Error")?[da,n]:[Hn,n]},Rn=([e,t])=>e===Zn&&(t==="function"||t==="symbol"),lm=(e,t,n,r)=>{const i=(o,l)=>{const u=r.push(o)-1;return n.set(l,u),u},s=o=>{if(n.has(o))return n.get(o);let[l,u]=un(o);switch(l){case Zn:{let d=o;switch(u){case"bigint":l=pa,d=o.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);d=null;break;case"undefined":return i([ua],o)}return i([l,d],o)}case hn:{if(u){let m=o;return u==="DataView"?m=new Uint8Array(o.buffer):u==="ArrayBuffer"&&(m=new Uint8Array(o)),i([u,[...m]],o)}const d=[],p=i([l,d],o);for(const m of o)d.push(s(m));return p}case Hn:{if(u)switch(u){case"BigInt":return i([u,o.toString()],o);case"Boolean":case"Number":case"String":return i([u,o.valueOf()],o)}if(t&&"toJSON"in o)return s(o.toJSON());const d=[],p=i([l,d],o);for(const m of am(o))(e||!Rn(un(o[m])))&&d.push([s(m),s(o[m])]);return p}case ai:return i([l,o.toISOString()],o);case li:{const{source:d,flags:p}=o;return i([l,{source:d,flags:p}],o)}case ci:{const d=[],p=i([l,d],o);for(const[m,f]of o)(e||!(Rn(un(m))||Rn(un(f))))&&d.push([s(m),s(f)]);return p}case ui:{const d=[],p=i([l,d],o);for(const m of o)(e||!Rn(un(m)))&&d.push(s(m));return p}}const{message:c}=o;return i([l,{name:u,message:c}],o)};return s},Fo=(e,{json:t,lossy:n}={})=>{const r=[];return lm(!(t||n),!!t,new Map,r)(e),r},Wn=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Bo(Fo(e,t)):structuredClone(e):(e,t)=>Bo(Fo(e,t));function cm(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function um(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function dm(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||cm,r=e.options.footnoteBackLabel||um,i=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",o=e.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let u=-1;for(;++u0&&h.push({type:"text",value:" "});let E=typeof n=="string"?n:n(u,f);typeof E=="string"&&(E={type:"text",value:E}),h.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(u,f),className:["data-footnote-backref"]},children:Array.isArray(E)?E:[E]})}const v=d[d.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const E=v.children[v.children.length-1];E&&E.type==="text"?E.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...h)}else d.push(...h);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:e.wrap(d,!0)};e.patch(c,b),l.push(b)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:{...Wn(o),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:e.wrap(l,!0)},{type:"text",value:` -`}]}}const vn=(function(e){if(e==null)return hm;if(typeof e=="function")return Jn(e);if(typeof e=="object")return Array.isArray(e)?pm(e):fm(e);if(typeof e=="string")return mm(e);throw new Error("Expected function, string, or object as test")});function pm(e){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let f=fa,g,x,y;if((!t||s(u,c,d[d.length-1]||void 0))&&(f=ym(n(u,d)),f[0]===zr))return f;if("children"in u&&u.children){const b=u;if(b.children&&f[0]!==xm)for(x=(r?b.children.length:-1)+o,y=d.concat(b);x>-1&&x":""))+")"})}return m;function m(){let f=fa,h,x,v;if((!t||s(u,c,d[d.length-1]||void 0))&&(f=ym(n(u,d)),f[0]===zr))return f;if("children"in u&&u.children){const b=u;if(b.children&&f[0]!==xm)for(x=(r?b.children.length:-1)+o,v=d.concat(b);x>-1&&x0&&n.push({type:"text",value:` `}),n}function zo(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Uo(e,t){const n=Em(e,t),r=n.one(e,void 0),i=dm(n),s=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&s.children.push({type:"text",value:` -`},i),s}function Sm(e,t){return e&&"run"in e?async function(n,r){const i=Uo(n,{file:r,...t});await e.run(i,r)}:function(n,r){return Uo(n,{file:r,...e||t})}}function $o(e){if(e)throw e}var gr,Ho;function Tm(){if(Ho)return gr;Ho=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(c){return typeof Array.isArray=="function"?Array.isArray(c):t.call(c)==="[object Array]"},s=function(c){if(!c||t.call(c)!=="[object Object]")return!1;var d=e.call(c,"constructor"),p=c.constructor&&c.constructor.prototype&&e.call(c.constructor.prototype,"isPrototypeOf");if(c.constructor&&!d&&!p)return!1;var m;for(m in c);return typeof m>"u"||e.call(c,m)},o=function(c,d){n&&d.name==="__proto__"?n(c,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):c[d.name]=d.newValue},l=function(c,d){if(d==="__proto__")if(e.call(c,d)){if(r)return r(c,d).value}else return;return c[d]};return gr=function u(){var c,d,p,m,f,g,x=arguments[0],y=1,b=arguments.length,k=!1;for(typeof x=="boolean"&&(k=x,x=arguments[1]||{},y=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});yo.length;let u;l&&o.push(i);try{u=e.apply(this,o)}catch(c){const d=c;if(l&&n)throw d;return i(d)}l||(u&&u.then&&typeof u.then=="function"?u.then(s,i):u instanceof Error?i(u):s(u))}function i(o,...l){n||(n=!0,t(o,...l))}function s(o){i(null,o)}}const mt={basename:Rm,dirname:Im,extname:Om,join:Lm,sep:"/"};function Rm(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');En(e);let n=0,r=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else r<0&&(s=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let o=-1,l=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else o<0&&(s=!0,o=i+1),l>-1&&(e.codePointAt(i)===t.codePointAt(l--)?l<0&&(r=i):(l=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function Im(e){if(En(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function Om(e){En(e);let t=e.length,n=-1,r=0,i=-1,s=0,o;for(;t--;){const l=e.codePointAt(t);if(l===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),l===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||n<0||s===0||s===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function Lm(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function Dm(e,t){let n="",r=0,i=-1,s=0,o=-1,l,u;for(;++o<=e.length;){if(o2){if(u=n.lastIndexOf("/"),u!==n.length-1){u<0?(n="",r=0):(n=n.slice(0,u),r=n.length-1-n.lastIndexOf("/")),i=o,s=0;continue}}else if(n.length>0){n="",r=0,i=o,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1;i=o,s=0}else l===46&&s>-1?s++:s=-1}return n}function En(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Pm={cwd:Bm};function Bm(){return"/"}function Hr(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Fm(e){if(typeof e=="string")e=new URL(e);else if(!Hr(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return zm(e)}function zm(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n0){let[f,...g]=d;const x=r[m][1];$r(x)&&$r(f)&&(f=br(!0,x,f)),r[m]=[c,f,...g]}}}}const Wm=new di().freeze();function Er(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function kr(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function wr(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Ko(e){if(!$r(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Go(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function In(e){return Km(e)?e:new ha(e)}function Km(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Gm(e){return typeof e=="string"||qm(e)}function qm(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Vm="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qo=[],Vo={allowDangerousHtml:!0},Ym=/^(https?|ircs?|mailto|xmpp)$/i,Xm=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Zm(e){const t=Jm(e),n=Qm(e);return eh(t.runSync(t.parse(n),n),e)}function Jm(e){const t=e.rehypePlugins||qo,n=e.remarkPlugins||qo,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Vo}:Vo;return Wm().use(If).use(n).use(Sm,r).use(t)}function Qm(e){const t=e.children||"",n=new ha;return typeof t=="string"&&(n.value=t),n}function eh(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,s=t.disallowedElements,o=t.skipHtml,l=t.unwrapDisallowed,u=t.urlTransform||th;for(const d of Xm)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+Vm+d.id,void 0);return Qn(e,c),md(e,{Fragment:a.Fragment,components:i,ignoreInvalidStyle:!0,jsx:a.jsx,jsxs:a.jsxs,passKeys:!0,passNode:!0});function c(d,p,m){if(d.type==="raw"&&m&&typeof p=="number")return o?m.children.splice(p,1):m.children[p]={type:"text",value:d.value},p;if(d.type==="element"){let f;for(f in fr)if(Object.hasOwn(fr,f)&&Object.hasOwn(d.properties,f)){const g=d.properties[f],x=fr[f];(x===null||x.includes(d.tagName))&&(d.properties[f]=u(String(g||""),f,d))}}if(d.type==="element"){let f=n?!n.includes(d.tagName):s?s.includes(d.tagName):!1;if(!f&&r&&typeof p=="number"&&(f=!r(d,p,m)),f&&m&&typeof p=="number")return l&&d.children?m.children.splice(p,1,...d.children):m.children.splice(p,1),p}}}function th(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||Ym.test(e.slice(0,t))?e:""}const Yo=(function(e,t,n){const r=vn(n);if(!e||!e.type||!e.children)throw new Error("Expected parent node");if(typeof t=="number"){if(t<0||t===Number.POSITIVE_INFINITY)throw new Error("Expected positive finite number as index")}else if(t=e.children.indexOf(t),t<0)throw new Error("Expected child node or index");for(;++tc&&(c=d):d&&(c!==void 0&&c>-1&&u.push(` +`},i),s}function Sm(e,t){return e&&"run"in e?async function(n,r){const i=Uo(n,{file:r,...t});await e.run(i,r)}:function(n,r){return Uo(n,{file:r,...e||t})}}function $o(e){if(e)throw e}var gr,Ho;function Tm(){if(Ho)return gr;Ho=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(c){return typeof Array.isArray=="function"?Array.isArray(c):t.call(c)==="[object Array]"},s=function(c){if(!c||t.call(c)!=="[object Object]")return!1;var d=e.call(c,"constructor"),p=c.constructor&&c.constructor.prototype&&e.call(c.constructor.prototype,"isPrototypeOf");if(c.constructor&&!d&&!p)return!1;var m;for(m in c);return typeof m>"u"||e.call(c,m)},o=function(c,d){n&&d.name==="__proto__"?n(c,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):c[d.name]=d.newValue},l=function(c,d){if(d==="__proto__")if(e.call(c,d)){if(r)return r(c,d).value}else return;return c[d]};return gr=function u(){var c,d,p,m,f,h,x=arguments[0],v=1,b=arguments.length,E=!1;for(typeof x=="boolean"&&(E=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});vo.length;let u;l&&o.push(i);try{u=e.apply(this,o)}catch(c){const d=c;if(l&&n)throw d;return i(d)}l||(u&&u.then&&typeof u.then=="function"?u.then(s,i):u instanceof Error?i(u):s(u))}function i(o,...l){n||(n=!0,t(o,...l))}function s(o){i(null,o)}}const ht={basename:Rm,dirname:Im,extname:Om,join:Lm,sep:"/"};function Rm(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');En(e);let n=0,r=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else r<0&&(s=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let o=-1,l=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else o<0&&(s=!0,o=i+1),l>-1&&(e.codePointAt(i)===t.codePointAt(l--)?l<0&&(r=i):(l=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function Im(e){if(En(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function Om(e){En(e);let t=e.length,n=-1,r=0,i=-1,s=0,o;for(;t--;){const l=e.codePointAt(t);if(l===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),l===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||n<0||s===0||s===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function Lm(...e){let t=-1,n;for(;++t0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function Dm(e,t){let n="",r=0,i=-1,s=0,o=-1,l,u;for(;++o<=e.length;){if(o2){if(u=n.lastIndexOf("/"),u!==n.length-1){u<0?(n="",r=0):(n=n.slice(0,u),r=n.length-1-n.lastIndexOf("/")),i=o,s=0;continue}}else if(n.length>0){n="",r=0,i=o,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1;i=o,s=0}else l===46&&s>-1?s++:s=-1}return n}function En(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Pm={cwd:Bm};function Bm(){return"/"}function Hr(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Fm(e){if(typeof e=="string")e=new URL(e);else if(!Hr(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return zm(e)}function zm(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n0){let[f,...h]=d;const x=r[m][1];$r(x)&&$r(f)&&(f=br(!0,x,f)),r[m]=[c,f,...h]}}}}const Wm=new di().freeze();function Er(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function kr(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function wr(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Ko(e){if(!$r(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Go(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function In(e){return Km(e)?e:new ha(e)}function Km(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Gm(e){return typeof e=="string"||qm(e)}function qm(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Vm="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qo=[],Vo={allowDangerousHtml:!0},Ym=/^(https?|ircs?|mailto|xmpp)$/i,Xm=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Zm(e){const t=Jm(e),n=Qm(e);return eh(t.runSync(t.parse(n),n),e)}function Jm(e){const t=e.rehypePlugins||qo,n=e.remarkPlugins||qo,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Vo}:Vo;return Wm().use(If).use(n).use(Sm,r).use(t)}function Qm(e){const t=e.children||"",n=new ha;return typeof t=="string"&&(n.value=t),n}function eh(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,s=t.disallowedElements,o=t.skipHtml,l=t.unwrapDisallowed,u=t.urlTransform||th;for(const d of Xm)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+Vm+d.id,void 0);return Qn(e,c),md(e,{Fragment:a.Fragment,components:i,ignoreInvalidStyle:!0,jsx:a.jsx,jsxs:a.jsxs,passKeys:!0,passNode:!0});function c(d,p,m){if(d.type==="raw"&&m&&typeof p=="number")return o?m.children.splice(p,1):m.children[p]={type:"text",value:d.value},p;if(d.type==="element"){let f;for(f in fr)if(Object.hasOwn(fr,f)&&Object.hasOwn(d.properties,f)){const h=d.properties[f],x=fr[f];(x===null||x.includes(d.tagName))&&(d.properties[f]=u(String(h||""),f,d))}}if(d.type==="element"){let f=n?!n.includes(d.tagName):s?s.includes(d.tagName):!1;if(!f&&r&&typeof p=="number"&&(f=!r(d,p,m)),f&&m&&typeof p=="number")return l&&d.children?m.children.splice(p,1,...d.children):m.children.splice(p,1),p}}}function th(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||Ym.test(e.slice(0,t))?e:""}const Yo=(function(e,t,n){const r=vn(n);if(!e||!e.type||!e.children)throw new Error("Expected parent node");if(typeof t=="number"){if(t<0||t===Number.POSITIVE_INFINITY)throw new Error("Expected positive finite number as index")}else if(t=e.children.indexOf(t),t<0)throw new Error("Expected child node or index");for(;++tc&&(c=d):d&&(c!==void 0&&c>-1&&u.push(` `.repeat(c)||" "),c=-1,u.push(d))}return u.join("")}function ba(e,t,n){return e.type==="element"?ch(e,t,n):e.type==="text"?n.whitespace==="normal"?xa(e,n):uh(e):[]}function ch(e,t,n){const r=ya(e,n),i=e.children||[];let s=-1,o=[];if(ah(e))return o;let l,u;for(Wr(e)||Qo(e)&&Yo(t,e,Qo)?u=` -`:sh(e)?(l=2,u=2):ga(e)&&(l=1,u=1);++s]+>")+")",l={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},p={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},m={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},f=t.optional(i)+e.IDENT_RE+"\\s*\\(",g=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],x=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],y=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],b=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],j={type:x,keyword:g,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:y},L={className:"function.dispatch",relevance:0,keywords:{_hint:b},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},T=[L,p,l,n,e.C_BLOCK_COMMENT_MODE,d,c],B={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:j,contains:T.concat([{begin:/\(/,end:/\)/,keywords:j,contains:T.concat(["self"]),relevance:0}]),relevance:0},O={className:"function",begin:"("+o+"[\\*&\\s]+)+"+f,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:j,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:j,relevance:0},{begin:f,returnBegin:!0,contains:[m],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[c,d]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:j,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,c,d,l,{begin:/\(/,end:/\)/,keywords:j,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,c,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,p]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:j,illegal:"",keywords:j,contains:["self",l]},{begin:e.IDENT_RE+"::",keywords:j},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function gh(e){const t={type:["boolean","byte","word","String"],built_in:["KeyboardController","MouseController","SoftwareSerial","EthernetServer","EthernetClient","LiquidCrystal","RobotControl","GSMVoiceCall","EthernetUDP","EsploraTFT","HttpClient","RobotMotor","WiFiClient","GSMScanner","FileSystem","Scheduler","GSMServer","YunClient","YunServer","IPAddress","GSMClient","GSMModem","Keyboard","Ethernet","Console","GSMBand","Esplora","Stepper","Process","WiFiUDP","GSM_SMS","Mailbox","USBHost","Firmata","PImage","Client","Server","GSMPIN","FileIO","Bridge","Serial","EEPROM","Stream","Mouse","Audio","Servo","File","Task","GPRS","WiFi","Wire","TFT","GSM","SPI","SD"],_hints:["setup","loop","runShellCommandAsynchronously","analogWriteResolution","retrieveCallingNumber","printFirmwareVersion","analogReadResolution","sendDigitalPortPair","noListenOnLocalhost","readJoystickButton","setFirmwareVersion","readJoystickSwitch","scrollDisplayRight","getVoiceCallStatus","scrollDisplayLeft","writeMicroseconds","delayMicroseconds","beginTransmission","getSignalStrength","runAsynchronously","getAsynchronously","listenOnLocalhost","getCurrentCarrier","readAccelerometer","messageAvailable","sendDigitalPorts","lineFollowConfig","countryNameWrite","runShellCommand","readStringUntil","rewindDirectory","readTemperature","setClockDivider","readLightSensor","endTransmission","analogReference","detachInterrupt","countryNameRead","attachInterrupt","encryptionType","readBytesUntil","robotNameWrite","readMicrophone","robotNameRead","cityNameWrite","userNameWrite","readJoystickY","readJoystickX","mouseReleased","openNextFile","scanNetworks","noInterrupts","digitalWrite","beginSpeaker","mousePressed","isActionDone","mouseDragged","displayLogos","noAutoscroll","addParameter","remoteNumber","getModifiers","keyboardRead","userNameRead","waitContinue","processInput","parseCommand","printVersion","readNetworks","writeMessage","blinkVersion","cityNameRead","readMessage","setDataMode","parsePacket","isListening","setBitOrder","beginPacket","isDirectory","motorsWrite","drawCompass","digitalRead","clearScreen","serialEvent","rightToLeft","setTextSize","leftToRight","requestFrom","keyReleased","compassRead","analogWrite","interrupts","WiFiServer","disconnect","playMelody","parseFloat","autoscroll","getPINUsed","setPINUsed","setTimeout","sendAnalog","readSlider","analogRead","beginWrite","createChar","motorsStop","keyPressed","tempoWrite","readButton","subnetMask","debugPrint","macAddress","writeGreen","randomSeed","attachGPRS","readString","sendString","remotePort","releaseAll","mouseMoved","background","getXChange","getYChange","answerCall","getResult","voiceCall","endPacket","constrain","getSocket","writeJSON","getButton","available","connected","findUntil","readBytes","exitValue","readGreen","writeBlue","startLoop","IPAddress","isPressed","sendSysex","pauseMode","gatewayIP","setCursor","getOemKey","tuneWrite","noDisplay","loadImage","switchPIN","onRequest","onReceive","changePIN","playFile","noBuffer","parseInt","overflow","checkPIN","knobRead","beginTFT","bitClear","updateIR","bitWrite","position","writeRGB","highByte","writeRed","setSpeed","readBlue","noStroke","remoteIP","transfer","shutdown","hangCall","beginSMS","endWrite","attached","maintain","noCursor","checkReg","checkPUK","shiftOut","isValid","shiftIn","pulseIn","connect","println","localIP","pinMode","getIMEI","display","noBlink","process","getBand","running","beginSD","drawBMP","lowByte","setBand","release","bitRead","prepare","pointTo","readRed","setMode","noFill","remove","listen","stroke","detach","attach","noTone","exists","buffer","height","bitSet","circle","config","cursor","random","IRread","setDNS","endSMS","getKey","micros","millis","begin","print","write","ready","flush","width","isPIN","blink","clear","press","mkdir","rmdir","close","point","yield","image","BSSID","click","delay","read","text","move","peek","beep","rect","line","open","seek","fill","size","turn","stop","home","find","step","tone","sqrt","RSSI","SSID","end","bit","tan","cos","sin","pow","map","abs","max","min","get","run","put"],literal:["DIGITAL_MESSAGE","FIRMATA_STRING","ANALOG_MESSAGE","REPORT_DIGITAL","REPORT_ANALOG","INPUT_PULLUP","SET_PIN_MODE","INTERNAL2V56","SYSTEM_RESET","LED_BUILTIN","INTERNAL1V1","SYSEX_START","INTERNAL","EXTERNAL","DEFAULT","OUTPUT","INPUT","HIGH","LOW"]},n=hh(e),r=n.keywords;return r.type=[...r.type,...t.type],r.literal=[...r.literal,...t.literal],r.built_in=[...r.built_in,...t.built_in],r._hints=t._hints,n.name="Arduino",n.aliases=["ino"],n.supersetOf="cpp",n}function bh(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const i={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},s=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},l={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(l);const u={match:/\\"/},c={className:"string",begin:/'/,end:/'/},d={match:/\\'/},p={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},m=["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"],f=e.SHEBANG({binary:`(${m.join("|")})`,relevance:10}),g={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},x=["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],y=["true","false"],b={match:/(\/[a-z._-]+)+/},k=["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset"],A=["alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias"],j=["autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp"],L=["chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"];return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:x,literal:y,built_in:[...k,...A,"set","shopt",...j,...L]},contains:[f,e.SHEBANG(),g,p,s,o,b,l,u,c,d,n]}}function xh(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",l={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},p={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},m={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},f=t.optional(i)+e.IDENT_RE+"\\s*\\(",y={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},b=[p,l,n,e.C_BLOCK_COMMENT_MODE,d,c],k={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:y,contains:b.concat([{begin:/\(/,end:/\)/,keywords:y,contains:b.concat(["self"]),relevance:0}]),relevance:0},A={begin:"("+o+"[\\*&\\s]+)+"+f,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:y,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:y,relevance:0},{begin:f,returnBegin:!0,contains:[e.inherit(m,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:y,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,c,d,l,{begin:/\(/,end:/\)/,keywords:y,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,c,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,p]};return{name:"C",aliases:["h"],keywords:y,disableAutodetect:!0,illegal:"=]/,contains:[{beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:p,strings:c,keywords:y}}}function yh(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="(?!struct)("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",l={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},p={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},m={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},f=t.optional(i)+e.IDENT_RE+"\\s*\\(",g=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],x=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],y=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],b=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],j={type:x,keyword:g,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:y},L={className:"function.dispatch",relevance:0,keywords:{_hint:b},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},T=[L,p,l,n,e.C_BLOCK_COMMENT_MODE,d,c],B={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:j,contains:T.concat([{begin:/\(/,end:/\)/,keywords:j,contains:T.concat(["self"]),relevance:0}]),relevance:0},O={className:"function",begin:"("+o+"[\\*&\\s]+)+"+f,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:j,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:j,relevance:0},{begin:f,returnBegin:!0,contains:[m],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[c,d]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:j,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,c,d,l,{begin:/\(/,end:/\)/,keywords:j,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,c,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,p]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:j,illegal:"",keywords:j,contains:["self",l]},{begin:e.IDENT_RE+"::",keywords:j},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function vh(e){const t=["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],n=["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"],r=["default","false","null","true"],i=["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"],s=["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"],o={keyword:i.concat(s),built_in:t,literal:r},l=e.inherit(e.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),u={className:"number",variants:[{begin:"\\b(0b[01']+)"},{begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},c={className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},d={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},p=e.inherit(d,{illegal:/\n/}),m={className:"subst",begin:/\{/,end:/\}/,keywords:o},f=e.inherit(m,{illegal:/\n/}),g={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,f]},x={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},m]},y=e.inherit(x,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},f]});m.contains=[x,g,d,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,u,e.C_BLOCK_COMMENT_MODE],f.contains=[y,g,p,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,u,e.inherit(e.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];const b={variants:[c,x,g,d,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},k={begin:"<",end:">",contains:[{beginKeywords:"in out"},l]},A=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",j={begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:o,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:""},{begin:""}]}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},b,u,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},l,k,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[l,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[l,k,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+A+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:o,contains:[{beginKeywords:n.join(" "),relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[e.TITLE_MODE,k],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,relevance:0,contains:[b,u,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},j]}}const Eh=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),kh=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],wh=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],_h=[...kh,...wh],Nh=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),Sh=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Th=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Ch=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function Ah(e){const t=e.regex,n=Eh(e),r={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},i="and or not only",s=/@-?\w[\w]*(-\w+)*/,o="[a-zA-Z-][a-zA-Z0-9_-]*",l=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,r,n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\."+o,relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+Sh.join("|")+")"},{begin:":(:)?("+Th.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Ch.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...l,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...l,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:s},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:i,attribute:Nh.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...l,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+_h.join("|")+")\\b"}]}}function Mh(e){const t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}function Rh(e){const s={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:s,illegal:"va(e,t,n-1))}function Lh(e){const t=e.regex,n="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=n+va("(?:<"+n+"~~~(?:\\s*,\\s*"+n+"~~~)*>)?",/~~~/g,2),u={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},c={className:"meta",begin:"@"+n,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},d={className:"params",begin:/\(/,end:/\)/,keywords:u,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:u,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[t.concat(/(?!else)/,n),/\s+/,n,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,n],className:{1:"keyword",3:"title.class"},contains:[d,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:u,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:u,relevance:0,contains:[c,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,es,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},es,c]}}const ts="[A-Za-z$_][0-9A-Za-z$_]*",jh=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Dh=["true","false","null","undefined","NaN","Infinity"],Ea=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ka=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],wa=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Ph=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Bh=[].concat(wa,Ea,ka);function Fh(e){const t=e.regex,n=($,{after:q})=>{const h="",end:""},s=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:($,q)=>{const h=$[0].length+$.index,F=$.input[h];if(F==="<"||F===","){q.ignoreMatch();return}F===">"&&(n($,{after:h})||q.ignoreMatch());let U;const v=$.input.substring(h);if(U=v.match(/^\s*=/)){q.ignoreMatch();return}if((U=v.match(/^\s+extends\s+/))&&U.index===0){q.ignoreMatch();return}}},l={$pattern:ts,keyword:jh,literal:Dh,built_in:Bh,"variable.language":Ph},u="[0-9](_?[0-9])*",c=`\\.(${u})`,d="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",p={className:"number",variants:[{begin:`(\\b(${d})((${c})|\\.)?|(${c}))[eE][+-]?(${u})\\b`},{begin:`\\b(${d})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},m={className:"subst",begin:"\\$\\{",end:"\\}",keywords:l,contains:[]},f={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"xml"}},g={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"css"}},x={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"graphql"}},y={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,m]},k={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:r+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},A=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,g,x,y,{match:/\$\d+/},p];m.contains=A.concat({begin:/\{/,end:/\}/,keywords:l,contains:["self"].concat(A)});const j=[].concat(k,m.contains),L=j.concat([{begin:/(\s*)\(/,end:/\)/,keywords:l,contains:["self"].concat(j)}]),T={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:L},B={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,"(",t.concat(/\./,r),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,r],scope:{1:"keyword",3:"title.class"}}]},O={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...Ea,...ka]}},E={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},w={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[T],illegal:/%/},M={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function I($){return t.concat("(?!",$.join("|"),")")}const D={match:t.concat(/\b/,I([...wa,"super","import"].map($=>`${$}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},N={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},_={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},T]},R="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",W={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(R)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[T]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:l,exports:{PARAMS_CONTAINS:L,CLASS_REFERENCE:O},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),E,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,g,x,y,k,{match:/\$\d+/},p,O,{scope:"attr",match:r+t.lookahead(":"),relevance:0},W,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[k,e.REGEXP_MODE,{className:"function",begin:R,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:L}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:s},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[T,e.inherit(e.TITLE_MODE,{begin:r,className:"title.function"})]},{match:/\.\.\./,relevance:0},N,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[T]},D,M,B,_,{match:/\$[(.]/}]}}function zh(e){const t={className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},n={match:/[{}[\],:]/,className:"punctuation",relevance:0},r=["true","false","null"],i={scope:"literal",beginKeywords:r.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:r},contains:[t,n,e.QUOTE_STRING_MODE,i,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}var Jt="[0-9](_*[0-9])*",jn=`\\.(${Jt})`,Dn="[0-9a-fA-F](_*[0-9a-fA-F])*",Uh={className:"number",variants:[{begin:`(\\b(${Jt})((${jn})|\\.)?|(${jn}))[eE][+-]?(${Jt})[fFdD]?\\b`},{begin:`\\b(${Jt})((${jn})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${jn})[fFdD]?\\b`},{begin:`\\b(${Jt})[fFdD]\\b`},{begin:`\\b0[xX]((${Dn})\\.?|(${Dn})?\\.(${Dn}))[pP][+-]?(${Jt})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${Dn})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function $h(e){const t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},n={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},r={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@"},i={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},s={className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},o={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[s,i]},{begin:"'",end:"'",illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,s,i]}]};i.contains.push(o);const l={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?"},u={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[e.inherit(o,{className:"string"}),"self"]}]},c=Uh,d=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),p={variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},m=p;return m.variants[1].contains=[p],p.variants[1].contains=[m],{name:"Kotlin",aliases:["kt","kts"],keywords:t,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,d,n,r,l,u,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:t,relevance:5,contains:[{begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin://,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[p,e.C_LINE_COMMENT_MODE,d],relevance:0},e.C_LINE_COMMENT_MODE,d,l,u,o,e.C_NUMBER_MODE]},d]},{begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},e.UNDERSCORE_TITLE_MODE,{className:"type",begin://,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},l,u]},o,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:` -`},c]}}const Hh=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),Wh=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],Kh=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Gh=[...Wh,...Kh],qh=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),_a=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Na=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Vh=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),Yh=_a.concat(Na).sort().reverse();function Xh(e){const t=Hh(e),n=Yh,r="and or not only",i="[\\w-]+",s="("+i+"|@\\{"+i+"\\})",o=[],l=[],u=function(A){return{className:"string",begin:"~?"+A+".*?"+A}},c=function(A,j,L){return{className:A,begin:j,relevance:L}},d={$pattern:/[a-z-]+/,keyword:r,attribute:qh.join(" ")},p={begin:"\\(",end:"\\)",contains:l,keywords:d,relevance:0};l.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,u("'"),u('"'),t.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}},t.HEXCOLOR,p,c("variable","@@?"+i,10),c("variable","@\\{"+i+"\\}"),c("built_in","~?`[^`]*?`"),{className:"attribute",begin:i+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},t.IMPORTANT,{beginKeywords:"and not"},t.FUNCTION_DISPATCH);const m=l.concat({begin:/\{/,end:/\}/,contains:o}),f={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(l)},g={begin:s+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Vh.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:l}}]},x={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:d,returnEnd:!0,contains:l,relevance:0}},y={className:"variable",variants:[{begin:"@"+i+"\\s*:",relevance:15},{begin:"@"+i}],starts:{end:"[;}]",returnEnd:!0,contains:m}},b={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:s,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:`[<='$"]`,relevance:0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,f,c("keyword","all\\b"),c("variable","@\\{"+i+"\\}"),{begin:"\\b("+Gh.join("|")+")\\b",className:"selector-tag"},t.CSS_NUMBER_MODE,c("selector-tag",s,0),c("selector-id","#"+s),c("selector-class","\\."+s,0),c("selector-tag","&",0),t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+_a.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+Na.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:m},{begin:"!important"},t.FUNCTION_DISPATCH]},k={begin:i+`:(:)?(${n.join("|")})`,returnBegin:!0,contains:[b]};return o.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,x,y,k,g,b,f,t.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:`[=>'/<($"]`,contains:o}}function Zh(e){const t="\\[=*\\[",n="\\]=*\\]",r={begin:t,end:n,contains:["self"]},i=[e.COMMENT("--(?!"+t+")","$"),e.COMMENT("--"+t,n,{contains:[r],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:i.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:i}].concat(i)},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:t,end:n,contains:[r],relevance:5}])}}function Jh(e){const t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%",subLanguage:"xml",relevance:0},r={begin:"^[-\\*]{3,}",end:"$"},i={className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},s={className:"bullet",begin:"^[ ]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},o={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},l=/[A-Za-z][A-Za-z0-9+.-]*/,u={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:t.concat(/\[.+?\]\(/,l,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},c={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},d={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},p=e.inherit(c,{contains:[]}),m=e.inherit(d,{contains:[]});c.contains.push(m),d.contains.push(p);let f=[n,u];return[c,d,p,m].forEach(b=>{b.contains=b.contains.concat(f)}),f=f.concat(c,d),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:f},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:f}]}]},n,s,c,d,{className:"quote",begin:"^>\\s+",contains:f,end:"$"},i,r,u,o,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function eg(e){const t={className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},n=/[a-zA-Z@][a-zA-Z0-9_]*/,l={"variable.language":["this","super"],$pattern:n,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},u={$pattern:n,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:l,illegal:"/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+u.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:u,contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE,relevance:0}]}}function tg(e){const t=e.regex,n=["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"],r=/[dualxmsipngr]{0,12}/,i={$pattern:/[\w.]+/,keyword:n.join(" ")},s={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:i},o={begin:/->\{/,end:/\}/},l={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},u={scope:"variable",variants:[{begin:/\$\d/},{begin:t.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[l]},c={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},d=[e.BACKSLASH_ESCAPE,s,u],p=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],m=(x,y,b="\\1")=>{const k=b==="\\1"?b:t.concat(b,y);return t.concat(t.concat("(?:",x,")"),y,/(?:\\.|[^\\\/])*?/,k,/(?:\\.|[^\\\/])*?/,b,r)},f=(x,y,b)=>t.concat(t.concat("(?:",x,")"),y,/(?:\\.|[^\\\/])*?/,b,r),g=[u,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),o,{className:"string",contains:d,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},c,{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:m("s|tr|y",t.either(...p,{capture:!0}))},{begin:m("s|tr|y","\\(","\\)")},{begin:m("s|tr|y","\\[","\\]")},{begin:m("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:f("(?:m|qr)?",/\//,/\//)},{begin:f("m|qr",t.either(...p,{capture:!0}),/\1/)},{begin:f("m|qr",/\(/,/\)/)},{begin:f("m|qr",/\[/,/\]/)},{begin:f("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,l]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,l,c]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return s.contains=g,o.contains=g,{name:"Perl",aliases:["pl","pm"],keywords:i,contains:g}}function ng(e){const t=e.regex,n=/(?![A-Za-z0-9])(?![$])/,r=t.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,n),i=t.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,n),s=t.concat(/[A-Z]+/,n),o={scope:"variable",match:"\\$+"+r},l={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},u={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},c=e.inherit(e.APOS_STRING_MODE,{illegal:null}),d=e.inherit(e.QUOTE_STRING_MODE,{illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(u)}),p={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:e.QUOTE_STRING_MODE.contains.concat(u),"on:begin":(N,_)=>{_.data._beginMatch=N[1]||N[2]},"on:end":(N,_)=>{_.data._beginMatch!==N[1]&&_.ignoreMatch()}},m=e.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),f=`[ -]`,g={scope:"string",variants:[d,c,p,m]},x={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},y=["false","null","true"],b=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],k=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],j={keyword:b,literal:(N=>{const _=[];return N.forEach(R=>{_.push(R),R.toLowerCase()===R?_.push(R.toUpperCase()):_.push(R.toLowerCase())}),_})(y),built_in:k},L=N=>N.map(_=>_.replace(/\|\d+$/,"")),T={variants:[{match:[/new/,t.concat(f,"+"),t.concat("(?!",L(k).join("\\b|"),"\\b)"),i],scope:{1:"keyword",4:"title.class"}}]},B=t.concat(r,"\\b(?!\\()"),O={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),B],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[i,t.concat(/::/,t.lookahead(/(?!class\b)/)),B],scope:{1:"title.class",3:"variable.constant"}},{match:[i,t.concat("::",t.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},E={scope:"attr",match:t.concat(r,t.lookahead(":"),t.lookahead(/(?!::)/))},w={relevance:0,begin:/\(/,end:/\)/,keywords:j,contains:[E,o,O,e.C_BLOCK_COMMENT_MODE,g,x,T]},M={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",L(b).join("\\b|"),"|",L(k).join("\\b|"),"\\b)"),r,t.concat(f,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[w]};w.contains.push(M);const I=[E,O,e.C_BLOCK_COMMENT_MODE,g,x,T],D={begin:t.concat(/#\[\s*\\?/,t.either(i,s)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:y,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:y,keyword:["new","array"]},contains:["self",...I]},...I,{scope:"meta",variants:[{match:i},{match:s}]}]};return{case_insensitive:!1,keywords:j,contains:[D,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},l,{scope:"variable.language",match:/\$this\b/},o,M,O,{match:[/const/,/\s/,r],scope:{1:"keyword",3:"variable.constant"}},T,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:j,contains:["self",D,o,O,e.C_BLOCK_COMMENT_MODE,g,x]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},g,x]}}function rg(e){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}}function ig(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}function og(e){const t=e.regex,n=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],l={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},u={className:"meta",begin:/^(>>>|\.\.\.) /},c={className:"subst",begin:/\{/,end:/\}/,keywords:l,illegal:/#/},d={begin:/\{\{/,relevance:0},p={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,u],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,u],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,u,d,c]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,u,d,c]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,d,c]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,d,c]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},m="[0-9](_?[0-9])*",f=`(\\b(${m}))?\\.(${m})|\\b(${m})\\.`,g=`\\b|${r.join("|")}`,x={className:"number",relevance:0,variants:[{begin:`(\\b(${m})|(${f}))[eE][+-]?(${m})[jJ]?(?=${g})`},{begin:`(${f})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${g})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${g})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${g})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${g})`},{begin:`\\b(${m})[jJ](?=${g})`}]},y={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:l,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},b={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:["self",u,x,p,e.HASH_COMMENT_MODE]}]};return c.contains=[p,x,u],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:l,illegal:/(<\/|\?)|=>/,contains:[u,x,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},p,y,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[b]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[x,b,p]}]}}function sg(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}}function ag(e){const t=e.regex,n=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,r=t.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),i=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,s=t.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:n,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:t.lookahead(t.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:n},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[i,r]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,r]},{scope:{1:"punctuation",2:"number"},match:[s,r]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,r]}]},{scope:{3:"operator"},match:[n,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:i},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:s},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}}function lg(e){const t=e.regex,n="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",r=t.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=t.concat(r,/(::\w+)*/),o={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},l={className:"doctag",begin:"@[A-Za-z]+"},u={begin:"#<",end:">"},c=[e.COMMENT("#","$",{contains:[l]}),e.COMMENT("^=begin","^=end",{contains:[l],relevance:10}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],d={className:"subst",begin:/#\{/,end:/\}/,keywords:o},p={className:"string",contains:[e.BACKSLASH_ESCAPE,d],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:t.concat(/<<[-~]?'?/,t.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,d]})]}]},m="[1-9](_?[0-9])*|0",f="[0-9](_?[0-9])*",g={className:"number",relevance:0,variants:[{begin:`\\b(${m})(\\.(${f}))?([eE][+-]?(${f})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},x={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:o}]},T=[p,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:o},{match:[/(include|extend)\s+/,i],scope:{2:"title.class"},keywords:o},{relevance:0,match:[i,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:r,scope:"title.class"},{match:[/def/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[x]},{begin:e.IDENT_RE+"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[p,{begin:n}],relevance:0},g,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:o},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,d],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(u,c),relevance:0}].concat(u,c);d.contains=T,x.contains=T;const w=[{begin:/^\s*=>/,starts:{end:"$",contains:T}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:o,contains:T}}];return c.unshift(u),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:o,illegal:/\/\*/,contains:[e.SHEBANG({binary:"ruby"})].concat(w).concat(c).concat(T)}}function cg(e){const t=e.regex,n=/(r#)?/,r=t.concat(n,e.UNDERSCORE_IDENT_RE),i=t.concat(n,e.IDENT_RE),s={className:"title.function.invoke",relevance:0,begin:t.concat(/\b/,/(?!let|for|while|if|else|match\b)/,i,t.lookahead(/\s*\(/))},o="([ui](8|16|32|64|128|size)|f(32|64))?",l=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],u=["true","false","Some","None","Ok","Err"],c=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],d=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:d,keyword:l,literal:u,built_in:c},illegal:""},s]}}const ug=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),dg=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],pg=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],fg=[...dg,...pg],mg=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),hg=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),gg=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),bg=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function xg(e){const t=ug(e),n=gg,r=hg,i="@[a-z-]+",s="and or not only",l={className:"variable",begin:"(\\$"+"[a-zA-Z-][a-zA-Z0-9_-]*"+")\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+fg.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+n.join("|")+")"},l,{begin:/\(/,end:/\)/,contains:[t.CSS_NUMBER_MODE]},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+bg.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[t.BLOCK_COMMENT,l,t.HEXCOLOR,t.CSS_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.IMPORTANT,t.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:s,attribute:mg.join(" ")},contains:[{begin:i,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},l,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.HEXCOLOR,t.CSS_NUMBER_MODE]},t.FUNCTION_DISPATCH]}}function yg(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}function vg(e){const t=e.regex,n=e.COMMENT("--","$"),r={scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},i={begin:/"/,end:/"/,contains:[{match:/""/}]},s=["true","false","unknown"],o=["double precision","large object","with timezone","without timezone"],l=["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],u=["add","asc","collation","desc","final","first","last","view"],c=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year"],d=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],p=["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"],m=["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"],f=d,g=[...c,...u].filter(L=>!d.includes(L)),x={scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},y={scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},b={match:t.concat(/\b/,t.either(...f),/\s*\(/),relevance:0,keywords:{built_in:f}};function k(L){return t.concat(/\b/,t.either(...L.map(T=>T.replace(/\s+/,"\\s+"))),/\b/)}const A={scope:"keyword",match:k(m),relevance:0};function j(L,{exceptions:T,when:B}={}){const O=B;return T=T||[],L.map(E=>E.match(/\|\d+$/)||T.includes(E)?E:O(E)?`${E}|0`:E)}return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:j(g,{when:L=>L.length<3}),literal:s,type:l,built_in:p},contains:[{scope:"type",match:k(o)},A,b,x,r,i,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,y]}}function Sa(e){return e?typeof e=="string"?e:e.source:null}function dn(e){return _e("(?=",e,")")}function _e(...e){return e.map(n=>Sa(n)).join("")}function Eg(e){const t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function Ge(...e){return"("+(Eg(e).capture?"":"?:")+e.map(r=>Sa(r)).join("|")+")"}const fi=e=>_e(/\b/,e,/\w$/.test(e)?/\b/:/\B/),kg=["Protocol","Type"].map(fi),ns=["init","self"].map(fi),wg=["Any","Self"],_r=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],rs=["false","nil","true"],_g=["assignment","associativity","higherThan","left","lowerThan","none","right"],Ng=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],is=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],Ta=Ge(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),Ca=Ge(Ta,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),Nr=_e(Ta,Ca,"*"),Aa=Ge(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),Kn=Ge(Aa,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),ft=_e(Aa,Kn,"*"),Pn=_e(/[A-Z]/,Kn,"*"),Sg=["attached","autoclosure",_e(/convention\(/,Ge("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",_e(/objc\(/,ft,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],Tg=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function Cg(e){const t={match:/\s+/,relevance:0},n=e.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[e.C_LINE_COMMENT_MODE,n],i={match:[/\./,Ge(...kg,...ns)],className:{2:"keyword"}},s={match:_e(/\./,Ge(..._r)),relevance:0},o=_r.filter(ye=>typeof ye=="string").concat(["_|0"]),l=_r.filter(ye=>typeof ye!="string").concat(wg).map(fi),u={variants:[{className:"keyword",match:Ge(...l,...ns)}]},c={$pattern:Ge(/\b\w+/,/#\w+/),keyword:o.concat(Ng),literal:rs},d=[i,s,u],p={match:_e(/\./,Ge(...is)),relevance:0},m={className:"built_in",match:_e(/\b/,Ge(...is),/(?=\()/)},f=[p,m],g={match:/->/,relevance:0},x={className:"operator",relevance:0,variants:[{match:Nr},{match:`\\.(\\.|${Ca})+`}]},y=[g,x],b="([0-9]_*)+",k="([0-9a-fA-F]_*)+",A={className:"number",relevance:0,variants:[{match:`\\b(${b})(\\.(${b}))?([eE][+-]?(${b}))?\\b`},{match:`\\b0x(${k})(\\.(${k}))?([pP][+-]?(${b}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},j=(ye="")=>({className:"subst",variants:[{match:_e(/\\/,ye,/[0\\tnr"']/)},{match:_e(/\\/,ye,/u\{[0-9a-fA-F]{1,8}\}/)}]}),L=(ye="")=>({className:"subst",match:_e(/\\/,ye,/[\t ]*(?:[\r\n]|\r\n)/)}),T=(ye="")=>({className:"subst",label:"interpol",begin:_e(/\\/,ye,/\(/),end:/\)/}),B=(ye="")=>({begin:_e(ye,/"""/),end:_e(/"""/,ye),contains:[j(ye),L(ye),T(ye)]}),O=(ye="")=>({begin:_e(ye,/"/),end:_e(/"/,ye),contains:[j(ye),T(ye)]}),E={className:"string",variants:[B(),B("#"),B("##"),B("###"),O(),O("#"),O("##"),O("###")]},w=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],M={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:w},I=ye=>{const at=_e(ye,/\//),nt=_e(/\//,ye);return{begin:at,end:nt,contains:[...w,{scope:"comment",begin:`#(?!.*${nt})`,end:/$/}]}},D={scope:"regexp",variants:[I("###"),I("##"),I("#"),M]},N={match:_e(/`/,ft,/`/)},_={className:"variable",match:/\$\d+/},R={className:"variable",match:`\\$${Kn}+`},W=[N,_,R],$={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:Tg,contains:[...y,A,E]}]}},q={scope:"keyword",match:_e(/@/,Ge(...Sg),dn(Ge(/\(/,/\s+/)))},h={scope:"meta",match:_e(/@/,ft)},F=[$,q,h],U={match:dn(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:_e(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,Kn,"+")},{className:"type",match:Pn,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:_e(/\s+&\s+/,dn(Pn)),relevance:0}]},v={begin://,keywords:c,contains:[...r,...d,...F,g,U]};U.contains.push(v);const oe={match:_e(ft,/\s*:/),keywords:"_|0",relevance:0},ae={begin:/\(/,end:/\)/,relevance:0,keywords:c,contains:["self",oe,...r,D,...d,...f,...y,A,E,...W,...F,U]},K={begin://,keywords:"repeat each",contains:[...r,U]},re={begin:Ge(dn(_e(ft,/\s*:/)),dn(_e(ft,/\s+/,ft,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:ft}]},de={begin:/\(/,end:/\)/,keywords:c,contains:[re,...r,...d,...y,A,E,...F,U,ae],endsParent:!0,illegal:/["']/},be={match:[/(func|macro)/,/\s+/,Ge(N.match,ft,Nr)],className:{1:"keyword",3:"title.function"},contains:[K,de,t],illegal:[/\[/,/%/]},Oe={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[K,de,t],illegal:/\[|%/},Re={match:[/operator/,/\s+/,Nr],className:{1:"keyword",3:"title"}},st={begin:[/precedencegroup/,/\s+/,Pn],className:{1:"keyword",3:"title"},contains:[U],keywords:[..._g,...rs],end:/}/},St={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},Pt={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},yt={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,ft,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:c,contains:[K,...d,{begin:/:/,end:/\{/,keywords:c,contains:[{scope:"title.class.inherited",match:Pn},...d],relevance:0}]};for(const ye of E.variants){const at=ye.contains.find(vt=>vt.label==="interpol");at.keywords=c;const nt=[...d,...f,...y,A,E,...W];at.contains=[...nt,{begin:/\(/,end:/\)/,contains:["self",...nt]}]}return{name:"Swift",keywords:c,contains:[...r,be,Oe,St,Pt,yt,Re,st,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},D,...d,...f,...y,A,E,...W,...F,U,ae]}}const Gn="[A-Za-z$_][0-9A-Za-z$_]*",Ma=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Ra=["true","false","null","undefined","NaN","Infinity"],Ia=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],Oa=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],La=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],ja=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Da=[].concat(La,Ia,Oa);function Ag(e){const t=e.regex,n=($,{after:q})=>{const h="",end:""},s=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:($,q)=>{const h=$[0].length+$.index,F=$.input[h];if(F==="<"||F===","){q.ignoreMatch();return}F===">"&&(n($,{after:h})||q.ignoreMatch());let U;const v=$.input.substring(h);if(U=v.match(/^\s*=/)){q.ignoreMatch();return}if((U=v.match(/^\s+extends\s+/))&&U.index===0){q.ignoreMatch();return}}},l={$pattern:Gn,keyword:Ma,literal:Ra,built_in:Da,"variable.language":ja},u="[0-9](_?[0-9])*",c=`\\.(${u})`,d="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",p={className:"number",variants:[{begin:`(\\b(${d})((${c})|\\.)?|(${c}))[eE][+-]?(${u})\\b`},{begin:`\\b(${d})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},m={className:"subst",begin:"\\$\\{",end:"\\}",keywords:l,contains:[]},f={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"xml"}},g={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"css"}},x={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"graphql"}},y={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,m]},k={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:r+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},A=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,g,x,y,{match:/\$\d+/},p];m.contains=A.concat({begin:/\{/,end:/\}/,keywords:l,contains:["self"].concat(A)});const j=[].concat(k,m.contains),L=j.concat([{begin:/(\s*)\(/,end:/\)/,keywords:l,contains:["self"].concat(j)}]),T={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:L},B={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,"(",t.concat(/\./,r),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,r],scope:{1:"keyword",3:"title.class"}}]},O={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...Ia,...Oa]}},E={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},w={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[T],illegal:/%/},M={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function I($){return t.concat("(?!",$.join("|"),")")}const D={match:t.concat(/\b/,I([...La,"super","import"].map($=>`${$}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},N={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},_={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},T]},R="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",W={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(R)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[T]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:l,exports:{PARAMS_CONTAINS:L,CLASS_REFERENCE:O},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),E,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,g,x,y,k,{match:/\$\d+/},p,O,{scope:"attr",match:r+t.lookahead(":"),relevance:0},W,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[k,e.REGEXP_MODE,{className:"function",begin:R,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:L}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:s},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[T,e.inherit(e.TITLE_MODE,{begin:r,className:"title.function"})]},{match:/\.\.\./,relevance:0},N,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[T]},D,M,B,_,{match:/\$[(.]/}]}}function Mg(e){const t=e.regex,n=Ag(e),r=Gn,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],s={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},o={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:i},contains:[n.exports.CLASS_REFERENCE]},l={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},u=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],c={$pattern:Gn,keyword:Ma.concat(u),literal:Ra,built_in:Da.concat(i),"variable.language":ja},d={className:"meta",begin:"@"+r},p=(x,y,b)=>{const k=x.contains.findIndex(A=>A.label===y);if(k===-1)throw new Error("can not find mode to replace");x.contains.splice(k,1,b)};Object.assign(n.keywords,c),n.exports.PARAMS_CONTAINS.push(d);const m=n.contains.find(x=>x.scope==="attr"),f=Object.assign({},m,{match:t.concat(r,t.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,m,f]),n.contains=n.contains.concat([d,s,o,f]),p(n,"shebang",e.SHEBANG()),p(n,"use_strict",l);const g=n.contains.find(x=>x.label==="func.def");return g.relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}function Rg(e){const t=e.regex,n={className:"string",begin:/"(""|[^/n])"C\b/},r={className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},i=/\d{1,2}\/\d{1,2}\/\d{4}/,s=/\d{4}-\d{1,2}-\d{1,2}/,o=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,l=/\d{1,2}(:\d{1,2}){1,2}/,u={className:"literal",variants:[{begin:t.concat(/# */,t.either(s,i),/ *#/)},{begin:t.concat(/# */,l,/ *#/)},{begin:t.concat(/# */,o,/ *#/)},{begin:t.concat(/# */,t.either(s,i),/ +/,t.either(o,l),/ *#/)}]},c={className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},d={className:"label",begin:/^\w+:/},p=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),m=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[n,r,u,c,d,p,m,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[m]}]}}function Ig(e){e.regex;const t=e.COMMENT(/\(;/,/;\)/);t.contains.push("self");const n=e.COMMENT(/;;/,/$/),r=["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"],i={begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},s={className:"variable",begin:/\$[\w_]+/},o={match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},l={className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/},u={match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},c={className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/};return{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:r},contains:[n,t,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},s,o,i,e.QUOTE_STRING_MODE,u,c,l]}}function Og(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r=/[\p{L}0-9._:-]+/u,i={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},s={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(s,{begin:/\(/,end:/\)/}),l=e.inherit(e.APOS_STRING_MODE,{className:"string"}),u=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),c={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin://,relevance:10,contains:[s,u,l,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[s,o,u,l]}]}]},e.COMMENT(//,{relevance:10}),{begin://,relevance:10},i,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[u]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[c],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[c],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:c}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function Lg(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},i={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},s={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},o={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,i]},l=e.inherit(o,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),m={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},f={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},g={begin:/\{/,end:/\}/,contains:[f],illegal:"\\n",relevance:0},x={begin:"\\[",end:"\\]",contains:[f],illegal:"\\n",relevance:0},y=[r,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},m,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},g,x,s,o],b=[...y];return b.pop(),b.push(l),f.contains=b,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:y}}const jg={arduino:gh,bash:bh,c:xh,cpp:yh,csharp:vh,css:Ah,diff:Mh,go:Rh,graphql:Ih,ini:Oh,java:Lh,javascript:Fh,json:zh,kotlin:$h,less:Xh,lua:Zh,makefile:Jh,markdown:Qh,objectivec:eg,perl:tg,php:ng,"php-template":rg,plaintext:ig,python:og,"python-repl":sg,r:ag,ruby:lg,rust:cg,scss:xg,shell:yg,sql:vg,swift:Cg,typescript:Mg,vbnet:Rg,wasm:Ig,xml:Og,yaml:Lg};var Sr,os;function Dg(){if(os)return Sr;os=1;function e(C){return C instanceof Map?C.clear=C.delete=C.set=function(){throw new Error("map is read-only")}:C instanceof Set&&(C.add=C.clear=C.delete=function(){throw new Error("set is read-only")}),Object.freeze(C),Object.getOwnPropertyNames(C).forEach(z=>{const Y=C[z],ce=typeof Y;(ce==="object"||ce==="function")&&!Object.isFrozen(Y)&&e(Y)}),C}class t{constructor(z){z.data===void 0&&(z.data={}),this.data=z.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(C){return C.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function r(C,...z){const Y=Object.create(null);for(const ce in C)Y[ce]=C[ce];return z.forEach(function(ce){for(const Le in ce)Y[Le]=ce[Le]}),Y}const i="",s=C=>!!C.scope,o=(C,{prefix:z})=>{if(C.startsWith("language:"))return C.replace("language:","language-");if(C.includes(".")){const Y=C.split(".");return[`${z}${Y.shift()}`,...Y.map((ce,Le)=>`${ce}${"_".repeat(Le+1)}`)].join(" ")}return`${z}${C}`};class l{constructor(z,Y){this.buffer="",this.classPrefix=Y.classPrefix,z.walk(this)}addText(z){this.buffer+=n(z)}openNode(z){if(!s(z))return;const Y=o(z.scope,{prefix:this.classPrefix});this.span(Y)}closeNode(z){s(z)&&(this.buffer+=i)}value(){return this.buffer}span(z){this.buffer+=``}}const u=(C={})=>{const z={children:[]};return Object.assign(z,C),z};class c{constructor(){this.rootNode=u(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(z){this.top.children.push(z)}openNode(z){const Y=u({scope:z});this.add(Y),this.stack.push(Y)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(z){return this.constructor._walk(z,this.rootNode)}static _walk(z,Y){return typeof Y=="string"?z.addText(Y):Y.children&&(z.openNode(Y),Y.children.forEach(ce=>this._walk(z,ce)),z.closeNode(Y)),z}static _collapse(z){typeof z!="string"&&z.children&&(z.children.every(Y=>typeof Y=="string")?z.children=[z.children.join("")]:z.children.forEach(Y=>{c._collapse(Y)}))}}class d extends c{constructor(z){super(),this.options=z}addText(z){z!==""&&this.add(z)}startScope(z){this.openNode(z)}endScope(){this.closeNode()}__addSublanguage(z,Y){const ce=z.root;Y&&(ce.scope=`language:${Y}`),this.add(ce)}toHTML(){return new l(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function p(C){return C?typeof C=="string"?C:C.source:null}function m(C){return x("(?=",C,")")}function f(C){return x("(?:",C,")*")}function g(C){return x("(?:",C,")?")}function x(...C){return C.map(Y=>p(Y)).join("")}function y(C){const z=C[C.length-1];return typeof z=="object"&&z.constructor===Object?(C.splice(C.length-1,1),z):{}}function b(...C){return"("+(y(C).capture?"":"?:")+C.map(ce=>p(ce)).join("|")+")"}function k(C){return new RegExp(C.toString()+"|").exec("").length-1}function A(C,z){const Y=C&&C.exec(z);return Y&&Y.index===0}const j=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function L(C,{joinWith:z}){let Y=0;return C.map(ce=>{Y+=1;const Le=Y;let je=p(ce),ee="";for(;je.length>0;){const J=j.exec(je);if(!J){ee+=je;break}ee+=je.substring(0,J.index),je=je.substring(J.index+J[0].length),J[0][0]==="\\"&&J[1]?ee+="\\"+String(Number(J[1])+Le):(ee+=J[0],J[0]==="("&&Y++)}return ee}).map(ce=>`(${ce})`).join(z)}const T=/\b\B/,B="[a-zA-Z]\\w*",O="[a-zA-Z_]\\w*",E="\\b\\d+(\\.\\d+)?",w="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",M="\\b(0b[01]+)",I="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",D=(C={})=>{const z=/^#![ ]*\//;return C.binary&&(C.begin=x(z,/.*\b/,C.binary,/\b.*/)),r({scope:"meta",begin:z,end:/$/,relevance:0,"on:begin":(Y,ce)=>{Y.index!==0&&ce.ignoreMatch()}},C)},N={begin:"\\\\[\\s\\S]",relevance:0},_={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[N]},R={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[N]},W={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},$=function(C,z,Y={}){const ce=r({scope:"comment",begin:C,end:z,contains:[]},Y);ce.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const Le=b("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return ce.contains.push({begin:x(/[ ]+/,"(",Le,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),ce},q=$("//","$"),h=$("/\\*","\\*/"),F=$("#","$"),U={scope:"number",begin:E,relevance:0},v={scope:"number",begin:w,relevance:0},oe={scope:"number",begin:M,relevance:0},ae={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[N,{begin:/\[/,end:/\]/,relevance:0,contains:[N]}]},K={scope:"title",begin:B,relevance:0},re={scope:"title",begin:O,relevance:0},de={begin:"\\.\\s*"+O,relevance:0};var Oe=Object.freeze({__proto__:null,APOS_STRING_MODE:_,BACKSLASH_ESCAPE:N,BINARY_NUMBER_MODE:oe,BINARY_NUMBER_RE:M,COMMENT:$,C_BLOCK_COMMENT_MODE:h,C_LINE_COMMENT_MODE:q,C_NUMBER_MODE:v,C_NUMBER_RE:w,END_SAME_AS_BEGIN:function(C){return Object.assign(C,{"on:begin":(z,Y)=>{Y.data._beginMatch=z[1]},"on:end":(z,Y)=>{Y.data._beginMatch!==z[1]&&Y.ignoreMatch()}})},HASH_COMMENT_MODE:F,IDENT_RE:B,MATCH_NOTHING_RE:T,METHOD_GUARD:de,NUMBER_MODE:U,NUMBER_RE:E,PHRASAL_WORDS_MODE:W,QUOTE_STRING_MODE:R,REGEXP_MODE:ae,RE_STARTERS_RE:I,SHEBANG:D,TITLE_MODE:K,UNDERSCORE_IDENT_RE:O,UNDERSCORE_TITLE_MODE:re});function Re(C,z){C.input[C.index-1]==="."&&z.ignoreMatch()}function st(C,z){C.className!==void 0&&(C.scope=C.className,delete C.className)}function St(C,z){z&&C.beginKeywords&&(C.begin="\\b("+C.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",C.__beforeBegin=Re,C.keywords=C.keywords||C.beginKeywords,delete C.beginKeywords,C.relevance===void 0&&(C.relevance=0))}function Pt(C,z){Array.isArray(C.illegal)&&(C.illegal=b(...C.illegal))}function yt(C,z){if(C.match){if(C.begin||C.end)throw new Error("begin & end are not supported with match");C.begin=C.match,delete C.match}}function ye(C,z){C.relevance===void 0&&(C.relevance=1)}const at=(C,z)=>{if(!C.beforeMatch)return;if(C.starts)throw new Error("beforeMatch cannot be used with starts");const Y=Object.assign({},C);Object.keys(C).forEach(ce=>{delete C[ce]}),C.keywords=Y.keywords,C.begin=x(Y.beforeMatch,m(Y.begin)),C.starts={relevance:0,contains:[Object.assign(Y,{endsParent:!0})]},C.relevance=0,delete Y.beforeMatch},nt=["of","and","for","in","not","or","if","then","parent","list","value"],vt="keyword";function Bt(C,z,Y=vt){const ce=Object.create(null);return typeof C=="string"?Le(Y,C.split(" ")):Array.isArray(C)?Le(Y,C):Object.keys(C).forEach(function(je){Object.assign(ce,Bt(C[je],z,je))}),ce;function Le(je,ee){z&&(ee=ee.map(J=>J.toLowerCase())),ee.forEach(function(J){const le=J.split("|");ce[le[0]]=[je,Gt(le[0],le[1])]})}}function Gt(C,z){return z?Number(z):Z(C)?0:1}function Z(C){return nt.includes(C.toLowerCase())}const he={},Ie=C=>{console.error(C)},fe=(C,...z)=>{console.log(`WARN: ${C}`,...z)},P=(C,z)=>{he[`${C}/${z}`]||(console.log(`Deprecated as of ${C}. ${z}`),he[`${C}/${z}`]=!0)},H=new Error;function Q(C,z,{key:Y}){let ce=0;const Le=C[Y],je={},ee={};for(let J=1;J<=z.length;J++)ee[J+ce]=Le[J],je[J+ce]=!0,ce+=k(z[J-1]);C[Y]=ee,C[Y]._emit=je,C[Y]._multi=!0}function se(C){if(Array.isArray(C.begin)){if(C.skip||C.excludeBegin||C.returnBegin)throw Ie("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),H;if(typeof C.beginScope!="object"||C.beginScope===null)throw Ie("beginScope must be object"),H;Q(C,C.begin,{key:"beginScope"}),C.begin=L(C.begin,{joinWith:""})}}function ke(C){if(Array.isArray(C.end)){if(C.skip||C.excludeEnd||C.returnEnd)throw Ie("skip, excludeEnd, returnEnd not compatible with endScope: {}"),H;if(typeof C.endScope!="object"||C.endScope===null)throw Ie("endScope must be object"),H;Q(C,C.end,{key:"endScope"}),C.end=L(C.end,{joinWith:""})}}function We(C){C.scope&&typeof C.scope=="object"&&C.scope!==null&&(C.beginScope=C.scope,delete C.scope)}function Et(C){We(C),typeof C.beginScope=="string"&&(C.beginScope={_wrap:C.beginScope}),typeof C.endScope=="string"&&(C.endScope={_wrap:C.endScope}),se(C),ke(C)}function lt(C){function z(ee,J){return new RegExp(p(ee),"m"+(C.case_insensitive?"i":"")+(C.unicodeRegex?"u":"")+(J?"g":""))}class Y{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(J,le){le.position=this.position++,this.matchIndexes[this.matchAt]=le,this.regexes.push([le,J]),this.matchAt+=k(J)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const J=this.regexes.map(le=>le[1]);this.matcherRe=z(L(J,{joinWith:"|"}),!0),this.lastIndex=0}exec(J){this.matcherRe.lastIndex=this.lastIndex;const le=this.matcherRe.exec(J);if(!le)return null;const Fe=le.findIndex((sn,er)=>er>0&&sn!==void 0),De=this.matchIndexes[Fe];return le.splice(0,Fe),Object.assign(le,De)}}class ce{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(J){if(this.multiRegexes[J])return this.multiRegexes[J];const le=new Y;return this.rules.slice(J).forEach(([Fe,De])=>le.addRule(Fe,De)),le.compile(),this.multiRegexes[J]=le,le}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(J,le){this.rules.push([J,le]),le.type==="begin"&&this.count++}exec(J){const le=this.getMatcher(this.regexIndex);le.lastIndex=this.lastIndex;let Fe=le.exec(J);if(this.resumingScanAtSamePosition()&&!(Fe&&Fe.index===this.lastIndex)){const De=this.getMatcher(0);De.lastIndex=this.lastIndex+1,Fe=De.exec(J)}return Fe&&(this.regexIndex+=Fe.position+1,this.regexIndex===this.count&&this.considerAll()),Fe}}function Le(ee){const J=new ce;return ee.contains.forEach(le=>J.addRule(le.begin,{rule:le,type:"begin"})),ee.terminatorEnd&&J.addRule(ee.terminatorEnd,{type:"end"}),ee.illegal&&J.addRule(ee.illegal,{type:"illegal"}),J}function je(ee,J){const le=ee;if(ee.isCompiled)return le;[st,yt,Et,at].forEach(De=>De(ee,J)),C.compilerExtensions.forEach(De=>De(ee,J)),ee.__beforeBegin=null,[St,Pt,ye].forEach(De=>De(ee,J)),ee.isCompiled=!0;let Fe=null;return typeof ee.keywords=="object"&&ee.keywords.$pattern&&(ee.keywords=Object.assign({},ee.keywords),Fe=ee.keywords.$pattern,delete ee.keywords.$pattern),Fe=Fe||/\w+/,ee.keywords&&(ee.keywords=Bt(ee.keywords,C.case_insensitive)),le.keywordPatternRe=z(Fe,!0),J&&(ee.begin||(ee.begin=/\B|\b/),le.beginRe=z(le.begin),!ee.end&&!ee.endsWithParent&&(ee.end=/\B|\b/),ee.end&&(le.endRe=z(le.end)),le.terminatorEnd=p(le.end)||"",ee.endsWithParent&&J.terminatorEnd&&(le.terminatorEnd+=(ee.end?"|":"")+J.terminatorEnd)),ee.illegal&&(le.illegalRe=z(ee.illegal)),ee.contains||(ee.contains=[]),ee.contains=[].concat(...ee.contains.map(function(De){return Ft(De==="self"?ee:De)})),ee.contains.forEach(function(De){je(De,le)}),ee.starts&&je(ee.starts,J),le.matcher=Le(le),le}if(C.compilerExtensions||(C.compilerExtensions=[]),C.contains&&C.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return C.classNameAliases=r(C.classNameAliases||{}),je(C)}function Tt(C){return C?C.endsWithParent||Tt(C.starts):!1}function Ft(C){return C.variants&&!C.cachedVariants&&(C.cachedVariants=C.variants.map(function(z){return r(C,{variants:null},z)})),C.cachedVariants?C.cachedVariants:Tt(C)?r(C,{starts:C.starts?r(C.starts):null}):Object.isFrozen(C)?r(C):C}var Ke="11.11.1";class Ct extends Error{constructor(z,Y){super(z),this.name="HTMLInjectionError",this.html=Y}}const Xe=n,bi=r,xi=Symbol("nomatch"),sl=7,yi=function(C){const z=Object.create(null),Y=Object.create(null),ce=[];let Le=!0;const je="Could not find the language '{}', did you forget to load/include a language module?",ee={disableAutodetect:!0,name:"Plain text",contains:[]};let J={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:d};function le(V){return J.noHighlightRe.test(V)}function Fe(V){let ne=V.className+" ";ne+=V.parentNode?V.parentNode.className:"";const xe=J.languageDetectRe.exec(ne);if(xe){const Se=At(xe[1]);return Se||(fe(je.replace("{}",xe[1])),fe("Falling back to no-highlight mode for this block.",V)),Se?xe[1]:"no-highlight"}return ne.split(/\s+/).find(Se=>le(Se)||At(Se))}function De(V,ne,xe){let Se="",Be="";typeof ne=="object"?(Se=V,xe=ne.ignoreIllegals,Be=ne.language):(P("10.7.0","highlight(lang, code, ...args) has been deprecated."),P("10.7.0",`Please use highlight(code, options) instead. -https://github.com/highlightjs/highlight.js/issues/2277`),Be=V,Se=ne),xe===void 0&&(xe=!0);const ct={code:Se,language:Be};wn("before:highlight",ct);const Mt=ct.result?ct.result:sn(ct.language,ct.code,xe);return Mt.code=ct.code,wn("after:highlight",Mt),Mt}function sn(V,ne,xe,Se){const Be=Object.create(null);function ct(X,te){return X.keywords[te]}function Mt(){if(!ue.keywords){ze.addText(Te);return}let X=0;ue.keywordPatternRe.lastIndex=0;let te=ue.keywordPatternRe.exec(Te),me="";for(;te;){me+=Te.substring(X,te.index);const we=pt.case_insensitive?te[0].toLowerCase():te[0],Ue=ct(ue,we);if(Ue){const[kt,wl]=Ue;if(ze.addText(me),me="",Be[we]=(Be[we]||0)+1,Be[we]<=sl&&(Sn+=wl),kt.startsWith("_"))me+=te[0];else{const _l=pt.classNameAliases[kt]||kt;dt(te[0],_l)}}else me+=te[0];X=ue.keywordPatternRe.lastIndex,te=ue.keywordPatternRe.exec(Te)}me+=Te.substring(X),ze.addText(me)}function _n(){if(Te==="")return;let X=null;if(typeof ue.subLanguage=="string"){if(!z[ue.subLanguage]){ze.addText(Te);return}X=sn(ue.subLanguage,Te,!0,Ti[ue.subLanguage]),Ti[ue.subLanguage]=X._top}else X=tr(Te,ue.subLanguage.length?ue.subLanguage:null);ue.relevance>0&&(Sn+=X.relevance),ze.__addSublanguage(X._emitter,X.language)}function Ze(){ue.subLanguage!=null?_n():Mt(),Te=""}function dt(X,te){X!==""&&(ze.startScope(te),ze.addText(X),ze.endScope())}function wi(X,te){let me=1;const we=te.length-1;for(;me<=we;){if(!X._emit[me]){me++;continue}const Ue=pt.classNameAliases[X[me]]||X[me],kt=te[me];Ue?dt(kt,Ue):(Te=kt,Mt(),Te=""),me++}}function _i(X,te){return X.scope&&typeof X.scope=="string"&&ze.openNode(pt.classNameAliases[X.scope]||X.scope),X.beginScope&&(X.beginScope._wrap?(dt(Te,pt.classNameAliases[X.beginScope._wrap]||X.beginScope._wrap),Te=""):X.beginScope._multi&&(wi(X.beginScope,te),Te="")),ue=Object.create(X,{parent:{value:ue}}),ue}function Ni(X,te,me){let we=A(X.endRe,me);if(we){if(X["on:end"]){const Ue=new t(X);X["on:end"](te,Ue),Ue.isMatchIgnored&&(we=!1)}if(we){for(;X.endsParent&&X.parent;)X=X.parent;return X}}if(X.endsWithParent)return Ni(X.parent,te,me)}function xl(X){return ue.matcher.regexIndex===0?(Te+=X[0],1):(or=!0,0)}function yl(X){const te=X[0],me=X.rule,we=new t(me),Ue=[me.__beforeBegin,me["on:begin"]];for(const kt of Ue)if(kt&&(kt(X,we),we.isMatchIgnored))return xl(te);return me.skip?Te+=te:(me.excludeBegin&&(Te+=te),Ze(),!me.returnBegin&&!me.excludeBegin&&(Te=te)),_i(me,X),me.returnBegin?0:te.length}function vl(X){const te=X[0],me=ne.substring(X.index),we=Ni(ue,X,me);if(!we)return xi;const Ue=ue;ue.endScope&&ue.endScope._wrap?(Ze(),dt(te,ue.endScope._wrap)):ue.endScope&&ue.endScope._multi?(Ze(),wi(ue.endScope,X)):Ue.skip?Te+=te:(Ue.returnEnd||Ue.excludeEnd||(Te+=te),Ze(),Ue.excludeEnd&&(Te=te));do ue.scope&&ze.closeNode(),!ue.skip&&!ue.subLanguage&&(Sn+=ue.relevance),ue=ue.parent;while(ue!==we.parent);return we.starts&&_i(we.starts,X),Ue.returnEnd?0:te.length}function El(){const X=[];for(let te=ue;te!==pt;te=te.parent)te.scope&&X.unshift(te.scope);X.forEach(te=>ze.openNode(te))}let Nn={};function Si(X,te){const me=te&&te[0];if(Te+=X,me==null)return Ze(),0;if(Nn.type==="begin"&&te.type==="end"&&Nn.index===te.index&&me===""){if(Te+=ne.slice(te.index,te.index+1),!Le){const we=new Error(`0 width match regex (${V})`);throw we.languageName=V,we.badRule=Nn.rule,we}return 1}if(Nn=te,te.type==="begin")return yl(te);if(te.type==="illegal"&&!xe){const we=new Error('Illegal lexeme "'+me+'" for mode "'+(ue.scope||"")+'"');throw we.mode=ue,we}else if(te.type==="end"){const we=vl(te);if(we!==xi)return we}if(te.type==="illegal"&&me==="")return Te+=` -`,1;if(ir>1e5&&ir>te.index*3)throw new Error("potential infinite loop, way more iterations than matches");return Te+=me,me.length}const pt=At(V);if(!pt)throw Ie(je.replace("{}",V)),new Error('Unknown language: "'+V+'"');const kl=lt(pt);let rr="",ue=Se||kl;const Ti={},ze=new J.__emitter(J);El();let Te="",Sn=0,zt=0,ir=0,or=!1;try{if(pt.__emitTokens)pt.__emitTokens(ne,ze);else{for(ue.matcher.considerAll();;){ir++,or?or=!1:ue.matcher.considerAll(),ue.matcher.lastIndex=zt;const X=ue.matcher.exec(ne);if(!X)break;const te=ne.substring(zt,X.index),me=Si(te,X);zt=X.index+me}Si(ne.substring(zt))}return ze.finalize(),rr=ze.toHTML(),{language:V,value:rr,relevance:Sn,illegal:!1,_emitter:ze,_top:ue}}catch(X){if(X.message&&X.message.includes("Illegal"))return{language:V,value:Xe(ne),illegal:!0,relevance:0,_illegalBy:{message:X.message,index:zt,context:ne.slice(zt-100,zt+100),mode:X.mode,resultSoFar:rr},_emitter:ze};if(Le)return{language:V,value:Xe(ne),illegal:!1,relevance:0,errorRaised:X,_emitter:ze,_top:ue};throw X}}function er(V){const ne={value:Xe(V),illegal:!1,relevance:0,_top:ee,_emitter:new J.__emitter(J)};return ne._emitter.addText(V),ne}function tr(V,ne){ne=ne||J.languages||Object.keys(z);const xe=er(V),Se=ne.filter(At).filter(ki).map(Ze=>sn(Ze,V,!1));Se.unshift(xe);const Be=Se.sort((Ze,dt)=>{if(Ze.relevance!==dt.relevance)return dt.relevance-Ze.relevance;if(Ze.language&&dt.language){if(At(Ze.language).supersetOf===dt.language)return 1;if(At(dt.language).supersetOf===Ze.language)return-1}return 0}),[ct,Mt]=Be,_n=ct;return _n.secondBest=Mt,_n}function al(V,ne,xe){const Se=ne&&Y[ne]||xe;V.classList.add("hljs"),V.classList.add(`language-${Se}`)}function nr(V){let ne=null;const xe=Fe(V);if(le(xe))return;if(wn("before:highlightElement",{el:V,language:xe}),V.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",V);return}if(V.children.length>0&&(J.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(V)),J.throwUnescapedHTML))throw new Ct("One of your code blocks includes unescaped HTML.",V.innerHTML);ne=V;const Se=ne.textContent,Be=xe?De(Se,{language:xe,ignoreIllegals:!0}):tr(Se);V.innerHTML=Be.value,V.dataset.highlighted="yes",al(V,xe,Be.language),V.result={language:Be.language,re:Be.relevance,relevance:Be.relevance},Be.secondBest&&(V.secondBest={language:Be.secondBest.language,relevance:Be.secondBest.relevance}),wn("after:highlightElement",{el:V,result:Be,text:Se})}function ll(V){J=bi(J,V)}const cl=()=>{kn(),P("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function ul(){kn(),P("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let vi=!1;function kn(){function V(){kn()}if(document.readyState==="loading"){vi||window.addEventListener("DOMContentLoaded",V,!1),vi=!0;return}document.querySelectorAll(J.cssSelector).forEach(nr)}function dl(V,ne){let xe=null;try{xe=ne(C)}catch(Se){if(Ie("Language definition for '{}' could not be registered.".replace("{}",V)),Le)Ie(Se);else throw Se;xe=ee}xe.name||(xe.name=V),z[V]=xe,xe.rawDefinition=ne.bind(null,C),xe.aliases&&Ei(xe.aliases,{languageName:V})}function pl(V){delete z[V];for(const ne of Object.keys(Y))Y[ne]===V&&delete Y[ne]}function fl(){return Object.keys(z)}function At(V){return V=(V||"").toLowerCase(),z[V]||z[Y[V]]}function Ei(V,{languageName:ne}){typeof V=="string"&&(V=[V]),V.forEach(xe=>{Y[xe.toLowerCase()]=ne})}function ki(V){const ne=At(V);return ne&&!ne.disableAutodetect}function ml(V){V["before:highlightBlock"]&&!V["before:highlightElement"]&&(V["before:highlightElement"]=ne=>{V["before:highlightBlock"](Object.assign({block:ne.el},ne))}),V["after:highlightBlock"]&&!V["after:highlightElement"]&&(V["after:highlightElement"]=ne=>{V["after:highlightBlock"](Object.assign({block:ne.el},ne))})}function hl(V){ml(V),ce.push(V)}function gl(V){const ne=ce.indexOf(V);ne!==-1&&ce.splice(ne,1)}function wn(V,ne){const xe=V;ce.forEach(function(Se){Se[xe]&&Se[xe](ne)})}function bl(V){return P("10.7.0","highlightBlock will be removed entirely in v12.0"),P("10.7.0","Please use highlightElement now."),nr(V)}Object.assign(C,{highlight:De,highlightAuto:tr,highlightAll:kn,highlightElement:nr,highlightBlock:bl,configure:ll,initHighlighting:cl,initHighlightingOnLoad:ul,registerLanguage:dl,unregisterLanguage:pl,listLanguages:fl,getLanguage:At,registerAliases:Ei,autoDetection:ki,inherit:bi,addPlugin:hl,removePlugin:gl}),C.debugMode=function(){Le=!1},C.safeMode=function(){Le=!0},C.versionString=Ke,C.regex={concat:x,lookahead:m,either:b,optional:g,anyNumberOfTimes:f};for(const V in Oe)typeof Oe[V]=="object"&&e(Oe[V]);return Object.assign(C,Oe),C},qt=yi({});return qt.newInstance=()=>yi({}),Sr=qt,qt.HighlightJS=qt,qt.default=qt,Sr}var Pg=Dg();const Bg=Gr(Pg),ss={},Fg="hljs-";function zg(e){const t=Bg.newInstance();return e&&s(e),{highlight:n,highlightAuto:r,listLanguages:i,register:s,registerAlias:o,registered:l};function n(u,c,d){const p=d||ss,m=typeof p.prefix=="string"?p.prefix:Fg;if(!t.getLanguage(u))throw new Error("Unknown language: `"+u+"` is not registered");t.configure({__emitter:Ug,classPrefix:m});const f=t.highlight(c,{ignoreIllegals:!0,language:u});if(f.errorRaised)throw new Error("Could not highlight with `Highlight.js`",{cause:f.errorRaised});const g=f._emitter.root,x=g.data;return x.language=f.language,x.relevance=f.relevance,g}function r(u,c){const p=(c||ss).subset||i();let m=-1,f=0,g;for(;++mf&&(f=y.data.relevance,g=y)}return g||{type:"root",children:[],data:{language:void 0,relevance:f}}}function i(){return t.listLanguages()}function s(u,c){if(typeof u=="string")t.registerLanguage(u,c);else{let d;for(d in u)Object.hasOwn(u,d)&&t.registerLanguage(d,u[d])}}function o(u,c){if(typeof u=="string")t.registerAliases(typeof c=="string"?c:[...c],{languageName:u});else{let d;for(d in u)if(Object.hasOwn(u,d)){const p=u[d];t.registerAliases(typeof p=="string"?p:[...p],{languageName:d})}}}function l(u){return!!t.getLanguage(u)}}class Ug{constructor(t){this.options=t,this.root={type:"root",children:[],data:{language:void 0,relevance:0}},this.stack=[this.root]}addText(t){if(t==="")return;const n=this.stack[this.stack.length-1],r=n.children[n.children.length-1];r&&r.type==="text"?r.value+=t:n.children.push({type:"text",value:t})}startScope(t){this.openNode(String(t))}endScope(){this.closeNode()}__addSublanguage(t,n){const r=this.stack[this.stack.length-1],i=t.root.children;n?r.children.push({type:"element",tagName:"span",properties:{className:[n]},children:i}):r.children.push(...i)}openNode(t){const n=this,r=t.split(".").map(function(o,l){return l?o+"_".repeat(l):n.options.classPrefix+o}),i=this.stack[this.stack.length-1],s={type:"element",tagName:"span",properties:{className:r},children:[]};i.children.push(s),this.stack.push(s)}closeNode(){this.stack.pop()}finalize(){}toHTML(){return""}}const $g={};function Hg(e){const t=e||$g,n=t.aliases,r=t.detect||!1,i=t.languages||jg,s=t.plainText,o=t.prefix,l=t.subset;let u="hljs";const c=zg(i);if(n&&c.registerAlias(n),o){const d=o.indexOf("-");u=d===-1?o:o.slice(0,d)}return function(d,p){Qn(d,"element",function(m,f,g){if(m.tagName!=="code"||!g||g.type!=="element"||g.tagName!=="pre")return;const x=Wg(m);if(x===!1||!x&&!r||x&&s&&s.includes(x))return;Array.isArray(m.properties.className)||(m.properties.className=[]),m.properties.className.includes(u)||m.properties.className.unshift(u);const y=lh(m,{whitespace:"pre"});let b;try{b=x?c.highlight(x,y,{prefix:o}):c.highlightAuto(y,{prefix:o,subset:l})}catch(k){const A=k;if(x&&/Unknown language/.test(A.message)){p.message("Cannot highlight as `"+x+"`, it’s not registered",{ancestors:[g,m],cause:A,place:m.position,ruleId:"missing-language",source:"rehype-highlight"});return}throw A}!x&&b.data&&b.data.language&&m.properties.className.push("language-"+b.data.language),b.children.length>0&&(m.children=b.children)})}}function Wg(e){const t=e.properties.className;let n=-1;if(!Array.isArray(t))return;let r;for(;++n0?{type:"text",value:T}:void 0),T===!1?m.lastIndex=j+1:(g!==j&&k.push({type:"text",value:c.value.slice(g,j)}),Array.isArray(T)?k.push(...T):T&&k.push(T),g=j+A[0].length,b=!0),!m.global)break;A=m.exec(c.value)}return b?(g?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const i=as(e,"(");let s=as(e,")");for(;r!==-1&&i>s;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),s++;return[e,n]}function Pa(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||Ht(n)||Yn(n))&&(!t||n!==47)}Ba.peek=gb;function lb(){this.buffer()}function cb(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function ub(){this.buffer()}function db(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function pb(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=ut(this.sliceSerialize(e)).toLowerCase(),n.label=t}function fb(e){this.exit(e)}function mb(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=ut(this.sliceSerialize(e)).toLowerCase(),n.label=t}function hb(e){this.exit(e)}function gb(){return"["}function Ba(e,t,n,r){const i=n.createTracker(r);let s=i.move("[^");const o=n.enter("footnoteReference"),l=n.enter("reference");return s+=i.move(n.safe(n.associationId(e),{after:"]",before:s})),l(),o(),s+=i.move("]"),s}function bb(){return{enter:{gfmFootnoteCallString:lb,gfmFootnoteCall:cb,gfmFootnoteDefinitionLabelString:ub,gfmFootnoteDefinition:db},exit:{gfmFootnoteCallString:pb,gfmFootnoteCall:fb,gfmFootnoteDefinitionLabelString:mb,gfmFootnoteDefinition:hb}}}function xb(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Ba},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,s,o){const l=s.createTracker(o);let u=l.move("[^");const c=s.enter("footnoteDefinition"),d=s.enter("label");return u+=l.move(s.safe(s.associationId(r),{before:u,after:"]"})),d(),u+=l.move("]:"),r.children&&r.children.length>0&&(l.shift(4),u+=l.move((t?` -`:" ")+s.indentLines(s.containerFlow(r,l.current()),t?Fa:yb))),c(),u}}function yb(e,t,n){return t===0?e:Fa(e,t,n)}function Fa(e,t,n){return(n?"":" ")+e}const vb=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];za.peek=Nb;function Eb(){return{canContainEols:["delete"],enter:{strikethrough:wb},exit:{strikethrough:_b}}}function kb(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:vb}],handlers:{delete:za}}}function wb(e){this.enter({type:"delete",children:[]},e)}function _b(e){this.exit(e)}function za(e,t,n,r){const i=n.createTracker(r),s=n.enter("strikethrough");let o=i.move("~~");return o+=n.containerPhrasing(e,{...i.current(),before:o,after:"~"}),o+=i.move("~~"),s(),o}function Nb(){return"~"}function Sb(e){return e.length}function Tb(e,t){const n=t||{},r=(n.align||[]).concat(),i=n.stringLength||Sb,s=[],o=[],l=[],u=[];let c=0,d=-1;for(;++dc&&(c=e[d].length);++bu[b])&&(u[b]=A)}x.push(k)}o[d]=x,l[d]=y}let p=-1;if(typeof r=="object"&&"length"in r)for(;++pu[p]&&(u[p]=k),f[p]=k),m[p]=A}o.splice(1,0,m),l.splice(1,0,f),d=-1;const g=[];for(;++d]+>")+")",l={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},p={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},m={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},f=t.optional(i)+e.IDENT_RE+"\\s*\\(",h=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],x=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],v=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],b=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],D={type:x,keyword:h,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:v},L={className:"function.dispatch",relevance:0,keywords:{_hint:b},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},T=[L,p,l,n,e.C_BLOCK_COMMENT_MODE,d,c],B={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:D,contains:T.concat([{begin:/\(/,end:/\)/,keywords:D,contains:T.concat(["self"]),relevance:0}]),relevance:0},O={className:"function",begin:"("+o+"[\\*&\\s]+)+"+f,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:D,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:D,relevance:0},{begin:f,returnBegin:!0,contains:[m],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[c,d]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:D,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,c,d,l,{begin:/\(/,end:/\)/,keywords:D,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,c,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,p]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:D,illegal:"",keywords:D,contains:["self",l]},{begin:e.IDENT_RE+"::",keywords:D},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function gh(e){const t={type:["boolean","byte","word","String"],built_in:["KeyboardController","MouseController","SoftwareSerial","EthernetServer","EthernetClient","LiquidCrystal","RobotControl","GSMVoiceCall","EthernetUDP","EsploraTFT","HttpClient","RobotMotor","WiFiClient","GSMScanner","FileSystem","Scheduler","GSMServer","YunClient","YunServer","IPAddress","GSMClient","GSMModem","Keyboard","Ethernet","Console","GSMBand","Esplora","Stepper","Process","WiFiUDP","GSM_SMS","Mailbox","USBHost","Firmata","PImage","Client","Server","GSMPIN","FileIO","Bridge","Serial","EEPROM","Stream","Mouse","Audio","Servo","File","Task","GPRS","WiFi","Wire","TFT","GSM","SPI","SD"],_hints:["setup","loop","runShellCommandAsynchronously","analogWriteResolution","retrieveCallingNumber","printFirmwareVersion","analogReadResolution","sendDigitalPortPair","noListenOnLocalhost","readJoystickButton","setFirmwareVersion","readJoystickSwitch","scrollDisplayRight","getVoiceCallStatus","scrollDisplayLeft","writeMicroseconds","delayMicroseconds","beginTransmission","getSignalStrength","runAsynchronously","getAsynchronously","listenOnLocalhost","getCurrentCarrier","readAccelerometer","messageAvailable","sendDigitalPorts","lineFollowConfig","countryNameWrite","runShellCommand","readStringUntil","rewindDirectory","readTemperature","setClockDivider","readLightSensor","endTransmission","analogReference","detachInterrupt","countryNameRead","attachInterrupt","encryptionType","readBytesUntil","robotNameWrite","readMicrophone","robotNameRead","cityNameWrite","userNameWrite","readJoystickY","readJoystickX","mouseReleased","openNextFile","scanNetworks","noInterrupts","digitalWrite","beginSpeaker","mousePressed","isActionDone","mouseDragged","displayLogos","noAutoscroll","addParameter","remoteNumber","getModifiers","keyboardRead","userNameRead","waitContinue","processInput","parseCommand","printVersion","readNetworks","writeMessage","blinkVersion","cityNameRead","readMessage","setDataMode","parsePacket","isListening","setBitOrder","beginPacket","isDirectory","motorsWrite","drawCompass","digitalRead","clearScreen","serialEvent","rightToLeft","setTextSize","leftToRight","requestFrom","keyReleased","compassRead","analogWrite","interrupts","WiFiServer","disconnect","playMelody","parseFloat","autoscroll","getPINUsed","setPINUsed","setTimeout","sendAnalog","readSlider","analogRead","beginWrite","createChar","motorsStop","keyPressed","tempoWrite","readButton","subnetMask","debugPrint","macAddress","writeGreen","randomSeed","attachGPRS","readString","sendString","remotePort","releaseAll","mouseMoved","background","getXChange","getYChange","answerCall","getResult","voiceCall","endPacket","constrain","getSocket","writeJSON","getButton","available","connected","findUntil","readBytes","exitValue","readGreen","writeBlue","startLoop","IPAddress","isPressed","sendSysex","pauseMode","gatewayIP","setCursor","getOemKey","tuneWrite","noDisplay","loadImage","switchPIN","onRequest","onReceive","changePIN","playFile","noBuffer","parseInt","overflow","checkPIN","knobRead","beginTFT","bitClear","updateIR","bitWrite","position","writeRGB","highByte","writeRed","setSpeed","readBlue","noStroke","remoteIP","transfer","shutdown","hangCall","beginSMS","endWrite","attached","maintain","noCursor","checkReg","checkPUK","shiftOut","isValid","shiftIn","pulseIn","connect","println","localIP","pinMode","getIMEI","display","noBlink","process","getBand","running","beginSD","drawBMP","lowByte","setBand","release","bitRead","prepare","pointTo","readRed","setMode","noFill","remove","listen","stroke","detach","attach","noTone","exists","buffer","height","bitSet","circle","config","cursor","random","IRread","setDNS","endSMS","getKey","micros","millis","begin","print","write","ready","flush","width","isPIN","blink","clear","press","mkdir","rmdir","close","point","yield","image","BSSID","click","delay","read","text","move","peek","beep","rect","line","open","seek","fill","size","turn","stop","home","find","step","tone","sqrt","RSSI","SSID","end","bit","tan","cos","sin","pow","map","abs","max","min","get","run","put"],literal:["DIGITAL_MESSAGE","FIRMATA_STRING","ANALOG_MESSAGE","REPORT_DIGITAL","REPORT_ANALOG","INPUT_PULLUP","SET_PIN_MODE","INTERNAL2V56","SYSTEM_RESET","LED_BUILTIN","INTERNAL1V1","SYSEX_START","INTERNAL","EXTERNAL","DEFAULT","OUTPUT","INPUT","HIGH","LOW"]},n=hh(e),r=n.keywords;return r.type=[...r.type,...t.type],r.literal=[...r.literal,...t.literal],r.built_in=[...r.built_in,...t.built_in],r._hints=t._hints,n.name="Arduino",n.aliases=["ino"],n.supersetOf="cpp",n}function bh(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const i={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},s=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},l={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(l);const u={match:/\\"/},c={className:"string",begin:/'/,end:/'/},d={match:/\\'/},p={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},m=["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"],f=e.SHEBANG({binary:`(${m.join("|")})`,relevance:10}),h={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},x=["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],v=["true","false"],b={match:/(\/[a-z._-]+)+/},E=["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset"],A=["alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias"],D=["autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp"],L=["chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"];return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:x,literal:v,built_in:[...E,...A,"set","shopt",...D,...L]},contains:[f,e.SHEBANG(),h,p,s,o,b,l,u,c,d,n]}}function xh(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",l={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},p={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},m={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},f=t.optional(i)+e.IDENT_RE+"\\s*\\(",v={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},b=[p,l,n,e.C_BLOCK_COMMENT_MODE,d,c],E={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:v,contains:b.concat([{begin:/\(/,end:/\)/,keywords:v,contains:b.concat(["self"]),relevance:0}]),relevance:0},A={begin:"("+o+"[\\*&\\s]+)+"+f,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:v,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:v,relevance:0},{begin:f,returnBegin:!0,contains:[e.inherit(m,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:v,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,c,d,l,{begin:/\(/,end:/\)/,keywords:v,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,c,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,p]};return{name:"C",aliases:["h"],keywords:v,disableAutodetect:!0,illegal:"=]/,contains:[{beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:p,strings:c,keywords:v}}}function yh(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="(?!struct)("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",l={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},p={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},m={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},f=t.optional(i)+e.IDENT_RE+"\\s*\\(",h=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],x=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],v=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],b=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],D={type:x,keyword:h,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:v},L={className:"function.dispatch",relevance:0,keywords:{_hint:b},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},T=[L,p,l,n,e.C_BLOCK_COMMENT_MODE,d,c],B={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:D,contains:T.concat([{begin:/\(/,end:/\)/,keywords:D,contains:T.concat(["self"]),relevance:0}]),relevance:0},O={className:"function",begin:"("+o+"[\\*&\\s]+)+"+f,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:D,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:D,relevance:0},{begin:f,returnBegin:!0,contains:[m],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[c,d]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:D,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,c,d,l,{begin:/\(/,end:/\)/,keywords:D,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,c,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,p]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:D,illegal:"",keywords:D,contains:["self",l]},{begin:e.IDENT_RE+"::",keywords:D},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function vh(e){const t=["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],n=["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"],r=["default","false","null","true"],i=["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"],s=["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"],o={keyword:i.concat(s),built_in:t,literal:r},l=e.inherit(e.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),u={className:"number",variants:[{begin:"\\b(0b[01']+)"},{begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},c={className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},d={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},p=e.inherit(d,{illegal:/\n/}),m={className:"subst",begin:/\{/,end:/\}/,keywords:o},f=e.inherit(m,{illegal:/\n/}),h={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,f]},x={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},m]},v=e.inherit(x,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},f]});m.contains=[x,h,d,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,u,e.C_BLOCK_COMMENT_MODE],f.contains=[v,h,p,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,u,e.inherit(e.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];const b={variants:[c,x,h,d,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},E={begin:"<",end:">",contains:[{beginKeywords:"in out"},l]},A=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",D={begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:o,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:""},{begin:""}]}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},b,u,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},l,E,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[l,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[l,E,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+A+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:o,contains:[{beginKeywords:n.join(" "),relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[e.TITLE_MODE,E],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,relevance:0,contains:[b,u,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},D]}}const Eh=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),kh=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],wh=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],_h=[...kh,...wh],Nh=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),Sh=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Th=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Ch=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function Ah(e){const t=e.regex,n=Eh(e),r={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},i="and or not only",s=/@-?\w[\w]*(-\w+)*/,o="[a-zA-Z-][a-zA-Z0-9_-]*",l=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,r,n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\."+o,relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+Sh.join("|")+")"},{begin:":(:)?("+Th.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Ch.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...l,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...l,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:s},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:i,attribute:Nh.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...l,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+_h.join("|")+")\\b"}]}}function Mh(e){const t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}function Rh(e){const s={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:s,illegal:"va(e,t,n-1))}function Lh(e){const t=e.regex,n="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=n+va("(?:<"+n+"~~~(?:\\s*,\\s*"+n+"~~~)*>)?",/~~~/g,2),u={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},c={className:"meta",begin:"@"+n,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},d={className:"params",begin:/\(/,end:/\)/,keywords:u,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:u,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[t.concat(/(?!else)/,n),/\s+/,n,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,n],className:{1:"keyword",3:"title.class"},contains:[d,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:u,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:u,relevance:0,contains:[c,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,es,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},es,c]}}const ts="[A-Za-z$_][0-9A-Za-z$_]*",jh=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Dh=["true","false","null","undefined","NaN","Infinity"],Ea=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ka=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],wa=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Ph=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Bh=[].concat(wa,Ea,ka);function Fh(e){const t=e.regex,n=($,{after:V})=>{const g="",end:""},s=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:($,V)=>{const g=$[0].length+$.index,F=$.input[g];if(F==="<"||F===","){V.ignoreMatch();return}F===">"&&(n($,{after:g})||V.ignoreMatch());let U;const y=$.input.substring(g);if(U=y.match(/^\s*=/)){V.ignoreMatch();return}if((U=y.match(/^\s+extends\s+/))&&U.index===0){V.ignoreMatch();return}}},l={$pattern:ts,keyword:jh,literal:Dh,built_in:Bh,"variable.language":Ph},u="[0-9](_?[0-9])*",c=`\\.(${u})`,d="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",p={className:"number",variants:[{begin:`(\\b(${d})((${c})|\\.)?|(${c}))[eE][+-]?(${u})\\b`},{begin:`\\b(${d})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},m={className:"subst",begin:"\\$\\{",end:"\\}",keywords:l,contains:[]},f={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"xml"}},h={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"css"}},x={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"graphql"}},v={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,m]},E={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:r+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},A=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,h,x,v,{match:/\$\d+/},p];m.contains=A.concat({begin:/\{/,end:/\}/,keywords:l,contains:["self"].concat(A)});const D=[].concat(E,m.contains),L=D.concat([{begin:/(\s*)\(/,end:/\)/,keywords:l,contains:["self"].concat(D)}]),T={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:L},B={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,"(",t.concat(/\./,r),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,r],scope:{1:"keyword",3:"title.class"}}]},O={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...Ea,...ka]}},k={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},w={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[T],illegal:/%/},M={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function I($){return t.concat("(?!",$.join("|"),")")}const j={match:t.concat(/\b/,I([...wa,"super","import"].map($=>`${$}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},_={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},N={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},T]},R="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",W={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(R)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[T]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:l,exports:{PARAMS_CONTAINS:L,CLASS_REFERENCE:O},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),k,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,h,x,v,E,{match:/\$\d+/},p,O,{scope:"attr",match:r+t.lookahead(":"),relevance:0},W,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[E,e.REGEXP_MODE,{className:"function",begin:R,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:L}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:s},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[T,e.inherit(e.TITLE_MODE,{begin:r,className:"title.function"})]},{match:/\.\.\./,relevance:0},_,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[T]},j,M,B,N,{match:/\$[(.]/}]}}function zh(e){const t={className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},n={match:/[{}[\],:]/,className:"punctuation",relevance:0},r=["true","false","null"],i={scope:"literal",beginKeywords:r.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:r},contains:[t,n,e.QUOTE_STRING_MODE,i,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}var Jt="[0-9](_*[0-9])*",jn=`\\.(${Jt})`,Dn="[0-9a-fA-F](_*[0-9a-fA-F])*",Uh={className:"number",variants:[{begin:`(\\b(${Jt})((${jn})|\\.)?|(${jn}))[eE][+-]?(${Jt})[fFdD]?\\b`},{begin:`\\b(${Jt})((${jn})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${jn})[fFdD]?\\b`},{begin:`\\b(${Jt})[fFdD]\\b`},{begin:`\\b0[xX]((${Dn})\\.?|(${Dn})?\\.(${Dn}))[pP][+-]?(${Jt})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${Dn})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function $h(e){const t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},n={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},r={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@"},i={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},s={className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},o={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[s,i]},{begin:"'",end:"'",illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,s,i]}]};i.contains.push(o);const l={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?"},u={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[e.inherit(o,{className:"string"}),"self"]}]},c=Uh,d=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),p={variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},m=p;return m.variants[1].contains=[p],p.variants[1].contains=[m],{name:"Kotlin",aliases:["kt","kts"],keywords:t,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,d,n,r,l,u,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:t,relevance:5,contains:[{begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin://,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[p,e.C_LINE_COMMENT_MODE,d],relevance:0},e.C_LINE_COMMENT_MODE,d,l,u,o,e.C_NUMBER_MODE]},d]},{begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},e.UNDERSCORE_TITLE_MODE,{className:"type",begin://,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},l,u]},o,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:` +`},c]}}const Hh=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),Wh=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],Kh=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Gh=[...Wh,...Kh],qh=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),_a=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Na=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Vh=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),Yh=_a.concat(Na).sort().reverse();function Xh(e){const t=Hh(e),n=Yh,r="and or not only",i="[\\w-]+",s="("+i+"|@\\{"+i+"\\})",o=[],l=[],u=function(A){return{className:"string",begin:"~?"+A+".*?"+A}},c=function(A,D,L){return{className:A,begin:D,relevance:L}},d={$pattern:/[a-z-]+/,keyword:r,attribute:qh.join(" ")},p={begin:"\\(",end:"\\)",contains:l,keywords:d,relevance:0};l.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,u("'"),u('"'),t.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}},t.HEXCOLOR,p,c("variable","@@?"+i,10),c("variable","@\\{"+i+"\\}"),c("built_in","~?`[^`]*?`"),{className:"attribute",begin:i+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},t.IMPORTANT,{beginKeywords:"and not"},t.FUNCTION_DISPATCH);const m=l.concat({begin:/\{/,end:/\}/,contains:o}),f={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(l)},h={begin:s+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Vh.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:l}}]},x={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:d,returnEnd:!0,contains:l,relevance:0}},v={className:"variable",variants:[{begin:"@"+i+"\\s*:",relevance:15},{begin:"@"+i}],starts:{end:"[;}]",returnEnd:!0,contains:m}},b={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:s,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:`[<='$"]`,relevance:0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,f,c("keyword","all\\b"),c("variable","@\\{"+i+"\\}"),{begin:"\\b("+Gh.join("|")+")\\b",className:"selector-tag"},t.CSS_NUMBER_MODE,c("selector-tag",s,0),c("selector-id","#"+s),c("selector-class","\\."+s,0),c("selector-tag","&",0),t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+_a.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+Na.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:m},{begin:"!important"},t.FUNCTION_DISPATCH]},E={begin:i+`:(:)?(${n.join("|")})`,returnBegin:!0,contains:[b]};return o.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,x,v,E,h,b,f,t.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:`[=>'/<($"]`,contains:o}}function Zh(e){const t="\\[=*\\[",n="\\]=*\\]",r={begin:t,end:n,contains:["self"]},i=[e.COMMENT("--(?!"+t+")","$"),e.COMMENT("--"+t,n,{contains:[r],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:i.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:i}].concat(i)},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:t,end:n,contains:[r],relevance:5}])}}function Jh(e){const t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%",subLanguage:"xml",relevance:0},r={begin:"^[-\\*]{3,}",end:"$"},i={className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},s={className:"bullet",begin:"^[ ]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},o={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},l=/[A-Za-z][A-Za-z0-9+.-]*/,u={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:t.concat(/\[.+?\]\(/,l,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},c={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},d={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},p=e.inherit(c,{contains:[]}),m=e.inherit(d,{contains:[]});c.contains.push(m),d.contains.push(p);let f=[n,u];return[c,d,p,m].forEach(b=>{b.contains=b.contains.concat(f)}),f=f.concat(c,d),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:f},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:f}]}]},n,s,c,d,{className:"quote",begin:"^>\\s+",contains:f,end:"$"},i,r,u,o,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function eg(e){const t={className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},n=/[a-zA-Z@][a-zA-Z0-9_]*/,l={"variable.language":["this","super"],$pattern:n,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},u={$pattern:n,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:l,illegal:"/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+u.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:u,contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE,relevance:0}]}}function tg(e){const t=e.regex,n=["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"],r=/[dualxmsipngr]{0,12}/,i={$pattern:/[\w.]+/,keyword:n.join(" ")},s={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:i},o={begin:/->\{/,end:/\}/},l={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},u={scope:"variable",variants:[{begin:/\$\d/},{begin:t.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[l]},c={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},d=[e.BACKSLASH_ESCAPE,s,u],p=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],m=(x,v,b="\\1")=>{const E=b==="\\1"?b:t.concat(b,v);return t.concat(t.concat("(?:",x,")"),v,/(?:\\.|[^\\\/])*?/,E,/(?:\\.|[^\\\/])*?/,b,r)},f=(x,v,b)=>t.concat(t.concat("(?:",x,")"),v,/(?:\\.|[^\\\/])*?/,b,r),h=[u,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),o,{className:"string",contains:d,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},c,{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:m("s|tr|y",t.either(...p,{capture:!0}))},{begin:m("s|tr|y","\\(","\\)")},{begin:m("s|tr|y","\\[","\\]")},{begin:m("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:f("(?:m|qr)?",/\//,/\//)},{begin:f("m|qr",t.either(...p,{capture:!0}),/\1/)},{begin:f("m|qr",/\(/,/\)/)},{begin:f("m|qr",/\[/,/\]/)},{begin:f("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,l]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,l,c]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return s.contains=h,o.contains=h,{name:"Perl",aliases:["pl","pm"],keywords:i,contains:h}}function ng(e){const t=e.regex,n=/(?![A-Za-z0-9])(?![$])/,r=t.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,n),i=t.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,n),s=t.concat(/[A-Z]+/,n),o={scope:"variable",match:"\\$+"+r},l={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},u={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},c=e.inherit(e.APOS_STRING_MODE,{illegal:null}),d=e.inherit(e.QUOTE_STRING_MODE,{illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(u)}),p={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:e.QUOTE_STRING_MODE.contains.concat(u),"on:begin":(_,N)=>{N.data._beginMatch=_[1]||_[2]},"on:end":(_,N)=>{N.data._beginMatch!==_[1]&&N.ignoreMatch()}},m=e.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),f=`[ +]`,h={scope:"string",variants:[d,c,p,m]},x={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},v=["false","null","true"],b=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],E=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],D={keyword:b,literal:(_=>{const N=[];return _.forEach(R=>{N.push(R),R.toLowerCase()===R?N.push(R.toUpperCase()):N.push(R.toLowerCase())}),N})(v),built_in:E},L=_=>_.map(N=>N.replace(/\|\d+$/,"")),T={variants:[{match:[/new/,t.concat(f,"+"),t.concat("(?!",L(E).join("\\b|"),"\\b)"),i],scope:{1:"keyword",4:"title.class"}}]},B=t.concat(r,"\\b(?!\\()"),O={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),B],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[i,t.concat(/::/,t.lookahead(/(?!class\b)/)),B],scope:{1:"title.class",3:"variable.constant"}},{match:[i,t.concat("::",t.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},k={scope:"attr",match:t.concat(r,t.lookahead(":"),t.lookahead(/(?!::)/))},w={relevance:0,begin:/\(/,end:/\)/,keywords:D,contains:[k,o,O,e.C_BLOCK_COMMENT_MODE,h,x,T]},M={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",L(b).join("\\b|"),"|",L(E).join("\\b|"),"\\b)"),r,t.concat(f,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[w]};w.contains.push(M);const I=[k,O,e.C_BLOCK_COMMENT_MODE,h,x,T],j={begin:t.concat(/#\[\s*\\?/,t.either(i,s)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:v,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:v,keyword:["new","array"]},contains:["self",...I]},...I,{scope:"meta",variants:[{match:i},{match:s}]}]};return{case_insensitive:!1,keywords:D,contains:[j,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},l,{scope:"variable.language",match:/\$this\b/},o,M,O,{match:[/const/,/\s/,r],scope:{1:"keyword",3:"variable.constant"}},T,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:D,contains:["self",j,o,O,e.C_BLOCK_COMMENT_MODE,h,x]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},h,x]}}function rg(e){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}}function ig(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}function og(e){const t=e.regex,n=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],l={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},u={className:"meta",begin:/^(>>>|\.\.\.) /},c={className:"subst",begin:/\{/,end:/\}/,keywords:l,illegal:/#/},d={begin:/\{\{/,relevance:0},p={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,u],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,u],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,u,d,c]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,u,d,c]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,d,c]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,d,c]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},m="[0-9](_?[0-9])*",f=`(\\b(${m}))?\\.(${m})|\\b(${m})\\.`,h=`\\b|${r.join("|")}`,x={className:"number",relevance:0,variants:[{begin:`(\\b(${m})|(${f}))[eE][+-]?(${m})[jJ]?(?=${h})`},{begin:`(${f})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${h})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${h})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${h})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${h})`},{begin:`\\b(${m})[jJ](?=${h})`}]},v={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:l,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},b={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:["self",u,x,p,e.HASH_COMMENT_MODE]}]};return c.contains=[p,x,u],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:l,illegal:/(<\/|\?)|=>/,contains:[u,x,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},p,v,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[b]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[x,b,p]}]}}function sg(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}}function ag(e){const t=e.regex,n=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,r=t.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),i=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,s=t.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:n,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:t.lookahead(t.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:n},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[i,r]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,r]},{scope:{1:"punctuation",2:"number"},match:[s,r]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,r]}]},{scope:{3:"operator"},match:[n,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:i},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:s},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}}function lg(e){const t=e.regex,n="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",r=t.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=t.concat(r,/(::\w+)*/),o={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},l={className:"doctag",begin:"@[A-Za-z]+"},u={begin:"#<",end:">"},c=[e.COMMENT("#","$",{contains:[l]}),e.COMMENT("^=begin","^=end",{contains:[l],relevance:10}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],d={className:"subst",begin:/#\{/,end:/\}/,keywords:o},p={className:"string",contains:[e.BACKSLASH_ESCAPE,d],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:t.concat(/<<[-~]?'?/,t.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,d]})]}]},m="[1-9](_?[0-9])*|0",f="[0-9](_?[0-9])*",h={className:"number",relevance:0,variants:[{begin:`\\b(${m})(\\.(${f}))?([eE][+-]?(${f})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},x={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:o}]},T=[p,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:o},{match:[/(include|extend)\s+/,i],scope:{2:"title.class"},keywords:o},{relevance:0,match:[i,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:r,scope:"title.class"},{match:[/def/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[x]},{begin:e.IDENT_RE+"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[p,{begin:n}],relevance:0},h,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:o},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,d],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(u,c),relevance:0}].concat(u,c);d.contains=T,x.contains=T;const w=[{begin:/^\s*=>/,starts:{end:"$",contains:T}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:o,contains:T}}];return c.unshift(u),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:o,illegal:/\/\*/,contains:[e.SHEBANG({binary:"ruby"})].concat(w).concat(c).concat(T)}}function cg(e){const t=e.regex,n=/(r#)?/,r=t.concat(n,e.UNDERSCORE_IDENT_RE),i=t.concat(n,e.IDENT_RE),s={className:"title.function.invoke",relevance:0,begin:t.concat(/\b/,/(?!let|for|while|if|else|match\b)/,i,t.lookahead(/\s*\(/))},o="([ui](8|16|32|64|128|size)|f(32|64))?",l=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],u=["true","false","Some","None","Ok","Err"],c=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],d=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:d,keyword:l,literal:u,built_in:c},illegal:""},s]}}const ug=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),dg=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],pg=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],fg=[...dg,...pg],mg=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),hg=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),gg=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),bg=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function xg(e){const t=ug(e),n=gg,r=hg,i="@[a-z-]+",s="and or not only",l={className:"variable",begin:"(\\$"+"[a-zA-Z-][a-zA-Z0-9_-]*"+")\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+fg.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+n.join("|")+")"},l,{begin:/\(/,end:/\)/,contains:[t.CSS_NUMBER_MODE]},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+bg.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[t.BLOCK_COMMENT,l,t.HEXCOLOR,t.CSS_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.IMPORTANT,t.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:s,attribute:mg.join(" ")},contains:[{begin:i,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},l,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.HEXCOLOR,t.CSS_NUMBER_MODE]},t.FUNCTION_DISPATCH]}}function yg(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}function vg(e){const t=e.regex,n=e.COMMENT("--","$"),r={scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},i={begin:/"/,end:/"/,contains:[{match:/""/}]},s=["true","false","unknown"],o=["double precision","large object","with timezone","without timezone"],l=["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],u=["add","asc","collation","desc","final","first","last","view"],c=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year"],d=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],p=["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"],m=["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"],f=d,h=[...c,...u].filter(L=>!d.includes(L)),x={scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},v={scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},b={match:t.concat(/\b/,t.either(...f),/\s*\(/),relevance:0,keywords:{built_in:f}};function E(L){return t.concat(/\b/,t.either(...L.map(T=>T.replace(/\s+/,"\\s+"))),/\b/)}const A={scope:"keyword",match:E(m),relevance:0};function D(L,{exceptions:T,when:B}={}){const O=B;return T=T||[],L.map(k=>k.match(/\|\d+$/)||T.includes(k)?k:O(k)?`${k}|0`:k)}return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:D(h,{when:L=>L.length<3}),literal:s,type:l,built_in:p},contains:[{scope:"type",match:E(o)},A,b,x,r,i,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,v]}}function Sa(e){return e?typeof e=="string"?e:e.source:null}function dn(e){return _e("(?=",e,")")}function _e(...e){return e.map(n=>Sa(n)).join("")}function Eg(e){const t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function Ge(...e){return"("+(Eg(e).capture?"":"?:")+e.map(r=>Sa(r)).join("|")+")"}const fi=e=>_e(/\b/,e,/\w$/.test(e)?/\b/:/\B/),kg=["Protocol","Type"].map(fi),ns=["init","self"].map(fi),wg=["Any","Self"],_r=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],rs=["false","nil","true"],_g=["assignment","associativity","higherThan","left","lowerThan","none","right"],Ng=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],is=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],Ta=Ge(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),Ca=Ge(Ta,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),Nr=_e(Ta,Ca,"*"),Aa=Ge(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),Kn=Ge(Aa,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),mt=_e(Aa,Kn,"*"),Pn=_e(/[A-Z]/,Kn,"*"),Sg=["attached","autoclosure",_e(/convention\(/,Ge("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",_e(/objc\(/,mt,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],Tg=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function Cg(e){const t={match:/\s+/,relevance:0},n=e.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[e.C_LINE_COMMENT_MODE,n],i={match:[/\./,Ge(...kg,...ns)],className:{2:"keyword"}},s={match:_e(/\./,Ge(..._r)),relevance:0},o=_r.filter(ye=>typeof ye=="string").concat(["_|0"]),l=_r.filter(ye=>typeof ye!="string").concat(wg).map(fi),u={variants:[{className:"keyword",match:Ge(...l,...ns)}]},c={$pattern:Ge(/\b\w+/,/#\w+/),keyword:o.concat(Ng),literal:rs},d=[i,s,u],p={match:_e(/\./,Ge(...is)),relevance:0},m={className:"built_in",match:_e(/\b/,Ge(...is),/(?=\()/)},f=[p,m],h={match:/->/,relevance:0},x={className:"operator",relevance:0,variants:[{match:Nr},{match:`\\.(\\.|${Ca})+`}]},v=[h,x],b="([0-9]_*)+",E="([0-9a-fA-F]_*)+",A={className:"number",relevance:0,variants:[{match:`\\b(${b})(\\.(${b}))?([eE][+-]?(${b}))?\\b`},{match:`\\b0x(${E})(\\.(${E}))?([pP][+-]?(${b}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},D=(ye="")=>({className:"subst",variants:[{match:_e(/\\/,ye,/[0\\tnr"']/)},{match:_e(/\\/,ye,/u\{[0-9a-fA-F]{1,8}\}/)}]}),L=(ye="")=>({className:"subst",match:_e(/\\/,ye,/[\t ]*(?:[\r\n]|\r\n)/)}),T=(ye="")=>({className:"subst",label:"interpol",begin:_e(/\\/,ye,/\(/),end:/\)/}),B=(ye="")=>({begin:_e(ye,/"""/),end:_e(/"""/,ye),contains:[D(ye),L(ye),T(ye)]}),O=(ye="")=>({begin:_e(ye,/"/),end:_e(/"/,ye),contains:[D(ye),T(ye)]}),k={className:"string",variants:[B(),B("#"),B("##"),B("###"),O(),O("#"),O("##"),O("###")]},w=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],M={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:w},I=ye=>{const lt=_e(ye,/\//),nt=_e(/\//,ye);return{begin:lt,end:nt,contains:[...w,{scope:"comment",begin:`#(?!.*${nt})`,end:/$/}]}},j={scope:"regexp",variants:[I("###"),I("##"),I("#"),M]},_={match:_e(/`/,mt,/`/)},N={className:"variable",match:/\$\d+/},R={className:"variable",match:`\\$${Kn}+`},W=[_,N,R],$={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:Tg,contains:[...v,A,k]}]}},V={scope:"keyword",match:_e(/@/,Ge(...Sg),dn(Ge(/\(/,/\s+/)))},g={scope:"meta",match:_e(/@/,mt)},F=[$,V,g],U={match:dn(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:_e(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,Kn,"+")},{className:"type",match:Pn,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:_e(/\s+&\s+/,dn(Pn)),relevance:0}]},y={begin://,keywords:c,contains:[...r,...d,...F,h,U]};U.contains.push(y);const Q={match:_e(mt,/\s*:/),keywords:"_|0",relevance:0},se={begin:/\(/,end:/\)/,relevance:0,keywords:c,contains:["self",Q,...r,j,...d,...f,...v,A,k,...W,...F,U]},K={begin://,keywords:"repeat each",contains:[...r,U]},ie={begin:Ge(dn(_e(mt,/\s*:/)),dn(_e(mt,/\s+/,mt,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:mt}]},de={begin:/\(/,end:/\)/,keywords:c,contains:[ie,...r,...d,...v,A,k,...F,U,se],endsParent:!0,illegal:/["']/},be={match:[/(func|macro)/,/\s+/,Ge(_.match,mt,Nr)],className:{1:"keyword",3:"title.function"},contains:[K,de,t],illegal:[/\[/,/%/]},Oe={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[K,de,t],illegal:/\[|%/},Re={match:[/operator/,/\s+/,Nr],className:{1:"keyword",3:"title"}},at={begin:[/precedencegroup/,/\s+/,Pn],className:{1:"keyword",3:"title"},contains:[U],keywords:[..._g,...rs],end:/}/},St={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},Pt={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},yt={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,mt,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:c,contains:[K,...d,{begin:/:/,end:/\{/,keywords:c,contains:[{scope:"title.class.inherited",match:Pn},...d],relevance:0}]};for(const ye of k.variants){const lt=ye.contains.find(vt=>vt.label==="interpol");lt.keywords=c;const nt=[...d,...f,...v,A,k,...W];lt.contains=[...nt,{begin:/\(/,end:/\)/,contains:["self",...nt]}]}return{name:"Swift",keywords:c,contains:[...r,be,Oe,St,Pt,yt,Re,at,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},j,...d,...f,...v,A,k,...W,...F,U,se]}}const Gn="[A-Za-z$_][0-9A-Za-z$_]*",Ma=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Ra=["true","false","null","undefined","NaN","Infinity"],Ia=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],Oa=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],La=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],ja=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Da=[].concat(La,Ia,Oa);function Ag(e){const t=e.regex,n=($,{after:V})=>{const g="",end:""},s=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:($,V)=>{const g=$[0].length+$.index,F=$.input[g];if(F==="<"||F===","){V.ignoreMatch();return}F===">"&&(n($,{after:g})||V.ignoreMatch());let U;const y=$.input.substring(g);if(U=y.match(/^\s*=/)){V.ignoreMatch();return}if((U=y.match(/^\s+extends\s+/))&&U.index===0){V.ignoreMatch();return}}},l={$pattern:Gn,keyword:Ma,literal:Ra,built_in:Da,"variable.language":ja},u="[0-9](_?[0-9])*",c=`\\.(${u})`,d="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",p={className:"number",variants:[{begin:`(\\b(${d})((${c})|\\.)?|(${c}))[eE][+-]?(${u})\\b`},{begin:`\\b(${d})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},m={className:"subst",begin:"\\$\\{",end:"\\}",keywords:l,contains:[]},f={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"xml"}},h={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"css"}},x={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"graphql"}},v={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,m]},E={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:r+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},A=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,h,x,v,{match:/\$\d+/},p];m.contains=A.concat({begin:/\{/,end:/\}/,keywords:l,contains:["self"].concat(A)});const D=[].concat(E,m.contains),L=D.concat([{begin:/(\s*)\(/,end:/\)/,keywords:l,contains:["self"].concat(D)}]),T={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:L},B={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,"(",t.concat(/\./,r),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,r],scope:{1:"keyword",3:"title.class"}}]},O={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...Ia,...Oa]}},k={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},w={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[T],illegal:/%/},M={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function I($){return t.concat("(?!",$.join("|"),")")}const j={match:t.concat(/\b/,I([...La,"super","import"].map($=>`${$}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},_={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},N={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},T]},R="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",W={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(R)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[T]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:l,exports:{PARAMS_CONTAINS:L,CLASS_REFERENCE:O},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),k,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,h,x,v,E,{match:/\$\d+/},p,O,{scope:"attr",match:r+t.lookahead(":"),relevance:0},W,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[E,e.REGEXP_MODE,{className:"function",begin:R,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:L}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:s},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[T,e.inherit(e.TITLE_MODE,{begin:r,className:"title.function"})]},{match:/\.\.\./,relevance:0},_,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[T]},j,M,B,N,{match:/\$[(.]/}]}}function Mg(e){const t=e.regex,n=Ag(e),r=Gn,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],s={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},o={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:i},contains:[n.exports.CLASS_REFERENCE]},l={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},u=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],c={$pattern:Gn,keyword:Ma.concat(u),literal:Ra,built_in:Da.concat(i),"variable.language":ja},d={className:"meta",begin:"@"+r},p=(x,v,b)=>{const E=x.contains.findIndex(A=>A.label===v);if(E===-1)throw new Error("can not find mode to replace");x.contains.splice(E,1,b)};Object.assign(n.keywords,c),n.exports.PARAMS_CONTAINS.push(d);const m=n.contains.find(x=>x.scope==="attr"),f=Object.assign({},m,{match:t.concat(r,t.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,m,f]),n.contains=n.contains.concat([d,s,o,f]),p(n,"shebang",e.SHEBANG()),p(n,"use_strict",l);const h=n.contains.find(x=>x.label==="func.def");return h.relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}function Rg(e){const t=e.regex,n={className:"string",begin:/"(""|[^/n])"C\b/},r={className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},i=/\d{1,2}\/\d{1,2}\/\d{4}/,s=/\d{4}-\d{1,2}-\d{1,2}/,o=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,l=/\d{1,2}(:\d{1,2}){1,2}/,u={className:"literal",variants:[{begin:t.concat(/# */,t.either(s,i),/ *#/)},{begin:t.concat(/# */,l,/ *#/)},{begin:t.concat(/# */,o,/ *#/)},{begin:t.concat(/# */,t.either(s,i),/ +/,t.either(o,l),/ *#/)}]},c={className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},d={className:"label",begin:/^\w+:/},p=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),m=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[n,r,u,c,d,p,m,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[m]}]}}function Ig(e){e.regex;const t=e.COMMENT(/\(;/,/;\)/);t.contains.push("self");const n=e.COMMENT(/;;/,/$/),r=["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"],i={begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},s={className:"variable",begin:/\$[\w_]+/},o={match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},l={className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/},u={match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},c={className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/};return{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:r},contains:[n,t,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},s,o,i,e.QUOTE_STRING_MODE,u,c,l]}}function Og(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r=/[\p{L}0-9._:-]+/u,i={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},s={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(s,{begin:/\(/,end:/\)/}),l=e.inherit(e.APOS_STRING_MODE,{className:"string"}),u=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),c={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin://,relevance:10,contains:[s,u,l,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[s,o,u,l]}]}]},e.COMMENT(//,{relevance:10}),{begin://,relevance:10},i,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[u]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[c],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[c],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:c}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function Lg(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},i={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},s={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},o={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,i]},l=e.inherit(o,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),m={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},f={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},h={begin:/\{/,end:/\}/,contains:[f],illegal:"\\n",relevance:0},x={begin:"\\[",end:"\\]",contains:[f],illegal:"\\n",relevance:0},v=[r,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},m,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},h,x,s,o],b=[...v];return b.pop(),b.push(l),f.contains=b,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:v}}const jg={arduino:gh,bash:bh,c:xh,cpp:yh,csharp:vh,css:Ah,diff:Mh,go:Rh,graphql:Ih,ini:Oh,java:Lh,javascript:Fh,json:zh,kotlin:$h,less:Xh,lua:Zh,makefile:Jh,markdown:Qh,objectivec:eg,perl:tg,php:ng,"php-template":rg,plaintext:ig,python:og,"python-repl":sg,r:ag,ruby:lg,rust:cg,scss:xg,shell:yg,sql:vg,swift:Cg,typescript:Mg,vbnet:Rg,wasm:Ig,xml:Og,yaml:Lg};var Sr,os;function Dg(){if(os)return Sr;os=1;function e(C){return C instanceof Map?C.clear=C.delete=C.set=function(){throw new Error("map is read-only")}:C instanceof Set&&(C.add=C.clear=C.delete=function(){throw new Error("set is read-only")}),Object.freeze(C),Object.getOwnPropertyNames(C).forEach(z=>{const Y=C[z],ce=typeof Y;(ce==="object"||ce==="function")&&!Object.isFrozen(Y)&&e(Y)}),C}class t{constructor(z){z.data===void 0&&(z.data={}),this.data=z.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(C){return C.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function r(C,...z){const Y=Object.create(null);for(const ce in C)Y[ce]=C[ce];return z.forEach(function(ce){for(const Le in ce)Y[Le]=ce[Le]}),Y}const i="",s=C=>!!C.scope,o=(C,{prefix:z})=>{if(C.startsWith("language:"))return C.replace("language:","language-");if(C.includes(".")){const Y=C.split(".");return[`${z}${Y.shift()}`,...Y.map((ce,Le)=>`${ce}${"_".repeat(Le+1)}`)].join(" ")}return`${z}${C}`};class l{constructor(z,Y){this.buffer="",this.classPrefix=Y.classPrefix,z.walk(this)}addText(z){this.buffer+=n(z)}openNode(z){if(!s(z))return;const Y=o(z.scope,{prefix:this.classPrefix});this.span(Y)}closeNode(z){s(z)&&(this.buffer+=i)}value(){return this.buffer}span(z){this.buffer+=``}}const u=(C={})=>{const z={children:[]};return Object.assign(z,C),z};class c{constructor(){this.rootNode=u(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(z){this.top.children.push(z)}openNode(z){const Y=u({scope:z});this.add(Y),this.stack.push(Y)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(z){return this.constructor._walk(z,this.rootNode)}static _walk(z,Y){return typeof Y=="string"?z.addText(Y):Y.children&&(z.openNode(Y),Y.children.forEach(ce=>this._walk(z,ce)),z.closeNode(Y)),z}static _collapse(z){typeof z!="string"&&z.children&&(z.children.every(Y=>typeof Y=="string")?z.children=[z.children.join("")]:z.children.forEach(Y=>{c._collapse(Y)}))}}class d extends c{constructor(z){super(),this.options=z}addText(z){z!==""&&this.add(z)}startScope(z){this.openNode(z)}endScope(){this.closeNode()}__addSublanguage(z,Y){const ce=z.root;Y&&(ce.scope=`language:${Y}`),this.add(ce)}toHTML(){return new l(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function p(C){return C?typeof C=="string"?C:C.source:null}function m(C){return x("(?=",C,")")}function f(C){return x("(?:",C,")*")}function h(C){return x("(?:",C,")?")}function x(...C){return C.map(Y=>p(Y)).join("")}function v(C){const z=C[C.length-1];return typeof z=="object"&&z.constructor===Object?(C.splice(C.length-1,1),z):{}}function b(...C){return"("+(v(C).capture?"":"?:")+C.map(ce=>p(ce)).join("|")+")"}function E(C){return new RegExp(C.toString()+"|").exec("").length-1}function A(C,z){const Y=C&&C.exec(z);return Y&&Y.index===0}const D=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function L(C,{joinWith:z}){let Y=0;return C.map(ce=>{Y+=1;const Le=Y;let je=p(ce),te="";for(;je.length>0;){const J=D.exec(je);if(!J){te+=je;break}te+=je.substring(0,J.index),je=je.substring(J.index+J[0].length),J[0][0]==="\\"&&J[1]?te+="\\"+String(Number(J[1])+Le):(te+=J[0],J[0]==="("&&Y++)}return te}).map(ce=>`(${ce})`).join(z)}const T=/\b\B/,B="[a-zA-Z]\\w*",O="[a-zA-Z_]\\w*",k="\\b\\d+(\\.\\d+)?",w="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",M="\\b(0b[01]+)",I="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",j=(C={})=>{const z=/^#![ ]*\//;return C.binary&&(C.begin=x(z,/.*\b/,C.binary,/\b.*/)),r({scope:"meta",begin:z,end:/$/,relevance:0,"on:begin":(Y,ce)=>{Y.index!==0&&ce.ignoreMatch()}},C)},_={begin:"\\\\[\\s\\S]",relevance:0},N={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[_]},R={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[_]},W={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},$=function(C,z,Y={}){const ce=r({scope:"comment",begin:C,end:z,contains:[]},Y);ce.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const Le=b("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return ce.contains.push({begin:x(/[ ]+/,"(",Le,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),ce},V=$("//","$"),g=$("/\\*","\\*/"),F=$("#","$"),U={scope:"number",begin:k,relevance:0},y={scope:"number",begin:w,relevance:0},Q={scope:"number",begin:M,relevance:0},se={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[_,{begin:/\[/,end:/\]/,relevance:0,contains:[_]}]},K={scope:"title",begin:B,relevance:0},ie={scope:"title",begin:O,relevance:0},de={begin:"\\.\\s*"+O,relevance:0};var Oe=Object.freeze({__proto__:null,APOS_STRING_MODE:N,BACKSLASH_ESCAPE:_,BINARY_NUMBER_MODE:Q,BINARY_NUMBER_RE:M,COMMENT:$,C_BLOCK_COMMENT_MODE:g,C_LINE_COMMENT_MODE:V,C_NUMBER_MODE:y,C_NUMBER_RE:w,END_SAME_AS_BEGIN:function(C){return Object.assign(C,{"on:begin":(z,Y)=>{Y.data._beginMatch=z[1]},"on:end":(z,Y)=>{Y.data._beginMatch!==z[1]&&Y.ignoreMatch()}})},HASH_COMMENT_MODE:F,IDENT_RE:B,MATCH_NOTHING_RE:T,METHOD_GUARD:de,NUMBER_MODE:U,NUMBER_RE:k,PHRASAL_WORDS_MODE:W,QUOTE_STRING_MODE:R,REGEXP_MODE:se,RE_STARTERS_RE:I,SHEBANG:j,TITLE_MODE:K,UNDERSCORE_IDENT_RE:O,UNDERSCORE_TITLE_MODE:ie});function Re(C,z){C.input[C.index-1]==="."&&z.ignoreMatch()}function at(C,z){C.className!==void 0&&(C.scope=C.className,delete C.className)}function St(C,z){z&&C.beginKeywords&&(C.begin="\\b("+C.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",C.__beforeBegin=Re,C.keywords=C.keywords||C.beginKeywords,delete C.beginKeywords,C.relevance===void 0&&(C.relevance=0))}function Pt(C,z){Array.isArray(C.illegal)&&(C.illegal=b(...C.illegal))}function yt(C,z){if(C.match){if(C.begin||C.end)throw new Error("begin & end are not supported with match");C.begin=C.match,delete C.match}}function ye(C,z){C.relevance===void 0&&(C.relevance=1)}const lt=(C,z)=>{if(!C.beforeMatch)return;if(C.starts)throw new Error("beforeMatch cannot be used with starts");const Y=Object.assign({},C);Object.keys(C).forEach(ce=>{delete C[ce]}),C.keywords=Y.keywords,C.begin=x(Y.beforeMatch,m(Y.begin)),C.starts={relevance:0,contains:[Object.assign(Y,{endsParent:!0})]},C.relevance=0,delete Y.beforeMatch},nt=["of","and","for","in","not","or","if","then","parent","list","value"],vt="keyword";function Bt(C,z,Y=vt){const ce=Object.create(null);return typeof C=="string"?Le(Y,C.split(" ")):Array.isArray(C)?Le(Y,C):Object.keys(C).forEach(function(je){Object.assign(ce,Bt(C[je],z,je))}),ce;function Le(je,te){z&&(te=te.map(J=>J.toLowerCase())),te.forEach(function(J){const le=J.split("|");ce[le[0]]=[je,qt(le[0],le[1])]})}}function qt(C,z){return z?Number(z):Z(C)?0:1}function Z(C){return nt.includes(C.toLowerCase())}const he={},Ie=C=>{console.error(C)},fe=(C,...z)=>{console.log(`WARN: ${C}`,...z)},P=(C,z)=>{he[`${C}/${z}`]||(console.log(`Deprecated as of ${C}. ${z}`),he[`${C}/${z}`]=!0)},H=new Error;function ee(C,z,{key:Y}){let ce=0;const Le=C[Y],je={},te={};for(let J=1;J<=z.length;J++)te[J+ce]=Le[J],je[J+ce]=!0,ce+=E(z[J-1]);C[Y]=te,C[Y]._emit=je,C[Y]._multi=!0}function ae(C){if(Array.isArray(C.begin)){if(C.skip||C.excludeBegin||C.returnBegin)throw Ie("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),H;if(typeof C.beginScope!="object"||C.beginScope===null)throw Ie("beginScope must be object"),H;ee(C,C.begin,{key:"beginScope"}),C.begin=L(C.begin,{joinWith:""})}}function ke(C){if(Array.isArray(C.end)){if(C.skip||C.excludeEnd||C.returnEnd)throw Ie("skip, excludeEnd, returnEnd not compatible with endScope: {}"),H;if(typeof C.endScope!="object"||C.endScope===null)throw Ie("endScope must be object"),H;ee(C,C.end,{key:"endScope"}),C.end=L(C.end,{joinWith:""})}}function We(C){C.scope&&typeof C.scope=="object"&&C.scope!==null&&(C.beginScope=C.scope,delete C.scope)}function Et(C){We(C),typeof C.beginScope=="string"&&(C.beginScope={_wrap:C.beginScope}),typeof C.endScope=="string"&&(C.endScope={_wrap:C.endScope}),ae(C),ke(C)}function ct(C){function z(te,J){return new RegExp(p(te),"m"+(C.case_insensitive?"i":"")+(C.unicodeRegex?"u":"")+(J?"g":""))}class Y{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(J,le){le.position=this.position++,this.matchIndexes[this.matchAt]=le,this.regexes.push([le,J]),this.matchAt+=E(J)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const J=this.regexes.map(le=>le[1]);this.matcherRe=z(L(J,{joinWith:"|"}),!0),this.lastIndex=0}exec(J){this.matcherRe.lastIndex=this.lastIndex;const le=this.matcherRe.exec(J);if(!le)return null;const Fe=le.findIndex((sn,er)=>er>0&&sn!==void 0),De=this.matchIndexes[Fe];return le.splice(0,Fe),Object.assign(le,De)}}class ce{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(J){if(this.multiRegexes[J])return this.multiRegexes[J];const le=new Y;return this.rules.slice(J).forEach(([Fe,De])=>le.addRule(Fe,De)),le.compile(),this.multiRegexes[J]=le,le}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(J,le){this.rules.push([J,le]),le.type==="begin"&&this.count++}exec(J){const le=this.getMatcher(this.regexIndex);le.lastIndex=this.lastIndex;let Fe=le.exec(J);if(this.resumingScanAtSamePosition()&&!(Fe&&Fe.index===this.lastIndex)){const De=this.getMatcher(0);De.lastIndex=this.lastIndex+1,Fe=De.exec(J)}return Fe&&(this.regexIndex+=Fe.position+1,this.regexIndex===this.count&&this.considerAll()),Fe}}function Le(te){const J=new ce;return te.contains.forEach(le=>J.addRule(le.begin,{rule:le,type:"begin"})),te.terminatorEnd&&J.addRule(te.terminatorEnd,{type:"end"}),te.illegal&&J.addRule(te.illegal,{type:"illegal"}),J}function je(te,J){const le=te;if(te.isCompiled)return le;[at,yt,Et,lt].forEach(De=>De(te,J)),C.compilerExtensions.forEach(De=>De(te,J)),te.__beforeBegin=null,[St,Pt,ye].forEach(De=>De(te,J)),te.isCompiled=!0;let Fe=null;return typeof te.keywords=="object"&&te.keywords.$pattern&&(te.keywords=Object.assign({},te.keywords),Fe=te.keywords.$pattern,delete te.keywords.$pattern),Fe=Fe||/\w+/,te.keywords&&(te.keywords=Bt(te.keywords,C.case_insensitive)),le.keywordPatternRe=z(Fe,!0),J&&(te.begin||(te.begin=/\B|\b/),le.beginRe=z(le.begin),!te.end&&!te.endsWithParent&&(te.end=/\B|\b/),te.end&&(le.endRe=z(le.end)),le.terminatorEnd=p(le.end)||"",te.endsWithParent&&J.terminatorEnd&&(le.terminatorEnd+=(te.end?"|":"")+J.terminatorEnd)),te.illegal&&(le.illegalRe=z(te.illegal)),te.contains||(te.contains=[]),te.contains=[].concat(...te.contains.map(function(De){return Ft(De==="self"?te:De)})),te.contains.forEach(function(De){je(De,le)}),te.starts&&je(te.starts,J),le.matcher=Le(le),le}if(C.compilerExtensions||(C.compilerExtensions=[]),C.contains&&C.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return C.classNameAliases=r(C.classNameAliases||{}),je(C)}function Tt(C){return C?C.endsWithParent||Tt(C.starts):!1}function Ft(C){return C.variants&&!C.cachedVariants&&(C.cachedVariants=C.variants.map(function(z){return r(C,{variants:null},z)})),C.cachedVariants?C.cachedVariants:Tt(C)?r(C,{starts:C.starts?r(C.starts):null}):Object.isFrozen(C)?r(C):C}var Ke="11.11.1";class Ct extends Error{constructor(z,Y){super(z),this.name="HTMLInjectionError",this.html=Y}}const Xe=n,bi=r,xi=Symbol("nomatch"),sl=7,yi=function(C){const z=Object.create(null),Y=Object.create(null),ce=[];let Le=!0;const je="Could not find the language '{}', did you forget to load/include a language module?",te={disableAutodetect:!0,name:"Plain text",contains:[]};let J={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:d};function le(q){return J.noHighlightRe.test(q)}function Fe(q){let re=q.className+" ";re+=q.parentNode?q.parentNode.className:"";const xe=J.languageDetectRe.exec(re);if(xe){const Se=At(xe[1]);return Se||(fe(je.replace("{}",xe[1])),fe("Falling back to no-highlight mode for this block.",q)),Se?xe[1]:"no-highlight"}return re.split(/\s+/).find(Se=>le(Se)||At(Se))}function De(q,re,xe){let Se="",Be="";typeof re=="object"?(Se=q,xe=re.ignoreIllegals,Be=re.language):(P("10.7.0","highlight(lang, code, ...args) has been deprecated."),P("10.7.0",`Please use highlight(code, options) instead. +https://github.com/highlightjs/highlight.js/issues/2277`),Be=q,Se=re),xe===void 0&&(xe=!0);const ut={code:Se,language:Be};wn("before:highlight",ut);const Mt=ut.result?ut.result:sn(ut.language,ut.code,xe);return Mt.code=ut.code,wn("after:highlight",Mt),Mt}function sn(q,re,xe,Se){const Be=Object.create(null);function ut(X,ne){return X.keywords[ne]}function Mt(){if(!ue.keywords){ze.addText(Te);return}let X=0;ue.keywordPatternRe.lastIndex=0;let ne=ue.keywordPatternRe.exec(Te),me="";for(;ne;){me+=Te.substring(X,ne.index);const we=ft.case_insensitive?ne[0].toLowerCase():ne[0],Ue=ut(ue,we);if(Ue){const[kt,wl]=Ue;if(ze.addText(me),me="",Be[we]=(Be[we]||0)+1,Be[we]<=sl&&(Sn+=wl),kt.startsWith("_"))me+=ne[0];else{const _l=ft.classNameAliases[kt]||kt;pt(ne[0],_l)}}else me+=ne[0];X=ue.keywordPatternRe.lastIndex,ne=ue.keywordPatternRe.exec(Te)}me+=Te.substring(X),ze.addText(me)}function _n(){if(Te==="")return;let X=null;if(typeof ue.subLanguage=="string"){if(!z[ue.subLanguage]){ze.addText(Te);return}X=sn(ue.subLanguage,Te,!0,Ti[ue.subLanguage]),Ti[ue.subLanguage]=X._top}else X=tr(Te,ue.subLanguage.length?ue.subLanguage:null);ue.relevance>0&&(Sn+=X.relevance),ze.__addSublanguage(X._emitter,X.language)}function Ze(){ue.subLanguage!=null?_n():Mt(),Te=""}function pt(X,ne){X!==""&&(ze.startScope(ne),ze.addText(X),ze.endScope())}function wi(X,ne){let me=1;const we=ne.length-1;for(;me<=we;){if(!X._emit[me]){me++;continue}const Ue=ft.classNameAliases[X[me]]||X[me],kt=ne[me];Ue?pt(kt,Ue):(Te=kt,Mt(),Te=""),me++}}function _i(X,ne){return X.scope&&typeof X.scope=="string"&&ze.openNode(ft.classNameAliases[X.scope]||X.scope),X.beginScope&&(X.beginScope._wrap?(pt(Te,ft.classNameAliases[X.beginScope._wrap]||X.beginScope._wrap),Te=""):X.beginScope._multi&&(wi(X.beginScope,ne),Te="")),ue=Object.create(X,{parent:{value:ue}}),ue}function Ni(X,ne,me){let we=A(X.endRe,me);if(we){if(X["on:end"]){const Ue=new t(X);X["on:end"](ne,Ue),Ue.isMatchIgnored&&(we=!1)}if(we){for(;X.endsParent&&X.parent;)X=X.parent;return X}}if(X.endsWithParent)return Ni(X.parent,ne,me)}function xl(X){return ue.matcher.regexIndex===0?(Te+=X[0],1):(or=!0,0)}function yl(X){const ne=X[0],me=X.rule,we=new t(me),Ue=[me.__beforeBegin,me["on:begin"]];for(const kt of Ue)if(kt&&(kt(X,we),we.isMatchIgnored))return xl(ne);return me.skip?Te+=ne:(me.excludeBegin&&(Te+=ne),Ze(),!me.returnBegin&&!me.excludeBegin&&(Te=ne)),_i(me,X),me.returnBegin?0:ne.length}function vl(X){const ne=X[0],me=re.substring(X.index),we=Ni(ue,X,me);if(!we)return xi;const Ue=ue;ue.endScope&&ue.endScope._wrap?(Ze(),pt(ne,ue.endScope._wrap)):ue.endScope&&ue.endScope._multi?(Ze(),wi(ue.endScope,X)):Ue.skip?Te+=ne:(Ue.returnEnd||Ue.excludeEnd||(Te+=ne),Ze(),Ue.excludeEnd&&(Te=ne));do ue.scope&&ze.closeNode(),!ue.skip&&!ue.subLanguage&&(Sn+=ue.relevance),ue=ue.parent;while(ue!==we.parent);return we.starts&&_i(we.starts,X),Ue.returnEnd?0:ne.length}function El(){const X=[];for(let ne=ue;ne!==ft;ne=ne.parent)ne.scope&&X.unshift(ne.scope);X.forEach(ne=>ze.openNode(ne))}let Nn={};function Si(X,ne){const me=ne&&ne[0];if(Te+=X,me==null)return Ze(),0;if(Nn.type==="begin"&&ne.type==="end"&&Nn.index===ne.index&&me===""){if(Te+=re.slice(ne.index,ne.index+1),!Le){const we=new Error(`0 width match regex (${q})`);throw we.languageName=q,we.badRule=Nn.rule,we}return 1}if(Nn=ne,ne.type==="begin")return yl(ne);if(ne.type==="illegal"&&!xe){const we=new Error('Illegal lexeme "'+me+'" for mode "'+(ue.scope||"")+'"');throw we.mode=ue,we}else if(ne.type==="end"){const we=vl(ne);if(we!==xi)return we}if(ne.type==="illegal"&&me==="")return Te+=` +`,1;if(ir>1e5&&ir>ne.index*3)throw new Error("potential infinite loop, way more iterations than matches");return Te+=me,me.length}const ft=At(q);if(!ft)throw Ie(je.replace("{}",q)),new Error('Unknown language: "'+q+'"');const kl=ct(ft);let rr="",ue=Se||kl;const Ti={},ze=new J.__emitter(J);El();let Te="",Sn=0,zt=0,ir=0,or=!1;try{if(ft.__emitTokens)ft.__emitTokens(re,ze);else{for(ue.matcher.considerAll();;){ir++,or?or=!1:ue.matcher.considerAll(),ue.matcher.lastIndex=zt;const X=ue.matcher.exec(re);if(!X)break;const ne=re.substring(zt,X.index),me=Si(ne,X);zt=X.index+me}Si(re.substring(zt))}return ze.finalize(),rr=ze.toHTML(),{language:q,value:rr,relevance:Sn,illegal:!1,_emitter:ze,_top:ue}}catch(X){if(X.message&&X.message.includes("Illegal"))return{language:q,value:Xe(re),illegal:!0,relevance:0,_illegalBy:{message:X.message,index:zt,context:re.slice(zt-100,zt+100),mode:X.mode,resultSoFar:rr},_emitter:ze};if(Le)return{language:q,value:Xe(re),illegal:!1,relevance:0,errorRaised:X,_emitter:ze,_top:ue};throw X}}function er(q){const re={value:Xe(q),illegal:!1,relevance:0,_top:te,_emitter:new J.__emitter(J)};return re._emitter.addText(q),re}function tr(q,re){re=re||J.languages||Object.keys(z);const xe=er(q),Se=re.filter(At).filter(ki).map(Ze=>sn(Ze,q,!1));Se.unshift(xe);const Be=Se.sort((Ze,pt)=>{if(Ze.relevance!==pt.relevance)return pt.relevance-Ze.relevance;if(Ze.language&&pt.language){if(At(Ze.language).supersetOf===pt.language)return 1;if(At(pt.language).supersetOf===Ze.language)return-1}return 0}),[ut,Mt]=Be,_n=ut;return _n.secondBest=Mt,_n}function al(q,re,xe){const Se=re&&Y[re]||xe;q.classList.add("hljs"),q.classList.add(`language-${Se}`)}function nr(q){let re=null;const xe=Fe(q);if(le(xe))return;if(wn("before:highlightElement",{el:q,language:xe}),q.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",q);return}if(q.children.length>0&&(J.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(q)),J.throwUnescapedHTML))throw new Ct("One of your code blocks includes unescaped HTML.",q.innerHTML);re=q;const Se=re.textContent,Be=xe?De(Se,{language:xe,ignoreIllegals:!0}):tr(Se);q.innerHTML=Be.value,q.dataset.highlighted="yes",al(q,xe,Be.language),q.result={language:Be.language,re:Be.relevance,relevance:Be.relevance},Be.secondBest&&(q.secondBest={language:Be.secondBest.language,relevance:Be.secondBest.relevance}),wn("after:highlightElement",{el:q,result:Be,text:Se})}function ll(q){J=bi(J,q)}const cl=()=>{kn(),P("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function ul(){kn(),P("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let vi=!1;function kn(){function q(){kn()}if(document.readyState==="loading"){vi||window.addEventListener("DOMContentLoaded",q,!1),vi=!0;return}document.querySelectorAll(J.cssSelector).forEach(nr)}function dl(q,re){let xe=null;try{xe=re(C)}catch(Se){if(Ie("Language definition for '{}' could not be registered.".replace("{}",q)),Le)Ie(Se);else throw Se;xe=te}xe.name||(xe.name=q),z[q]=xe,xe.rawDefinition=re.bind(null,C),xe.aliases&&Ei(xe.aliases,{languageName:q})}function pl(q){delete z[q];for(const re of Object.keys(Y))Y[re]===q&&delete Y[re]}function fl(){return Object.keys(z)}function At(q){return q=(q||"").toLowerCase(),z[q]||z[Y[q]]}function Ei(q,{languageName:re}){typeof q=="string"&&(q=[q]),q.forEach(xe=>{Y[xe.toLowerCase()]=re})}function ki(q){const re=At(q);return re&&!re.disableAutodetect}function ml(q){q["before:highlightBlock"]&&!q["before:highlightElement"]&&(q["before:highlightElement"]=re=>{q["before:highlightBlock"](Object.assign({block:re.el},re))}),q["after:highlightBlock"]&&!q["after:highlightElement"]&&(q["after:highlightElement"]=re=>{q["after:highlightBlock"](Object.assign({block:re.el},re))})}function hl(q){ml(q),ce.push(q)}function gl(q){const re=ce.indexOf(q);re!==-1&&ce.splice(re,1)}function wn(q,re){const xe=q;ce.forEach(function(Se){Se[xe]&&Se[xe](re)})}function bl(q){return P("10.7.0","highlightBlock will be removed entirely in v12.0"),P("10.7.0","Please use highlightElement now."),nr(q)}Object.assign(C,{highlight:De,highlightAuto:tr,highlightAll:kn,highlightElement:nr,highlightBlock:bl,configure:ll,initHighlighting:cl,initHighlightingOnLoad:ul,registerLanguage:dl,unregisterLanguage:pl,listLanguages:fl,getLanguage:At,registerAliases:Ei,autoDetection:ki,inherit:bi,addPlugin:hl,removePlugin:gl}),C.debugMode=function(){Le=!1},C.safeMode=function(){Le=!0},C.versionString=Ke,C.regex={concat:x,lookahead:m,either:b,optional:h,anyNumberOfTimes:f};for(const q in Oe)typeof Oe[q]=="object"&&e(Oe[q]);return Object.assign(C,Oe),C},Vt=yi({});return Vt.newInstance=()=>yi({}),Sr=Vt,Vt.HighlightJS=Vt,Vt.default=Vt,Sr}var Pg=Dg();const Bg=Gr(Pg),ss={},Fg="hljs-";function zg(e){const t=Bg.newInstance();return e&&s(e),{highlight:n,highlightAuto:r,listLanguages:i,register:s,registerAlias:o,registered:l};function n(u,c,d){const p=d||ss,m=typeof p.prefix=="string"?p.prefix:Fg;if(!t.getLanguage(u))throw new Error("Unknown language: `"+u+"` is not registered");t.configure({__emitter:Ug,classPrefix:m});const f=t.highlight(c,{ignoreIllegals:!0,language:u});if(f.errorRaised)throw new Error("Could not highlight with `Highlight.js`",{cause:f.errorRaised});const h=f._emitter.root,x=h.data;return x.language=f.language,x.relevance=f.relevance,h}function r(u,c){const p=(c||ss).subset||i();let m=-1,f=0,h;for(;++mf&&(f=v.data.relevance,h=v)}return h||{type:"root",children:[],data:{language:void 0,relevance:f}}}function i(){return t.listLanguages()}function s(u,c){if(typeof u=="string")t.registerLanguage(u,c);else{let d;for(d in u)Object.hasOwn(u,d)&&t.registerLanguage(d,u[d])}}function o(u,c){if(typeof u=="string")t.registerAliases(typeof c=="string"?c:[...c],{languageName:u});else{let d;for(d in u)if(Object.hasOwn(u,d)){const p=u[d];t.registerAliases(typeof p=="string"?p:[...p],{languageName:d})}}}function l(u){return!!t.getLanguage(u)}}class Ug{constructor(t){this.options=t,this.root={type:"root",children:[],data:{language:void 0,relevance:0}},this.stack=[this.root]}addText(t){if(t==="")return;const n=this.stack[this.stack.length-1],r=n.children[n.children.length-1];r&&r.type==="text"?r.value+=t:n.children.push({type:"text",value:t})}startScope(t){this.openNode(String(t))}endScope(){this.closeNode()}__addSublanguage(t,n){const r=this.stack[this.stack.length-1],i=t.root.children;n?r.children.push({type:"element",tagName:"span",properties:{className:[n]},children:i}):r.children.push(...i)}openNode(t){const n=this,r=t.split(".").map(function(o,l){return l?o+"_".repeat(l):n.options.classPrefix+o}),i=this.stack[this.stack.length-1],s={type:"element",tagName:"span",properties:{className:r},children:[]};i.children.push(s),this.stack.push(s)}closeNode(){this.stack.pop()}finalize(){}toHTML(){return""}}const $g={};function Hg(e){const t=e||$g,n=t.aliases,r=t.detect||!1,i=t.languages||jg,s=t.plainText,o=t.prefix,l=t.subset;let u="hljs";const c=zg(i);if(n&&c.registerAlias(n),o){const d=o.indexOf("-");u=d===-1?o:o.slice(0,d)}return function(d,p){Qn(d,"element",function(m,f,h){if(m.tagName!=="code"||!h||h.type!=="element"||h.tagName!=="pre")return;const x=Wg(m);if(x===!1||!x&&!r||x&&s&&s.includes(x))return;Array.isArray(m.properties.className)||(m.properties.className=[]),m.properties.className.includes(u)||m.properties.className.unshift(u);const v=lh(m,{whitespace:"pre"});let b;try{b=x?c.highlight(x,v,{prefix:o}):c.highlightAuto(v,{prefix:o,subset:l})}catch(E){const A=E;if(x&&/Unknown language/.test(A.message)){p.message("Cannot highlight as `"+x+"`, it’s not registered",{ancestors:[h,m],cause:A,place:m.position,ruleId:"missing-language",source:"rehype-highlight"});return}throw A}!x&&b.data&&b.data.language&&m.properties.className.push("language-"+b.data.language),b.children.length>0&&(m.children=b.children)})}}function Wg(e){const t=e.properties.className;let n=-1;if(!Array.isArray(t))return;let r;for(;++n0?{type:"text",value:T}:void 0),T===!1?m.lastIndex=D+1:(h!==D&&E.push({type:"text",value:c.value.slice(h,D)}),Array.isArray(T)?E.push(...T):T&&E.push(T),h=D+A[0].length,b=!0),!m.global)break;A=m.exec(c.value)}return b?(h?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const i=as(e,"(");let s=as(e,")");for(;r!==-1&&i>s;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),s++;return[e,n]}function Pa(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||Wt(n)||Yn(n))&&(!t||n!==47)}Ba.peek=gb;function lb(){this.buffer()}function cb(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function ub(){this.buffer()}function db(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function pb(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=dt(this.sliceSerialize(e)).toLowerCase(),n.label=t}function fb(e){this.exit(e)}function mb(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=dt(this.sliceSerialize(e)).toLowerCase(),n.label=t}function hb(e){this.exit(e)}function gb(){return"["}function Ba(e,t,n,r){const i=n.createTracker(r);let s=i.move("[^");const o=n.enter("footnoteReference"),l=n.enter("reference");return s+=i.move(n.safe(n.associationId(e),{after:"]",before:s})),l(),o(),s+=i.move("]"),s}function bb(){return{enter:{gfmFootnoteCallString:lb,gfmFootnoteCall:cb,gfmFootnoteDefinitionLabelString:ub,gfmFootnoteDefinition:db},exit:{gfmFootnoteCallString:pb,gfmFootnoteCall:fb,gfmFootnoteDefinitionLabelString:mb,gfmFootnoteDefinition:hb}}}function xb(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Ba},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,s,o){const l=s.createTracker(o);let u=l.move("[^");const c=s.enter("footnoteDefinition"),d=s.enter("label");return u+=l.move(s.safe(s.associationId(r),{before:u,after:"]"})),d(),u+=l.move("]:"),r.children&&r.children.length>0&&(l.shift(4),u+=l.move((t?` +`:" ")+s.indentLines(s.containerFlow(r,l.current()),t?Fa:yb))),c(),u}}function yb(e,t,n){return t===0?e:Fa(e,t,n)}function Fa(e,t,n){return(n?"":" ")+e}const vb=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];za.peek=Nb;function Eb(){return{canContainEols:["delete"],enter:{strikethrough:wb},exit:{strikethrough:_b}}}function kb(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:vb}],handlers:{delete:za}}}function wb(e){this.enter({type:"delete",children:[]},e)}function _b(e){this.exit(e)}function za(e,t,n,r){const i=n.createTracker(r),s=n.enter("strikethrough");let o=i.move("~~");return o+=n.containerPhrasing(e,{...i.current(),before:o,after:"~"}),o+=i.move("~~"),s(),o}function Nb(){return"~"}function Sb(e){return e.length}function Tb(e,t){const n=t||{},r=(n.align||[]).concat(),i=n.stringLength||Sb,s=[],o=[],l=[],u=[];let c=0,d=-1;for(;++dc&&(c=e[d].length);++bu[b])&&(u[b]=A)}x.push(E)}o[d]=x,l[d]=v}let p=-1;if(typeof r=="object"&&"length"in r)for(;++pu[p]&&(u[p]=E),f[p]=E),m[p]=A}o.splice(1,0,m),l.splice(1,0,f),d=-1;const h=[];for(;++d "),s.shift(2);const o=n.indentLines(n.containerFlow(e,s.current()),Mb);return i(),o}function Mb(e,t,n){return">"+(n?"":" ")+e}function Rb(e,t){return cs(e,t.inConstruct,!0)&&!cs(e,t.notInConstruct,!1)}function cs(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++ro&&(o=s):s=1,i=r+t.length,r=n.indexOf(t,i);return o}function Ob(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Lb(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function jb(e,t,n,r){const i=Lb(n),s=e.value||"",o=i==="`"?"GraveAccent":"Tilde";if(Ob(e,n)){const p=n.enter("codeIndented"),m=n.indentLines(s,Db);return p(),m}const l=n.createTracker(r),u=i.repeat(Math.max(Ib(s,i)+1,3)),c=n.enter("codeFenced");let d=l.move(u);if(e.lang){const p=n.enter(`codeFencedLang${o}`);d+=l.move(n.safe(e.lang,{before:d,after:" ",encode:["`"],...l.current()})),p()}if(e.lang&&e.meta){const p=n.enter(`codeFencedMeta${o}`);d+=l.move(" "),d+=l.move(n.safe(e.meta,{before:d,after:` @@ -101,6 +101,6 @@ https://github.com/highlightjs/highlight.js/issues/2277`),Be=V,Se=ne),xe===void `+(i===1?"=":"-").repeat(m.length-(Math.max(m.lastIndexOf("\r"),m.lastIndexOf(` `))+1))}const o="#".repeat(i),l=n.enter("headingAtx"),u=n.enter("phrasing");s.move(o+" ");let c=n.containerPhrasing(e,{before:"# ",after:` `,...s.current()});return/^[\t ]/.test(c)&&(c=bn(c.charCodeAt(0))+c.slice(1)),c=c?o+" "+c:o,n.options.closeAtx&&(c+=" "+o),u(),l(),c}$a.peek=$b;function $a(e){return e.value||""}function $b(){return"<"}Ha.peek=Hb;function Ha(e,t,n,r){const i=mi(n),s=i==='"'?"Quote":"Apostrophe",o=n.enter("image");let l=n.enter("label");const u=n.createTracker(r);let c=u.move("![");return c+=u.move(n.safe(e.alt,{before:c,after:"]",...u.current()})),c+=u.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),c+=u.move("<"),c+=u.move(n.safe(e.url,{before:c,after:">",...u.current()})),c+=u.move(">")):(l=n.enter("destinationRaw"),c+=u.move(n.safe(e.url,{before:c,after:e.title?" ":")",...u.current()}))),l(),e.title&&(l=n.enter(`title${s}`),c+=u.move(" "+i),c+=u.move(n.safe(e.title,{before:c,after:i,...u.current()})),c+=u.move(i),l()),c+=u.move(")"),o(),c}function Hb(){return"!"}Wa.peek=Wb;function Wa(e,t,n,r){const i=e.referenceType,s=n.enter("imageReference");let o=n.enter("label");const l=n.createTracker(r);let u=l.move("![");const c=n.safe(e.alt,{before:u,after:"]",...l.current()});u+=l.move(c+"]["),o();const d=n.stack;n.stack=[],o=n.enter("reference");const p=n.safe(n.associationId(e),{before:u,after:"]",...l.current()});return o(),n.stack=d,s(),i==="full"||!c||c!==p?u+=l.move(p+"]"):i==="shortcut"?u=u.slice(0,-1):u+=l.move("]"),u}function Wb(){return"!"}Ka.peek=Kb;function Ka(e,t,n){let r=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++s\u007F]/.test(e.url))}qa.peek=Gb;function qa(e,t,n,r){const i=mi(n),s=i==='"'?"Quote":"Apostrophe",o=n.createTracker(r);let l,u;if(Ga(e,n)){const d=n.stack;n.stack=[],l=n.enter("autolink");let p=o.move("<");return p+=o.move(n.containerPhrasing(e,{before:p,after:">",...o.current()})),p+=o.move(">"),l(),n.stack=d,p}l=n.enter("link"),u=n.enter("label");let c=o.move("[");return c+=o.move(n.containerPhrasing(e,{before:c,after:"](",...o.current()})),c+=o.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=n.enter("destinationLiteral"),c+=o.move("<"),c+=o.move(n.safe(e.url,{before:c,after:">",...o.current()})),c+=o.move(">")):(u=n.enter("destinationRaw"),c+=o.move(n.safe(e.url,{before:c,after:e.title?" ":")",...o.current()}))),u(),e.title&&(u=n.enter(`title${s}`),c+=o.move(" "+i),c+=o.move(n.safe(e.title,{before:c,after:i,...o.current()})),c+=o.move(i),u()),c+=o.move(")"),l(),c}function Gb(e,t,n){return Ga(e,n)?"<":"["}Va.peek=qb;function Va(e,t,n,r){const i=e.referenceType,s=n.enter("linkReference");let o=n.enter("label");const l=n.createTracker(r);let u=l.move("[");const c=n.containerPhrasing(e,{before:u,after:"]",...l.current()});u+=l.move(c+"]["),o();const d=n.stack;n.stack=[],o=n.enter("reference");const p=n.safe(n.associationId(e),{before:u,after:"]",...l.current()});return o(),n.stack=d,s(),i==="full"||!c||c!==p?u+=l.move(p+"]"):i==="shortcut"?u=u.slice(0,-1):u+=l.move("]"),u}function qb(){return"["}function hi(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function Vb(e){const t=hi(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function Yb(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function Ya(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function Xb(e,t,n,r){const i=n.enter("list"),s=n.bulletCurrent;let o=e.ordered?Yb(n):hi(n);const l=e.ordered?o==="."?")":".":Vb(n);let u=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((o==="*"||o==="-")&&d&&(!d.children||!d.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(u=!0),Ya(n)===o&&d){let p=-1;for(;++p-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let o=s.length+1;(i==="tab"||i==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);const l=n.createTracker(r);l.move(s+" ".repeat(o-s.length)),l.shift(o);const u=n.enter("listItem"),c=n.indentLines(n.containerFlow(e,l.current()),d);return u(),c;function d(p,m,f){return m?(f?"":" ".repeat(o))+p:(f?s:s+" ".repeat(o-s.length))+p}}function Qb(e,t,n,r){const i=n.enter("paragraph"),s=n.enter("phrasing"),o=n.containerPhrasing(e,r);return s(),i(),o}const ex=vn(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function tx(e,t,n,r){return(e.children.some(function(o){return ex(o)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function nx(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}Xa.peek=rx;function Xa(e,t,n,r){const i=nx(n),s=n.enter("strong"),o=n.createTracker(r),l=o.move(i+i);let u=o.move(n.containerPhrasing(e,{after:i,before:l,...o.current()}));const c=u.charCodeAt(0),d=qn(r.before.charCodeAt(r.before.length-1),c,i);d.inside&&(u=bn(c)+u.slice(1));const p=u.charCodeAt(u.length-1),m=qn(r.after.charCodeAt(0),p,i);m.inside&&(u=u.slice(0,-1)+bn(p));const f=o.move(i+i);return s(),n.attentionEncodeSurroundingInfo={after:m.outside,before:d.outside},l+u+f}function rx(e,t,n){return n.options.strong||"*"}function ix(e,t,n,r){return n.safe(e.value,r)}function ox(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function sx(e,t,n){const r=(Ya(n)+(n.options.ruleSpaces?" ":"")).repeat(ox(n));return n.options.ruleSpaces?r.slice(0,-1):r}const Za={blockquote:Ab,break:us,code:jb,definition:Pb,emphasis:Ua,hardBreak:us,heading:Ub,html:$a,image:Ha,imageReference:Wa,inlineCode:Ka,link:qa,linkReference:Va,list:Xb,listItem:Jb,paragraph:Qb,root:tx,strong:Xa,text:ix,thematicBreak:sx};function ax(){return{enter:{table:lx,tableData:ds,tableHeader:ds,tableRow:ux},exit:{codeText:dx,table:cx,tableData:Mr,tableHeader:Mr,tableRow:Mr}}}function lx(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function cx(e){this.exit(e),this.data.inTable=void 0}function ux(e){this.enter({type:"tableRow",children:[]},e)}function Mr(e){this.exit(e)}function ds(e){this.enter({type:"tableCell",children:[]},e)}function dx(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,px));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function px(e,t){return t==="|"?t:e}function fx(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,s=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:m,table:o,tableCell:u,tableRow:l}};function o(f,g,x,y){return c(d(f,x,y),f.align)}function l(f,g,x,y){const b=p(f,x,y),k=c([b]);return k.slice(0,k.indexOf(` -`))}function u(f,g,x,y){const b=x.enter("tableCell"),k=x.enter("phrasing"),A=x.containerPhrasing(f,{...y,before:s,after:s});return k(),b(),A}function c(f,g){return Tb(f,{align:g,alignDelimiters:r,padding:n,stringLength:i})}function d(f,g,x){const y=f.children;let b=-1;const k=[],A=g.enter("table");for(;++b0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const Rx={tokenize:Fx,partial:!0};function Ix(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Dx,continuation:{tokenize:Px},exit:Bx}},text:{91:{name:"gfmFootnoteCall",tokenize:jx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Ox,resolveTo:Lx}}}}function Ox(e,t,n){const r=this;let i=r.events.length;const s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o;for(;i--;){const u=r.events[i][1];if(u.type==="labelImage"){o=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return l;function l(u){if(!o||!o._balanced)return n(u);const c=ut(r.sliceSerialize({start:o.end,end:r.now()}));return c.codePointAt(0)!==94||!s.includes(c.slice(1))?n(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),t(u))}}function Lx(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},l=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",s,t],["enter",o,t],["exit",o,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...l),e}function jx(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s=0,o;return l;function l(p){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),u}function u(p){return p!==94?n(p):(e.enter("gfmFootnoteCallMarker"),e.consume(p),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",c)}function c(p){if(s>999||p===93&&!o||p===null||p===91||Ne(p))return n(p);if(p===93){e.exit("chunkString");const m=e.exit("gfmFootnoteCallString");return i.includes(ut(r.sliceSerialize(m)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(p)}return Ne(p)||(o=!0),s++,e.consume(p),p===92?d:c}function d(p){return p===91||p===92||p===93?(e.consume(p),s++,c):c(p)}}function Dx(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s,o=0,l;return u;function u(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):n(g)}function d(g){if(o>999||g===93&&!l||g===null||g===91||Ne(g))return n(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return s=ut(r.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),m}return Ne(g)||(l=!0),o++,e.consume(g),g===92?p:d}function p(g){return g===91||g===92||g===93?(e.consume(g),o++,d):d(g)}function m(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),i.includes(s)||i.push(s),ve(e,f,"gfmFootnoteDefinitionWhitespace")):n(g)}function f(g){return t(g)}}function Px(e,t,n){return e.check(yn,t,e.attempt(Rx,t,n))}function Bx(e){e.exit("gfmFootnoteDefinition")}function Fx(e,t,n){const r=this;return ve(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const o=r.events[r.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(s):n(s)}}function zx(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:s,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(o,l){let u=-1;for(;++u1?u(g):(o.consume(g),p++,f);if(p<2&&!n)return u(g);const y=o.exit("strikethroughSequenceTemporary"),b=nn(g);return y._open=!b||b===2&&!!x,y._close=!x||x===2&&!!b,l(g)}}}class Ux{constructor(){this.map=[]}add(t,n,r){$x(this,t,n,r)}consume(t){if(this.map.sort(function(s,o){return s[0]-o[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let i=r.pop();for(;i;){for(const s of i)t.push(s);i=r.pop()}this.map.length=0}}function $x(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i-1;){const N=r.events[M][1].type;if(N==="lineEnding"||N==="linePrefix")M--;else break}const I=M>-1?r.events[M][1].type:null,D=I==="tableHead"||I==="tableRow"?T:u;return D===T&&r.parser.lazy[r.now().line]?n(w):D(w)}function u(w){return e.enter("tableHead"),e.enter("tableRow"),c(w)}function c(w){return w===124||(o=!0,s+=1),d(w)}function d(w){return w===null?n(w):ie(w)?s>1?(s=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),f):n(w):ge(w)?ve(e,d,"whitespace")(w):(s+=1,o&&(o=!1,i+=1),w===124?(e.enter("tableCellDivider"),e.consume(w),e.exit("tableCellDivider"),o=!0,d):(e.enter("data"),p(w)))}function p(w){return w===null||w===124||Ne(w)?(e.exit("data"),d(w)):(e.consume(w),w===92?m:p)}function m(w){return w===92||w===124?(e.consume(w),p):p(w)}function f(w){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(w):(e.enter("tableDelimiterRow"),o=!1,ge(w)?ve(e,g,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(w):g(w))}function g(w){return w===45||w===58?y(w):w===124?(o=!0,e.enter("tableCellDivider"),e.consume(w),e.exit("tableCellDivider"),x):L(w)}function x(w){return ge(w)?ve(e,y,"whitespace")(w):y(w)}function y(w){return w===58?(s+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(w),e.exit("tableDelimiterMarker"),b):w===45?(s+=1,b(w)):w===null||ie(w)?j(w):L(w)}function b(w){return w===45?(e.enter("tableDelimiterFiller"),k(w)):L(w)}function k(w){return w===45?(e.consume(w),k):w===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(w),e.exit("tableDelimiterMarker"),A):(e.exit("tableDelimiterFiller"),A(w))}function A(w){return ge(w)?ve(e,j,"whitespace")(w):j(w)}function j(w){return w===124?g(w):w===null||ie(w)?!o||i!==s?L(w):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(w)):L(w)}function L(w){return n(w)}function T(w){return e.enter("tableRow"),B(w)}function B(w){return w===124?(e.enter("tableCellDivider"),e.consume(w),e.exit("tableCellDivider"),B):w===null||ie(w)?(e.exit("tableRow"),t(w)):ge(w)?ve(e,B,"whitespace")(w):(e.enter("data"),O(w))}function O(w){return w===null||w===124||Ne(w)?(e.exit("data"),B(w)):(e.consume(w),w===92?E:O)}function E(w){return w===92||w===124?(e.consume(w),O):O(w)}}function Gx(e,t){let n=-1,r=!0,i=0,s=[0,0,0,0],o=[0,0,0,0],l=!1,u=0,c,d,p;const m=new Ux;for(;++nn[2]+1){const g=n[2]+1,x=n[3]-n[2]-1;e.add(g,x,[])}}e.add(n[3]+1,0,[["exit",p,t]])}return i!==void 0&&(s.end=Object.assign({},Qt(t.events,i)),e.add(i,0,[["exit",s,t]]),s=void 0),s}function fs(e,t,n,r,i){const s=[],o=Qt(t.events,n);i&&(i.end=Object.assign({},o),s.push(["exit",i,t])),r.end=Object.assign({},o),s.push(["exit",r,t]),e.add(n+1,0,s)}function Qt(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const qx={name:"tasklistCheck",tokenize:Yx};function Vx(){return{text:{91:qx}}}function Yx(e,t,n){const r=this;return i;function i(u){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),s)}function s(u){return Ne(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),o):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),o):n(u)}function o(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),l):n(u)}function l(u){return ie(u)?t(u):ge(u)?e.check({tokenize:Xx},t,n)(u):n(u)}}function Xx(e,t,n){return ve(e,r,"whitespace");function r(i){return i===null?n(i):t(i)}}function Zx(e){return Ys([kx(),Ix(),zx(e),Wx(),Vx()])}const Jx={};function Qx(e){const t=this,n=e||Jx,r=t.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),s=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),o=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(Zx(n)),s.push(xx()),o.push(yx(n))}const ey={user:{label:"You",color:"var(--info)"},assistant:{label:"AI",color:"var(--success)"},tool:{label:"Tool",color:"var(--warning)"},plan:{label:"Plan",color:"var(--accent)"}};function ty({message:e}){const t=e.planItems??[];return a.jsxs("div",{className:"py-1.5",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:"var(--accent)"}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--accent)"},children:"Plan"})]}),a.jsx("div",{className:"pl-2.5 space-y-1 mt-1",children:t.map((n,r)=>a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.status==="completed"?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",children:a.jsx("path",{d:"M20 6L9 17l-5-5"})}):n.status==="in_progress"?a.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center",children:a.jsx("span",{className:"w-2 h-2 rounded-full animate-pulse",style:{background:"var(--accent)"}})}):a.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center",children:a.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:"var(--text-muted)",opacity:.4}})}),a.jsx("span",{style:{color:n.status==="completed"?"var(--text-muted)":"var(--text-primary)",textDecoration:n.status==="completed"?"line-through":"none"},children:n.title})]},r))})]})}function ny({tc:e}){const t=e.status==="pending",n=e.status==="denied",[r,i]=S.useState(!1),s=e.result!==void 0,o=c=>{if(!e.tool_call_id)return;const d=ht.getState().sessionId;d&&(ht.getState().resolveToolApproval(e.tool_call_id,c),Xr().sendToolApproval(d,e.tool_call_id,c))};if(t)return a.jsxs("div",{className:"ml-2.5 rounded-lg overflow-hidden",style:{border:"1px solid color-mix(in srgb, var(--warning) 40%, var(--border))"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"color-mix(in srgb, var(--warning) 10%, var(--bg-secondary))"},children:[a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--warning)"},children:"Action Required"}),a.jsx("span",{className:"text-[11px] font-mono px-1.5 py-0.5 rounded",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--text-primary)"},children:e.tool})]}),e.args!=null&&a.jsx("pre",{className:"px-3 py-2 text-[11px] font-mono whitespace-pre-wrap break-words overflow-y-auto leading-normal",style:{background:"var(--bg-secondary)",color:"var(--text-secondary)",maxHeight:200},children:JSON.stringify(e.args,null,2)}),a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",style:{background:"var(--bg-secondary)",borderTop:"1px solid var(--border)"},children:[a.jsx("button",{onClick:()=>o(!0),className:"text-xs font-semibold px-3 py-1.5 rounded cursor-pointer transition-colors",style:{background:"color-mix(in srgb, var(--success) 15%, var(--bg-secondary))",color:"var(--success)",border:"1px solid color-mix(in srgb, var(--success) 30%, var(--border))"},onMouseEnter:c=>{c.currentTarget.style.background="color-mix(in srgb, var(--success) 25%, var(--bg-secondary))"},onMouseLeave:c=>{c.currentTarget.style.background="color-mix(in srgb, var(--success) 15%, var(--bg-secondary))"},children:"Approve"}),a.jsx("button",{onClick:()=>o(!1),className:"text-xs font-semibold px-3 py-1.5 rounded cursor-pointer transition-colors",style:{background:"color-mix(in srgb, var(--error) 15%, var(--bg-secondary))",color:"var(--error)",border:"1px solid color-mix(in srgb, var(--error) 30%, var(--border))"},onMouseEnter:c=>{c.currentTarget.style.background="color-mix(in srgb, var(--error) 25%, var(--bg-secondary))"},onMouseLeave:c=>{c.currentTarget.style.background="color-mix(in srgb, var(--error) 15%, var(--bg-secondary))"},children:"Reject"})]})]});const l=n?"var(--error)":s?e.is_error?"var(--error)":"var(--success)":"var(--text-muted)",u=n?"✗":s?e.is_error?"✗":"✓":"•";return a.jsxs("div",{className:"pl-2.5",children:[a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("button",{onClick:()=>i(!r),className:"inline-flex items-center gap-1 text-[11px] font-mono px-2 py-1 rounded cursor-pointer hover:brightness-125",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:l},children:[u," ",e.tool,n&&a.jsx("span",{className:"ml-1 text-[10px] uppercase",children:"Denied"}),a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{transform:r?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s",marginLeft:2},children:a.jsx("path",{d:"M6 9l6 6 6-6"})})]})}),r&&a.jsxs("div",{className:"mt-1.5 space-y-2",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider mb-1 font-semibold",style:{color:"var(--text-muted)"},children:"Arguments"}),a.jsx("pre",{className:"text-[11px] font-mono p-2 rounded overflow-x-auto whitespace-pre-wrap",style:{background:"var(--bg-primary)",color:"var(--text-secondary)"},children:JSON.stringify(e.args,null,2)})]}),s&&a.jsxs("div",{children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider mb-1 font-semibold",style:{color:e.is_error?"var(--error)":"var(--text-muted)"},children:e.is_error?"Error":"Result"}),a.jsx("pre",{className:"text-[11px] font-mono p-2 rounded overflow-x-auto whitespace-pre-wrap max-h-48 overflow-y-auto",style:{background:"var(--bg-primary)",color:e.is_error?"var(--error)":"var(--text-secondary)"},children:e.result})]})]})]})}const ms=3;function ry({message:e}){const t=e.toolCalls??(e.toolCall?[e.toolCall]:[]),[n,r]=S.useState(!1);if(t.length===0)return null;const i=t.length-ms,s=i>0&&!n,o=s?t.slice(-ms):t;return a.jsxs("div",{className:"py-1.5",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:"var(--warning)"}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--warning)"},children:t.length===1?"Tool":`Tools (${t.length})`})]}),a.jsxs("div",{className:"space-y-1",children:[s&&a.jsxs("button",{onClick:()=>r(!0),className:"ml-2.5 inline-flex items-center gap-1 text-[11px] font-mono px-2 py-1 rounded cursor-pointer hover:brightness-125",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:"var(--text-muted)"},children:[i," more tool ",i===1?"call":"calls",a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{marginLeft:2},children:a.jsx("path",{d:"M6 9l6 6 6-6"})})]}),o.map((l,u)=>a.jsx(ny,{tc:l},s?u+i:u))]})]})}function iy({message:e}){if(e.role==="plan")return a.jsx(ty,{message:e});if(e.role==="tool")return a.jsx(ry,{message:e});const t=e.role==="user"?"user":"assistant",n=ey[t];return a.jsxs("div",{className:"py-1.5",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:n.color}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:n.color},children:n.label})]}),e.content&&(e.role==="user"?a.jsx("div",{className:"text-sm leading-relaxed pl-2.5 max-w-prose",style:{color:"var(--text-primary)"},children:e.content}):a.jsx("div",{className:"text-sm leading-relaxed pl-2.5 max-w-prose chat-markdown",style:{color:"var(--text-secondary)"},children:a.jsx(Zm,{remarkPlugins:[Qx],rehypePlugins:[Hg],children:e.content})}))]})}function oy(){const e=S.useRef(Xr()).current,[t,n]=S.useState(""),r=S.useRef(null),i=S.useRef(!0),s=zn(h=>h.enabled),o=zn(h=>h.status),l=!s||o==="authenticated",{sessionId:u,status:c,messages:d,models:p,selectedModel:m,modelsLoading:f,skills:g,selectedSkillIds:x,skillsLoading:y,setModels:b,setSelectedModel:k,setModelsLoading:A,setSkills:j,setSelectedSkillIds:L,toggleSkill:T,setSkillsLoading:B,addUserMessage:O,clearSession:E}=ht();S.useEffect(()=>{l&&(p.length>0||(A(!0),Bu().then(h=>{if(b(h),h.length>0&&!m){const F=h.find(U=>U.model_name.includes("claude"));k(F?F.model_name:h[0].model_name)}}).catch(console.error).finally(()=>A(!1))))},[l,p.length,m,b,k,A]),S.useEffect(()=>{g.length>0||(B(!0),Fu().then(h=>{j(h),L(h.map(F=>F.id))}).catch(console.error).finally(()=>B(!1)))},[g.length,j,L,B]);const[w,M]=S.useState(!1),I=()=>{const h=r.current;if(!h)return;const F=h.scrollHeight-h.scrollTop-h.clientHeight<40;i.current=F,M(h.scrollTop>100)};S.useEffect(()=>{i.current&&r.current&&(r.current.scrollTop=r.current.scrollHeight)});const D=c==="thinking"||c==="executing"||c==="planning",N=S.useRef(null),_=()=>{const h=N.current;h&&(h.style.height="auto",h.style.height=Math.min(h.scrollHeight,200)+"px")},R=S.useCallback(()=>{const h=t.trim();!h||!m||D||(i.current=!0,O(h),e.sendAgentMessage(h,m,u,x),n(""),requestAnimationFrame(()=>{const F=N.current;F&&(F.style.height="auto")}))},[t,m,D,u,x,O,e]),W=S.useCallback(()=>{u&&e.sendAgentStop(u)},[u,e]),$=h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),R())},q=!D&&!!m&&t.trim().length>0;return l?a.jsxs("div",{className:"flex flex-col h-full",style:{background:"var(--bg-primary)"},children:[a.jsx(hs,{selectedModel:m,models:p,modelsLoading:f,onModelChange:k,skills:g,selectedSkillIds:x,skillsLoading:y,onToggleSkill:T,onClear:E,onStop:W,hasMessages:d.length>0,isBusy:D}),a.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[a.jsxs("div",{ref:r,onScroll:I,className:"h-full overflow-y-auto px-3 py-2 space-y-0.5",children:[d.length===0&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 gap-3",style:{color:"var(--text-muted)"},children:[a.jsx("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),a.jsxs("div",{className:"text-center space-y-1.5",children:[a.jsx("p",{className:"text-sm font-medium",style:{color:"var(--text-secondary)"},children:"Ask the agent to help you code"}),a.jsxs("p",{className:"text-xs leading-relaxed",children:["Create agents, functions, evaluations,",a.jsx("br",{}),"or ask questions about your project."]})]})]}),d.map(h=>a.jsx(iy,{message:h},h.id)),D&&a.jsx("div",{className:"py-1.5",children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{background:"var(--success)"}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--success)"},children:c==="thinking"?"Thinking...":c==="executing"?"Executing...":"Planning..."})]})})]}),w&&a.jsx("button",{onClick:()=>{var h;i.current=!1,(h=r.current)==null||h.scrollTo({top:0,behavior:"smooth"})},className:"absolute top-2 right-3 w-6 h-6 flex items-center justify-center rounded-full cursor-pointer transition-opacity opacity-70 hover:opacity-100",style:{background:"var(--bg-tertiary)",color:"var(--text-primary)"},title:"Scroll to top",children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("polyline",{points:"18 15 12 9 6 15"})})})]}),a.jsxs("div",{className:"flex items-end gap-2 px-3 py-2 border-t",style:{borderColor:"var(--border)"},children:[a.jsx("textarea",{ref:N,value:t,onChange:h=>{n(h.target.value),_()},onKeyDown:$,disabled:D||!m,placeholder:D?"Waiting for response...":"Message...",rows:2,className:"flex-1 bg-transparent text-sm py-1 disabled:opacity-40 placeholder:text-[var(--text-muted)] resize-none",style:{color:"var(--text-primary)",maxHeight:200,overflow:"auto"}}),a.jsx("button",{onClick:R,disabled:!q,className:"text-xs font-semibold px-3 py-1.5 rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed shrink-0","aria-label":"Send message",style:{color:q?"var(--accent)":"var(--text-muted)",background:"transparent"},onMouseEnter:h=>{q&&(h.currentTarget.style.background="color-mix(in srgb, var(--accent) 10%, transparent)")},onMouseLeave:h=>{h.currentTarget.style.background="transparent"},children:"Send"})]})]}):a.jsxs("div",{className:"flex flex-col h-full",style:{background:"var(--bg-primary)"},children:[a.jsx(hs,{selectedModel:m,models:p,modelsLoading:f,onModelChange:k,skills:g,selectedSkillIds:x,skillsLoading:y,onToggleSkill:T,onClear:E,onStop:W,hasMessages:!1,isBusy:!1}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:a.jsxs("div",{className:"text-center",style:{color:"var(--text-muted)"},children:[a.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"mx-auto mb-2",strokeLinecap:"round",children:[a.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),a.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),a.jsx("p",{className:"text-sm font-medium mb-1",children:"Sign in to use Agent"}),a.jsx("p",{className:"text-xs",children:"Authentication is required to access the coding agent."})]})})]})}function hs({selectedModel:e,models:t,modelsLoading:n,onModelChange:r,skills:i,selectedSkillIds:s,skillsLoading:o,onToggleSkill:l,onClear:u,onStop:c,hasMessages:d,isBusy:p}){const[m,f]=S.useState(!1),g=S.useRef(null);return S.useEffect(()=>{if(!m)return;const x=y=>{g.current&&!g.current.contains(y.target)&&f(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[m]),a.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-3 h-10 border-b",style:{borderColor:"var(--border)",background:"var(--bg-primary)"},children:[a.jsx("span",{className:"text-[11px] uppercase tracking-wider font-semibold shrink-0",style:{color:"var(--text-muted)"},children:"Agent"}),a.jsxs("select",{value:e??"",onChange:x=>r(x.target.value),className:"flex-1 text-[11px] rounded px-1.5 py-1 outline-none min-w-0 cursor-pointer",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"},disabled:n,children:[n&&a.jsx("option",{value:"",children:"Loading models..."}),!n&&t.length===0&&a.jsx("option",{value:"",children:"No models"}),t.map(x=>a.jsx("option",{value:x.model_name,children:x.model_name},x.model_name))]}),!o&&i.length>0&&a.jsxs("div",{className:"relative shrink-0",ref:g,children:[a.jsxs("button",{onClick:()=>f(!m),className:"text-[11px] font-semibold px-2 py-1 rounded cursor-pointer flex items-center gap-1",style:{background:s.length>0?"color-mix(in srgb, var(--accent) 15%, transparent)":"transparent",border:`1px solid ${s.length>0?"var(--accent)":"var(--border)"}`,color:s.length>0?"var(--accent)":"var(--text-muted)"},title:"Skills",children:[a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"}),a.jsx("path",{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"})]}),s.length>0&&a.jsx("span",{children:s.length})]}),m&&a.jsx("div",{className:"absolute top-full right-0 mt-1 rounded shadow-lg z-50 py-1 max-h-64 overflow-y-auto",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",width:"190px"},children:i.map(x=>a.jsxs("button",{onClick:()=>l(x.id),className:"w-full text-left px-2 py-1 text-[11px] flex items-center gap-1.5 cursor-pointer",style:{color:"var(--text-primary)"},title:x.description,onMouseEnter:y=>{y.currentTarget.style.background="var(--bg-tertiary)"},onMouseLeave:y=>{y.currentTarget.style.background="transparent"},children:[a.jsx("span",{className:"w-3 h-3 rounded border flex items-center justify-center shrink-0",style:{borderColor:s.includes(x.id)?"var(--accent)":"var(--border)",background:s.includes(x.id)?"var(--accent)":"transparent"},children:s.includes(x.id)&&a.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("polyline",{points:"20 6 9 17 4 12"})})}),a.jsx("span",{className:"truncate",children:x.name})]},x.id))})]}),p&&a.jsx("button",{onClick:c,className:"shrink-0 text-[11px] font-semibold px-2 py-1 rounded cursor-pointer",style:{background:"transparent",border:"1px solid var(--error)",color:"var(--error)"},title:"Stop",onMouseEnter:x=>{x.currentTarget.style.background="color-mix(in srgb, var(--error) 10%, transparent)"},onMouseLeave:x=>{x.currentTarget.style.background="transparent"},children:"Stop"}),d&&!p&&a.jsx("button",{onClick:u,className:"shrink-0 w-6 h-6 flex items-center justify-center rounded cursor-pointer",style:{background:"transparent",border:"none",color:"var(--text-muted)"},title:"New session",onMouseEnter:x=>{x.currentTarget.style.color="var(--text-primary)"},onMouseLeave:x=>{x.currentTarget.style.color="var(--text-muted)"},children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("polyline",{points:"1 4 1 10 7 10"}),a.jsx("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]})})]})}function sy(){const e=Yl(),t=ic(),[n,r]=S.useState(!1),[i,s]=S.useState(248),[o,l]=S.useState(!1),[u,c]=S.useState(380),[d,p]=S.useState(!1),{runs:m,selectedRunId:f,setRuns:g,upsertRun:x,selectRun:y,setTraces:b,setLogs:k,setChatMessages:A,setEntrypoints:j,setStateEvents:L,setGraphCache:T,setActiveNode:B,removeActiveNode:O}=Ee(),{section:E,view:w,runId:M,setupEntrypoint:I,setupMode:D,evalCreating:N,evalSetId:_,evalRunId:R,evalRunItemName:W,evaluatorCreateType:$,evaluatorId:q,evaluatorFilter:h,explorerFile:F,navigate:U}=ot(),{setEvalSets:v,setEvaluators:oe,setLocalEvaluators:ae,setEvalRuns:K}=Ae();S.useEffect(()=>{E==="debug"&&w==="details"&&M&&M!==f&&y(M)},[E,w,M,f,y]);const re=zn(Z=>Z.init),de=bs(Z=>Z.init);S.useEffect(()=>{Ql().then(g).catch(console.error),ys().then(Z=>j(Z.map(he=>he.name))).catch(console.error),re(),de()},[g,j,re,de]),S.useEffect(()=>{E==="evals"&&(vs().then(Z=>v(Z)).catch(console.error),fc().then(Z=>K(Z)).catch(console.error)),(E==="evals"||E==="evaluators")&&(ac().then(Z=>oe(Z)).catch(console.error),Zr().then(Z=>ae(Z)).catch(console.error))},[E,v,oe,ae,K]);const be=Ae(Z=>Z.evalSets),Oe=Ae(Z=>Z.evalRuns);S.useEffect(()=>{if(E!=="evals"||N||_||R)return;const Z=Object.values(Oe).sort((Ie,fe)=>new Date(fe.start_time??0).getTime()-new Date(Ie.start_time??0).getTime());if(Z.length>0){U(`#/evals/runs/${Z[0].id}`);return}const he=Object.values(be);he.length>0&&U(`#/evals/sets/${he[0].id}`)},[E,N,_,R,Oe,be,U]),S.useEffect(()=>{const Z=he=>{he.key==="Escape"&&n&&r(!1)};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[n]);const Re=f?m[f]:null,st=S.useCallback((Z,he)=>{x(he),b(Z,he.traces),k(Z,he.logs);const Ie=he.messages.map(fe=>{const P=fe.contentParts??fe.content_parts??[],H=fe.toolCalls??fe.tool_calls??[];return{message_id:fe.messageId??fe.message_id,role:fe.role??"assistant",content:P.filter(Q=>{const se=Q.mimeType??Q.mime_type??"";return se.startsWith("text/")||se==="application/json"}).map(Q=>{const se=Q.data;return(se==null?void 0:se.inline)??""}).join(` -`).trim()??"",tool_calls:H.length>0?H.map(Q=>({name:Q.name??"",has_result:!!Q.result})):void 0}});if(A(Z,Ie),he.graph&&he.graph.nodes.length>0&&T(Z,he.graph),he.states&&he.states.length>0&&(L(Z,he.states.map(fe=>({node_name:fe.node_name,qualified_node_name:fe.qualified_node_name,phase:fe.phase,timestamp:new Date(fe.timestamp).getTime(),payload:fe.payload}))),he.status!=="completed"&&he.status!=="failed"))for(const fe of he.states)fe.phase==="started"?B(Z,fe.node_name,fe.qualified_node_name):fe.phase==="completed"&&O(Z,fe.node_name)},[x,b,k,A,L,T,B,O]);S.useEffect(()=>{if(!f)return;e.subscribe(f),ar(f).then(he=>st(f,he)).catch(console.error);const Z=setTimeout(()=>{const he=Ee.getState().runs[f];he&&(he.status==="pending"||he.status==="running")&&ar(f).then(Ie=>st(f,Ie)).catch(console.error)},2e3);return()=>{clearTimeout(Z),e.unsubscribe(f)}},[f,e,st]);const St=S.useRef(null);S.useEffect(()=>{var Ie,fe;if(!f)return;const Z=Re==null?void 0:Re.status,he=St.current;if(St.current=Z??null,Z&&(Z==="completed"||Z==="failed")&&he!==Z){const P=Ee.getState(),H=((Ie=P.traces[f])==null?void 0:Ie.length)??0,Q=((fe=P.logs[f])==null?void 0:fe.length)??0,se=(Re==null?void 0:Re.trace_count)??0,ke=(Re==null?void 0:Re.log_count)??0;(Hst(f,We)).catch(console.error)}},[f,Re==null?void 0:Re.status,st]);const Pt=Z=>{U(`#/debug/runs/${Z}/traces`),y(Z),r(!1)},yt=Z=>{U(`#/debug/runs/${Z}/traces`),y(Z),r(!1)},ye=()=>{U("#/debug/new"),r(!1)},at=Z=>{Z==="debug"?U("#/debug/new"):Z==="evals"?U("#/evals"):Z==="evaluators"?U("#/evaluators"):Z==="explorer"&&U("#/explorer")},nt=S.useCallback(Z=>{Z.preventDefault(),l(!0);const he="touches"in Z?Z.touches[0].clientX:Z.clientX,Ie=i,fe=H=>{const Q="touches"in H?H.touches[0].clientX:H.clientX,se=Math.max(200,Math.min(480,Ie+(Q-he)));s(se)},P=()=>{l(!1),document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",P),document.removeEventListener("touchmove",fe),document.removeEventListener("touchend",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",fe),document.addEventListener("mouseup",P),document.addEventListener("touchmove",fe,{passive:!1}),document.addEventListener("touchend",P)},[i]),vt=S.useCallback(Z=>{Z.preventDefault(),p(!0);const he="touches"in Z?Z.touches[0].clientX:Z.clientX,Ie=u,fe=H=>{const Q="touches"in H?H.touches[0].clientX:H.clientX,se=Math.max(280,Math.min(500,Ie-(Q-he)));c(se)},P=()=>{p(!1),document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",P),document.removeEventListener("touchmove",fe),document.removeEventListener("touchend",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",fe),document.addEventListener("mouseup",P),document.addEventListener("touchmove",fe,{passive:!1}),document.addEventListener("touchend",P)},[u]),Bt=Me(Z=>Z.openTabs),Gt=()=>E==="explorer"?Bt.length>0||F?a.jsx(Pu,{}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)]",children:"Select a file to view"}):E==="evals"?N?a.jsx(ao,{}):R?a.jsx(Eu,{evalRunId:R,itemName:W}):_?a.jsx(bu,{evalSetId:_}):a.jsx(ao,{}):E==="evaluators"?$?a.jsx(Lu,{category:$}):a.jsx(Mu,{evaluatorId:q,evaluatorFilter:h}):w==="new"?a.jsx(wc,{}):w==="setup"&&I&&D?a.jsx(Vc,{entrypoint:I,mode:D,ws:e,onRunCreated:Pt,isMobile:t}):Re?a.jsx(fu,{run:Re,ws:e,isMobile:t}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)]",children:"Select a run or create a new one"});return t?a.jsxs("div",{className:"flex flex-col h-screen w-screen",children:[a.jsxs("div",{className:"flex flex-1 overflow-hidden relative",children:[!n&&a.jsx("button",{onClick:()=>r(!0),className:"fixed top-2 left-2 z-40 w-9 h-9 flex items-center justify-center rounded-lg cursor-pointer",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)"},children:a.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),a.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),a.jsx("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),n&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-50",style:{background:"rgba(0,0,0,0.5)"},onClick:()=>r(!1)}),a.jsxs("aside",{className:"fixed inset-y-0 left-0 z-50 w-64 bg-[var(--sidebar-bg)] border-r border-[var(--border)] flex flex-col",children:[a.jsxs("div",{className:"px-3 h-10 border-b border-[var(--border)] flex items-center justify-between",children:[a.jsxs("button",{onClick:()=>{U("#/debug/new"),r(!1)},className:"flex items-center gap-2 cursor-pointer",style:{background:"none",border:"none"},children:[a.jsx("img",{src:"/favicon.ico",width:"14",height:"14",alt:"UiPath"}),a.jsx("span",{className:"text-[10px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"Developer Console"})]}),a.jsx("button",{onClick:()=>r(!1),className:"w-6 h-6 flex items-center justify-center rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)",background:"transparent",border:"none"},children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),E==="debug"&&a.jsx(Oi,{runs:Object.values(m),selectedRunId:f,onSelectRun:yt,onNewRun:ye}),E==="evals"&&a.jsx(to,{}),E==="evaluators"&&a.jsx(lo,{}),E==="explorer"&&a.jsx(uo,{})]})]}),a.jsx("main",{className:"flex-1 overflow-hidden bg-[var(--bg-primary)]",children:Gt()})]}),a.jsx(Li,{}),a.jsx(Xi,{}),a.jsx(Qi,{})]}):a.jsxs("div",{className:"flex flex-col h-screen w-screen",children:[a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsxs("aside",{className:"shrink-0 flex flex-col",style:{width:i,background:"var(--sidebar-bg)"},children:[a.jsxs("div",{className:"flex h-10 border-b shrink-0",style:{borderColor:"var(--border)"},children:[a.jsx("button",{onClick:()=>U("#/debug/new"),className:"w-12 shrink-0 flex items-center justify-center cursor-pointer transition-colors border-r",style:{background:"var(--activity-bar-bg)",border:"none",borderRight:"1px solid var(--border)"},onMouseEnter:Z=>{Z.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:Z=>{Z.currentTarget.style.background="var(--activity-bar-bg)"},children:a.jsx("img",{src:"/favicon.ico",width:"20",height:"20",alt:"UiPath"})}),a.jsx("div",{className:"flex-1 flex items-center px-3",style:{background:"var(--sidebar-bg)"},children:a.jsx("span",{className:"text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:E==="debug"?"Developer Console":E==="evals"?"Evaluations":E==="evaluators"?"Evaluators":"Explorer"})})]}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsx(sc,{section:E,onSectionChange:at}),a.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[E==="debug"&&a.jsx(Oi,{runs:Object.values(m),selectedRunId:f,onSelectRun:yt,onNewRun:ye}),E==="evals"&&a.jsx(to,{}),E==="evaluators"&&a.jsx(lo,{}),E==="explorer"&&a.jsx(uo,{})]})]})]}),a.jsx("div",{onMouseDown:nt,onTouchStart:nt,className:"shrink-0 drag-handle-col",style:o?{background:"var(--accent)"}:void 0}),a.jsxs("main",{className:"flex-1 overflow-hidden bg-[var(--bg-primary)] flex",children:[a.jsx("div",{className:"flex-1 overflow-hidden",children:Gt()}),E==="explorer"&&a.jsxs(a.Fragment,{children:[a.jsx("div",{onMouseDown:vt,onTouchStart:vt,className:"shrink-0 drag-handle-col",style:d?{background:"var(--accent)"}:void 0}),a.jsx("div",{className:"shrink-0 overflow-hidden",style:{width:u,borderLeft:"1px solid var(--border)"},children:a.jsx(oy,{})})]})]})]}),a.jsx(Li,{}),a.jsx(Xi,{}),a.jsx(Qi,{})]})}Cl.createRoot(document.getElementById("root")).render(a.jsx(S.StrictMode,{children:a.jsx(sy,{})}));export{Zm as M,Qx as a,Hg as r,Ee as u}; +`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:m,table:o,tableCell:u,tableRow:l}};function o(f,h,x,v){return c(d(f,x,v),f.align)}function l(f,h,x,v){const b=p(f,x,v),E=c([b]);return E.slice(0,E.indexOf(` +`))}function u(f,h,x,v){const b=x.enter("tableCell"),E=x.enter("phrasing"),A=x.containerPhrasing(f,{...v,before:s,after:s});return E(),b(),A}function c(f,h){return Tb(f,{align:h,alignDelimiters:r,padding:n,stringLength:i})}function d(f,h,x){const v=f.children;let b=-1;const E=[],A=h.enter("table");for(;++b0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const Rx={tokenize:Fx,partial:!0};function Ix(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Dx,continuation:{tokenize:Px},exit:Bx}},text:{91:{name:"gfmFootnoteCall",tokenize:jx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Ox,resolveTo:Lx}}}}function Ox(e,t,n){const r=this;let i=r.events.length;const s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o;for(;i--;){const u=r.events[i][1];if(u.type==="labelImage"){o=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return l;function l(u){if(!o||!o._balanced)return n(u);const c=dt(r.sliceSerialize({start:o.end,end:r.now()}));return c.codePointAt(0)!==94||!s.includes(c.slice(1))?n(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),t(u))}}function Lx(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},l=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",s,t],["enter",o,t],["exit",o,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...l),e}function jx(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s=0,o;return l;function l(p){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),u}function u(p){return p!==94?n(p):(e.enter("gfmFootnoteCallMarker"),e.consume(p),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",c)}function c(p){if(s>999||p===93&&!o||p===null||p===91||Ne(p))return n(p);if(p===93){e.exit("chunkString");const m=e.exit("gfmFootnoteCallString");return i.includes(dt(r.sliceSerialize(m)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(p)}return Ne(p)||(o=!0),s++,e.consume(p),p===92?d:c}function d(p){return p===91||p===92||p===93?(e.consume(p),s++,c):c(p)}}function Dx(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s,o=0,l;return u;function u(h){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(h){return h===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):n(h)}function d(h){if(o>999||h===93&&!l||h===null||h===91||Ne(h))return n(h);if(h===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return s=dt(r.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(h),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),m}return Ne(h)||(l=!0),o++,e.consume(h),h===92?p:d}function p(h){return h===91||h===92||h===93?(e.consume(h),o++,d):d(h)}function m(h){return h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),i.includes(s)||i.push(s),ve(e,f,"gfmFootnoteDefinitionWhitespace")):n(h)}function f(h){return t(h)}}function Px(e,t,n){return e.check(yn,t,e.attempt(Rx,t,n))}function Bx(e){e.exit("gfmFootnoteDefinition")}function Fx(e,t,n){const r=this;return ve(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const o=r.events[r.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(s):n(s)}}function zx(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:s,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(o,l){let u=-1;for(;++u1?u(h):(o.consume(h),p++,f);if(p<2&&!n)return u(h);const v=o.exit("strikethroughSequenceTemporary"),b=nn(h);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,l(h)}}}class Ux{constructor(){this.map=[]}add(t,n,r){$x(this,t,n,r)}consume(t){if(this.map.sort(function(s,o){return s[0]-o[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let i=r.pop();for(;i;){for(const s of i)t.push(s);i=r.pop()}this.map.length=0}}function $x(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i-1;){const _=r.events[M][1].type;if(_==="lineEnding"||_==="linePrefix")M--;else break}const I=M>-1?r.events[M][1].type:null,j=I==="tableHead"||I==="tableRow"?T:u;return j===T&&r.parser.lazy[r.now().line]?n(w):j(w)}function u(w){return e.enter("tableHead"),e.enter("tableRow"),c(w)}function c(w){return w===124||(o=!0,s+=1),d(w)}function d(w){return w===null?n(w):oe(w)?s>1?(s=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),f):n(w):ge(w)?ve(e,d,"whitespace")(w):(s+=1,o&&(o=!1,i+=1),w===124?(e.enter("tableCellDivider"),e.consume(w),e.exit("tableCellDivider"),o=!0,d):(e.enter("data"),p(w)))}function p(w){return w===null||w===124||Ne(w)?(e.exit("data"),d(w)):(e.consume(w),w===92?m:p)}function m(w){return w===92||w===124?(e.consume(w),p):p(w)}function f(w){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(w):(e.enter("tableDelimiterRow"),o=!1,ge(w)?ve(e,h,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(w):h(w))}function h(w){return w===45||w===58?v(w):w===124?(o=!0,e.enter("tableCellDivider"),e.consume(w),e.exit("tableCellDivider"),x):L(w)}function x(w){return ge(w)?ve(e,v,"whitespace")(w):v(w)}function v(w){return w===58?(s+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(w),e.exit("tableDelimiterMarker"),b):w===45?(s+=1,b(w)):w===null||oe(w)?D(w):L(w)}function b(w){return w===45?(e.enter("tableDelimiterFiller"),E(w)):L(w)}function E(w){return w===45?(e.consume(w),E):w===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(w),e.exit("tableDelimiterMarker"),A):(e.exit("tableDelimiterFiller"),A(w))}function A(w){return ge(w)?ve(e,D,"whitespace")(w):D(w)}function D(w){return w===124?h(w):w===null||oe(w)?!o||i!==s?L(w):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(w)):L(w)}function L(w){return n(w)}function T(w){return e.enter("tableRow"),B(w)}function B(w){return w===124?(e.enter("tableCellDivider"),e.consume(w),e.exit("tableCellDivider"),B):w===null||oe(w)?(e.exit("tableRow"),t(w)):ge(w)?ve(e,B,"whitespace")(w):(e.enter("data"),O(w))}function O(w){return w===null||w===124||Ne(w)?(e.exit("data"),B(w)):(e.consume(w),w===92?k:O)}function k(w){return w===92||w===124?(e.consume(w),O):O(w)}}function Gx(e,t){let n=-1,r=!0,i=0,s=[0,0,0,0],o=[0,0,0,0],l=!1,u=0,c,d,p;const m=new Ux;for(;++nn[2]+1){const h=n[2]+1,x=n[3]-n[2]-1;e.add(h,x,[])}}e.add(n[3]+1,0,[["exit",p,t]])}return i!==void 0&&(s.end=Object.assign({},Qt(t.events,i)),e.add(i,0,[["exit",s,t]]),s=void 0),s}function fs(e,t,n,r,i){const s=[],o=Qt(t.events,n);i&&(i.end=Object.assign({},o),s.push(["exit",i,t])),r.end=Object.assign({},o),s.push(["exit",r,t]),e.add(n+1,0,s)}function Qt(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const qx={name:"tasklistCheck",tokenize:Yx};function Vx(){return{text:{91:qx}}}function Yx(e,t,n){const r=this;return i;function i(u){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),s)}function s(u){return Ne(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),o):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),o):n(u)}function o(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),l):n(u)}function l(u){return oe(u)?t(u):ge(u)?e.check({tokenize:Xx},t,n)(u):n(u)}}function Xx(e,t,n){return ve(e,r,"whitespace");function r(i){return i===null?n(i):t(i)}}function Zx(e){return Ys([kx(),Ix(),zx(e),Wx(),Vx()])}const Jx={};function Qx(e){const t=this,n=e||Jx,r=t.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),s=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),o=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(Zx(n)),s.push(xx()),o.push(yx(n))}const ey={user:{label:"You",color:"var(--info)"},assistant:{label:"AI",color:"var(--success)"},tool:{label:"Tool",color:"var(--warning)"},plan:{label:"Plan",color:"var(--accent)"},thinking:{label:"Reasoning",color:"var(--text-muted)"}};function ty({message:e}){const[t,n]=S.useState(!1);return a.jsxs("div",{className:"py-1.5",children:[a.jsxs("button",{onClick:()=>n(!t),className:"flex items-center gap-1.5 mb-0.5 cursor-pointer",style:{background:"none",border:"none",padding:0},children:[a.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:"var(--text-muted)",opacity:.5}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--text-muted)"},children:"Reasoning"}),a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-muted)",strokeWidth:"2",style:{transform:t?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s",marginLeft:2},children:a.jsx("path",{d:"M6 9l6 6 6-6"})})]}),t&&a.jsx("div",{className:"text-[12px] leading-relaxed pl-2.5 max-w-prose whitespace-pre-wrap",style:{color:"var(--text-muted)",fontStyle:"italic"},children:e.content})]})}function ny({message:e}){const t=e.planItems??[];return a.jsxs("div",{className:"py-1.5",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:"var(--accent)"}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--accent)"},children:"Plan"})]}),a.jsx("div",{className:"pl-2.5 space-y-1 mt-1",children:t.map((n,r)=>a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.status==="completed"?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",children:a.jsx("path",{d:"M20 6L9 17l-5-5"})}):n.status==="in_progress"?a.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center",children:a.jsx("span",{className:"w-2 h-2 rounded-full animate-pulse",style:{background:"var(--accent)"}})}):a.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center",children:a.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:"var(--text-muted)",opacity:.4}})}),a.jsx("span",{style:{color:n.status==="completed"?"var(--text-muted)":"var(--text-primary)",textDecoration:n.status==="completed"?"line-through":"none"},children:n.title})]},r))})]})}function ry({tc:e}){const t=e.status==="pending",n=e.status==="denied",[r,i]=S.useState(!1),s=e.result!==void 0,o=c=>{if(!e.tool_call_id)return;const d=rt.getState().sessionId;d&&(rt.getState().resolveToolApproval(e.tool_call_id,c),Xr().sendToolApproval(d,e.tool_call_id,c))};if(t)return a.jsxs("div",{className:"ml-2.5 rounded-lg overflow-hidden",style:{border:"1px solid color-mix(in srgb, var(--warning) 40%, var(--border))"},children:[a.jsxs("div",{className:"px-3 py-2 flex items-center gap-2",style:{background:"color-mix(in srgb, var(--warning) 10%, var(--bg-secondary))"},children:[a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--warning)"},children:"Action Required"}),a.jsx("span",{className:"text-[11px] font-mono px-1.5 py-0.5 rounded",style:{background:"color-mix(in srgb, var(--warning) 15%, var(--bg-secondary))",color:"var(--text-primary)"},children:e.tool})]}),e.args!=null&&a.jsx("pre",{className:"px-3 py-2 text-[11px] font-mono whitespace-pre-wrap break-words overflow-y-auto leading-normal",style:{background:"var(--bg-secondary)",color:"var(--text-secondary)",maxHeight:200},children:JSON.stringify(e.args,null,2)}),a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",style:{background:"var(--bg-secondary)",borderTop:"1px solid var(--border)"},children:[a.jsx("button",{onClick:()=>o(!0),className:"text-xs font-semibold px-3 py-1.5 rounded cursor-pointer transition-colors",style:{background:"color-mix(in srgb, var(--success) 15%, var(--bg-secondary))",color:"var(--success)",border:"1px solid color-mix(in srgb, var(--success) 30%, var(--border))"},onMouseEnter:c=>{c.currentTarget.style.background="color-mix(in srgb, var(--success) 25%, var(--bg-secondary))"},onMouseLeave:c=>{c.currentTarget.style.background="color-mix(in srgb, var(--success) 15%, var(--bg-secondary))"},children:"Approve"}),a.jsx("button",{onClick:()=>o(!1),className:"text-xs font-semibold px-3 py-1.5 rounded cursor-pointer transition-colors",style:{background:"color-mix(in srgb, var(--error) 15%, var(--bg-secondary))",color:"var(--error)",border:"1px solid color-mix(in srgb, var(--error) 30%, var(--border))"},onMouseEnter:c=>{c.currentTarget.style.background="color-mix(in srgb, var(--error) 25%, var(--bg-secondary))"},onMouseLeave:c=>{c.currentTarget.style.background="color-mix(in srgb, var(--error) 15%, var(--bg-secondary))"},children:"Reject"})]})]});const l=n?"var(--error)":s?e.is_error?"var(--error)":"var(--success)":"var(--text-muted)",u=n?"✗":s?e.is_error?"✗":"✓":"•";return a.jsxs("div",{className:"pl-2.5",children:[a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("button",{onClick:()=>i(!r),className:"inline-flex items-center gap-1 text-[11px] font-mono px-2 py-1 rounded cursor-pointer hover:brightness-125",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:l},children:[u," ",e.tool,n&&a.jsx("span",{className:"ml-1 text-[10px] uppercase",children:"Denied"}),a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{transform:r?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s",marginLeft:2},children:a.jsx("path",{d:"M6 9l6 6 6-6"})})]})}),r&&a.jsxs("div",{className:"mt-1.5 space-y-2",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider mb-1 font-semibold",style:{color:"var(--text-muted)"},children:"Arguments"}),a.jsx("pre",{className:"text-[11px] font-mono p-2 rounded overflow-x-auto whitespace-pre-wrap",style:{background:"var(--bg-primary)",color:"var(--text-secondary)"},children:JSON.stringify(e.args,null,2)})]}),s&&a.jsxs("div",{children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider mb-1 font-semibold",style:{color:e.is_error?"var(--error)":"var(--text-muted)"},children:e.is_error?"Error":"Result"}),a.jsx("pre",{className:"text-[11px] font-mono p-2 rounded overflow-x-auto whitespace-pre-wrap max-h-48 overflow-y-auto",style:{background:"var(--bg-primary)",color:e.is_error?"var(--error)":"var(--text-secondary)"},children:e.result})]})]})]})}const ms=3;function iy({message:e}){const t=e.toolCalls??(e.toolCall?[e.toolCall]:[]),[n,r]=S.useState(!1);if(t.length===0)return null;const i=t.length-ms,s=i>0&&!n,o=s?t.slice(-ms):t;return a.jsxs("div",{className:"py-1.5",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:"var(--warning)"}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--warning)"},children:t.length===1?"Tool":`Tools (${t.length})`})]}),a.jsxs("div",{className:"space-y-1",children:[s&&a.jsxs("button",{onClick:()=>r(!0),className:"ml-2.5 inline-flex items-center gap-1 text-[11px] font-mono px-2 py-1 rounded cursor-pointer hover:brightness-125",style:{background:"var(--bg-primary)",border:"1px solid var(--border)",color:"var(--text-muted)"},children:[i," more tool ",i===1?"call":"calls",a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{marginLeft:2},children:a.jsx("path",{d:"M6 9l6 6 6-6"})})]}),o.map((l,u)=>a.jsx(ry,{tc:l},s?u+i:u))]})]})}function oy({message:e}){if(e.role==="thinking")return a.jsx(ty,{message:e});if(e.role==="plan")return a.jsx(ny,{message:e});if(e.role==="tool")return a.jsx(iy,{message:e});const t=e.role==="user"?"user":"assistant",n=ey[t];return a.jsxs("div",{className:"py-1.5",children:[a.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:n.color}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:n.color},children:n.label})]}),e.content&&(e.role==="user"?a.jsx("div",{className:"text-sm leading-relaxed pl-2.5 max-w-prose",style:{color:"var(--text-primary)"},children:e.content}):a.jsx("div",{className:"text-sm leading-relaxed pl-2.5 max-w-prose chat-markdown",style:{color:"var(--text-secondary)"},children:a.jsx(Zm,{remarkPlugins:[Qx],rehypePlugins:[Hg],children:e.content})}))]})}function sy(){const e=S.useRef(Xr()).current,[t,n]=S.useState(""),r=S.useRef(null),i=S.useRef(!0),s=zn(y=>y.enabled),o=zn(y=>y.status),l=!s||o==="authenticated",{sessionId:u,status:c,messages:d,models:p,selectedModel:m,modelsLoading:f,skills:h,selectedSkillIds:x,skillsLoading:v,setModels:b,setSelectedModel:E,setModelsLoading:A,setSkills:D,setSelectedSkillIds:L,toggleSkill:T,setSkillsLoading:B,addUserMessage:O,clearSession:k}=rt();S.useEffect(()=>{l&&(p.length>0||(A(!0),Bu().then(y=>{if(b(y),y.length>0&&!m){const Q=y.find(se=>se.model_name.includes("claude"));E(Q?Q.model_name:y[0].model_name)}}).catch(console.error).finally(()=>A(!1))))},[l,p.length,m,b,E,A]),S.useEffect(()=>{h.length>0||(B(!0),Fu().then(y=>{D(y),L(y.map(Q=>Q.id))}).catch(console.error).finally(()=>B(!1)))},[h.length,D,L,B]);const[w,M]=S.useState(!1),I=()=>{const y=r.current;if(!y)return;const Q=y.scrollHeight-y.scrollTop-y.clientHeight<40;i.current=Q,M(y.scrollTop>100)};S.useEffect(()=>{i.current&&r.current&&(r.current.scrollTop=r.current.scrollHeight)});const j=c==="thinking"||c==="executing"||c==="planning",_=d[d.length-1],N=j&&(_==null?void 0:_.role)==="assistant"&&!_.done,R=j&&!N,W=S.useRef(null),$=()=>{const y=W.current;y&&(y.style.height="auto",y.style.height=Math.min(y.scrollHeight,200)+"px")},V=S.useCallback(()=>{const y=t.trim();!y||!m||j||(i.current=!0,O(y),e.sendAgentMessage(y,m,u,x),n(""),requestAnimationFrame(()=>{const Q=W.current;Q&&(Q.style.height="auto")}))},[t,m,j,u,x,O,e]),g=S.useCallback(()=>{u&&e.sendAgentStop(u)},[u,e]),F=y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),V())},U=!j&&!!m&&t.trim().length>0;return l?a.jsxs("div",{className:"flex flex-col h-full",style:{background:"var(--bg-primary)"},children:[a.jsx(hs,{selectedModel:m,models:p,modelsLoading:f,onModelChange:E,skills:h,selectedSkillIds:x,skillsLoading:v,onToggleSkill:T,onClear:k,onStop:g,hasMessages:d.length>0,isBusy:j}),a.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[a.jsxs("div",{ref:r,onScroll:I,className:"h-full overflow-y-auto px-3 py-2 space-y-0.5",children:[d.length===0&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 gap-3",style:{color:"var(--text-muted)"},children:[a.jsx("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),a.jsxs("div",{className:"text-center space-y-1.5",children:[a.jsx("p",{className:"text-sm font-medium",style:{color:"var(--text-secondary)"},children:"Ask the agent to help you code"}),a.jsxs("p",{className:"text-xs leading-relaxed",children:["Create agents, functions, evaluations,",a.jsx("br",{}),"or ask questions about your project."]})]})]}),d.map(y=>a.jsx(oy,{message:y},y.id)),R&&a.jsx("div",{className:"py-1.5",children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{background:"var(--success)"}}),a.jsx("span",{className:"text-[11px] font-semibold",style:{color:"var(--success)"},children:c==="thinking"?"Thinking...":c==="executing"?"Executing...":"Planning..."})]})})]}),w&&a.jsx("button",{onClick:()=>{var y;i.current=!1,(y=r.current)==null||y.scrollTo({top:0,behavior:"smooth"})},className:"absolute top-2 right-3 w-6 h-6 flex items-center justify-center rounded-full cursor-pointer transition-opacity opacity-70 hover:opacity-100",style:{background:"var(--bg-tertiary)",color:"var(--text-primary)"},title:"Scroll to top",children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("polyline",{points:"18 15 12 9 6 15"})})})]}),a.jsxs("div",{className:"flex items-end gap-2 px-3 py-2 border-t",style:{borderColor:"var(--border)"},children:[a.jsx("textarea",{ref:W,value:t,onChange:y=>{n(y.target.value),$()},onKeyDown:F,disabled:j||!m,placeholder:j?"Waiting for response...":"Message...",rows:2,className:"flex-1 bg-transparent text-sm py-1 disabled:opacity-40 placeholder:text-[var(--text-muted)] resize-none",style:{color:"var(--text-primary)",maxHeight:200,overflow:"auto"}}),a.jsx("button",{onClick:V,disabled:!U,className:"text-xs font-semibold px-3 py-1.5 rounded transition-colors cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed shrink-0","aria-label":"Send message",style:{color:U?"var(--accent)":"var(--text-muted)",background:"transparent"},onMouseEnter:y=>{U&&(y.currentTarget.style.background="color-mix(in srgb, var(--accent) 10%, transparent)")},onMouseLeave:y=>{y.currentTarget.style.background="transparent"},children:"Send"})]})]}):a.jsxs("div",{className:"flex flex-col h-full",style:{background:"var(--bg-primary)"},children:[a.jsx(hs,{selectedModel:m,models:p,modelsLoading:f,onModelChange:E,skills:h,selectedSkillIds:x,skillsLoading:v,onToggleSkill:T,onClear:k,onStop:g,hasMessages:!1,isBusy:!1}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:a.jsxs("div",{className:"text-center",style:{color:"var(--text-muted)"},children:[a.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",className:"mx-auto mb-2",strokeLinecap:"round",children:[a.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),a.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),a.jsx("p",{className:"text-sm font-medium mb-1",children:"Sign in to use Agent"}),a.jsx("p",{className:"text-xs",children:"Authentication is required to access the coding agent."})]})})]})}function hs({selectedModel:e,models:t,modelsLoading:n,onModelChange:r,skills:i,selectedSkillIds:s,skillsLoading:o,onToggleSkill:l,onClear:u,onStop:c,hasMessages:d,isBusy:p}){const[m,f]=S.useState(!1),h=S.useRef(null);return S.useEffect(()=>{if(!m)return;const x=v=>{h.current&&!h.current.contains(v.target)&&f(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[m]),a.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-3 h-10 border-b",style:{borderColor:"var(--border)",background:"var(--bg-primary)"},children:[a.jsx("span",{className:"text-[11px] uppercase tracking-wider font-semibold shrink-0",style:{color:"var(--text-muted)"},children:"Agent"}),a.jsxs("select",{value:e??"",onChange:x=>r(x.target.value),className:"flex-1 text-[11px] rounded px-1.5 py-1 outline-none min-w-0 cursor-pointer",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",color:"var(--text-primary)"},disabled:n,children:[n&&a.jsx("option",{value:"",children:"Loading models..."}),!n&&t.length===0&&a.jsx("option",{value:"",children:"No models"}),t.map(x=>a.jsx("option",{value:x.model_name,children:x.model_name},x.model_name))]}),!o&&i.length>0&&a.jsxs("div",{className:"relative shrink-0",ref:h,children:[a.jsxs("button",{onClick:()=>f(!m),className:"text-[11px] font-semibold px-2 py-1 rounded cursor-pointer flex items-center gap-1",style:{background:s.length>0?"color-mix(in srgb, var(--accent) 15%, transparent)":"transparent",border:`1px solid ${s.length>0?"var(--accent)":"var(--border)"}`,color:s.length>0?"var(--accent)":"var(--text-muted)"},title:"Skills",children:[a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"}),a.jsx("path",{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"})]}),s.length>0&&a.jsx("span",{children:s.length})]}),m&&a.jsx("div",{className:"absolute top-full right-0 mt-1 rounded shadow-lg z-50 py-1 max-h-64 overflow-y-auto",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)",width:"190px"},children:i.map(x=>a.jsxs("button",{onClick:()=>l(x.id),className:"w-full text-left px-2 py-1 text-[11px] flex items-center gap-1.5 cursor-pointer",style:{color:"var(--text-primary)"},title:x.description,onMouseEnter:v=>{v.currentTarget.style.background="var(--bg-tertiary)"},onMouseLeave:v=>{v.currentTarget.style.background="transparent"},children:[a.jsx("span",{className:"w-3 h-3 rounded border flex items-center justify-center shrink-0",style:{borderColor:s.includes(x.id)?"var(--accent)":"var(--border)",background:s.includes(x.id)?"var(--accent)":"transparent"},children:s.includes(x.id)&&a.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("polyline",{points:"20 6 9 17 4 12"})})}),a.jsx("span",{className:"truncate",children:x.name})]},x.id))})]}),p&&a.jsx("button",{onClick:c,className:"shrink-0 text-[11px] font-semibold px-2 py-1 rounded cursor-pointer",style:{background:"transparent",border:"1px solid var(--error)",color:"var(--error)"},title:"Stop",onMouseEnter:x=>{x.currentTarget.style.background="color-mix(in srgb, var(--error) 10%, transparent)"},onMouseLeave:x=>{x.currentTarget.style.background="transparent"},children:"Stop"}),d&&!p&&a.jsx("button",{onClick:u,className:"shrink-0 w-6 h-6 flex items-center justify-center rounded cursor-pointer",style:{background:"transparent",border:"none",color:"var(--text-muted)"},title:"New session",onMouseEnter:x=>{x.currentTarget.style.color="var(--text-primary)"},onMouseLeave:x=>{x.currentTarget.style.color="var(--text-muted)"},children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("polyline",{points:"1 4 1 10 7 10"}),a.jsx("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]})})]})}function ay(){const e=Yl(),t=ic(),[n,r]=S.useState(!1),[i,s]=S.useState(248),[o,l]=S.useState(!1),[u,c]=S.useState(380),[d,p]=S.useState(!1),{runs:m,selectedRunId:f,setRuns:h,upsertRun:x,selectRun:v,setTraces:b,setLogs:E,setChatMessages:A,setEntrypoints:D,setStateEvents:L,setGraphCache:T,setActiveNode:B,removeActiveNode:O}=Ee(),{section:k,view:w,runId:M,setupEntrypoint:I,setupMode:j,evalCreating:_,evalSetId:N,evalRunId:R,evalRunItemName:W,evaluatorCreateType:$,evaluatorId:V,evaluatorFilter:g,explorerFile:F,navigate:U}=st(),{setEvalSets:y,setEvaluators:Q,setLocalEvaluators:se,setEvalRuns:K}=Ae();S.useEffect(()=>{k==="debug"&&w==="details"&&M&&M!==f&&v(M)},[k,w,M,f,v]);const ie=zn(Z=>Z.init),de=bs(Z=>Z.init);S.useEffect(()=>{Ql().then(h).catch(console.error),ys().then(Z=>D(Z.map(he=>he.name))).catch(console.error),ie(),de()},[h,D,ie,de]),S.useEffect(()=>{k==="evals"&&(vs().then(Z=>y(Z)).catch(console.error),fc().then(Z=>K(Z)).catch(console.error)),(k==="evals"||k==="evaluators")&&(ac().then(Z=>Q(Z)).catch(console.error),Zr().then(Z=>se(Z)).catch(console.error))},[k,y,Q,se,K]);const be=Ae(Z=>Z.evalSets),Oe=Ae(Z=>Z.evalRuns);S.useEffect(()=>{if(k!=="evals"||_||N||R)return;const Z=Object.values(Oe).sort((Ie,fe)=>new Date(fe.start_time??0).getTime()-new Date(Ie.start_time??0).getTime());if(Z.length>0){U(`#/evals/runs/${Z[0].id}`);return}const he=Object.values(be);he.length>0&&U(`#/evals/sets/${he[0].id}`)},[k,_,N,R,Oe,be,U]),S.useEffect(()=>{const Z=he=>{he.key==="Escape"&&n&&r(!1)};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[n]);const Re=f?m[f]:null,at=S.useCallback((Z,he)=>{x(he),b(Z,he.traces),E(Z,he.logs);const Ie=he.messages.map(fe=>{const P=fe.contentParts??fe.content_parts??[],H=fe.toolCalls??fe.tool_calls??[];return{message_id:fe.messageId??fe.message_id,role:fe.role??"assistant",content:P.filter(ee=>{const ae=ee.mimeType??ee.mime_type??"";return ae.startsWith("text/")||ae==="application/json"}).map(ee=>{const ae=ee.data;return(ae==null?void 0:ae.inline)??""}).join(` +`).trim()??"",tool_calls:H.length>0?H.map(ee=>({name:ee.name??"",has_result:!!ee.result})):void 0}});if(A(Z,Ie),he.graph&&he.graph.nodes.length>0&&T(Z,he.graph),he.states&&he.states.length>0&&(L(Z,he.states.map(fe=>({node_name:fe.node_name,qualified_node_name:fe.qualified_node_name,phase:fe.phase,timestamp:new Date(fe.timestamp).getTime(),payload:fe.payload}))),he.status!=="completed"&&he.status!=="failed"))for(const fe of he.states)fe.phase==="started"?B(Z,fe.node_name,fe.qualified_node_name):fe.phase==="completed"&&O(Z,fe.node_name)},[x,b,E,A,L,T,B,O]);S.useEffect(()=>{if(!f)return;e.subscribe(f),ar(f).then(he=>at(f,he)).catch(console.error);const Z=setTimeout(()=>{const he=Ee.getState().runs[f];he&&(he.status==="pending"||he.status==="running")&&ar(f).then(Ie=>at(f,Ie)).catch(console.error)},2e3);return()=>{clearTimeout(Z),e.unsubscribe(f)}},[f,e,at]);const St=S.useRef(null);S.useEffect(()=>{var Ie,fe;if(!f)return;const Z=Re==null?void 0:Re.status,he=St.current;if(St.current=Z??null,Z&&(Z==="completed"||Z==="failed")&&he!==Z){const P=Ee.getState(),H=((Ie=P.traces[f])==null?void 0:Ie.length)??0,ee=((fe=P.logs[f])==null?void 0:fe.length)??0,ae=(Re==null?void 0:Re.trace_count)??0,ke=(Re==null?void 0:Re.log_count)??0;(Hat(f,We)).catch(console.error)}},[f,Re==null?void 0:Re.status,at]);const Pt=Z=>{U(`#/debug/runs/${Z}/traces`),v(Z),r(!1)},yt=Z=>{U(`#/debug/runs/${Z}/traces`),v(Z),r(!1)},ye=()=>{U("#/debug/new"),r(!1)},lt=Z=>{Z==="debug"?U("#/debug/new"):Z==="evals"?U("#/evals"):Z==="evaluators"?U("#/evaluators"):Z==="explorer"&&U("#/explorer")},nt=S.useCallback(Z=>{Z.preventDefault(),l(!0);const he="touches"in Z?Z.touches[0].clientX:Z.clientX,Ie=i,fe=H=>{const ee="touches"in H?H.touches[0].clientX:H.clientX,ae=Math.max(200,Math.min(480,Ie+(ee-he)));s(ae)},P=()=>{l(!1),document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",P),document.removeEventListener("touchmove",fe),document.removeEventListener("touchend",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",fe),document.addEventListener("mouseup",P),document.addEventListener("touchmove",fe,{passive:!1}),document.addEventListener("touchend",P)},[i]),vt=S.useCallback(Z=>{Z.preventDefault(),p(!0);const he="touches"in Z?Z.touches[0].clientX:Z.clientX,Ie=u,fe=H=>{const ee="touches"in H?H.touches[0].clientX:H.clientX,ae=Math.max(280,Math.min(500,Ie-(ee-he)));c(ae)},P=()=>{p(!1),document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",P),document.removeEventListener("touchmove",fe),document.removeEventListener("touchend",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",fe),document.addEventListener("mouseup",P),document.addEventListener("touchmove",fe,{passive:!1}),document.addEventListener("touchend",P)},[u]),Bt=Me(Z=>Z.openTabs),qt=()=>k==="explorer"?Bt.length>0||F?a.jsx(Pu,{}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)]",children:"Select a file to view"}):k==="evals"?_?a.jsx(ao,{}):R?a.jsx(Eu,{evalRunId:R,itemName:W}):N?a.jsx(bu,{evalSetId:N}):a.jsx(ao,{}):k==="evaluators"?$?a.jsx(Lu,{category:$}):a.jsx(Mu,{evaluatorId:V,evaluatorFilter:g}):w==="new"?a.jsx(wc,{}):w==="setup"&&I&&j?a.jsx(Vc,{entrypoint:I,mode:j,ws:e,onRunCreated:Pt,isMobile:t}):Re?a.jsx(fu,{run:Re,ws:e,isMobile:t}):a.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text-muted)]",children:"Select a run or create a new one"});return t?a.jsxs("div",{className:"flex flex-col h-screen w-screen",children:[a.jsxs("div",{className:"flex flex-1 overflow-hidden relative",children:[!n&&a.jsx("button",{onClick:()=>r(!0),className:"fixed top-2 left-2 z-40 w-9 h-9 flex items-center justify-center rounded-lg cursor-pointer",style:{background:"var(--bg-secondary)",border:"1px solid var(--border)"},children:a.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),a.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),a.jsx("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),n&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-50",style:{background:"rgba(0,0,0,0.5)"},onClick:()=>r(!1)}),a.jsxs("aside",{className:"fixed inset-y-0 left-0 z-50 w-64 bg-[var(--sidebar-bg)] border-r border-[var(--border)] flex flex-col",children:[a.jsxs("div",{className:"px-3 h-10 border-b border-[var(--border)] flex items-center justify-between",children:[a.jsxs("button",{onClick:()=>{U("#/debug/new"),r(!1)},className:"flex items-center gap-2 cursor-pointer",style:{background:"none",border:"none"},children:[a.jsx("img",{src:"/favicon.ico",width:"14",height:"14",alt:"UiPath"}),a.jsx("span",{className:"text-[10px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:"Developer Console"})]}),a.jsx("button",{onClick:()=>r(!1),className:"w-6 h-6 flex items-center justify-center rounded cursor-pointer transition-colors",style:{color:"var(--text-muted)",background:"transparent",border:"none"},children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),k==="debug"&&a.jsx(Oi,{runs:Object.values(m),selectedRunId:f,onSelectRun:yt,onNewRun:ye}),k==="evals"&&a.jsx(to,{}),k==="evaluators"&&a.jsx(lo,{}),k==="explorer"&&a.jsx(uo,{})]})]}),a.jsx("main",{className:"flex-1 overflow-hidden bg-[var(--bg-primary)]",children:qt()})]}),a.jsx(Li,{}),a.jsx(Xi,{}),a.jsx(Qi,{})]}):a.jsxs("div",{className:"flex flex-col h-screen w-screen",children:[a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsxs("aside",{className:"shrink-0 flex flex-col",style:{width:i,background:"var(--sidebar-bg)"},children:[a.jsxs("div",{className:"flex h-10 border-b shrink-0",style:{borderColor:"var(--border)"},children:[a.jsx("button",{onClick:()=>U("#/debug/new"),className:"w-12 shrink-0 flex items-center justify-center cursor-pointer transition-colors border-r",style:{background:"var(--activity-bar-bg)",border:"none",borderRight:"1px solid var(--border)"},onMouseEnter:Z=>{Z.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:Z=>{Z.currentTarget.style.background="var(--activity-bar-bg)"},children:a.jsx("img",{src:"/favicon.ico",width:"20",height:"20",alt:"UiPath"})}),a.jsx("div",{className:"flex-1 flex items-center px-3",style:{background:"var(--sidebar-bg)"},children:a.jsx("span",{className:"text-[11px] uppercase tracking-widest font-semibold",style:{color:"var(--text-muted)"},children:k==="debug"?"Developer Console":k==="evals"?"Evaluations":k==="evaluators"?"Evaluators":"Explorer"})})]}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsx(sc,{section:k,onSectionChange:lt}),a.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[k==="debug"&&a.jsx(Oi,{runs:Object.values(m),selectedRunId:f,onSelectRun:yt,onNewRun:ye}),k==="evals"&&a.jsx(to,{}),k==="evaluators"&&a.jsx(lo,{}),k==="explorer"&&a.jsx(uo,{})]})]})]}),a.jsx("div",{onMouseDown:nt,onTouchStart:nt,className:"shrink-0 drag-handle-col",style:o?{background:"var(--accent)"}:void 0}),a.jsxs("main",{className:"flex-1 overflow-hidden bg-[var(--bg-primary)] flex",children:[a.jsx("div",{className:"flex-1 overflow-hidden",children:qt()}),k==="explorer"&&a.jsxs(a.Fragment,{children:[a.jsx("div",{onMouseDown:vt,onTouchStart:vt,className:"shrink-0 drag-handle-col",style:d?{background:"var(--accent)"}:void 0}),a.jsx("div",{className:"shrink-0 overflow-hidden",style:{width:u,borderLeft:"1px solid var(--border)"},children:a.jsx(sy,{})})]})]})]}),a.jsx(Li,{}),a.jsx(Xi,{}),a.jsx(Qi,{})]})}Cl.createRoot(document.getElementById("root")).render(a.jsx(S.StrictMode,{children:a.jsx(ay,{})}));export{Zm as M,Qx as a,Hg as r,Ee as u}; diff --git a/src/uipath/dev/server/static/index.html b/src/uipath/dev/server/static/index.html index 2d437c9..924dd29 100644 --- a/src/uipath/dev/server/static/index.html +++ b/src/uipath/dev/server/static/index.html @@ -5,7 +5,7 @@ UiPath Developer Console - + diff --git a/src/uipath/dev/server/ws/manager.py b/src/uipath/dev/server/ws/manager.py index 958fd20..d27d16c 100644 --- a/src/uipath/dev/server/ws/manager.py +++ b/src/uipath/dev/server/ws/manager.py @@ -301,6 +301,44 @@ def broadcast_agent_error(self, session_id: str, message: str) -> None: for ws in self._connections: self._enqueue(ws, msg) + def broadcast_agent_thinking(self, session_id: str, content: str) -> None: + """Broadcast agent thinking/reasoning to all connected clients.""" + msg = server_message( + ServerEvent.AGENT_THINKING, + {"session_id": session_id, "content": content}, + ) + for ws in self._connections: + self._enqueue(ws, msg) + + def broadcast_agent_text_delta(self, session_id: str, delta: str) -> None: + """Broadcast a streaming text token to all connected clients.""" + msg = server_message( + ServerEvent.AGENT_TEXT_DELTA, + {"session_id": session_id, "delta": delta}, + ) + for ws in self._connections: + self._enqueue(ws, msg) + + def broadcast_agent_token_usage( + self, + session_id: str, + prompt_tokens: int, + completion_tokens: int, + total_session_tokens: int, + ) -> None: + """Broadcast token usage stats to all connected clients.""" + msg = server_message( + ServerEvent.AGENT_TOKEN_USAGE, + { + "session_id": session_id, + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens, + "total_session_tokens": total_session_tokens, + }, + ) + for ws in self._connections: + self._enqueue(ws, msg) + def _schedule_broadcast(self, run_id: str, message: dict[str, Any]) -> None: """Enqueue a message for all subscribers of a run.""" subscribers = self._subscriptions.get(run_id) diff --git a/src/uipath/dev/server/ws/protocol.py b/src/uipath/dev/server/ws/protocol.py index b5bd0f8..aa822b9 100644 --- a/src/uipath/dev/server/ws/protocol.py +++ b/src/uipath/dev/server/ws/protocol.py @@ -27,6 +27,9 @@ class ServerEvent(str, Enum): AGENT_TOOL_RESULT = "agent.tool_result" AGENT_TOOL_APPROVAL = "agent.tool_approval" AGENT_ERROR = "agent.error" + AGENT_THINKING = "agent.thinking" + AGENT_TEXT_DELTA = "agent.text_delta" + AGENT_TOKEN_USAGE = "agent.token_usage" class ClientCommand(str, Enum): diff --git a/src/uipath/dev/services/agent/__init__.py b/src/uipath/dev/services/agent/__init__.py new file mode 100644 index 0000000..9314ba8 --- /dev/null +++ b/src/uipath/dev/services/agent/__init__.py @@ -0,0 +1,33 @@ +"""Agent harness — deep agent architecture with loop innovations.""" + +from uipath.dev.services.agent.events import ( + AgentEvent, + ErrorOccurred, + PlanUpdated, + StatusChanged, + TextDelta, + TextGenerated, + ThinkingGenerated, + TokenUsageUpdated, + ToolApprovalRequired, + ToolCompleted, + ToolStarted, +) +from uipath.dev.services.agent.service import AgentService +from uipath.dev.services.agent.session import AgentSession + +__all__ = [ + "AgentEvent", + "AgentService", + "AgentSession", + "ErrorOccurred", + "PlanUpdated", + "StatusChanged", + "TextDelta", + "TextGenerated", + "ThinkingGenerated", + "TokenUsageUpdated", + "ToolApprovalRequired", + "ToolCompleted", + "ToolStarted", +] diff --git a/src/uipath/dev/services/agent/context.py b/src/uipath/dev/services/agent/context.py new file mode 100644 index 0000000..275450b --- /dev/null +++ b/src/uipath/dev/services/agent/context.py @@ -0,0 +1,108 @@ +"""Context window management — compaction + stale tool result pruning.""" + +from __future__ import annotations + +from uipath.dev.services.agent.provider import ModelProvider +from uipath.dev.services.agent.session import AgentSession + +COMPACTION_TRIGGER_RATIO = 0.75 +KEEP_RECENT = 4 # Keep last 4 messages (2 turns) for continuity + +_DEFAULT_CONTEXT_WINDOW = 128_000 + +# Prefix → context window size. Matched longest-prefix-first against model names +# like "gpt-5.1-2025-11-13". +MODEL_CONTEXT_WINDOWS: dict[str, int] = { + "gpt-4o-mini": 128_000, + "gpt-4o": 128_000, + "gpt-4.1-mini": 1_048_576, + "gpt-4.1-nano": 1_048_576, + "gpt-4.1": 1_048_576, + "gpt-5.1": 1_048_576, + "gpt-5.2": 1_048_576, + "gpt-5": 1_048_576, +} + + +def get_context_window(model: str) -> int: + """Return the context window size for a model, matching by prefix.""" + for prefix, size in MODEL_CONTEXT_WINDOWS.items(): + if model.startswith(prefix): + return size + return _DEFAULT_CONTEXT_WINDOW + + +MAX_TOOL_RESULTS_KEPT = 10 +MIN_RESULT_SIZE_TO_CLEAR = 500 + + +async def maybe_compact( + session: AgentSession, + provider: ModelProvider, + system_prompt: str, +) -> bool: + """Check if compaction is needed and perform it if so. + + Returns True if compaction was performed. + """ + window_size = get_context_window(session.model) + if session.total_prompt_tokens < window_size * COMPACTION_TRIGGER_RATIO: + return False + + summary_prompt = ( + "Summarize the conversation so far. Preserve:\n" + "- The user's original request and any clarifications\n" + "- Key decisions made and their rationale\n" + "- Current state of the task (what's done, what remains)\n" + "- File paths and code patterns that were discovered\n" + "- Any errors encountered and how they were resolved\n" + "Be concise but don't lose critical context." + ) + + summary_response = await provider.complete( + messages=[ + {"role": "system", "content": summary_prompt}, + *session.messages, + ], + tools=[], + model=session.model, + max_tokens=2048, + ) + + recent = ( + session.messages[-KEEP_RECENT:] if len(session.messages) > KEEP_RECENT else [] + ) + session.messages = [ + { + "role": "assistant", + "content": f"[Conversation Summary]\n{summary_response.content}", + }, + *recent, + ] + session.compaction_count += 1 + return True + + +def prune_stale_tool_results(session: AgentSession) -> int: + """Replace old tool results with placeholders. Returns chars freed.""" + tool_result_indices = [ + i + for i, m in enumerate(session.messages) + if m.get("role") == "tool" + and len(m.get("content", "")) > MIN_RESULT_SIZE_TO_CLEAR + ] + + to_clear = ( + tool_result_indices[:-MAX_TOOL_RESULTS_KEPT] + if len(tool_result_indices) > MAX_TOOL_RESULTS_KEPT + else [] + ) + + freed = 0 + for idx in to_clear: + msg = session.messages[idx] + original_len = len(msg["content"]) + msg["content"] = f"[tool result cleared — {original_len} chars]" + freed += original_len + + return freed diff --git a/src/uipath/dev/services/agent/events.py b/src/uipath/dev/services/agent/events.py new file mode 100644 index 0000000..e9655c1 --- /dev/null +++ b/src/uipath/dev/services/agent/events.py @@ -0,0 +1,91 @@ +"""Typed event system for the agent harness.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class AgentEvent: + """Base class for all agent events.""" + + session_id: str + + +@dataclass +class StatusChanged(AgentEvent): + """Agent status changed.""" + + status: str = "" + + +@dataclass +class TextGenerated(AgentEvent): + """Final text response (or chunk with done=True).""" + + content: str = "" + done: bool = False + + +@dataclass +class TextDelta(AgentEvent): + """Streaming text token.""" + + delta: str = "" + + +@dataclass +class ThinkingGenerated(AgentEvent): + """Model thinking/reasoning content.""" + + content: str = "" + + +@dataclass +class PlanUpdated(AgentEvent): + """Plan items updated.""" + + items: list[dict[str, str]] = field(default_factory=list) + + +@dataclass +class ToolStarted(AgentEvent): + """Tool execution started.""" + + tool: str = "" + args: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class ToolCompleted(AgentEvent): + """Tool execution completed.""" + + tool: str = "" + result: str = "" + is_error: bool = False + + +@dataclass +class ToolApprovalRequired(AgentEvent): + """Tool requires user approval before execution.""" + + tool_call_id: str = "" + tool: str = "" + args: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class ErrorOccurred(AgentEvent): + """An error occurred in the agent loop.""" + + message: str = "" + + +@dataclass +class TokenUsageUpdated(AgentEvent): + """Token usage stats for the current turn.""" + + prompt_tokens: int = 0 + completion_tokens: int = 0 + total_session_tokens: int = 0 diff --git a/src/uipath/dev/services/agent/loop.py b/src/uipath/dev/services/agent/loop.py new file mode 100644 index 0000000..7f4f5af --- /dev/null +++ b/src/uipath/dev/services/agent/loop.py @@ -0,0 +1,579 @@ +"""Core agentic loop with streaming, parallel tools, retry, sub-agent dispatch.""" + +from __future__ import annotations + +import asyncio +import json +import logging +from collections.abc import AsyncIterator, Callable +from typing import Any + +from uipath.dev.services.agent.context import maybe_compact, prune_stale_tool_results +from uipath.dev.services.agent.events import ( + AgentEvent, + ErrorOccurred, + PlanUpdated, + StatusChanged, + TextDelta, + TextGenerated, + ThinkingGenerated, + TokenUsageUpdated, + ToolApprovalRequired, + ToolCompleted, + ToolStarted, +) +from uipath.dev.services.agent.provider import ModelProvider, StreamEvent, ToolCall +from uipath.dev.services.agent.session import AgentSession +from uipath.dev.services.agent.tools import ToolDefinition + +logger = logging.getLogger(__name__) + +MAX_ITERATIONS = 50 +MAX_RETRIES = 3 +RETRY_BASE_DELAY = 1.0 +SUB_AGENT_MAX_ITERATIONS = 15 + +# --------------------------------------------------------------------------- +# System prompt +# --------------------------------------------------------------------------- + +SYSTEM_PROMPT = """\ +You are a senior Python developer specializing in UiPath coded agents and automations. \ +You help users build, debug, test, and improve Python agents using the UiPath SDK. + +## Critical Rules + +### You Have a Shell — USE IT +- You have direct access to the user's terminal via the `bash` tool. +- NEVER tell the user to run commands themselves. ALWAYS use `bash` to execute commands directly. +- This includes: `uv run`, `uv sync`, `uipath init`, `uipath run`, `uipath eval`, `uipath pack`, `uipath publish`, and any other CLI commands. +- If something needs to be run, run it. Don't explain how to run it. +- The user is already authenticated — NEVER ask them to authenticate or run `uipath auth`. + +### Read Before Writing +- NEVER suggest code changes without first reading the relevant source files. +- NEVER assume what code looks like — use `read_file`, `glob`, and `grep` to verify. +- When asked about a function or class, read its implementation first. Do not guess signatures, return types, or behavior. +- Before editing a file, always read it to understand context, imports, and conventions. + +### Evidence-Based Responses +- Ground every suggestion in actual code you have read in the current session. +- When explaining behavior, quote or reference specific lines from the codebase. +- If you're unsure about something, search the code rather than speculating. +- If you cannot find what you need, say so explicitly instead of making assumptions. + +### Surgical, Minimal Changes +- Make the smallest change that solves the problem. Don't refactor adjacent code. +- Match the existing code style — indentation, naming conventions, import patterns. +- Only add imports, variables, or functions that your change requires. +- Don't add error handling, type hints, or docstrings beyond what was asked. + +## Workflow + +1. **Plan first**: Call `update_plan` with your steps before doing anything else. +2. **Explore**: Use `glob` and `grep` to find relevant files. Read them with `read_file`. +3. **Implement**: Use `edit_file` for targeted changes, `write_file` only for new files. +4. **Execute**: Use `bash` to run commands — installations, tests, linters, builds, `uv run` commands, etc. \ +When the user asks you to run something, always use the `bash` tool to execute it. Never tell the user to run commands themselves — you have a shell, use it. +5. **Verify**: Read back edited files to confirm correctness. Run tests or linters via `bash`. +6. **Update progress**: After completing each step, call `update_plan` to mark it as "completed" BEFORE moving on. \ +When starting a step, mark it as "in_progress". Always send the full plan array with all steps. +7. **Before your final response**: Call `update_plan` one last time to mark all remaining steps as "completed". \ +NEVER give your final summary without first ensuring every plan step is marked completed. +8. **Summarize**: When done, briefly state what you changed and why. + +## Full Build Cycle + +When building or modifying an agent or function, always complete the full cycle — don't stop at writing code: + +1. **Write the code** — implement the agent/function with Input/Output models and `@traced()` main function. +2. **Generate entry points** — run `uv run uipath init` via `bash`. +3. **Write evaluations** — create BOTH: + - **Evaluator files** in `evaluations/evaluators/` (e.g. `exact-match.json`, `json-similarity.json`) — these must exist first. + - **Eval set files** in `evaluations/eval-sets/` with test cases that reference the evaluator IDs. +4. **Run the evaluations** — execute `uv run uipath eval` via `bash` and report results. +5. **Pack & publish** — when the user asks to deploy, run via `bash`: + - `uv run uipath pack` — create a .nupkg package + - `uv run uipath publish -w` — publish to personal workspace (default) + - `uv run uipath publish -t` — publish to a specific tenant folder + +Never stop after just writing code. If you create an agent/function, you must also create evaluations and run them. \ +If you create eval sets, you must also create the evaluator files they reference — otherwise the eval run will fail. \ +If the user asks you to publish or deploy, use `bash` to run the commands — don't tell them to do it. \ +Default to publishing to personal workspace (`-w`) unless the user specifies a tenant folder. + +## Tools +- `read_file` — Read file contents (always use before editing) +- `write_file` — Create or overwrite a file +- `edit_file` — Surgical string replacement (old_string must be unique) +- `bash` — Execute a shell command (timeout: 30s). USE THIS to run commands for the user. +- `glob` — Find files matching a pattern (e.g. `**/*.py`) +- `grep` — Search file contents with regex +- `update_plan` — Create or update your task plan +- `read_reference` — Read a reference doc from the active skill (when skills are active) +- `dispatch_agent` — Spawn a sub-agent to handle a subtask in its own context +""" + + +async def _chain_async( + first: StreamEvent, rest: AsyncIterator[StreamEvent] +) -> AsyncIterator[StreamEvent]: + """Yield first, then yield from rest.""" + yield first + async for item in rest: + yield item + + +async def _empty_async_iter() -> AsyncIterator[StreamEvent]: + """Return an empty async iterator.""" + if False: # noqa: SIM108 — needed to make this an async generator + yield StreamEvent(type="done") + + +SUB_AGENT_PROMPT = """\ +You are a research sub-agent. You have access to read-only tools to explore the codebase. +Complete the task and provide a concise summary of your findings. +Be thorough but concise — your response will be returned to the parent agent. +""" + + +class AgentLoop: + """The core agentic loop with all innovations.""" + + def __init__( # noqa: D107 + self, + *, + provider: ModelProvider, + tools: list[ToolDefinition], + emit: Callable[[AgentEvent], None], + max_iterations: int = MAX_ITERATIONS, + allow_dispatch: bool = True, + # Approval support + pending_approvals: dict[str, asyncio.Event] | None = None, + approval_results: dict[str, bool] | None = None, + # Skill support + skill_service: Any | None = None, + ) -> None: + self.provider = provider + self.tools = tools + self.emit = emit + self.max_iterations = max_iterations + self.allow_dispatch = allow_dispatch + self._pending_approvals = ( + pending_approvals if pending_approvals is not None else {} + ) + self._approval_results = ( + approval_results if approval_results is not None else {} + ) + self._skill_service = skill_service + + async def run(self, session: AgentSession, system_prompt: str) -> None: + """Run the agent loop until completion or max iterations.""" + try: + # Build tool schemas — sorted for stable prefix ordering (prompt caching) + tool_schemas = sorted( + [t.to_openai_schema() for t in self.tools], + key=lambda t: t["function"]["name"], + ) + + tool_map = {t.name: t for t in self.tools} + + for iteration in range(self.max_iterations): + logger.info( + "Loop iteration %d, messages=%d", iteration, len(session.messages) + ) + if session._cancel_event.is_set(): + session.status = "done" + self.emit(StatusChanged(session.id, status="done")) + return + + # Prune stale tool results before each LLM call + prune_stale_tool_results(session) + + # Check if compaction is needed + await maybe_compact(session, self.provider, system_prompt) + + # Build messages with stable prefix + llm_messages = [ + {"role": "system", "content": system_prompt}, + *session.messages, + ] + + # Stream the response + accumulated_content = "" + accumulated_thinking = "" + tool_calls: list[ToolCall] = [] + finish_reason = "" + + stream = await self._call_model_with_retry( + llm_messages, tool_schemas, session + ) + async for event in stream: + match event.type: + case "text_delta": + self.emit(TextDelta(session.id, delta=event.delta)) + accumulated_content += event.delta + case "thinking_delta": + self.emit( + ThinkingGenerated(session.id, content=event.delta) + ) + accumulated_thinking += event.delta + case "tool_call": + if event.tool_call: + tool_calls.append(event.tool_call) + case "done": + finish_reason = event.finish_reason + # Track token usage + if event.usage: + session.total_prompt_tokens += event.usage.prompt_tokens + session.total_completion_tokens += ( + event.usage.completion_tokens + ) + session.turn_count += 1 + self.emit( + TokenUsageUpdated( + session.id, + prompt_tokens=event.usage.prompt_tokens, + completion_tokens=event.usage.completion_tokens, + total_session_tokens=session.total_prompt_tokens + + session.total_completion_tokens, + ) + ) + + # Build assistant message for conversation history + assistant_msg: dict[str, Any] = { + "role": "assistant", + "content": accumulated_content, + } + if tool_calls: + assistant_msg["tool_calls"] = [ + { + "id": tc.id, + "type": "function", + "function": { + "name": tc.name, + "arguments": tc.arguments, + }, + } + for tc in tool_calls + ] + session.messages.append(assistant_msg) + + # If no tool calls, we're done + if finish_reason == "stop" or not tool_calls: + # Content already streamed via TextDelta — just mark done + self.emit(TextGenerated(session.id, content="", done=True)) + session.status = "done" + self.emit(StatusChanged(session.id, status="done")) + return + + # Execute tool calls (parallel where possible) + logger.info( + "Executing %d tool calls: %s", + len(tool_calls), + [tc.name for tc in tool_calls], + ) + await self._execute_tools_parallel(tool_calls, session, tool_map) + logger.info("Tool execution complete, continuing loop") + + # After tools, set status back to thinking + self.emit(StatusChanged(session.id, status="thinking")) + + # Max iterations reached + self.emit( + TextGenerated( + session.id, + content="Reached maximum iterations. Stopping.", + done=True, + ) + ) + session.status = "done" + self.emit(StatusChanged(session.id, status="done")) + + except asyncio.CancelledError: + session.status = "done" + self.emit(StatusChanged(session.id, status="done")) + except Exception as e: + logger.exception("Agent loop error for session %s", session.id) + session.status = "error" + self.emit(ErrorOccurred(session.id, message=str(e))) + + async def _call_model_with_retry( + self, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]], + session: AgentSession, + ) -> AsyncIterator[StreamEvent]: + """Call the model with retry on transient errors. + + Retries only apply to connection/API errors before streaming starts. + Once streaming begins, errors are propagated directly. + """ + last_error: Exception | None = None + for attempt in range(MAX_RETRIES + 1): + try: + stream = self.provider.stream( + messages, + tools, + model=session.model, + max_tokens=4096, + temperature=0, + ) + # Try to get the first event to detect connection errors early + first = await stream.__anext__() + # Success — chain first event with the rest + return _chain_async(first, stream) + except StopAsyncIteration: + return _empty_async_iter() + except Exception as e: + last_error = e + if attempt == MAX_RETRIES or not self._is_retryable(e): + raise + delay = RETRY_BASE_DELAY * (2**attempt) + logger.warning( + "Retrying model call (attempt %d/%d) after %.1fs: %s", + attempt + 1, + MAX_RETRIES, + delay, + e, + ) + await asyncio.sleep(delay) + raise last_error # type: ignore[misc] + + @staticmethod + def _is_retryable(error: Exception) -> bool: + """Check if error is transient (rate limit, timeout, 5xx).""" + err_str = str(error).lower() + return any( + k in err_str for k in ("rate limit", "timeout", "429", "500", "502", "503") + ) + + async def _execute_tools_parallel( + self, + tool_calls: list[ToolCall], + session: AgentSession, + tool_map: dict[str, ToolDefinition], + ) -> None: + """Execute tool calls — approval sequentially, execution in parallel.""" + self.emit(StatusChanged(session.id, status="executing")) + + # Phase 1: Handle approval + special tools; collect tasks for parallel exec + tasks: list[tuple[ToolCall, asyncio.Task[str] | str | None]] = [] + + for tc in tool_calls: + if session._cancel_event.is_set(): + session.status = "done" + self.emit(StatusChanged(session.id, status="done")) + return + + tool_name = tc.name + try: + tool_args = json.loads(tc.arguments) + except json.JSONDecodeError: + tool_args = {} + + tool_def = tool_map.get(tool_name) + + # Handle update_plan specially (no approval, immediate) + if tool_name == "update_plan": + result = self._handle_update_plan(session, tool_args) + tasks.append((tc, result)) + continue + + # Handle read_reference specially + if tool_name == "read_reference": + result = self._handle_read_reference(session, tool_args) + self.emit(ToolStarted(session.id, tool=tool_name, args=tool_args)) + is_error = result.startswith("Error:") + self.emit( + ToolCompleted( + session.id, tool=tool_name, result=result, is_error=is_error + ) + ) + tasks.append((tc, result)) + continue + + # Handle dispatch_agent specially + if tool_name == "dispatch_agent" and self.allow_dispatch: + self.emit(ToolStarted(session.id, tool=tool_name, args=tool_args)) + result = await self._handle_dispatch_agent( + tool_args.get("task", ""), session + ) + self.emit( + ToolCompleted( + session.id, tool=tool_name, result=result, is_error=False + ) + ) + tasks.append((tc, result)) + continue + + self.emit(ToolStarted(session.id, tool=tool_name, args=tool_args)) + + # Approval gate for destructive tools (sequential for UX clarity) + if tool_def and tool_def.requires_approval: + logger.info( + "Requesting approval for tool=%s tc.id=%s", tool_name, tc.id + ) + approval_event = asyncio.Event() + self._pending_approvals[tc.id] = approval_event + self.emit( + ToolApprovalRequired( + session.id, + tool_call_id=tc.id, + tool=tool_name, + args=tool_args, + ) + ) + self.emit(StatusChanged(session.id, status="awaiting_approval")) + await approval_event.wait() + approved = self._approval_results.pop(tc.id, False) + self._pending_approvals.pop(tc.id, None) + logger.info( + "Approval resolved for tool=%s tc.id=%s approved=%s", + tool_name, + tc.id, + approved, + ) + + if session._cancel_event.is_set(): + session.status = "done" + self.emit(StatusChanged(session.id, status="done")) + return + + if not approved: + result = "Tool execution denied by user" + self.emit(StatusChanged(session.id, status="executing")) + self.emit( + ToolCompleted( + session.id, + tool=tool_name, + result=result, + is_error=True, + ) + ) + tasks.append((tc, result)) + continue + + self.emit(StatusChanged(session.id, status="executing")) + + # Queue for parallel execution + tasks.append((tc, None)) # None = needs execution + + # Phase 2: Execute all pending tools in parallel + exec_tasks: list[tuple[int, asyncio.Task[str]]] = [] + for i, (tc_item, res_item) in enumerate(tasks): + if res_item is not None: + continue # Already handled + tool_def = tool_map.get(tc_item.name) + if tool_def: + try: + tool_args = json.loads(tc_item.arguments) + except json.JSONDecodeError: + tool_args = {} + exec_task = asyncio.create_task( + self._execute_single_tool(tool_def, tool_args) + ) + exec_tasks.append((i, exec_task)) + else: + tasks[i] = (tc_item, f"Error: unknown tool '{tc_item.name}'") + + if exec_tasks: + gather_results = await asyncio.gather( + *[t for _, t in exec_tasks], return_exceptions=True + ) + for (idx, _), gather_result in zip(exec_tasks, gather_results, strict=True): + tc_done = tasks[idx][0] + if isinstance(gather_result, BaseException): + result_str = f"Error: {gather_result}" + is_error = True + else: + result_str = gather_result + is_error = result_str.startswith("Error:") + tasks[idx] = (tc_done, result_str) + self.emit( + ToolCompleted( + session.id, + tool=tc_done.name, + result=result_str, + is_error=is_error, + ) + ) + + # Phase 3: Append all tool results to session messages in order + for tc_final, result_final in tasks: + session.messages.append( + { + "role": "tool", + "tool_call_id": tc_final.id, + "content": result_final or "", + } + ) + + @staticmethod + async def _execute_single_tool( + tool_def: ToolDefinition, args: dict[str, Any] + ) -> str: + """Execute a single tool in a thread executor.""" + return await asyncio.get_event_loop().run_in_executor( + None, tool_def.handler, args + ) + + def _handle_update_plan(self, session: AgentSession, args: dict[str, Any]) -> str: + items = args.get("plan", []) + if not isinstance(items, list): + return "Error: plan must be an array" + + session.plan = items + self.emit(PlanUpdated(session.id, items=items)) + return "Plan updated" + + def _handle_read_reference( + self, session: AgentSession, args: dict[str, Any] + ) -> str: + """Read a reference file using the base from active skills.""" + from uipath.dev.services.agent.tools import MAX_FILE_CHARS + + ref_path = args.get("path", "") + if not ref_path or not self._skill_service or not session.skill_ids: + return "Error: no active skills or missing path" + base_skill_id = session.skill_ids[0] + try: + content = self._skill_service.get_reference(base_skill_id, ref_path) + if len(content) > MAX_FILE_CHARS: + content = ( + content[:MAX_FILE_CHARS] + + f"\n... [truncated at {MAX_FILE_CHARS} chars]" + ) + return content + except (FileNotFoundError, PermissionError) as e: + return f"Error: {e}" + + async def _handle_dispatch_agent( + self, task: str, parent_session: AgentSession + ) -> str: + """Run a sub-agent with isolated context and return its result.""" + child_session = AgentSession(model=parent_session.model) + child_session.messages.append({"role": "user", "content": task}) + + # Read-only tools only, no dispatch_agent + child_tools = [ + t + for t in self.tools + if not t.requires_approval and t.name != "dispatch_agent" + ] + + child_loop = AgentLoop( + provider=self.provider, + tools=child_tools, + emit=lambda _e: None, # Sub-agent events are silent + max_iterations=SUB_AGENT_MAX_ITERATIONS, + allow_dispatch=False, + skill_service=self._skill_service, + ) + await child_loop.run(child_session, system_prompt=SUB_AGENT_PROMPT) + + # Extract final assistant message + for msg in reversed(child_session.messages): + if msg["role"] == "assistant" and msg.get("content"): + return msg["content"] + return "Sub-agent completed without producing a response." diff --git a/src/uipath/dev/services/agent/provider.py b/src/uipath/dev/services/agent/provider.py new file mode 100644 index 0000000..a19c71a --- /dev/null +++ b/src/uipath/dev/services/agent/provider.py @@ -0,0 +1,482 @@ +"""Model provider protocol + OpenAI-compatible streaming implementation.""" + +from __future__ import annotations + +import logging +import os +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from typing import Any, Protocol, runtime_checkable + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Data classes +# --------------------------------------------------------------------------- + + +@dataclass +class ToolCall: + """A tool call from the model.""" + + id: str + name: str + arguments: str # raw JSON string + + +@dataclass +class Usage: + """Token usage for a single completion.""" + + prompt_tokens: int = 0 + completion_tokens: int = 0 + + +@dataclass +class ModelResponse: + """Non-streaming model response.""" + + content: str = "" + tool_calls: list[ToolCall] = field(default_factory=list) + thinking: str | None = None + finish_reason: str = "" + usage: Usage | None = None + + +@dataclass +class StreamEvent: + """A single event from a streaming response.""" + + type: str # "text_delta" | "thinking_delta" | "tool_call" | "done" + delta: str = "" + tool_call: ToolCall | None = None + usage: Usage | None = None + finish_reason: str = "" + + +# --------------------------------------------------------------------------- +# Protocol +# --------------------------------------------------------------------------- + + +@runtime_checkable +class ModelProvider(Protocol): + """Protocol for model providers.""" + + async def complete( # noqa: D102 + self, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]], + *, + model: str, + max_tokens: int = 4096, + temperature: float = 0, + ) -> ModelResponse: ... + + def stream( # noqa: D102 + self, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]], + *, + model: str, + max_tokens: int = 4096, + temperature: float = 0, + ) -> AsyncIterator[StreamEvent]: ... + + +# --------------------------------------------------------------------------- +# OpenAI-compatible provider via UiPath LLM gateway +# --------------------------------------------------------------------------- + + +# Reasoning models don't support temperature. +_REASONING_PREFIXES = ("o1", "o3", "o4", "gpt-5") + + +def _is_reasoning_model(model: str) -> bool: + return any(model.startswith(p) for p in _REASONING_PREFIXES) + + +def _get_gateway_env() -> tuple[str, str]: + """Return (base_url, access_token) from environment.""" + base_url = os.environ.get("UIPATH_URL", "") + access_token = os.environ.get("UIPATH_ACCESS_TOKEN", "") + if not base_url or not access_token: + raise RuntimeError( + "Not authenticated — UIPATH_URL or UIPATH_ACCESS_TOKEN not set" + ) + return base_url, access_token + + +def _make_rewrite_transport(gateway_completions_url: str) -> Any: + """Create an httpx transport that rewrites all URLs to the gateway endpoint. + + The gateway uses the X-UiPath-LlmGateway-ApiFlavor header (not the URL) + to distinguish Chat Completions from Responses API payloads. + """ + import httpx + + class _RewriteTransport(httpx.AsyncHTTPTransport): + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + original = str(request.url) + params = request.url.params + request.url = httpx.URL(gateway_completions_url, params=params) + logger.info("URL rewrite: %s -> %s", original, str(request.url)) + return await super().handle_async_request(request) + + return _RewriteTransport() + + +class OpenAIProvider: + """OpenAI-compatible provider via UiPath LLM gateway.""" + + def __init__(self, model: str) -> None: + """Initialize with a model name.""" + self._model = model + self._completions_client = self._create_completions_client(model) + self._responses_client: Any = None # Lazy-created for reasoning models + + @staticmethod + def _create_completions_client(model_name: str) -> Any: + """Create an AsyncOpenAI client for the Chat Completions API.""" + from openai import AsyncOpenAI + + base_url, access_token = _get_gateway_env() + gateway_base = ( + f"{base_url.rstrip('/')}/agenthub_/llm/openai/deployments/{model_name}" + ) + return AsyncOpenAI( + api_key=access_token, + base_url=gateway_base, + default_query={"api-version": "2025-03-01-preview"}, + default_headers={ + "X-UiPath-LlmGateway-RequestingProduct": "AgentsPlayground", + "X-UiPath-LlmGateway-RequestingFeature": "uipath-dev", + }, + ) + + @staticmethod + def _create_responses_client(model_name: str) -> Any: + """Create an AsyncOpenAI client for the Responses API. + + Uses a URL-rewriting transport so the SDK's /responses path + gets redirected to the gateway's /completions endpoint. + The ApiFlavor header tells the gateway it's a Responses API payload. + """ + import httpx + from openai import AsyncOpenAI + + base_url, access_token = _get_gateway_env() + # The gateway's unified endpoint — uses the raw vendor/model path + # (same as uipath-langchain). ApiFlavor header tells the gateway + # whether the payload is Chat Completions or Responses API format. + completions_url = ( + f"{base_url.rstrip('/')}/agenthub_/llm" + f"/raw/vendor/openai/model/{model_name}/completions" + ) + # The SDK needs a base_url so it can construct /responses, + # but our transport will rewrite to the completions_url. + dummy_base = ( + f"{base_url.rstrip('/')}/agenthub_/llm/openai/deployments/{model_name}" + ) + return AsyncOpenAI( + api_key=access_token, + base_url=dummy_base, + default_query={"api-version": "2025-04-01-preview"}, + default_headers={ + "X-UiPath-LlmGateway-RequestingProduct": "AgentsPlayground", + "X-UiPath-LlmGateway-RequestingFeature": "uipath-dev", + "X-UiPath-LlmGateway-ApiFlavor": "auto", + }, + http_client=httpx.AsyncClient( + transport=_make_rewrite_transport(completions_url), + ), + ) + + def _get_responses_client(self) -> Any: + """Lazy-create and return the Responses API client.""" + if self._responses_client is None: + self._responses_client = self._create_responses_client(self._model) + return self._responses_client + + async def complete( + self, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]], + *, + model: str, + max_tokens: int = 4096, + temperature: float = 0, + ) -> ModelResponse: + """Non-streaming completion (used for compaction).""" + kwargs: dict[str, Any] = { + "model": model, + "messages": messages, + "max_completion_tokens": max_tokens, + } + if not _is_reasoning_model(model): + kwargs["temperature"] = temperature + if tools: + kwargs["tools"] = tools + kwargs["tool_choice"] = "auto" + + response = await self._completions_client.chat.completions.create(**kwargs) + choice = response.choices[0] + message = choice.message + + tool_calls = [] + if message.tool_calls: + for tc in message.tool_calls: + tool_calls.append( + ToolCall( + id=tc.id, + name=tc.function.name, + arguments=tc.function.arguments, + ) + ) + + usage = None + if response.usage: + usage = Usage( + prompt_tokens=response.usage.prompt_tokens, + completion_tokens=response.usage.completion_tokens, + ) + + return ModelResponse( + content=message.content or "", + tool_calls=tool_calls, + thinking=None, + finish_reason=choice.finish_reason or "", + usage=usage, + ) + + async def stream( + self, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]], + *, + model: str, + max_tokens: int = 4096, + temperature: float = 0, + ) -> AsyncIterator[StreamEvent]: + """Streaming completion yielding StreamEvent objects.""" + if _is_reasoning_model(model): + async for event in self._stream_responses( + messages, tools, model=model, max_tokens=max_tokens + ): + yield event + return + + # --- Chat Completions API (non-reasoning models) --- + async for event in self._stream_completions( + messages, tools, model=model, max_tokens=max_tokens, temperature=temperature + ): + yield event + + async def _stream_completions( + self, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]], + *, + model: str, + max_tokens: int = 4096, + temperature: float = 0, + ) -> AsyncIterator[StreamEvent]: + """Stream via Chat Completions API.""" + kwargs: dict[str, Any] = { + "model": model, + "messages": messages, + "max_completion_tokens": max_tokens, + "temperature": temperature, + "stream": True, + "stream_options": {"include_usage": True}, + } + if tools: + kwargs["tools"] = tools + kwargs["tool_choice"] = "auto" + + stream = await self._completions_client.chat.completions.create(**kwargs) + + pending_tool_calls: dict[int, dict[str, str]] = {} + finish_reason = "" + usage: Usage | None = None + + async for chunk in stream: + if chunk.usage: + usage = Usage( + prompt_tokens=chunk.usage.prompt_tokens, + completion_tokens=chunk.usage.completion_tokens, + ) + if not chunk.choices: + continue + + delta = chunk.choices[0].delta + if chunk.choices[0].finish_reason: + finish_reason = chunk.choices[0].finish_reason + + if delta.content: + yield StreamEvent(type="text_delta", delta=delta.content) + + if delta.tool_calls: + for tc_delta in delta.tool_calls: + idx = tc_delta.index + if idx not in pending_tool_calls: + pending_tool_calls[idx] = { + "id": tc_delta.id or "", + "name": ( + tc_delta.function.name + if tc_delta.function and tc_delta.function.name + else "" + ), + "arguments": "", + } + tc_data = pending_tool_calls[idx] + if tc_delta.id: + tc_data["id"] = tc_delta.id + if tc_delta.function: + if tc_delta.function.name: + tc_data["name"] = tc_delta.function.name + if tc_delta.function.arguments: + tc_data["arguments"] += tc_delta.function.arguments + + for _idx in sorted(pending_tool_calls): + tc_data = pending_tool_calls[_idx] + yield StreamEvent( + type="tool_call", + tool_call=ToolCall( + id=tc_data["id"], + name=tc_data["name"], + arguments=tc_data["arguments"], + ), + ) + + yield StreamEvent(type="done", finish_reason=finish_reason, usage=usage) + + # ------------------------------------------------------------------ + # Responses API streaming (reasoning models) + # ------------------------------------------------------------------ + + @staticmethod + def _convert_messages_to_input( + messages: list[dict[str, Any]], + ) -> list[dict[str, Any]]: + """Convert Chat Completions messages to Responses API input format.""" + result: list[dict[str, Any]] = [] + for msg in messages: + role = msg.get("role") + if role == "tool": + result.append( + { + "type": "function_call_output", + "call_id": msg["tool_call_id"], + "output": msg.get("content", ""), + } + ) + elif role == "assistant" and msg.get("tool_calls"): + if msg.get("content"): + result.append({"role": "assistant", "content": msg["content"]}) + for tc in msg["tool_calls"]: + func = tc.get("function", {}) + result.append( + { + "type": "function_call", + "call_id": tc["id"], + "name": func["name"], + "arguments": func.get("arguments", "{}"), + } + ) + else: + result.append(msg) + return result + + @staticmethod + def _convert_tools_to_responses( + tools: list[dict[str, Any]], + ) -> list[dict[str, Any]]: + """Convert Chat Completions tool schemas to Responses API format.""" + result: list[dict[str, Any]] = [] + for t in tools: + func = t.get("function", {}) + result.append( + { + "type": "function", + "name": func["name"], + "description": func.get("description", ""), + "parameters": func.get("parameters", {}), + } + ) + return result + + async def _stream_responses( + self, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]], + *, + model: str, + max_tokens: int = 4096, + ) -> AsyncIterator[StreamEvent]: + """Stream via Responses API — gives us reasoning summaries.""" + client = self._get_responses_client() + + input_items = self._convert_messages_to_input(messages) + + kwargs: dict[str, Any] = { + "model": model, + "input": input_items, + "max_output_tokens": max_tokens, + "reasoning": {"summary": "auto"}, + "stream": True, + } + if tools: + kwargs["tools"] = self._convert_tools_to_responses(tools) + + stream = await client.responses.create(**kwargs) + + usage: Usage | None = None + has_tool_calls = False + + async for event in stream: + event_type = event.type + + # Text content delta + if event_type == "response.output_text.delta": + yield StreamEvent(type="text_delta", delta=event.delta) + + # Reasoning summary delta + elif event_type == "response.reasoning_summary_text.delta": + yield StreamEvent(type="thinking_delta", delta=event.delta) + + # Function call completed — emit as tool_call + elif event_type == "response.output_item.done": + item = event.item + if item.type == "function_call": + has_tool_calls = True + yield StreamEvent( + type="tool_call", + tool_call=ToolCall( + id=item.call_id, + name=item.name, + arguments=item.arguments, + ), + ) + + # Response completed — extract usage + elif event_type == "response.completed": + resp = event.response + if resp.usage: + usage = Usage( + prompt_tokens=resp.usage.input_tokens, + completion_tokens=resp.usage.output_tokens, + ) + + # Match Chat Completions convention: "tool_calls" when tools were + # invoked, "stop" otherwise. The loop uses this to decide whether + # to execute tools or finish. + finish = "tool_calls" if has_tool_calls else "stop" + yield StreamEvent(type="done", finish_reason=finish, usage=usage) + + +def create_provider(model: str) -> OpenAIProvider: + """Factory to create the default provider for a model.""" + return OpenAIProvider(model) diff --git a/src/uipath/dev/services/agent/service.py b/src/uipath/dev/services/agent/service.py new file mode 100644 index 0000000..0202f74 --- /dev/null +++ b/src/uipath/dev/services/agent/service.py @@ -0,0 +1,137 @@ +"""AgentService — thin facade over AgentLoop (session management + orchestration).""" + +from __future__ import annotations + +import asyncio +import logging +from collections.abc import Callable +from pathlib import Path + +from uipath.dev.services.agent.events import AgentEvent, StatusChanged +from uipath.dev.services.agent.loop import SYSTEM_PROMPT, AgentLoop +from uipath.dev.services.agent.provider import create_provider +from uipath.dev.services.agent.session import AgentSession +from uipath.dev.services.agent.tools import ( + create_default_tools, + create_dispatch_agent_tool, + create_read_reference_tool, +) +from uipath.dev.services.skill_service import SkillService + +logger = logging.getLogger(__name__) + +_PROJECT_ROOT = Path.cwd().resolve() + + +class AgentService: + """Manages agent sessions and runs the agent loop.""" + + def __init__( # noqa: D107 + self, + *, + skill_service: SkillService | None = None, + on_event: Callable[[AgentEvent], None] | None = None, + ) -> None: + self._sessions: dict[str, AgentSession] = {} + self._skill_service = skill_service + self._on_event = on_event + self._pending_approvals: dict[str, asyncio.Event] = {} + self._approval_results: dict[str, bool] = {} + + def _emit(self, event: AgentEvent) -> None: + if self._on_event: + self._on_event(event) + + def _get_or_create_session( + self, session_id: str | None, model: str + ) -> AgentSession: + if session_id and session_id in self._sessions: + session = self._sessions[session_id] + if model: + session.model = model + return session + session = AgentSession(model=model) + self._sessions[session.id] = session + return session + + async def send_message( + self, + session_id: str | None, + text: str, + model: str, + skill_ids: list[str] | None = None, + ) -> None: + """Handle an incoming user message — append and start agent loop.""" + session = self._get_or_create_session(session_id, model) + if skill_ids is not None: + session.skill_ids = skill_ids + + # If already running, ignore + if session.status in ("thinking", "executing", "awaiting_approval"): + return + + session.messages.append({"role": "user", "content": text}) + session.status = "thinking" + session._cancel_event.clear() + + self._emit(StatusChanged(session.id, status="thinking")) + + session._task = asyncio.create_task(self._run_agent_loop(session)) + + def stop_session(self, session_id: str) -> None: + """Cancel a running agent session.""" + session = self._sessions.get(session_id) + if session: + session._cancel_event.set() + if session._task and not session._task.done(): + session._task.cancel() + + def resolve_tool_approval(self, tool_call_id: str, approved: bool) -> None: + """Resolve a pending tool approval request.""" + logger.info( + "resolve_tool_approval: tool_call_id=%s approved=%s pending_keys=%s", + tool_call_id, + approved, + list(self._pending_approvals.keys()), + ) + self._approval_results[tool_call_id] = approved + event = self._pending_approvals.get(tool_call_id) + if event: + logger.info("resolve_tool_approval: signaling event for %s", tool_call_id) + event.set() + else: + logger.info( + "resolve_tool_approval: no pending event for tool_call_id=%s", + tool_call_id, + ) + + async def _run_agent_loop(self, session: AgentSession) -> None: + """Create provider, build tools, and run the loop.""" + provider = create_provider(session.model) + + # Build system prompt (inject skill content for active skills) + system_prompt = SYSTEM_PROMPT + if session.skill_ids and self._skill_service: + for sid in session.skill_ids: + try: + skill_body = self._skill_service.get_skill_content(sid) + system_prompt += f"\n\n## Active Skill: {sid}\n\n{skill_body}" + except FileNotFoundError: + pass + + # Build tools list + tools = create_default_tools(_PROJECT_ROOT) + tools.append(create_dispatch_agent_tool()) + if session.skill_ids and self._skill_service: + tools.append(create_read_reference_tool()) + + loop = AgentLoop( + provider=provider, + tools=tools, + emit=self._emit, + pending_approvals=self._pending_approvals, + approval_results=self._approval_results, + skill_service=self._skill_service, + ) + + await loop.run(session, system_prompt=system_prompt) diff --git a/src/uipath/dev/services/agent/session.py b/src/uipath/dev/services/agent/session.py new file mode 100644 index 0000000..f764376 --- /dev/null +++ b/src/uipath/dev/services/agent/session.py @@ -0,0 +1,28 @@ +"""Agent session with token tracking.""" + +from __future__ import annotations + +import asyncio +import uuid +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class AgentSession: + """In-memory state for one agent conversation.""" + + id: str = field(default_factory=lambda: str(uuid.uuid4())) + model: str = "" + skill_ids: list[str] = field(default_factory=list) + messages: list[dict[str, Any]] = field(default_factory=list) + plan: list[dict[str, str]] = field(default_factory=list) + status: str = "idle" + # Token tracking + total_prompt_tokens: int = 0 + total_completion_tokens: int = 0 + turn_count: int = 0 + compaction_count: int = 0 + # Control + _cancel_event: asyncio.Event = field(default_factory=asyncio.Event) + _task: asyncio.Task[None] | None = field(default=None, repr=False) diff --git a/src/uipath/dev/services/agent/tools.py b/src/uipath/dev/services/agent/tools.py new file mode 100644 index 0000000..777c81a --- /dev/null +++ b/src/uipath/dev/services/agent/tools.py @@ -0,0 +1,478 @@ +"""Tool definitions and implementations for the agent harness.""" + +from __future__ import annotations + +import fnmatch +import os +import re +import signal +import subprocess +import sys +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +MAX_OUTPUT_CHARS = 50_000 +MAX_FILE_CHARS = 100_000 +MAX_GLOB_RESULTS = 200 +MAX_GREP_MATCHES = 100 +BASH_TIMEOUT = 30 +TOOLS_REQUIRING_APPROVAL = {"write_file", "edit_file", "bash"} + +# Matches standard ANSI CSI sequences, OSC sequences, and carriage returns. +_ANSI_RE = re.compile(r"\x1b\][^\x1b]*(?:\x1b\\|\x07)|\x1b\[[0-9;]*[A-Za-z]|\r") + + +# --------------------------------------------------------------------------- +# Tool definition +# --------------------------------------------------------------------------- + + +@dataclass +class ToolDefinition: + """A tool available to the agent.""" + + name: str + description: str + parameters: dict[str, Any] + handler: Callable[[dict[str, Any]], str] + requires_approval: bool = False + + def to_openai_schema(self) -> dict[str, Any]: + """Convert to OpenAI function-calling format.""" + return { + "type": "function", + "function": { + "name": self.name, + "description": self.description, + "parameters": self.parameters, + }, + } + + +# --------------------------------------------------------------------------- +# Path safety +# --------------------------------------------------------------------------- + + +def _resolve_safe(project_root: Path, path_str: str) -> Path: + """Resolve a path and ensure it stays within the project root.""" + p = Path(path_str) + if not p.is_absolute(): + p = project_root / p + resolved = p.resolve() + if not str(resolved).startswith(str(project_root)): + raise PermissionError(f"Path escapes project root: {path_str}") + return resolved + + +# --------------------------------------------------------------------------- +# Tool implementations +# --------------------------------------------------------------------------- + + +def _kill_process_tree(proc: subprocess.Popen[str]) -> None: + """Kill a process and all its children.""" + try: + if sys.platform == "win32": + subprocess.run( + ["taskkill", "/F", "/T", "/PID", str(proc.pid)], + capture_output=True, + ) + else: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except (ProcessLookupError, OSError): + pass + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + + +def _make_read_file(project_root: Path) -> Callable[[dict[str, Any]], str]: + def handler(args: dict[str, Any]) -> str: + path = _resolve_safe(project_root, args["path"]) + if not path.is_file(): + return f"Error: file not found: {args['path']}" + content = path.read_text(encoding="utf-8", errors="replace") + if len(content) > MAX_FILE_CHARS: + content = ( + content[:MAX_FILE_CHARS] + + f"\n... [truncated at {MAX_FILE_CHARS} chars]" + ) + return content + + return handler + + +def _make_write_file(project_root: Path) -> Callable[[dict[str, Any]], str]: + def handler(args: dict[str, Any]) -> str: + path = _resolve_safe(project_root, args["path"]) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(args["content"], encoding="utf-8") + return f"File written: {args['path']} ({len(args['content'])} chars)" + + return handler + + +def _make_edit_file(project_root: Path) -> Callable[[dict[str, Any]], str]: + def handler(args: dict[str, Any]) -> str: + path = _resolve_safe(project_root, args["path"]) + if not path.is_file(): + return f"Error: file not found: {args['path']}" + content = path.read_text(encoding="utf-8") + old_string = args["old_string"] + new_string = args["new_string"] + count = content.count(old_string) + if count == 0: + return "Error: old_string not found in file" + if count > 1: + return f"Error: old_string found {count} times, must be unique" + content = content.replace(old_string, new_string, 1) + path.write_text(content, encoding="utf-8") + return "Edit applied successfully" + + return handler + + +def _make_bash(project_root: Path) -> Callable[[dict[str, Any]], str]: + def handler(args: dict[str, Any]) -> str: + command = args["command"] + stdin_input = args.get("stdin") + try: + env = os.environ.copy() + env["PYTHONUTF8"] = "1" + env["NO_COLOR"] = "1" + env["TERM"] = "dumb" + popen_kwargs: dict[str, Any] = dict( + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + errors="replace", + cwd=str(project_root), + env=env, + ) + if stdin_input is not None: + popen_kwargs["stdin"] = subprocess.PIPE + else: + popen_kwargs["stdin"] = subprocess.DEVNULL + if sys.platform != "win32": + popen_kwargs["start_new_session"] = True + + proc = subprocess.Popen(command, **popen_kwargs) + try: + stdout, stderr = proc.communicate( + input=stdin_input, timeout=BASH_TIMEOUT + ) + except subprocess.TimeoutExpired: + _kill_process_tree(proc) + return f"Error: command timed out after {BASH_TIMEOUT}s" + + output = "" + if stdout: + output += stdout + if stderr: + output += ("\n" if output else "") + stderr + output = _ANSI_RE.sub("", output) + if proc.returncode != 0: + output += f"\n[exit code: {proc.returncode}]" + if not output: + output = "[no output]" + if len(output) > MAX_OUTPUT_CHARS: + output = ( + output[:MAX_OUTPUT_CHARS] + + f"\n... [truncated at {MAX_OUTPUT_CHARS} chars]" + ) + return output + except Exception as e: + return f"Error: {e}" + + return handler + + +def _make_glob(project_root: Path) -> Callable[[dict[str, Any]], str]: + def handler(args: dict[str, Any]) -> str: + pattern = args["pattern"] + base = _resolve_safe(project_root, args.get("path", ".")) + if not base.is_dir(): + return f"Error: directory not found: {args.get('path', '.')}" + matches = sorted(base.glob(pattern)) + matches = [m for m in matches if str(m.resolve()).startswith(str(project_root))] + if len(matches) > MAX_GLOB_RESULTS: + matches = matches[:MAX_GLOB_RESULTS] + truncated = True + else: + truncated = False + rel = [str(m.relative_to(project_root)) for m in matches] + result = "\n".join(rel) if rel else "No matches found" + if truncated: + result += f"\n... [truncated at {MAX_GLOB_RESULTS} results]" + return result + + return handler + + +def _make_grep(project_root: Path) -> Callable[[dict[str, Any]], str]: + def handler(args: dict[str, Any]) -> str: + pattern_str = args["pattern"] + base = _resolve_safe(project_root, args.get("path", ".")) + include = args.get("include", None) + try: + regex = re.compile(pattern_str) + except re.error as e: + return f"Error: invalid regex: {e}" + + matches: list[str] = [] + files_to_search: list[Path] = [] + + if base.is_file(): + files_to_search = [base] + elif base.is_dir(): + for root, _dirs, filenames in os.walk(base): + root_path = Path(root) + parts = root_path.relative_to(base).parts + if any( + p.startswith(".") or p in ("node_modules", "__pycache__", ".venv") + for p in parts + ): + continue + for fname in filenames: + if include and not fnmatch.fnmatch(fname, include): + continue + files_to_search.append(root_path / fname) + else: + return f"Error: path not found: {args.get('path', '.')}" + + for fpath in files_to_search: + if len(matches) >= MAX_GREP_MATCHES: + break + try: + text = fpath.read_text(encoding="utf-8", errors="replace") + except Exception: + continue + for i, line in enumerate(text.splitlines(), 1): + if regex.search(line): + rel = str(fpath.relative_to(project_root)) + matches.append(f"{rel}:{i}: {line.rstrip()}") + if len(matches) >= MAX_GREP_MATCHES: + break + + result = "\n".join(matches) if matches else "No matches found" + if len(matches) >= MAX_GREP_MATCHES: + result += f"\n... [truncated at {MAX_GREP_MATCHES} matches]" + return result + + return handler + + +# --------------------------------------------------------------------------- +# Tool schemas (parameter definitions) +# --------------------------------------------------------------------------- + +_READ_FILE_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "path": {"type": "string", "description": "Relative or absolute file path."} + }, + "required": ["path"], +} + +_WRITE_FILE_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "path": {"type": "string", "description": "Relative or absolute file path."}, + "content": {"type": "string", "description": "The full file content to write."}, + }, + "required": ["path", "content"], +} + +_EDIT_FILE_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "path": {"type": "string", "description": "Relative or absolute file path."}, + "old_string": { + "type": "string", + "description": "The exact string to find and replace.", + }, + "new_string": {"type": "string", "description": "The replacement string."}, + }, + "required": ["path", "old_string", "new_string"], +} + +_BASH_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "command": {"type": "string", "description": "The shell command to execute."}, + "stdin": { + "type": "string", + "description": "Optional input to feed to the command's stdin.", + }, + }, + "required": ["command"], +} + +_GLOB_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern, e.g. '**/*.py' or 'src/**/*.ts'.", + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to project root.", + }, + }, + "required": ["pattern"], +} + +_GREP_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regex pattern to search for.", + }, + "path": { + "type": "string", + "description": "File or directory to search in. Defaults to project root.", + }, + "include": { + "type": "string", + "description": "Glob filter for files, e.g. '*.py'.", + }, + }, + "required": ["pattern"], +} + +_UPDATE_PLAN_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "plan": { + "type": "array", + "description": "The full plan with updated statuses. Always send the complete plan, not just changed items.", + "items": { + "type": "object", + "properties": { + "title": {"type": "string", "description": "Step title"}, + "status": { + "type": "string", + "enum": ["pending", "in_progress", "completed"], + "description": "Step status", + }, + }, + "required": ["title", "status"], + }, + } + }, + "required": ["plan"], +} + +_READ_REFERENCE_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Relative path within the references/ directory.", + } + }, + "required": ["path"], +} + +_DISPATCH_AGENT_PARAMS: dict[str, Any] = { + "type": "object", + "properties": { + "task": { + "type": "string", + "description": "Description of the subtask for the sub-agent.", + } + }, + "required": ["task"], +} + + +# --------------------------------------------------------------------------- +# Factory +# --------------------------------------------------------------------------- + + +def create_default_tools(project_root: Path) -> list[ToolDefinition]: + """Factory that returns all built-in tools.""" + return [ + ToolDefinition( + name="read_file", + description="Read the contents of a file at the given path.", + parameters=_READ_FILE_PARAMS, + handler=_make_read_file(project_root), + ), + ToolDefinition( + name="write_file", + description="Create or overwrite a file with the given content.", + parameters=_WRITE_FILE_PARAMS, + handler=_make_write_file(project_root), + requires_approval=True, + ), + ToolDefinition( + name="edit_file", + description="Replace an exact string in a file with a new string. The old_string must appear exactly once.", + parameters=_EDIT_FILE_PARAMS, + handler=_make_edit_file(project_root), + requires_approval=True, + ), + ToolDefinition( + name="bash", + description=( + "Execute a shell command and return stdout/stderr. Timeout: 30s. " + "For commands that prompt for input, provide the expected input via the stdin parameter." + ), + parameters=_BASH_PARAMS, + handler=_make_bash(project_root), + requires_approval=True, + ), + ToolDefinition( + name="glob", + description="Find files matching a glob pattern. Returns up to 200 results.", + parameters=_GLOB_PARAMS, + handler=_make_glob(project_root), + ), + ToolDefinition( + name="grep", + description="Search file contents with a regex pattern. Returns up to 100 matches.", + parameters=_GREP_PARAMS, + handler=_make_grep(project_root), + ), + ToolDefinition( + name="update_plan", + description="Update the task plan. Call this first to outline steps, then update as you complete them.", + parameters=_UPDATE_PLAN_PARAMS, + handler=lambda args: "", # Handled specially in the loop + ), + ] + + +def create_read_reference_tool() -> ToolDefinition: + """Create the read_reference tool (added when skills are active).""" + return ToolDefinition( + name="read_reference", + description="Read a reference document from the skill's references directory.", + parameters=_READ_REFERENCE_PARAMS, + handler=lambda args: "", # Handled specially in the loop + ) + + +def create_dispatch_agent_tool() -> ToolDefinition: + """Create the dispatch_agent tool for sub-agent spawning.""" + return ToolDefinition( + name="dispatch_agent", + description=( + "Spawn a sub-agent to handle a complex subtask in its own context. " + "The sub-agent has access to read_file, glob, grep, and bash (read-only). " + "Use this for research tasks, large file analysis, or multi-file searches " + "that would fill up the main context." + ), + parameters=_DISPATCH_AGENT_PARAMS, + handler=lambda args: "", # Handled specially in the loop + ) diff --git a/src/uipath/dev/services/agent_service.py b/src/uipath/dev/services/agent_service.py deleted file mode 100644 index 7e44c04..0000000 --- a/src/uipath/dev/services/agent_service.py +++ /dev/null @@ -1,872 +0,0 @@ -"""Coding agent service — native agent loop with UiPath OpenAI client + tools.""" - -from __future__ import annotations - -import asyncio -import fnmatch -import json -import logging -import os -import re -import signal -import subprocess -import sys -import uuid -from collections.abc import Callable -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from uipath.dev.services.skill_service import SkillService - -logger = logging.getLogger(__name__) - -MAX_ITERATIONS = 50 -MAX_OUTPUT_CHARS = 50_000 -MAX_FILE_CHARS = 100_000 -MAX_GLOB_RESULTS = 200 -MAX_GREP_MATCHES = 100 -BASH_TIMEOUT = 30 -TOOLS_REQUIRING_APPROVAL = {"write_file", "edit_file", "bash"} - -# Matches standard ANSI CSI sequences, OSC sequences (e.g. hyperlinks), and -# carriage returns used by spinners to overwrite lines. -_ANSI_RE = re.compile(r"\x1b\][^\x1b]*(?:\x1b\\|\x07)|\x1b\[[0-9;]*[A-Za-z]|\r") - -# --------------------------------------------------------------------------- -# System prompt -# --------------------------------------------------------------------------- - -SYSTEM_PROMPT = """\ -You are a senior Python developer specializing in UiPath coded agents and automations. \ -You help users build, debug, test, and improve Python agents using the UiPath SDK. - -## Critical Rules - -### You Have a Shell — USE IT -- You have direct access to the user's terminal via the `bash` tool. -- NEVER tell the user to run commands themselves. ALWAYS use `bash` to execute commands directly. -- This includes: `uv run`, `uv sync`, `uipath init`, `uipath run`, `uipath eval`, `uipath pack`, `uipath publish`, and any other CLI commands. -- If something needs to be run, run it. Don't explain how to run it. -- The user is already authenticated — NEVER ask them to authenticate or run `uipath auth`. - -### Read Before Writing -- NEVER suggest code changes without first reading the relevant source files. -- NEVER assume what code looks like — use `read_file`, `glob`, and `grep` to verify. -- When asked about a function or class, read its implementation first. Do not guess signatures, return types, or behavior. -- Before editing a file, always read it to understand context, imports, and conventions. - -### Evidence-Based Responses -- Ground every suggestion in actual code you have read in the current session. -- When explaining behavior, quote or reference specific lines from the codebase. -- If you're unsure about something, search the code rather than speculating. -- If you cannot find what you need, say so explicitly instead of making assumptions. - -### Surgical, Minimal Changes -- Make the smallest change that solves the problem. Don't refactor adjacent code. -- Match the existing code style — indentation, naming conventions, import patterns. -- Only add imports, variables, or functions that your change requires. -- Don't add error handling, type hints, or docstrings beyond what was asked. - -## Workflow - -1. **Plan first**: Call `update_plan` with your steps before doing anything else. -2. **Explore**: Use `glob` and `grep` to find relevant files. Read them with `read_file`. -3. **Implement**: Use `edit_file` for targeted changes, `write_file` only for new files. -4. **Execute**: Use `bash` to run commands — installations, tests, linters, builds, `uv run` commands, etc. \ -When the user asks you to run something, always use the `bash` tool to execute it. Never tell the user to run commands themselves — you have a shell, use it. -5. **Verify**: Read back edited files to confirm correctness. Run tests or linters via `bash`. -6. **Update progress**: Mark plan steps as "completed" as you go, add new steps if scope expands. -7. **Summarize**: When done, briefly state what you changed and why. - -## Full Build Cycle - -When building or modifying an agent or function, always complete the full cycle — don't stop at writing code: - -1. **Write the code** — implement the agent/function with Input/Output models and `@traced()` main function. -2. **Generate entry points** — run `uv run uipath init` via `bash`. -3. **Write evaluations** — create BOTH: - - **Evaluator files** in `evaluations/evaluators/` (e.g. `exact-match.json`, `json-similarity.json`) — these must exist first. - - **Eval set files** in `evaluations/eval-sets/` with test cases that reference the evaluator IDs. -4. **Run the evaluations** — execute `uv run uipath eval` via `bash` and report results. -5. **Pack & publish** — when the user asks to deploy, run via `bash`: - - `uv run uipath pack` — create a .nupkg package - - `uv run uipath publish -w` — publish to personal workspace (default) - - `uv run uipath publish -t` — publish to a specific tenant folder - -Never stop after just writing code. If you create an agent/function, you must also create evaluations and run them. \ -If you create eval sets, you must also create the evaluator files they reference — otherwise the eval run will fail. \ -If the user asks you to publish or deploy, use `bash` to run the commands — don't tell them to do it. \ -Default to publishing to personal workspace (`-w`) unless the user specifies a tenant folder. - -## Tools -- `read_file` — Read file contents (always use before editing) -- `write_file` — Create or overwrite a file -- `edit_file` — Surgical string replacement (old_string must be unique) -- `bash` — Execute a shell command (timeout: 30s). USE THIS to run commands for the user — never tell the user to run commands manually when you can run them yourself. -- `glob` — Find files matching a pattern (e.g. `**/*.py`) -- `grep` — Search file contents with regex -- `update_plan` — Create or update your task plan -- `read_reference` — Read a reference doc from the active skill (when skills are active) -""" - -# --------------------------------------------------------------------------- -# Tool definitions (OpenAI function-calling format) -# --------------------------------------------------------------------------- - -TOOLS: list[dict[str, Any]] = [ - { - "type": "function", - "function": { - "name": "read_file", - "description": "Read the contents of a file at the given path.", - "parameters": { - "type": "object", - "properties": { - "path": { - "type": "string", - "description": "Relative or absolute file path.", - } - }, - "required": ["path"], - }, - }, - }, - { - "type": "function", - "function": { - "name": "write_file", - "description": "Create or overwrite a file with the given content.", - "parameters": { - "type": "object", - "properties": { - "path": { - "type": "string", - "description": "Relative or absolute file path.", - }, - "content": { - "type": "string", - "description": "The full file content to write.", - }, - }, - "required": ["path", "content"], - }, - }, - }, - { - "type": "function", - "function": { - "name": "edit_file", - "description": "Replace an exact string in a file with a new string. The old_string must appear exactly once.", - "parameters": { - "type": "object", - "properties": { - "path": { - "type": "string", - "description": "Relative or absolute file path.", - }, - "old_string": { - "type": "string", - "description": "The exact string to find and replace.", - }, - "new_string": { - "type": "string", - "description": "The replacement string.", - }, - }, - "required": ["path", "old_string", "new_string"], - }, - }, - }, - { - "type": "function", - "function": { - "name": "bash", - "description": "Execute a shell command and return stdout/stderr. Timeout: 30s. " - "For commands that prompt for input, provide the expected input via the stdin parameter.", - "parameters": { - "type": "object", - "properties": { - "command": { - "type": "string", - "description": "The shell command to execute.", - }, - "stdin": { - "type": "string", - "description": "Optional input to feed to the command's stdin. Use this for commands that prompt for input (e.g. confirmations, selections). Use newlines to separate multiple inputs.", - }, - }, - "required": ["command"], - }, - }, - }, - { - "type": "function", - "function": { - "name": "glob", - "description": "Find files matching a glob pattern. Returns up to 200 results.", - "parameters": { - "type": "object", - "properties": { - "pattern": { - "type": "string", - "description": "Glob pattern, e.g. '**/*.py' or 'src/**/*.ts'.", - }, - "path": { - "type": "string", - "description": "Directory to search in. Defaults to project root.", - }, - }, - "required": ["pattern"], - }, - }, - }, - { - "type": "function", - "function": { - "name": "grep", - "description": "Search file contents with a regex pattern. Returns up to 100 matches.", - "parameters": { - "type": "object", - "properties": { - "pattern": { - "type": "string", - "description": "Regex pattern to search for.", - }, - "path": { - "type": "string", - "description": "File or directory to search in. Defaults to project root.", - }, - "include": { - "type": "string", - "description": "Glob filter for files, e.g. '*.py'.", - }, - }, - "required": ["pattern"], - }, - }, - }, - { - "type": "function", - "function": { - "name": "update_plan", - "description": "Update the task plan. Call this first to outline steps, then update as you complete them.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": 'JSON array of plan items: [{"title": "...", "status": "pending|in_progress|completed"}]', - } - }, - "required": ["plan"], - }, - }, - }, -] - -READ_REFERENCE_TOOL: dict[str, Any] = { - "type": "function", - "function": { - "name": "read_reference", - "description": "Read a reference document from the skill's references directory.", - "parameters": { - "type": "object", - "properties": { - "path": { - "type": "string", - "description": "Relative path within the references/ directory, e.g. 'authentication.md' or 'evaluations/best-practices.md'.", - }, - }, - "required": ["path"], - }, - }, -} - - -# --------------------------------------------------------------------------- -# Session -# --------------------------------------------------------------------------- - - -@dataclass -class AgentSession: - """In-memory state for one agent conversation.""" - - id: str = field(default_factory=lambda: str(uuid.uuid4())) - model: str = "" - skill_ids: list[str] = field(default_factory=list) - messages: list[dict[str, Any]] = field(default_factory=list) - plan: list[dict[str, str]] = field(default_factory=list) - status: str = "idle" - _cancel_event: asyncio.Event = field(default_factory=asyncio.Event) - _task: asyncio.Task[None] | None = field(default=None, repr=False) - - -# --------------------------------------------------------------------------- -# Path safety -# --------------------------------------------------------------------------- - -_PROJECT_ROOT = Path.cwd().resolve() - - -def _resolve_safe(path_str: str) -> Path: - """Resolve a path and ensure it stays within the project root.""" - p = Path(path_str) - if not p.is_absolute(): - p = _PROJECT_ROOT / p - resolved = p.resolve() - if not str(resolved).startswith(str(_PROJECT_ROOT)): - raise PermissionError(f"Path escapes project root: {path_str}") - return resolved - - -# --------------------------------------------------------------------------- -# Tool implementations -# --------------------------------------------------------------------------- - - -def _tool_read_file(args: dict[str, Any]) -> str: - path = _resolve_safe(args["path"]) - if not path.is_file(): - return f"Error: file not found: {args['path']}" - content = path.read_text(encoding="utf-8", errors="replace") - if len(content) > MAX_FILE_CHARS: - content = ( - content[:MAX_FILE_CHARS] + f"\n... [truncated at {MAX_FILE_CHARS} chars]" - ) - return content - - -def _tool_write_file(args: dict[str, Any]) -> str: - path = _resolve_safe(args["path"]) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(args["content"], encoding="utf-8") - return f"File written: {args['path']} ({len(args['content'])} chars)" - - -def _tool_edit_file(args: dict[str, Any]) -> str: - path = _resolve_safe(args["path"]) - if not path.is_file(): - return f"Error: file not found: {args['path']}" - content = path.read_text(encoding="utf-8") - old_string = args["old_string"] - new_string = args["new_string"] - count = content.count(old_string) - if count == 0: - return "Error: old_string not found in file" - if count > 1: - return f"Error: old_string found {count} times, must be unique" - content = content.replace(old_string, new_string, 1) - path.write_text(content, encoding="utf-8") - return "Edit applied successfully" - - -def _kill_process_tree(proc: subprocess.Popen[str]) -> None: - """Kill a process and all its children.""" - try: - if sys.platform == "win32": - # taskkill /T kills the entire process tree on Windows - subprocess.run( - ["taskkill", "/F", "/T", "/PID", str(proc.pid)], - capture_output=True, - ) - else: - os.killpg(os.getpgid(proc.pid), signal.SIGKILL) - except (ProcessLookupError, OSError): - pass - try: - proc.wait(timeout=5) - except subprocess.TimeoutExpired: - proc.kill() - - -def _tool_bash(args: dict[str, Any]) -> str: - command = args["command"] - stdin_input = args.get("stdin") - try: - env = os.environ.copy() - env["PYTHONUTF8"] = "1" - env["NO_COLOR"] = "1" - env["TERM"] = "dumb" - popen_kwargs: dict[str, Any] = dict( - shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - encoding="utf-8", - errors="replace", - cwd=str(_PROJECT_ROOT), - env=env, - ) - # DEVNULL prevents hanging on interactive prompts when no input given. - # PIPE is used only when the agent explicitly provides stdin input. - if stdin_input is not None: - popen_kwargs["stdin"] = subprocess.PIPE - else: - popen_kwargs["stdin"] = subprocess.DEVNULL - # On Unix, create a new process group so we can kill the whole tree. - if sys.platform != "win32": - popen_kwargs["start_new_session"] = True - - proc = subprocess.Popen(command, **popen_kwargs) - try: - stdout, stderr = proc.communicate(input=stdin_input, timeout=BASH_TIMEOUT) - except subprocess.TimeoutExpired: - _kill_process_tree(proc) - return f"Error: command timed out after {BASH_TIMEOUT}s" - - output = "" - if stdout: - output += stdout - if stderr: - output += ("\n" if output else "") + stderr - # Strip ANSI escape sequences and spinner artifacts - output = _ANSI_RE.sub("", output) - if proc.returncode != 0: - output += f"\n[exit code: {proc.returncode}]" - if not output: - output = "[no output]" - if len(output) > MAX_OUTPUT_CHARS: - output = ( - output[:MAX_OUTPUT_CHARS] - + f"\n... [truncated at {MAX_OUTPUT_CHARS} chars]" - ) - return output - except Exception as e: - return f"Error: {e}" - - -def _tool_glob(args: dict[str, Any]) -> str: - pattern = args["pattern"] - base = _resolve_safe(args.get("path", ".")) - if not base.is_dir(): - return f"Error: directory not found: {args.get('path', '.')}" - matches = sorted(base.glob(pattern)) - # Filter to project root - matches = [m for m in matches if str(m.resolve()).startswith(str(_PROJECT_ROOT))] - if len(matches) > MAX_GLOB_RESULTS: - matches = matches[:MAX_GLOB_RESULTS] - truncated = True - else: - truncated = False - rel = [str(m.relative_to(_PROJECT_ROOT)) for m in matches] - result = "\n".join(rel) if rel else "No matches found" - if truncated: - result += f"\n... [truncated at {MAX_GLOB_RESULTS} results]" - return result - - -def _tool_grep(args: dict[str, Any]) -> str: - pattern_str = args["pattern"] - base = _resolve_safe(args.get("path", ".")) - include = args.get("include", None) - try: - regex = re.compile(pattern_str) - except re.error as e: - return f"Error: invalid regex: {e}" - - matches: list[str] = [] - files_to_search: list[Path] = [] - - if base.is_file(): - files_to_search = [base] - elif base.is_dir(): - for root, _dirs, filenames in os.walk(base): - # Skip hidden dirs and common non-code dirs - root_path = Path(root) - parts = root_path.relative_to(base).parts - if any( - p.startswith(".") or p in ("node_modules", "__pycache__", ".venv") - for p in parts - ): - continue - for fname in filenames: - if include and not fnmatch.fnmatch(fname, include): - continue - files_to_search.append(root_path / fname) - else: - return f"Error: path not found: {args.get('path', '.')}" - - for fpath in files_to_search: - if len(matches) >= MAX_GREP_MATCHES: - break - try: - text = fpath.read_text(encoding="utf-8", errors="replace") - except Exception: - continue - for i, line in enumerate(text.splitlines(), 1): - if regex.search(line): - rel = str(fpath.relative_to(_PROJECT_ROOT)) - matches.append(f"{rel}:{i}: {line.rstrip()}") - if len(matches) >= MAX_GREP_MATCHES: - break - - result = "\n".join(matches) if matches else "No matches found" - if len(matches) >= MAX_GREP_MATCHES: - result += f"\n... [truncated at {MAX_GREP_MATCHES} matches]" - return result - - -TOOL_HANDLERS: dict[str, Callable[[dict[str, Any]], str]] = { - "read_file": _tool_read_file, - "write_file": _tool_write_file, - "edit_file": _tool_edit_file, - "bash": _tool_bash, - "glob": _tool_glob, - "grep": _tool_grep, -} - - -# --------------------------------------------------------------------------- -# Agent service -# --------------------------------------------------------------------------- - - -class AgentService: - """Manages agent sessions and runs the agent loop.""" - - def __init__( - self, - *, - skill_service: SkillService | None = None, - on_status: Callable[[str, str], None] | None = None, - on_text: Callable[[str, str, bool], None] | None = None, - on_plan: Callable[[str, list[dict[str, str]]], None] | None = None, - on_tool_use: Callable[[str, str, dict[str, Any]], None] | None = None, - on_tool_result: Callable[[str, str, str, bool], None] | None = None, - on_tool_approval: Callable[[str, str, str, dict[str, Any]], None] | None = None, - on_error: Callable[[str, str], None] | None = None, - ) -> None: - """Initialize the agent service with event callbacks.""" - self._sessions: dict[str, AgentSession] = {} - self._skill_service = skill_service - self._on_status = on_status - self._on_text = on_text - self._on_plan = on_plan - self._on_tool_use = on_tool_use - self._on_tool_result = on_tool_result - self._on_tool_approval = on_tool_approval - self._on_error = on_error - self._pending_approvals: dict[str, asyncio.Event] = {} - self._approval_results: dict[str, bool] = {} - - def _get_or_create_session( - self, session_id: str | None, model: str - ) -> AgentSession: - if session_id and session_id in self._sessions: - session = self._sessions[session_id] - if model: - session.model = model - return session - session = AgentSession(model=model) - self._sessions[session.id] = session - return session - - async def send_message( - self, - session_id: str | None, - text: str, - model: str, - skill_ids: list[str] | None = None, - ) -> None: - """Handle an incoming user message — append and start agent loop.""" - session = self._get_or_create_session(session_id, model) - if skill_ids is not None: - session.skill_ids = skill_ids - - # If already running, ignore - if session.status == "thinking": - return - - session.messages.append({"role": "user", "content": text}) - session.status = "thinking" - session._cancel_event.clear() - - if self._on_status: - self._on_status(session.id, "thinking") - - session._task = asyncio.create_task(self._run_agent_loop(session)) - - def stop_session(self, session_id: str) -> None: - """Cancel a running agent session.""" - session = self._sessions.get(session_id) - if session: - session._cancel_event.set() - if session._task and not session._task.done(): - session._task.cancel() - - def resolve_tool_approval(self, tool_call_id: str, approved: bool) -> None: - """Resolve a pending tool approval request.""" - self._approval_results[tool_call_id] = approved - event = self._pending_approvals.get(tool_call_id) - if event: - event.set() - - async def _run_agent_loop(self, session: AgentSession) -> None: - """Core agent loop: call LLM, handle tool calls, repeat.""" - try: - client = self._create_client(session.model) - - # Build system prompt (inject skill content for active skills) - system_prompt = SYSTEM_PROMPT - if session.skill_ids and self._skill_service: - for sid in session.skill_ids: - try: - skill_body = self._skill_service.get_skill_content(sid) - system_prompt += f"\n\n## Active Skill: {sid}\n\n{skill_body}" - except FileNotFoundError: - pass - - # Build tools list (add read_reference when any skill is active) - tools = list(TOOLS) - if session.skill_ids and self._skill_service: - tools.append(READ_REFERENCE_TOOL) - - for _ in range(MAX_ITERATIONS): - if session._cancel_event.is_set(): - session.status = "done" - if self._on_status: - self._on_status(session.id, "done") - return - - # Build messages for LLM - llm_messages = [ - {"role": "system", "content": system_prompt}, - *session.messages, - ] - - response = await client.chat.completions.create( - model=session.model, - messages=llm_messages, - tools=tools, - tool_choice="auto", - max_completion_tokens=4096, - temperature=0, - ) - - choice = response.choices[0] - message = choice.message - finish_reason = choice.finish_reason - - # Build assistant message dict for conversation history - assistant_msg: dict[str, Any] = { - "role": "assistant", - "content": message.content or "", - } - if message.tool_calls: - assistant_msg["tool_calls"] = [ - { - "id": tc.id, - "type": "function", - "function": { - "name": tc.function.name, - "arguments": tc.function.arguments, - }, - } - for tc in message.tool_calls - ] - session.messages.append(assistant_msg) - - # If the model returned text with no tool calls, we're done - if finish_reason == "stop" or not message.tool_calls: - content = message.content or "" - if self._on_text: - self._on_text(session.id, content, True) - session.status = "done" - if self._on_status: - self._on_status(session.id, "done") - return - - # Execute tool calls - for tc in message.tool_calls: - if session._cancel_event.is_set(): - session.status = "done" - if self._on_status: - self._on_status(session.id, "done") - return - - tool_name = tc.function.name - try: - tool_args = json.loads(tc.function.arguments) - except json.JSONDecodeError: - tool_args = {} - - # Handle update_plan specially - if tool_name == "update_plan": - result = self._handle_update_plan(session, tool_args) - is_error = False - elif tool_name == "read_reference": - result, is_error = self._handle_read_reference( - session, tool_args - ) - if self._on_tool_use: - self._on_tool_use(session.id, tool_name, tool_args) - if self._on_tool_result: - self._on_tool_result( - session.id, tool_name, result, is_error - ) - else: - if self._on_status: - self._on_status(session.id, "executing") - if self._on_tool_use: - self._on_tool_use(session.id, tool_name, tool_args) - - # Approval gate for destructive tools - if tool_name in TOOLS_REQUIRING_APPROVAL: - approval_event = asyncio.Event() - self._pending_approvals[tc.id] = approval_event - if self._on_tool_approval: - self._on_tool_approval( - session.id, tc.id, tool_name, tool_args - ) - if self._on_status: - self._on_status(session.id, "awaiting_approval") - await approval_event.wait() - approved = self._approval_results.pop(tc.id, False) - self._pending_approvals.pop(tc.id, None) - - if session._cancel_event.is_set(): - session.status = "done" - if self._on_status: - self._on_status(session.id, "done") - return - - if not approved: - result = "Tool execution denied by user" - is_error = True - if self._on_status: - self._on_status(session.id, "executing") - if self._on_tool_result: - self._on_tool_result( - session.id, tool_name, result, is_error - ) - session.messages.append( - { - "role": "tool", - "tool_call_id": tc.id, - "content": result, - } - ) - continue - - if self._on_status: - self._on_status(session.id, "executing") - - handler = TOOL_HANDLERS.get(tool_name) - if handler: - try: - result = await asyncio.get_event_loop().run_in_executor( - None, handler, tool_args - ) - is_error = result.startswith("Error:") - except Exception as e: - result = f"Error: {e}" - is_error = True - else: - result = f"Error: unknown tool '{tool_name}'" - is_error = True - - if self._on_tool_result: - self._on_tool_result( - session.id, tool_name, result, is_error - ) - - # Append tool result to messages - session.messages.append( - { - "role": "tool", - "tool_call_id": tc.id, - "content": result, - } - ) - - # After tools, set status back to thinking - if self._on_status: - self._on_status(session.id, "thinking") - - # Max iterations reached - if self._on_text: - self._on_text( - session.id, - "Reached maximum iterations. Stopping.", - True, - ) - session.status = "done" - if self._on_status: - self._on_status(session.id, "done") - - except asyncio.CancelledError: - session.status = "done" - if self._on_status: - self._on_status(session.id, "done") - except Exception as e: - logger.exception("Agent loop error for session %s", session.id) - session.status = "error" - if self._on_error: - self._on_error(session.id, str(e)) - - def _handle_update_plan(self, session: AgentSession, args: dict[str, Any]) -> str: - raw = args.get("plan", "[]") - if isinstance(raw, list): - items = raw - else: - try: - items = json.loads(raw) - if not isinstance(items, list): - return "Error: plan must be a JSON array" - except (json.JSONDecodeError, TypeError) as e: - return f"Error: invalid JSON: {e}" - - session.plan = items - if self._on_plan: - self._on_plan(session.id, items) - return "Plan updated" - - def _handle_read_reference( - self, session: AgentSession, args: dict[str, Any] - ) -> tuple[str, bool]: - """Read a reference file using the base from active skills.""" - ref_path = args.get("path", "") - if not ref_path or not self._skill_service or not session.skill_ids: - return "Error: no active skills or missing path", True - # Derive base from first active skill (e.g. "uipath/authentication" -> "uipath") - base_skill_id = session.skill_ids[0] - try: - content = self._skill_service.get_reference(base_skill_id, ref_path) - if len(content) > MAX_FILE_CHARS: - content = ( - content[:MAX_FILE_CHARS] - + f"\n... [truncated at {MAX_FILE_CHARS} chars]" - ) - return content, False - except (FileNotFoundError, PermissionError) as e: - return f"Error: {e}", True - - @staticmethod - def _create_client(model_name: str) -> Any: - """Create an AsyncOpenAI client pointed at UiPath's passthrough endpoint.""" - from openai import AsyncOpenAI - - base_url = os.environ.get("UIPATH_URL", "") - access_token = os.environ.get("UIPATH_ACCESS_TOKEN", "") - if not base_url or not access_token: - raise RuntimeError( - "Not authenticated — UIPATH_URL or UIPATH_ACCESS_TOKEN not set" - ) - - # Passthrough endpoint: {base}/agenthub_/llm/openai/deployments/{model} - # OpenAI client appends /chat/completions automatically - gateway_base = ( - f"{base_url.rstrip('/')}/agenthub_/llm/openai/deployments/{model_name}" - ) - - return AsyncOpenAI( - api_key=access_token, - base_url=gateway_base, - default_query={"api-version": "2025-03-01-preview"}, - default_headers={ - "X-UiPath-LlmGateway-RequestingProduct": "AgentsPlayground", - "X-UiPath-LlmGateway-RequestingFeature": "uipath-dev", - }, - ) diff --git a/uv.lock b/uv.lock index a17c525..8a6b4d5 100644 --- a/uv.lock +++ b/uv.lock @@ -2266,7 +2266,7 @@ wheels = [ [[package]] name = "uipath-dev" -version = "0.0.63" +version = "0.0.64" source = { editable = "." } dependencies = [ { name = "fastapi" },