@erdoai/ui 0.1.73 → 0.1.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -48,4 +48,4 @@ $bm_rt = comp('system-solid-56-warning').layer('control').effect('primary')('Col
48
48
  color: transparent;
49
49
  }
50
50
  `,document.head.appendChild(t);}function He({item:t,className:e}){let[n,o]=gt.useState(false);gt.useEffect(()=>{Ya();},[]);let r=t.content_type==="redacted_thinking",s="",a=false;if(typeof t.content=="string")s=t.content;else if(t.content&&typeof t.content=="object")if(r)s=t.content.data||"Some of Claude's internal reasoning has been automatically encrypted for safety reasons. This doesn't affect the quality of responses.";else {let p=t.content;s=p.thinking||"",a=typeof p.signature=="string"&&p.signature.length>0;}let i=typeof t.state=="string"?t.state:"",l=(i==="in_progress"||i==="streaming"||i==="running")&&!a;return jsxRuntime.jsxs("div",{className:e,children:[jsxRuntime.jsxs("button",{onClick:()=>o(!n),className:"inline-flex items-center gap-1.5 text-left",children:[n?jsxRuntime.jsx(lucideReact.ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground/70"}):jsxRuntime.jsx(lucideReact.ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground/70"}),jsxRuntime.jsx("span",{className:`text-sm ${l?"erdo-thinking-shimmer":"text-muted-foreground"}`,children:r?"Encrypted thinking":"Thinking"})]}),n&&jsxRuntime.jsx("div",{className:"mt-1 pl-5 text-sm text-muted-foreground whitespace-pre-wrap",children:s||(l?"Thinking...":"")})]})}function Xa(t){try{return JSON.parse(t)}catch{return t}}function ti(t){if(!t)return "";try{return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return ""}}function Xn({log:t}){let e=typeof t.message=="string"?Xa(t.message):t.message,n=ti(t.timestamp),o="text-xs font-mono py-0.5 px-1.5 rounded flex items-start",r="";switch(t.level){case "error":o+=" bg-red-50/50 dark:bg-red-950/30 text-red-600 dark:text-red-400 border-l-2 border-red-400 dark:border-red-600",r="text-red-500 dark:text-red-400";break;case "requires_info":o+=" bg-yellow-50/50 dark:bg-yellow-950/30 text-yellow-600 dark:text-yellow-400 border-l-2 border-yellow-400 dark:border-yellow-600",r="text-yellow-500 dark:text-yellow-400";break;default:o+=" bg-blue-50/40 dark:bg-blue-900/20 text-blue-500/90 dark:text-blue-300/80 border-l-2 border-blue-300 dark:border-blue-600/50",r="text-blue-400 dark:text-blue-400/70";}return jsxRuntime.jsx("div",{className:"my-0.5",children:jsxRuntime.jsx("div",{className:o,children:jsxRuntime.jsxs("div",{className:"flex items-start gap-2",children:[n&&jsxRuntime.jsx("span",{className:"text-[10px] opacity-60 whitespace-nowrap w-16 flex-shrink-0 pt-0.5",children:n}),t.level==="error"&&jsxRuntime.jsx("span",{className:"inline-block mr-1 flex-shrink-0",children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`h-3 w-3 ${r}`,viewBox:"0 0 20 20",fill:"currentColor",children:jsxRuntime.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM8.28 7.22a.75.75 0 00-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 101.06 1.06L10 11.06l1.72 1.72a.75.75 0 101.06-1.06L11.06 10l1.72-1.72a.75.75 0 00-1.06-1.06L10 8.94 8.28 7.22z",clipRule:"evenodd"})})}),t.level==="requires_info"&&jsxRuntime.jsx("span",{className:"inline-block mr-1 flex-shrink-0",children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`h-3 w-3 ${r}`,viewBox:"0 0 20 20",fill:"currentColor",children:jsxRuntime.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})})}),t.level==="info"&&jsxRuntime.jsx("span",{className:"inline-block mr-1 flex-shrink-0",children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`h-3 w-3 ${r}`,viewBox:"0 0 20 20",fill:"currentColor",children:jsxRuntime.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})})}),jsxRuntime.jsx("div",{className:"flex-1 break-words whitespace-pre-wrap",children:String(e)})]})})})}function Ke({item:t,className:e}){let n=typeof t.content=="object"&&t.content!==null?t.content:{message:String(t.content)},o={level:n.level||"info",message:n.message||String(t.content),timestamp:n.timestamp};return jsxRuntime.jsx("div",{className:e,children:jsxRuntime.jsx(Xn,{log:o})})}function ri(t){if(!t||typeof t!="object")return null;let e=t;if(Array.isArray(e.results))return e;if(e.result&&typeof e.result=="object"){let n=e.result;if(Array.isArray(n.results))return n}return null}function Qe({item:t,className:e}){let n=ri(t.content);return n?.results?.length?jsxRuntime.jsx("div",{className:`rounded-lg border border-border/50 overflow-hidden ${e||""}`,children:jsxRuntime.jsx("div",{className:"divide-y divide-border/30",children:n.results.map(o=>{let r="";try{r=new URL(o.url).hostname.replace(/^www\./,"");}catch{}return jsxRuntime.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:"flex items-start gap-3 px-3 py-2 hover:bg-muted/50 transition-colors group",children:[jsxRuntime.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntime.jsx("div",{className:"text-sm text-foreground/90 group-hover:text-foreground group-hover:underline truncate",children:o.title}),o.description&&jsxRuntime.jsx("div",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:o.description})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-1 shrink-0 mt-0.5",children:[jsxRuntime.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:r}),jsxRuntime.jsx(lucideReact.ExternalLink,{className:"h-3 w-3 text-muted-foreground/40 group-hover:text-muted-foreground"})]})]},o.url)})})}):null}function si(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.content=="string")return e;if(e.result&&typeof e.result=="object"){let n=e.result;if(typeof n.content=="string")return n}return null}function ai(t){if(!t||typeof t!="object")return null;let n=t.input;return typeof n?.url=="string"?n.url:null}function Ze({item:t,className:e}){let n=si(t.content),o=ai(t.content),r=n?.url||o,s=n?.title,a=n?.content,i="";try{r&&(i=new URL(r).hostname.replace(/^www\./,""));}catch{}return !a&&!r?null:jsxRuntime.jsxs("div",{className:`rounded-lg border border-border/50 overflow-hidden ${e||""}`,children:[r&&jsxRuntime.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 px-3 py-2 border-b border-border/30 hover:bg-muted/50 transition-colors group",children:[jsxRuntime.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntime.jsx("div",{className:"text-sm text-foreground/90 group-hover:text-foreground truncate",children:s?.trim()||i||r}),s&&i&&jsxRuntime.jsx("div",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:i})]}),jsxRuntime.jsx(lucideReact.ExternalLink,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/40 group-hover:text-muted-foreground"})]}),a&&jsxRuntime.jsx("div",{className:"max-h-64 overflow-y-auto px-3 py-2 bg-muted/20",children:jsxRuntime.jsx(B,{content:a,className:"text-xs"})})]})}var xi=reactSyntaxHighlighter.Prism,xt=gt.memo(function({language:e,value:n,defaultOpen:o=false,title:r="View code",closeTitle:s="Hide code",className:a,theme:i="auto"}){let[c,l]=gt.useState(o),[u,p]=gt.useState(false),d=gt.useRef(null);gt.useEffect(()=>{if(!c){let h=d.current;h&&(h.scrollTop=h.scrollHeight);}},[c,n]);let m=gt.useMemo(()=>i!=="auto"?i:typeof window>"u"?"light":document.documentElement.classList.contains("dark")||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",[i]),x=gt.useMemo(()=>m==="dark"?prism.oneDark:prism.oneLight,[m]),y=gt.useCallback(async()=>{try{await navigator.clipboard.writeText(n),p(!0),setTimeout(()=>p(!1),2e3);}catch{let h=document.createElement("textarea");h.value=n,document.body.appendChild(h),h.select(),document.execCommand("copy"),document.body.removeChild(h),p(true),setTimeout(()=>p(false),2e3);}},[n]),k=gt.useMemo(()=>({margin:0,width:"100%",background:"transparent",padding:"1rem 0.5rem",fontSize:"0.825rem",maxWidth:"100vw",overflow:"auto"}),[]),f=gt.useMemo(()=>({userSelect:"none",minWidth:"2.5em",paddingRight:"1em",color:"rgb(161 161 170)",opacity:"0.5"}),[]),g=gt.useMemo(()=>({style:{fontFamily:"var(--font-mono, ui-monospace, monospace)",whiteSpace:"pre",wordBreak:"break-word"}}),[]);return jsxRuntime.jsx(ee__namespace.Root,{open:c,onOpenChange:l,className:a,children:jsxRuntime.jsxs("div",{className:"relative w-full font-sans rounded-lg overflow-hidden border border-zinc-200 dark:border-zinc-800",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between w-full px-4 py-1.5 bg-white/80 dark:bg-zinc-800/80 text-zinc-600 dark:text-zinc-100 backdrop-blur-sm border-b border-zinc-200 dark:border-zinc-800",children:[jsxRuntime.jsx("span",{className:"text-xs font-medium lowercase text-zinc-400 dark:text-zinc-500",children:e}),jsxRuntime.jsx("button",{onClick:y,className:"h-6 w-6 flex items-center justify-center rounded-md hover:bg-zinc-100 dark:hover:bg-zinc-700 transition-colors",children:u?jsxRuntime.jsx(lucideReact.Check,{className:"h-3 w-3 text-green-500"}):jsxRuntime.jsx(lucideReact.Copy,{className:"h-3 w-3 text-zinc-400 dark:text-zinc-500"})})]}),jsxRuntime.jsxs("div",{ref:d,className:`${c?"max-h-96":"max-h-[200px]"} overflow-auto relative`,children:[jsxRuntime.jsx("div",{className:"bg-zinc-50/50 dark:bg-zinc-950/70",children:jsxRuntime.jsx(xi,{language:e,style:x,PreTag:"div",showLineNumbers:true,wrapLines:false,wrapLongLines:false,startingLineNumber:1,className:"not-prose",customStyle:k,lineNumberStyle:f,codeTagProps:g,children:n})}),!c&&jsxRuntime.jsx("div",{className:"absolute bottom-0 inset-x-0 h-24 pointer-events-none bg-gradient-to-t from-zinc-50 dark:from-zinc-950 to-transparent",style:{marginBottom:"1.5rem"}})]}),jsxRuntime.jsx(ee__namespace.Trigger,{className:"absolute bottom-0 inset-x-0 flex items-center gap-2 text-sm text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300 p-2 justify-start bg-zinc-50/80 dark:bg-zinc-950/80 backdrop-blur-sm border-t border-zinc-200 dark:border-zinc-800 cursor-pointer",children:c?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.ChevronUp,{className:"h-4 w-4"}),s]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.ChevronDown,{className:"h-4 w-4"}),r]})})]})})});function ki(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;return "sql_query"in e||"thinking"in e||"error"in e?{thinking:typeof e.thinking=="string"?e.thinking:void 0,sql_query:typeof e.sql_query=="string"?e.sql_query:void 0,resource_key:typeof e.resource_key=="string"?e.resource_key:void 0,error:typeof e.error=="string"?e.error:void 0}:null}function bi(t){return ki(t.content)}function Xe({item:t,className:e}){let n=bi(t);if(!n)return null;let{thinking:o,sql_query:r,error:s}=n;return s?jsxRuntime.jsxs("div",{className:`text-destructive text-sm ${e||""}`,children:[jsxRuntime.jsx("div",{className:"font-medium",children:"Error"}),jsxRuntime.jsx("div",{children:s})]}):!r&&!o?null:jsxRuntime.jsxs("div",{className:`text-foreground whitespace-pre-wrap leading-normal ${e||""}`,children:[o&&jsxRuntime.jsx("div",{className:"mb-2",children:jsxRuntime.jsx(B,{content:o,className:"text-sm max-w-none"})}),r&&jsxRuntime.jsx("div",{className:"mb-2",children:jsxRuntime.jsx(xt,{language:"sql",value:r,defaultOpen:false})})]})}var Si=500,_i=300;function Ce({content:t,className:e}){let[n,o]=gt.useState(false);if(!t?.trim())return null;if(t.length<=Si)return jsxRuntime.jsx("div",{className:`text-sm text-muted-foreground ${e||""}`,children:jsxRuntime.jsx(B,{content:t,className:"text-sm max-w-none"})});let s=t.slice(0,_i).trimEnd()+"...";return jsxRuntime.jsx("div",{className:`text-sm text-muted-foreground ${e||""}`,children:n?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(B,{content:t,className:"text-sm max-w-none"}),jsxRuntime.jsx("button",{onClick:()=>o(false),className:"text-xs text-muted-foreground/70 hover:text-muted-foreground mt-1",children:"Show less"})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"text-sm",children:s}),jsxRuntime.jsx("button",{onClick:()=>o(true),className:"text-xs text-muted-foreground/70 hover:text-muted-foreground ml-1",children:"Show more"})]})})}function kt({children:t,defaultOpen:e=false,wrapperType:n="standard",compact:o=false,className:r}){let[s,a]=gt.useState(e),[i,c]=gt.useState(false),l=gt.useRef(null);gt.useEffect(()=>{let d=l.current;d&&(s||(d.scrollTop=d.scrollHeight),c(d.scrollHeight>d.clientHeight));},[s,t]);let u={standard:"bg-muted/30 border-border",info:"bg-info/10 border-info/30",warning:"bg-warning/10 border-warning/30"},p={standard:"text-muted-foreground hover:text-foreground",info:"text-info hover:text-info/80",warning:"text-warning hover:text-warning/80"};return jsxRuntime.jsx("div",{className:`relative text-sm ${o?"":"mb-2"} ${r||""}`,children:jsxRuntime.jsx(ee__namespace.Root,{open:s,onOpenChange:a,className:`border rounded-sm ${u[n]}`,children:jsxRuntime.jsxs("div",{ref:l,className:`overflow-y-auto ${s?"":"max-h-[200px]"}`,children:[i&&jsxRuntime.jsx(ee__namespace.Trigger,{className:`sticky top-0 text-center text-xs py-1 transition-opacity w-full cursor-pointer ${p[n]}`,children:s?"Less \u2193":"More \u2191"}),jsxRuntime.jsx("div",{className:`${o?"px-2 py-1":"p-2"} m-0 overflow-x-auto break-words whitespace-pre-wrap`,children:t})]})})})}function nr(t){return new Date(t).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Xt({children:t,timestamp:e}){return jsxRuntime.jsxs("div",{className:"flex",children:[e&&jsxRuntime.jsx("span",{className:"text-muted-foreground/60 mr-2 select-none",children:nr(e)}),jsxRuntime.jsx("span",{className:"text-foreground/80",children:t})]})}function te({children:t,timestamp:e}){return jsxRuntime.jsxs("div",{className:"flex",children:[e&&jsxRuntime.jsx("span",{className:"text-info/60 mr-2 select-none",children:nr(e)}),jsxRuntime.jsx("span",{className:"text-info/90",children:t})]})}function en({children:t,timestamp:e}){return jsxRuntime.jsxs("div",{className:"flex",children:[e&&jsxRuntime.jsx("span",{className:"text-warning/60 mr-2 select-none",children:nr(e)}),jsxRuntime.jsx("span",{className:"text-warning/90",children:t})]})}function rn({item:t,className:e}){if(!t.content)return null;let n=Ii(t.content)??Ni(t.parsedJson);if(!n)return null;let{step_by_step:o,thinking:r,code:s,warnings:a,error:i}=n;return i?jsxRuntime.jsx(kt,{wrapperType:"info",className:e,children:jsxRuntime.jsx(te,{children:i})}):!o&&!r&&!s&&!a?null:jsxRuntime.jsxs("div",{className:`text-foreground whitespace-pre-wrap leading-normal ${e||""}`,children:[o&&jsxRuntime.jsx(B,{content:o,className:"text-sm max-w-none"}),r&&jsxRuntime.jsx(Ce,{content:r,state:typeof t.state=="string"?t.state:void 0}),s&&jsxRuntime.jsx("div",{className:"mb-2",children:jsxRuntime.jsx(xt,{language:"python",value:s,defaultOpen:false})}),a&&jsxRuntime.jsxs("div",{className:"text-sm text-warning",children:[jsxRuntime.jsx("div",{className:"font-medium",children:"Warnings"}),jsxRuntime.jsx(B,{content:a,className:"text-sm max-w-none"})]})]})}function Ii(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}function Ni(t){if(!Array.isArray(t))return null;let n=t.find(o=>o.type==="json");return n&&typeof n.content=="object"&&n.content!==null?n.content:null}function sn({item:t,className:e}){let n=Ti(t);if(n.sort((a,i)=>a.index-i.index),n.length===0)return null;let o=n.some(a=>a.level==="error"),r=n.some(a=>a.level==="warning"),s=o?"info":r?"warning":"standard";return jsxRuntime.jsx("div",{className:`text-foreground leading-normal ${e||""}`,children:jsxRuntime.jsx(kt,{wrapperType:s,compact:true,children:n.map((a,i)=>jsxRuntime.jsx(Ei,{output:a},`${a.level}-${i}`))})})}function Ei({output:t}){switch(t.level){case "output":return jsxRuntime.jsx(Xt,{timestamp:t.timestamp,children:t.message});case "error":return jsxRuntime.jsx(te,{timestamp:t.timestamp,children:t.message});case "warning":return jsxRuntime.jsx(en,{timestamp:t.timestamp,children:t.message});default:return jsxRuntime.jsx("div",{className:"text-muted-foreground",children:t.message})}}function Ti(t){let e=yo(t.content);return e.length>0?e:yo(t.parsedJson)}function yo(t){return on(t).map((n,o)=>Di(n,o)).filter(n=>n!==null)}function on(t){if(Array.isArray(t))return t.every(Ai)?t.flatMap(e=>on(e.content)):t;if(typeof t=="string"){let e=$(t);return e!=null?on(e):on(ft(t))}if(t&&typeof t=="object"){let e=t;if(Array.isArray(e.outputs))return e.outputs;if(typeof e.message=="string"||typeof e.stdout=="string"||typeof e.stderr=="string"||typeof e.content=="string")return [e]}return []}function Di(t,e){if(!t||typeof t!="object")return null;let n=t,o=typeof n.message=="string"?n.message:typeof n.stdout=="string"?n.stdout:typeof n.stderr=="string"?n.stderr:typeof n.content=="string"?n.content:"";if(!o.trim())return null;let r=typeof n.level=="string"?n.level:n.stderr?"error":n.warning?"warning":"output";return {level:r==="error"||r==="warning"||r==="output"?r:"output",message:o,timestamp:typeof n.timestamp=="string"?n.timestamp:void 0,index:typeof n.index=="number"?n.index:e}}function Ai(t){return !!(t&&typeof t=="object"&&"type"in t&&"content"in t)}function Bi(t){if(!t?.result||t.status==="error")return false;let e=t.result;return typeof e=="string"?e.trim()!=="":Array.isArray(e)?e.length>0:typeof e=="object"&&e!==null?Object.keys(e).length>0:true}function Oi(t,e,n){if(e?.finished_message)return e.finished_message;if(e?.running_message)return e.running_message;if(!e&&n?.running_message)return n.running_message;let o=t||"tool";return e?`Completed ${o}`:`Running ${o}...`}function ne({toolGroup:t,ContentComponent:e,className:n,fallbackClassName:o}){let[r,s]=gt.useState(false),a=q(),i=e??a?.ContentComponent,c=t.invocation,l=t.result,u=Bi(l),p=c?.name||l?.name,d=Oi(p,l,c),m=l?l.status==="error"?"failed":"finished":"loading",x=l?.status==="error"?"text-gray-500/80 dark:text-gray-400/80":"text-gray-500 dark:text-gray-400";return jsxRuntime.jsxs(ee__namespace.Root,{open:r,onOpenChange:s,className:`relative w-full max-w-4xl space-y-2 leading-normal ${n||""}`,children:[jsxRuntime.jsxs(ee__namespace.Trigger,{className:`flex items-center justify-between text-sm transition-colors w-full ${x} ${u?"hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer":"cursor-default"}`,disabled:!u,children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(rt,{status:m}),jsxRuntime.jsx("span",{children:d})]}),u&&jsxRuntime.jsx(lucideReact.ChevronDown,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${r?"rotate-180":""}`})]}),u&&l&&jsxRuntime.jsx(ee__namespace.Content,{children:jsxRuntime.jsx("div",{className:"pl-6 mt-2",children:i?jsxRuntime.jsx(i,{content:{content:l.result,content_type:l.ui_content_type||"json"}}):jsxRuntime.jsx("pre",{className:o||"text-sm bg-gray-100 dark:bg-gray-800 p-2 rounded overflow-x-auto",children:JSON.stringify(l.result,null,2)})})})]})}var Ot={Success:"success",Error:"error",RequiresInfo:"requires info"};function Li(t){return t?t===Ot.Success?"finished":t===Ot.Error||t===Ot.RequiresInfo?"failed":"loading":"loading"}function ko(t){return t?t!==Ot.Success&&t!==Ot.Error&&t!==Ot.RequiresInfo:true}function Ui(t,e){let n=e||"agent",o=P(t?.message);return o||(t?.status===Ot.Success?`Finished ${n}`:`Running ${n}...`)}function an({content:t,botInvocation:e,isLoading:n=false,defaultOpen:o,adminLinkHref:r,adminLinkText:s="Open in Agent Designer",showAdminLink:a=false,onAdminClick:i,onExpand:c,EventsComponent:l,ContentComponent:u,className:p}){let d=()=>o!==void 0?o:ko(e?.currentStatus?.status),[m,x]=gt.useState(d),[y,k]=gt.useState(false),f=gt.useRef(null);if(gt.useEffect(()=>{if(e?.currentStatus){let T=e.currentStatus.status;if(f.current!==T&&(f.current=T,!y)){let E=ko(T);E&&!m?x(true):!E&&m&&x(false);}}},[e,y,m]),gt.useEffect(()=>{m&&e&&c&&c(t.invocation_id,t.bot_id,t.bot_name);},[m,e,c,t]),n&&!e&&!t.transparent)return jsxRuntime.jsxs("div",{className:`flex items-center gap-2 text-sm text-muted-foreground ${p||""}`,children:[jsxRuntime.jsx(rt,{status:"loading"}),jsxRuntime.jsxs("span",{children:["Loading ",t.bot_name,"..."]})]});if(!e)return null;let g=e.eventsByID&&Object.keys(e.eventsByID).length>0;if(t.transparent)return g?l?jsxRuntime.jsx(l,{eventsByID:e.eventsByID,defaultOpen:true}):jsxRuntime.jsx(Tt,{eventsByID:e.eventsByID,ContentComponent:u}):null;let h=Li(e.currentStatus?.status),b=Ui(e.currentStatus,t.bot_name),S=T=>{x(T),k(true);},v=T=>{i&&(T.preventDefault(),i(t.invocation_id,t.bot_id));};return jsxRuntime.jsxs(ee__namespace.Root,{open:m,onOpenChange:S,className:`relative w-full max-w-4xl space-y-2 leading-normal bot-invocation-content ${p||""}`,children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs(ee__namespace.Trigger,{className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[jsxRuntime.jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[jsxRuntime.jsx(rt,{status:h}),b]}),jsxRuntime.jsx(lucideReact.ChevronDown,{className:`h-4 w-4 transition-transform duration-200 ${m?"transform rotate-180":""}`})]}),a&&(r||i)&&jsxRuntime.jsxs("a",{href:r||"#",onClick:i?v:void 0,target:r?"_blank":void 0,rel:r?"noopener noreferrer":void 0,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[s,jsxRuntime.jsx(lucideReact.ArrowUpRight,{className:"h-3.5 w-3.5"})]})]}),jsxRuntime.jsx(ee__namespace.Content,{children:jsxRuntime.jsx("div",{className:"space-y-2 max-w-3xl",children:g?l?jsxRuntime.jsx(l,{eventsByID:e.eventsByID,defaultOpen:m}):jsxRuntime.jsx(Tt,{eventsByID:e.eventsByID,ContentComponent:u}):jsxRuntime.jsx("span",{className:"text-sm text-muted-foreground",children:"No events to display"})})})]})}function or({content:t,isSearching:e=false,className:n}){let o=[];Array.isArray(t)?o=t:typeof t=="object"&&t!==null&&"q"in t?o=t.q:typeof t=="string"&&(o=[t]);let r=o.filter(s=>s&&s.trim()!=="");return r.length===0?null:jsxRuntime.jsx("div",{className:`flex flex-wrap gap-2 ${n||""}`,children:r.map(s=>jsxRuntime.jsxs("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg text-sm bg-muted/50 text-foreground border border-border/30",children:[e?jsxRuntime.jsx(lucideReact.Loader2,{className:"h-3 w-3 mr-2 text-muted-foreground flex-shrink-0 animate-spin"}):jsxRuntime.jsx(lucideReact.Search,{className:"h-3 w-3 mr-2 text-muted-foreground flex-shrink-0"}),jsxRuntime.jsx("span",{className:"line-clamp-1",children:s})]},s))})}function sr({content:t,isSearching:e=false,className:n}){let o=[];if(Array.isArray(t))o=t;else if(typeof t=="object"&&t!==null&&"integration_queries"in t)o=t.integration_queries;else if(typeof t=="string")return null;let r=o.filter(s=>s&&s.query&&s.query.trim()!=="");return r.length===0?null:jsxRuntime.jsx("div",{className:`flex flex-wrap gap-2 ${n||""}`,children:r.map(s=>jsxRuntime.jsxs("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg text-sm bg-muted/50 text-foreground border border-border/30",children:[e?jsxRuntime.jsx(lucideReact.Loader2,{className:"h-3 w-3 mr-2 text-muted-foreground flex-shrink-0 animate-spin"}):jsxRuntime.jsx(lucideReact.Search,{className:"h-3 w-3 mr-2 text-muted-foreground flex-shrink-0"}),jsxRuntime.jsx("span",{className:"line-clamp-1",children:s.query})]},`${s.integration_config_id}-${s.resource_id}-${s.query}`))})}var Xi=120;function tl(t,e){return !t||t.length<=e?t:t.slice(0,e).trimEnd()+"..."}function el(t){switch(t){case "snippet":return lucideReact.Code;case "learning":return lucideReact.Brain;case "error":return lucideReact.AlertCircle;case "limitation":return lucideReact.AlertCircle;case "optimization":return lucideReact.Zap;default:return lucideReact.Lightbulb}}function nl(t){switch(t){case "snippet":return "Snippet";case "learning":return "Learning";case "error":return "Error";case "limitation":return "Limitation";case "optimization":return "Optimization";default:return t}}function rl({memory:t}){let[e,n]=gt.useState(false),o=el(t.type),r=nl(t.type),s=t.type==="snippet",a=tl(t.description||"",Xi),i=t.content&&t.content.trim()!=="",c=s&&i;return jsxRuntime.jsxs(ee__namespace.Root,{open:e,onOpenChange:n,className:"border border-border/50 rounded-lg overflow-hidden",children:[jsxRuntime.jsxs(ee__namespace.Trigger,{className:`w-full text-left p-3 flex items-start gap-3 ${c?"hover:bg-muted/50 cursor-pointer":"cursor-default"}`,disabled:!c,children:[jsxRuntime.jsx("div",{className:"flex-shrink-0 mt-0.5",children:jsxRuntime.jsx(o,{className:"h-4 w-4 text-muted-foreground"})}),jsxRuntime.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[jsxRuntime.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:r}),t.tags&&t.tags.length>0&&jsxRuntime.jsxs("div",{className:"flex gap-1 flex-wrap",children:[t.tags.slice(0,3).map((l,u)=>jsxRuntime.jsx("span",{className:"text-xs px-1.5 py-0.5 bg-muted rounded text-muted-foreground",children:l},u)),t.tags.length>3&&jsxRuntime.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",t.tags.length-3]})]})]}),jsxRuntime.jsx("p",{className:"text-sm text-foreground",children:s?a:t.description||t.content})]}),c&&jsxRuntime.jsx(lucideReact.ChevronDown,{className:`h-4 w-4 text-muted-foreground flex-shrink-0 transition-transform duration-200 ${e?"rotate-180":""}`})]}),c&&jsxRuntime.jsx(ee__namespace.Content,{children:jsxRuntime.jsx("div",{className:"border-t border-border/50 bg-muted/30",children:jsxRuntime.jsx("pre",{className:"p-3 text-sm overflow-x-auto whitespace-pre-wrap break-words font-mono",children:t.content})})})]})}function un({content:t,className:e}){let n=Array.isArray(t)?t:t?.memories;return !n||n.length===0?jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"No memories found."}):jsxRuntime.jsx("div",{className:`space-y-2 ${e||""}`,children:n.map(o=>jsxRuntime.jsx(rl,{memory:o},o.id))})}function ar(){return jsxRuntime.jsxs("span",{className:"inline-flex gap-1 text-muted-foreground",children:[jsxRuntime.jsx("span",{className:"animate-bounce",style:{animationDelay:"0ms"},children:"\u25CF"}),jsxRuntime.jsx("span",{className:"animate-bounce",style:{animationDelay:"150ms"},children:"\u25CF"}),jsxRuntime.jsx("span",{className:"animate-bounce",style:{animationDelay:"300ms"},children:"\u25CF"})]})}function _o(){return jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx(lucideReact.Loader2,{className:"animate-spin text-muted-foreground",size:24})})}function il(t){if(t.content_type==="bot_invocation"||t.content_type==="bot_invocation_result")return null;if(t.content&&typeof t.content=="object"){let n=t.content,o=n.tool_invocation_content;if(n.action_type==="bot.invoke"||o?.action_type==="bot.invoke")return null}if(t.content_type==="tool_invocation")return "tool_invocation";if(t.content_type==="tool_result")return "tool_result";if(!t.content||typeof t.content!="object")return null;let e=t.content;return "action_type"in e&&"name"in e&&"input"in e&&e.action_type!=="bot.invoke"?"result"in e?"tool_result":"tool_invocation":null}function Mt({content:t,className:e,components:n}){let r=q()?.onSuggestionClick,s=gt.useMemo(()=>l=>jsxRuntime.jsx(Mt,{...l,components:n}),[n]);if(!t.content||t.content==="")return null;if(t.content&&typeof t.content=="object"){let l=t.content,u=l.tool_invocation_content;if(l.action_type==="bot.invoke"||u?.action_type==="bot.invoke")return null}let a=il(t),i;a?i=a:i=P(t.ui_content_type)||t.content_type;let c=n?.[i];if(c)return jsxRuntime.jsx(c,{content:t,className:e});switch(i){case "text":return jsxRuntime.jsx(ye,{content:Co(t),className:e});case "markdown":return jsxRuntime.jsx(B,{content:Co(t),className:e});case "thinking":case "redacted_thinking":return jsxRuntime.jsx(He,{item:t,className:e});case "json":return jsxRuntime.jsx(zt,{content:t.content,className:e});case "codegen_json":return jsxRuntime.jsx(rn,{item:t,className:e});case "sql_generation":return jsxRuntime.jsx(Xe,{item:t,className:e});case "codeexec_output":return jsxRuntime.jsx(sn,{item:t,className:e});case "log":return jsxRuntime.jsx(Ke,{item:t,className:e});case "websearch":case "websearch_output":case "web_search":return jsxRuntime.jsx(Qe,{item:t,className:e});case "search_queries":return jsxRuntime.jsx(or,{content:t.content,className:e});case "integration_queries":return jsxRuntime.jsx(sr,{content:t.content,className:e});case "memory":return jsxRuntime.jsx(un,{content:t.content,className:e});case "webparse":case "webparse_output":case "web_parse":return jsxRuntime.jsx(Ze,{item:t,className:e});case "tool_group":return jsxRuntime.jsx(ne,{toolGroup:t.content,ContentComponent:s,className:e});case "bot_invocation":{let l=t.content,u=t.botInvocation;return jsxRuntime.jsx(an,{content:l,botInvocation:u,ContentComponent:s,className:e})}case "chart":case "ui_generation":{let l=t.invocation_id||t.created_by_invocation_id;if(t.chartConfig&&t.chartData)return jsxRuntime.jsx(Ge,{config:t.chartConfig,data:t.chartData,className:e});let u=Se(t.content);if(u&&u.length>0)return So(u,e,l,r);let p=Se(t.parsedJson);return p&&p.length>0?So(p,e,l,r):jsxRuntime.jsx("p",{className:"w-full max-w-4xl text-sm text-muted-foreground",children:"The LLM generated an invalid response. Please try again."})}case "table":return t.tableColumns&&t.tableData?jsxRuntime.jsx(We,{columns:t.tableColumns,data:t.tableData,className:e}):jsxRuntime.jsx(zt,{content:t.content,className:e});case "tool_invocation":{let l=t.content,u={invocation:{invocation_id:l.id||"",action:l.action_type||"",params:l.input||{},id:l.id||"",name:l.name||"",input:l.input||{},description:l.description,action_type:l.action_type,running_message:l.running_message}};return jsxRuntime.jsx(ne,{toolGroup:u,ContentComponent:s,className:e})}case "tool_result":{let l=t.content,u={invocation:{invocation_id:l.id||"",action:l.action_type||"",params:l.input||{}},result:{invocation_id:l.id||"",result:l.result}},p={...u,invocation:{...u.invocation,id:l.id||"",name:l.name||"",input:l.input||{},action_type:l.action_type,description:l.description},result:{...u.result,id:l.id||"",name:l.name||"",input:l.input||{},result:l.result,status:l.status||"success",action_type:l.action_type,description:l.description,ui_content_type:l.ui_content_type||P(t.ui_content_type),running_message:l.running_message||l.running_status,finished_message:l.finished_message||l.finished_status}};return jsxRuntime.jsx(ne,{toolGroup:p,ContentComponent:s,className:e})}default:return typeof t.content=="string"?jsxRuntime.jsx(ye,{content:t.content,className:e}):null}}function Co(t){return typeof t.content=="string"?t.content:""}function ll(t){let e=t?.children??t?.blocks;return Array.isArray(e)?e:void 0}function Se(t){if(t==null)return null;if(Array.isArray(t))return t.every(o=>o&&typeof o=="object"&&"type"in o&&"content"in o)?t:t.every(o=>o&&typeof o=="object"&&"_type"in o)?[{type:"json",content:{children:t}}]:null;if(typeof t=="object")return [{type:"json",content:t}];if(typeof t=="string"){let e=ft(t);return Se(e)}return null}function So(t,e,n,o){return jsxRuntime.jsx(jsxRuntime.Fragment,{children:t.map((r,s)=>{if(r.type==="text"){let a=r.content;return jsxRuntime.jsx(B,{content:a,className:e},`${s}-${a.length}`)}if(r.type==="json"){let a=r.content,i=ll(a);return i?jsxRuntime.jsx(gt__namespace.default.Fragment,{children:jsxRuntime.jsx(qe,{nodes:i,className:e,invocationId:n,onSuggestionClick:o})},`${s}-${i.length}`):he(a)?jsxRuntime.jsx(ar,{},s):jsxRuntime.jsx(zt,{content:a,className:e},`${s}-json`)}return null})})}function dl({result:t,isStreaming:e,className:n,components:o,streamingText:r}){let s=t?vo(t):[];return r&&s.length===0?jsxRuntime.jsxs("div",{className:n?`erdo-ui ${n}`:"erdo-ui space-y-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("div",{className:"animate-pulse w-2 h-2 bg-blue-500 rounded-full"}),jsxRuntime.jsx("span",{className:"text-sm text-gray-500",children:"Streaming response..."})]}),jsxRuntime.jsx("div",{className:"border rounded-lg p-4 whitespace-pre-wrap",children:r})]}):s.length===0&&!e?null:jsxRuntime.jsxs("div",{className:n?`erdo-ui ${n}`:"erdo-ui space-y-4",children:[s.map((a,i)=>jsxRuntime.jsx("div",{children:jsxRuntime.jsx(Mt,{content:a,components:o})},a.id||i)),e&&s.length===0&&!r&&jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("div",{className:"animate-pulse w-2 h-2 bg-blue-500 rounded-full"}),jsxRuntime.jsx("span",{className:"text-sm text-gray-500",children:"Processing..."})]})]})}function vo(t){let e=[],n=new Set;if(t.events)for(let o of t.events){let r=o.metadata,s=o.payload;if(r?.user_visibility==="visible"&&s?.status==="success"&&s?.output){let a=s.output;if(a.content&&Array.isArray(a.content))for(let i=0;i<a.content.length;i++){let c=a.content[i],l=c.id||`event-result-${i}`;if(n.has(l))continue;n.add(l);let u=r?.ui_content_type;e.push({id:l,content_type:c.content_type||"text",ui_content_type:u,content:c.content,data:c.data,chartConfig:c.chartConfig,chartData:c.chartData,tableColumns:c.tableColumns,tableData:c.tableData});}}}if(e.length===0&&t.result?.output?.content){let o=t.result.output.content;if(Array.isArray(o))for(let r=0;r<o.length;r++){let s=o[r],a=s.id||`result-${r}`;if(n.has(a))continue;n.add(a);let i=s.ui_content_type;e.push({...s,id:a,ui_content_type:i});}}return e}function pl(t){if(t.length===0)return t;let e=[];for(let n=0;n<t.length;n++){let o=t[n],r=n>0?t[n-1]:null,s=n<t.length-1?t[n+1]:null;if(o.type==="text"&&typeof o.content=="string"){let a=o.content,i=false;if(s?.type==="json"){let c=a;a=a.replace(/```(?:json)?\s*$/,""),c!==a&&(i=true);}if(r?.type==="json"){let c=a;a=a.replace(/^\s*```/,""),c!==a&&(i=true);}(!i||a.trim())&&e.push({...o,content:a});}else e.push(o);}return e}var ml=new Set(["=","("]);function fl(t){if(!t||t.length===0)return true;let e=t[t.length-1];return !ml.has(e)}function ir(t,e){if(t.user_visibility!=="visible"||!ge(t.content_type,t.ui_content_type.String))return typeof t.content=="object"?t:{...t,content:(t.content||"")+e};if(typeof t.content=="object"&&t.content!==null)return t;let n=t.parsedJson?t.parsedJson.map((u,p,d)=>p===d.length-1?{...u}:u):[],o=t.content||"",r=t._isInJson??false,s=t._charBuffer??"",a=t._jsonParser,i=n.length>0&&t._currentContent?n.length-1:-1;if(typeof e=="object")return {...t,content:o+JSON.stringify(e),parsedJson:[...n,e],_isInJson:r,_charBuffer:s,_jsonParser:a,_currentContent:void 0};for(let u of e){if(o+=u,!r&&u==="{"){let p=o.slice(0,-1);if(fl(p)){s="{";continue}}if(s&&Dt(u)){s+=u;continue}if(!r&&s?.match(/^\s*{\s*$/)&&u==='"'){r=true,a=new X;let d={content:a.add("{"),type:"json"},m=i>=0?n[i]:null;if(!m?.content)n=[...n,d],i=n.length-1;else if(typeof m.content=="string"&&m.content.match(/^\s*{$/))n=[...n.slice(0,-1),d],i=n.length-1;else {if(typeof m.content=="string"){let x={...m,content:m.content.replace(/{$/,"")};n=[...n.slice(0,-1),x,d];}else n=[...n,d];i=n.length-1;}}if(r)try{let d={type:"json",content:a.add(u)};n=[...n.slice(0,i),d],a.state==="END"&&(r=!1,i=-1);}catch(p){if(console.log("handleIncrementalMixedJsonParsing: content chunk",e),console.log("handleIncrementalMixedJsonParsing: accumulated content",o),console.warn("handleIncrementalMixedJsonParsing: JSON parse error, recovering as text",p),r=false,a=void 0,n.length>0&&i>=0&&n[i].type==="json"){let m=o.lastIndexOf("{"),y={type:"text",content:o.slice(m)};n=[...n.slice(0,i),y];}continue}else if(i<0||n[i]?.type!=="text"){let p={content:s+u,type:"text"};n=[...n,p],i=n.length-1;}else {let d={type:"text",content:n[i].content+s+u};n=[...n.slice(0,i),d];}s="";}let c=i>=0?n[i]:void 0,l=pl(n);return {...t,content:o,parsedJson:l,_isInJson:r,_charBuffer:s,_jsonParser:a,_currentContent:c}}function _e(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gl(t){if(!_e(t)||!("content"in t))return t;let e=t.content;return e===void 0?t:e}function ae(t,e){let n=gl(e);if((t==="thinking"||t==="redacted_thinking")&&typeof n=="string"){let o=$(n);return _e(o)?{content:o}:{content:n}}if(t==="json"&&typeof n=="string"){let o;try{let s=ft(n);Array.isArray(s)&&(o=s);}catch{}let r=$(n);return r!=null?{content:r,parsedJson:o}:{content:n,parsedJson:o}}return {content:n}}function yl(t,e){return typeof e=="string"?e:_e(e)?t==="redacted_thinking"?typeof e.data=="string"?e.data:"":typeof e.thinking=="string"?e.thinking:"":""}function pn(t,e,n){let o=ae(t,n);if(t!=="thinking"&&t!=="redacted_thinking")return o;let r=yl(t,e);return r?t==="redacted_thinking"?_e(o.content)&&typeof o.content.data!="string"?{...o,content:{...o.content,data:r}}:o:_e(o.content)&&typeof o.content.thinking!="string"?{...o,content:{...o.content,thinking:r}}:o:o}function mn(t){let e=t.metadata?.step_id??t.payload?.step_id;return typeof e=="string"?e:""}function lr(t){let e=t.metadata?.message_content_id??t.payload?.message_content_id;return typeof e=="string"?e:""}function hl(t){let e=t.metadata?.message_id;return typeof e=="string"?e:""}function cr(t,e){if(e.metadata?.content_type==="agent_invocation")return true;let n=hl(e);return !!(n&&n!==t.messageId)}function xl(t){return typeof t=="string"?t:typeof t=="object"&&t!==null&&"content"in t?String(t.content??""):""}function fn(){return {nodes:[],byStepId:{},byContentId:{},childrenByParentId:{},rootStepId:null,messageId:null,isStreaming:false}}function ur(t,e){switch(e.type){case "message created":return kl(t,e);case "message finished":return wo(t);case "step_started":return bl(t,e);case "step_finished":return Cl(t,e);case "create message content":return Sl(t,e);case "message content delta":return _l(t,e);case "message content result":return vl(t,e);case "status":return wl(t,e);default:return t}}function kl(t,e){let n=e.metadata?.message_id??e.payload?.message_id;if(!n)return t;let o=e.payload?.role,r=!!e.metadata?.invocation_id;return o==="assistant"||!o&&r?{...t,messageId:n}:t}function bl(t,e){let n=e.payload;if(!n?.step_id)return t;let o=t.byStepId[n.step_id],r=n.parent_step_id??null,s={kind:"step",id:n.step_id,parentId:r,type:n.type||o?.type||"agent",name:n.name||o?.name||"",key:n.key??o?.key,status:"running",contentType:n.content_type??o?.contentType,runningStatus:n.running_status??o?.runningStatus,finishedStatus:n.finished_status??o?.finishedStatus,hidden:n.hidden??o?.hidden},i=!r&&!t.rootStepId?n.step_id:t.rootStepId,c=r??"__root__",l=t.childrenByParentId[c]??[],u=l.includes(n.step_id)?t.childrenByParentId:{...t.childrenByParentId,[c]:[...l,n.step_id]},p=o?t.nodes.map(d=>d.kind==="step"&&d.id===n.step_id?s:d):[...t.nodes,s];return {...t,nodes:p,byStepId:{...t.byStepId,[n.step_id]:s},childrenByParentId:u,rootStepId:i,isStreaming:true}}function Cl(t,e){let n=e.payload;if(!n?.step_id)return t;let o=t.byStepId[n.step_id];if(!o){let c={kind:"step",id:n.step_id,parentId:null,type:"agent",name:"",status:n.status==="error"?"error":"completed",error:n.error,finishedStatus:n.finished_status};return {...t,nodes:[...t.nodes,c],byStepId:{...t.byStepId,[n.step_id]:c}}}let r={...o,status:n.status==="error"?"error":"completed",error:n.error??o.error,...n.finished_status?{finishedStatus:n.finished_status}:{}},s=n.step_id===t.rootStepId,a=t.nodes.map(c=>c.kind==="step"&&c.id===n.step_id?r:c.kind==="content"&&c.stepId===n.step_id?{...c,state:"completed"}:c),i={...t.byContentId};for(let[c,l]of Object.entries(i))l.stepId===n.step_id&&(i[c]={...l,state:"completed"});return {...t,nodes:a,byStepId:{...t.byStepId,[n.step_id]:r},byContentId:i,isStreaming:s?false:t.isStreaming}}function Sl(t,e){if(cr(t,e))return t;let n=lr(e);if(!n)return t;let o=mn(e)||null,r=typeof e.metadata?.content_type=="string"&&e.metadata.content_type||"text",s=typeof e.metadata?.ui_content_type=="string"&&e.metadata.ui_content_type||r,a=t.byContentId[n];if(a){let c={...a,stepId:a.stepId??o,contentType:a.contentType==="text"?r:a.contentType,uiContentType:a.uiContentType==="text"?s:a.uiContentType};return {...t,nodes:t.nodes.map(l=>l.kind==="content"&&l.id===n?c:l),byContentId:{...t.byContentId,[n]:c}}}let i={kind:"content",id:n,stepId:o,contentType:r,uiContentType:s,text:"",state:"streaming"};return {...t,nodes:[...t.nodes,i],byContentId:{...t.byContentId,[n]:i}}}function _l(t,e){if(cr(t,e))return t;let n=lr(e),o=xl(e.payload);if(!n||!o)return t;let r=t.byContentId[n],s=t;if(!r){let u=mn(e)||null,p=typeof e.metadata?.content_type=="string"&&e.metadata.content_type||"text",d=typeof e.metadata?.ui_content_type=="string"&&e.metadata.ui_content_type||p;r={kind:"content",id:n,stepId:u,contentType:p,uiContentType:d,text:"",state:"streaming"},s={...t,nodes:[...t.nodes,r],byContentId:{...t.byContentId,[n]:r}};}let a=r.text+o,i={},c=r.parsedContent;if(r.contentType==="json"){let u=Il(r,o);c=u.parsedContent,i=u._parserFields;}let l={...r,text:a,...c!==void 0?{parsedContent:c}:{},...i};return {...s,nodes:s.nodes.map(u=>u.kind==="content"&&u.id===n?l:u),byContentId:{...s.byContentId,[n]:l}}}function vl(t,e){if(cr(t,e))return t;let n=lr(e);if(!n)return t;let o=mn(e)||null,r=typeof e.metadata?.content_type=="string"&&e.metadata.content_type||"text",s=typeof e.metadata?.ui_content_type=="string"&&e.metadata.ui_content_type||r,a=t.byContentId[n],i=a?pn(r,a.result??a.text,e.payload):ae(r,e.payload);if(!a){let l={kind:"content",id:n,stepId:o,contentType:r,uiContentType:s,text:"",result:i.content,...i.parsedJson?{parsedContent:i.parsedJson}:{},state:"completed"};return {...t,nodes:[...t.nodes,l],byContentId:{...t.byContentId,[n]:l}}}let c={...a,result:i.content,...i.parsedJson?{parsedContent:i.parsedJson}:{},state:"completed"};return {...t,nodes:t.nodes.map(l=>l.kind==="content"&&l.id===n?c:l),byContentId:{...t.byContentId,[n]:c}}}function wo(t){let e=t.nodes.map(r=>r.kind==="content"&&r.state==="streaming"?{...r,state:"completed"}:r.kind==="step"&&r.status==="running"?{...r,status:"completed"}:r),n={...t.byContentId};for(let[r,s]of Object.entries(n))s.state==="streaming"&&(n[r]={...s,state:"completed"});let o={...t.byStepId};for(let[r,s]of Object.entries(o))s.status==="running"&&(o[r]={...s,status:"completed"});return {...t,nodes:e,byContentId:n,byStepId:o,isStreaming:false}}function wl(t,e){let n=mn(e)||null,o=e.payload,r=typeof o=="string"?o:o?.message||o?.status_message||o?.status||"";if(!r)return t;if(n){let a=t.byStepId[n];if(!a)return t;let i=a.status==="completed"||a.status==="error"?{...a,finishedStatus:r}:{...a,runningStatus:r};return {...t,nodes:t.nodes.map(c=>c.kind==="step"&&c.id===n?i:c),byStepId:{...t.byStepId,[n]:i}}}let s={kind:"status",stepId:null,message:r};return {...t,nodes:[...t.nodes,s]}}function Il(t,e){let n=t,o={content:n._rawText??t.text,user_visibility:"visible",content_type:"json",ui_content_type:{String:t.uiContentType||"json",Valid:true},parsedJson:t.parsedContent?[...t.parsedContent]:[],_jsonParser:n._jsonParser,_isInJson:n._isInJson,_charBuffer:n._charBuffer??"",_currentContent:n._currentContent},r=ir(o,e);return {parsedContent:r.parsedJson,_parserFields:{_rawText:r.content,_jsonParser:r._jsonParser,_isInJson:r._isInJson,_charBuffer:r._charBuffer,_currentContent:r._currentContent}}}function Nl(t){for(let e of t.nodes){if(e.kind==="step"){let n=t.byStepId[e.id];if(n&&n.type==="tool_call"&&!n.hidden)return true;continue}if(e.kind==="content"&&!(e.contentType==="tool_invocation"||e.contentType==="agent_invocation")&&(e.contentType==="tool_result"&&e.result||e.text||e.parsedContent?.length||e.result))return true}return false}function gn(t,e,n){return e.type!=="llm_call"?false:!(e.parentId===t.rootStepId)&&n.contentType==="text"}function ve(t){if(!t.rootStepId)return [];let e=[],n={};function o(s){if(!s)return false;if(s in n)return n[s];let a=s,i=false,c=[];for(;a;){if(a in n){i=i||n[a];break}c.push(a);let l=t.byStepId[a];if(!l)return false;if(l.hidden){i=true;break}a=l.parentId;}for(let l of c)n[l]=i;return i}function r(s){let a=false;if(s.contentType==="thinking"||s.contentType==="redacted_thinking"){let c=s.result??s.text;e.push({id:s.id,content_type:s.contentType,ui_content_type:s.uiContentType||s.contentType,content:c,state:s.state==="streaming"?"in_progress":"completed"}),a=true;}else if(s.contentType==="json"){if(s.parsedContent)for(let c=0;c<s.parsedContent.length;c++){let l=s.parsedContent[c];if(l.type==="text"&&l.content)e.push({id:`${s.id}-text-${c}`,content_type:"text",ui_content_type:"markdown",content:String(l.content)}),a=true;else if(l.type==="json"&&typeof l.content=="object"){let u=l.content;typeof u.output=="string"?e.push({id:`${s.id}-text-${c}`,content_type:"text",ui_content_type:"markdown",content:u.output}):typeof u.markdown=="string"?e.push({id:`${s.id}-text-${c}`,content_type:"text",ui_content_type:"markdown",content:u.markdown}):e.push({id:`${s.id}-json-${c}`,content_type:"json",ui_content_type:s.uiContentType||"ui_generation",content:u,state:s.state==="streaming"?"in_progress":"completed"}),a=true;}}else if(s.result){let c=typeof s.result=="string"?El(s.result):s.result;c&&typeof c=="object"&&(e.push({id:s.id,content_type:"json",ui_content_type:s.uiContentType||"json",content:c,state:s.state==="streaming"?"in_progress":"completed"}),a=true);}}if(a)return;let i=s.result??s.text;i&&e.push({id:s.id,content_type:s.contentType||"text",ui_content_type:s.uiContentType||"markdown",content:i,state:s.state==="streaming"?"in_progress":"completed"});}for(let s of t.nodes){if(s.kind!=="content"||s.contentType==="tool_invocation")continue;if(s.contentType==="tool_result"){s.result&&s.result.action_type!=="bot.invoke"&&e.push({id:s.id,content_type:"tool_result",ui_content_type:s.uiContentType||"tool_result",content:s.result});continue}if(s.stepId===null){r(s);continue}let a=t.byStepId[s.stepId];if(!a){r(s);continue}o(a.id)||a.type!=="tool_call"&&(a.type==="llm_call"&&gn(t,a,s)||r(s));}return e}function El(t){return t?$(t):null}function Bl(t){return (t.status==="completed"||t.status==="error")&&t.finishedStatus?t.finishedStatus:t.runningStatus?t.runningStatus:t.name.replace(/_/g," ")}function Ol(t){return t==="running"?"loading":t==="error"?"failed":"finished"}function Io(t,e){let n=t.byStepId[e];if(!n||n.type!=="agent"||(t.childrenByParentId[e]||[]).some(s=>{let a=t.byStepId[s];return !!a&&a.type==="agent"&&!a.hidden}))return false;for(let s of t.nodes){if(s.kind!=="step")continue;let a=t.byStepId[s.id];if(!a||a.type!=="agent"||a.hidden||a.id===e)continue;let i=a.id;for(;i;){if(i===e)return true;i=t.byStepId[i]?.parentId??null;}}return false}function Ml(t){return t==="info"?"info":t==="warning"?"warning":"standard"}function Vl(t){let e=t.trim();if(!e)return null;let n=new Set;n.add(e);let o=e.match(/^```[a-zA-Z0-9_-]*\n([\s\S]*?)\n```$/);o?.[1]&&n.add(o[1].trim());let r=e.indexOf("{"),s=e.lastIndexOf("}");r>=0&&s>r&&n.add(e.slice(r,s+1).trim());let a=e.indexOf("["),i=e.lastIndexOf("]");a>=0&&i>a&&n.add(e.slice(a,i+1).trim());for(let c of n){if(!c)continue;let l=$(c);if(l!=null)return typeof l=="string"?$(l)??l:l}return null}function No(t,e){let n=[],o="",r=[],s=0;function a(){r.length>0&&(n.push({id:`${e}-exec-${s}`,type:"codeexec",content:r.join(`
51
- `),wrapperType:Ml(o)}),s++,r=[]);}for(let i of t){let c=typeof i.message=="string"?i.message:"";if(!c)continue;let l=typeof i.level=="string"?i.level:"output";l!==o&&r.length>0&&a(),o=l,r.push(c);}return a(),n}function Eo(t,e,n){let o=[];for(let r of t){if(r.contentType==="tool_invocation"||r.contentType==="tool_result")continue;let s=`${e}-content-${r.id}`,a=r.state==="streaming"?"running":"completed";if(r.contentType==="thinking"||r.contentType==="redacted_thinking"){let i=r.result??r.text;if(!i)continue;o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType||r.contentType,content:i,state:r.state==="streaming"?"in_progress":"completed"},status:a});continue}if(r.result){let i=r.result;if(typeof r.result=="string")if(r.contentType==="json"){let c=$(r.result);if(c!=null)i=c;else {let l=Vl(r.result);if(l!==null)i=l;else if(!(r.parsedContent&&r.parsedContent.length>0))if(n){o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType||"ui_generation",content:r.result,state:r.state==="streaming"?"in_progress":"completed"}});continue}else {o.push({id:s,type:"text",content:r.result});continue}}}else {o.push({id:s,type:"text",content:r.result});continue}if(Array.isArray(i)&&i.length>0){o.push(...No(i,s));continue}if(typeof i=="object"&&i!==null){let c=i;if(typeof c.code=="string"){o.push({id:s,type:"codegen",contentData:c,status:a});continue}if(n){o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType,content:i,state:r.state==="streaming"?"in_progress":"completed"}});continue}}}if(r.contentType==="json"&&r.parsedContent){if(r.uiContentType==="codeexec_output"){let i=[];for(let c of r.parsedContent)c.type==="json"&&typeof c.content=="object"&&i.push(c.content);o.push(...No(i,s));continue}for(let i=0;i<r.parsedContent.length;i++){let c=r.parsedContent[i];if(c.type==="text"&&c.content)o.push({id:`${s}-text-${i}`,type:"text",content:String(c.content)});else if(c.type==="json"&&typeof c.content=="object"){let l=c.content;typeof l.code=="string"?o.push({id:`${s}-codegen-${i}`,type:"codegen",contentData:l,status:a}):typeof l.markdown=="string"?o.push({id:`${s}-text-${i}`,type:"text",content:l.markdown}):typeof l.output=="string"?o.push({id:`${s}-text-${i}`,type:"text",content:l.output}):n&&o.push({id:`${s}-content-${i}`,type:"content",contentItem:{id:`${s}-content-${i}`,content_type:"json",ui_content_type:r.uiContentType||"ui_generation",content:l,state:r.state==="streaming"?"in_progress":"completed"}});}}continue}r.text&&r.contentType!=="json"&&o.push({id:s,type:"text",content:r.text});}return o}function $l(t,e){if(!t.rootStepId)return [];let n=[],o={},r={},s=new Set,a={},i={},c={};function l(f){return r[f]||(r[f]=[]),r[f]}function u(f){if(f)return t.byStepId[f]}function p(f){if(!f)return false;if(f in c)return c[f];let g=f,h=[],b=false;for(;g;){if(g in c){b=b||c[g];break}h.push(g);let S=u(g);if(!S)break;if(S.hidden){b=true;break}g=S.parentId;}for(let S of h)c[S]=b;return b}function d(f){return p(f.id)}for(let f of t.nodes){if(f.kind!=="content"||!f.stepId||f.contentType==="tool_invocation"||f.contentType==="tool_result"||f.contentType==="agent_invocation"||!f.text&&!f.result&&!f.parsedContent?.length)continue;let g=u(f.stepId);if(!g||d(g)||g.type==="llm_call"&&gn(t,g,f))continue;let h=f.stepId;for(;h;){i[h]=true;let b=u(h);if(!b)break;h=b.parentId;}}function m(f){return !!i[f]}function x(f){if(!f)return null;if(f in a)return a[f];let g=f;for(;g;){let h=u(g);if(!h)break;let b=g===t.rootStepId,S=h.type==="agent"&&!h.hidden&&(!b||!Io(t,h.id)),v=h.type==="tool_call"&&!h.hidden;if(S||v)return a[f]=g,g;g=h.parentId;}return a[f]=null,null}function y(f,g){if(g.length===0)return;let h=x(f);if(!h){n.push(...g);return}let b=o[h];if(!b){l(h).push(...g);return}b.children||(b.children=[]),b.children.push(...g);}function k(f,g,h){if(!h||typeof h!="object")return [];let b=h,S=typeof b.result=="object"&&b.result!==null?b.result:b,v=[];typeof S.code=="string"&&S.code.trim()&&v.push({id:`${f}-${g}-codegen`,type:"codegen",contentData:S});let T=typeof S.output=="string"?S.output.trim():"";return T&&v.push({id:`${f}-${g}-output`,type:"codeexec",content:T}),v}for(let f of t.nodes){if(f.kind==="step"){let h=t.byStepId[f.id];if(!h||h.hidden||h.type==="llm_call"||h.id===t.rootStepId&&Io(t,h.id)||s.has(h.id))continue;s.add(h.id);let b={id:h.id,type:"step",label:Bl(h),status:h.status},S=r[h.id];S&&S.length>0&&(b.children=S,delete r[h.id]),o[h.id]=b,y(h.parentId,[b]);continue}if(f.kind!=="content"||f.contentType==="tool_invocation")continue;if(f.stepId===null){n.push(...Eo([f],"root",e));continue}let g=t.byStepId[f.stepId];if(g&&!d(g)&&!(g.type==="llm_call"&&gn(t,g,f))){if(g.type==="tool_call"&&f.contentType==="tool_result"){if(m(g.id))continue;y(g.id,k(g.id,f.id,f.result));continue}y(g.id,Eo([f],g.id,e));}}return n}function To({node:t,ContentComponent:e}){let[n,o]=gt.useState(t.status==="running"),r=gt.useRef(t.status==="running");if(gt.useEffect(()=>{r.current&&t.status!=="running"&&o(false),r.current=t.status==="running";},[t.status]),t.type==="text")return jsxRuntime.jsx(B,{content:t.content||"",className:"max-w-none"});if(t.type==="codegen"&&t.contentData){let{code:i,step_by_step:c,thinking:l}=t.contentData;return jsxRuntime.jsxs("div",{className:"space-y-2",children:[c&&jsxRuntime.jsx(B,{content:c,className:"text-sm max-w-none"}),l&&jsxRuntime.jsx(Ce,{content:l,state:t.status==="running"?"in_progress":"completed"}),i&&jsxRuntime.jsx(xt,{language:"python",value:i,defaultOpen:false})]})}if(t.type==="codeexec"&&t.content){let i=t.wrapperType||"standard";return jsxRuntime.jsx(kt,{wrapperType:i,compact:true,children:jsxRuntime.jsx(Xt,{children:t.content})})}if(t.type==="content"&&t.contentItem&&e)return jsxRuntime.jsx(e,{content:t.contentItem});if(t.type==="content"&&t.contentItem)return jsxRuntime.jsx(Mt,{content:t.contentItem});let s=!!t.children?.length,a=t.status==="running"?"text-foreground":"text-muted-foreground";return jsxRuntime.jsxs(ee__namespace.Root,{open:n,onOpenChange:o,className:"w-full",children:[jsxRuntime.jsxs(ee__namespace.Trigger,{className:`flex items-center justify-between w-full text-sm py-0.5 ${a} ${s?"hover:text-foreground cursor-pointer":"cursor-default"}`,disabled:!s,children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(rt,{status:Ol(t.status),size:14}),jsxRuntime.jsx("span",{children:t.label})]}),s&&jsxRuntime.jsx(lucideReact.ChevronDown,{className:`h-4 w-4 shrink-0 text-muted-foreground/50 transition-transform duration-200 ${n?"rotate-180":""}`})]}),s&&jsxRuntime.jsx(ee__namespace.Content,{children:jsxRuntime.jsx("div",{className:"ml-5 mt-1 flex flex-col gap-1",children:t.children?.map(i=>jsxRuntime.jsx(To,{node:i,ContentComponent:e},i.id))})})]})}function Do({agentState:t,ContentComponent:e,className:n}){if(!t.rootStepId)return null;let o=gt.useMemo(()=>$l(t,e),[t,e]);return o.length===0?null:jsxRuntime.jsx("div",{className:`flex flex-col gap-1 ${n||""}`,children:o.map(r=>jsxRuntime.jsx(To,{node:r,ContentComponent:e},r.id))})}function U(t){if(!t)throw new Error("Entity is null");if(!("_type"in t))throw new Error(`Entity ${JSON.stringify(t)} is missing _type`);return t._type}function Ll(t){return t.contents.length===0?null:t.contents[t.contents.length-1]||null}function Oo(t){return t.contents.length===0?null:t.contents[0]||null}function Ao(t){let e=false,n=t.contents.map(r=>r.state!=="in_progress"?r:(e=true,{...r,state:"completed",updated_at:new Date().toISOString()}));if(!e&&t.state==="completed")return t;let o={...t.contentsByID};for(let r of n)o[r.id]=r;return {...t,state:"completed",contents:n,contentsByID:o}}function mr(t,e){let n=U(t);switch(n){case "message":return t;case "step":let o=t;if(e){let a=o.eventsByID[e]?.Message;return a||$o({},"",e)}let s=Object.keys(o.eventsByID).reverse();for(let a of s){let i=o.eventsByID[a];if(i&&i.Message)return i.Message}throw new Error("Unable to find message for step");default:throw new Error(`Unable to have messages on entity type ${n}`)}}function Ul(t,e){switch(U(t)){case "message_content":return t;case "output_content":return t;case "message":return le(t,e);case "output":return ce(t,e);case "step":let o=xn(t,e);return o?ce(o,e):null;default:return null}}function le(t,e){let n=U(t);switch(n){case "message_content":return t;case "message":let o=mr(t);if(!o)throw new Error("Unable to find message to add content to");return e?o.contentsByID[e]:Ll(o);default:throw new Error(`Unable to have message content on entity type ${n}`)}}function ce(t,e){let n=U(t);switch(n){case "output_content":return t;case "output":let o=t;return e?o.contentsByID[e]||null:o.contents.length<=0?null:o.contents[o.contents.length-1]||null;case "step":let s=xn(t,e);return s?ce(s):null;case "invocation":if(!e)return null;let a=t.eventsByID[e];return !a||!a.Output?null:ce(a.Output);default:throw new Error(`Unable to have output content on entity type ${n}`)}}function fr(t,e){let n=U(t),o=null;switch(n){case "invocation":return t;case "message_content":if(o=t.botInvocation||null,!o)throw new Error("Unable to find bot invocation for message content");if(e&&o.bot_invocation.id!==e)throw new Error("Unable to find bot invocation for message content - mismatched ID");return o;case "message":if(o=Oo(t)?.botInvocation||null,!o)throw new Error("Unable to find bot invocation for message");if(e&&o.bot_invocation.id!==e)throw new Error("Unable to find bot invocation for message - mismatched ID");return o;case "output_content":return t.botInvocation||null;default:throw new Error(`Unable to have bot invocation on entity type ${n}`)}}function xn(t,e){let n=U(t);switch(n){case "output":return t;case "step":let o=t;if(e){let i=o.eventsByID[e]?.Output;if(!i)throw new Error("Unable to find output with id "+e);return i}let s=Object.keys(o.eventsByID).reverse();for(let i of s){let c=o.eventsByID[i];if(c&&c.Output)return c.Output}throw new Error("Unable to find output for step");case "invocation":if(!e)throw new Error("Unable to find output for invocation without ID");return t.eventsByID[e]?.Output||null;default:throw new Error(`Unable to have step outputs on entity type ${n}`)}}function Mo(t,e){let n=U(t);switch(n){case "result_handler":return t;case "step":if(!e)throw new Error("Unable to have result handlers on step without ID");let o=t.eventsByID[e];if(!o||!o.type||o.type!=="result_handler"||!o.ResultHandler)throw new Error(`Unable to find result handler with id ${e} on step ${t.id}`);return o.ResultHandler;default:throw new Error(`Unable to have result handlers on entity type ${n}`)}}function Vo(t,e){let n=U(t),o=null;switch(n){case "step":if(t.id===e||!e)return t;throw new Error("Unable to find step on step with id "+e);case "invocation":if(!e)throw new Error("Unable to have steps on bot invocation without ID");o=t;let r=o.eventsByID[e];if(!r)throw new Error("Unable to find step on invocation with id "+e);if(!r.Step)throw new Error("Unable to find step on invocation with id "+e);return r.Step;case "result_handler":if(!e)throw new Error("Unable to have steps on result handler without ID");let a=t.eventsByID[e];if(!a)throw new Error("Unable to find step on result handler with id "+e);if(!a.Step)throw new Error("Unable to find step on result handler with id "+e);return a.Step;default:throw new Error(`Unable to have steps on entity type ${n}`)}}var dr=class extends Error{};function jl(t,e,n){let o=null,r=e[0],s=e[1];n[r]=s;try{switch(r){case "message":o=mr(t,s);break;case "content":o=le(t,s);break;case "step":o=Vo(t,s);break;case "output":o=xn(t,s);break;case "output_content":o=ce(t,s);break;case "invocation":o=fr(t,s);break;case "result_handler":o=Mo(t,s);break}}catch(a){throw console.error("error finding next entity"),console.log("path",e),console.log("currentEntity",t),a}if(!o)throw console.log("path",e),console.log("currentEntity",t),console.log("nextEntity",o),new dr(`Unable to find next entity for path ${e.join("/")}`);return o}function $o(t,e,n,o){let r=t.payload;return {_type:"message",message:{id:n,thread_id:e,author_id:r.author_id||"app",author_entity_type:r.author_entity_type||"app",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),role:r.role||"assistant",avatar:"/teams/erdo-icon.png"},state:"in_progress",contents:[],contentsByID:{},contentIDToIdx:{}}}function Fl(t,e){return {_type:"message_content",id:t.metadata.message_content_id,message_id:e.message,content_type:t.metadata.content_type,created_by_invocation_id:t.metadata.invocation_id,invocation_id:t.metadata.invocation_id,state:"in_progress",user_visibility:t.metadata.user_visibility??"visible",bot_visibility:t.metadata.bot_visibility??"visible",content:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:t.metadata?.ui_content_type?{String:t.metadata.ui_content_type,Valid:true}:{String:"",Valid:false}}}function Jl(t,e){let n=t.metadata.content_type||"text",o=t.metadata?.ui_content_type,r=ae(n,t.payload);return {_type:"message_content",id:t.metadata.message_content_id,message_id:e.message,content:r.content,content_type:n,created_by_invocation_id:t.metadata.invocation_id,invocation_id:t.metadata.invocation_id,state:"completed",user_visibility:t.metadata.visibility||"visible",bot_visibility:"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:o?{String:o,Valid:true}:{String:"",Valid:false},parsedJson:r.parsedJson??null}}function Gl(t,e,n){let o=t.payload;return {_type:"step",id:e,invocation_id:n.invocation||"",step_id:o.step_id||"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_status_id:"",path:{String:"",Valid:false},action_type:{String:o.action_type,Valid:true},key:{String:o.key,Valid:true},bot_id:o.bot_id,result_handler_id:"",step_order:{Int32:o.step_order,Valid:true},output_content_type:{String:o.content_type,Valid:true},execution_mode:{String:o.execution_mode,Valid:true},output_behaviour:{String:o.output_behaviour,Valid:true},user_output_visibility:{String:t.metadata.visibility||"visible",Valid:true},output_channels:o.output_channels||[],running_message:{String:o.running_message||"",Valid:!!o.running_message},finished_message:{String:o.finished_message||"",Valid:!!o.finished_message},depends_on:[],eventsByID:{},currentStatus:null}}function Wl(t,e,n){let o=t.payload;return {_type:"result_handler",id:e,invocation_id:t.metadata.invocation_id||"",result_handler_id:o.result_handler_id||e,step_invocation_id:o.step_invocation_id||"",type:o.type||"",if_conditions:o.if_conditions||{},created_at:new Date().toISOString(),updated_at:new Date().toISOString(),output_content_type:o.output_content_type||"",result_handler_order:o.result_handler_order||0,eventsByID:{}}}function ql(t,e,n){return {_type:"output",id:e,step_id:n.step_id,output:{id:e,invocation_id:t.metadata?.invocation_id,path:t.metadata.path,created_at:new Date().toISOString(),updated_at:new Date().toISOString()},state:"in_progress",contents:[],contentsByID:{},contentIDToIdx:{}}}function Ro(t,e,n,o=null){return {_type:"output_content",id:e,output_id:n.output,content:"",content_type:t.metadata.content_type,state:"in_progress",invocation_id:t.metadata.invocation_id,user_visibility:o??t.metadata.user_visibility??"visible",bot_visibility:t.metadata.bot_visibility??"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:t.metadata.ui_content_type?{String:t.metadata.ui_content_type,Valid:true}:{String:"",Valid:false},output:null}}function Po(t,e,n,o=null){let r=t.metadata.content_type||"text",s=ae(r,t.payload),a=t.metadata?.ui_content_type;return {_type:"output_content",id:e,output_id:n.output,content:s.content,content_type:r,state:"completed",invocation_id:t.metadata.invocation_id,parsedJson:s.parsedJson??null,user_visibility:o||t.metadata.visibility||"visible",bot_visibility:"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:a?{String:a,Valid:true}:{String:"",Valid:false},output:null}}function zl(t,e,n){return {_type:"invocation",bot_invocation:{id:t.payload.invocation_id,bot_id:t.payload.bot_id,bot_name:t.payload.bot_name,created_by_user_id:t.payload.created_by_user_id,current_state_id:"",parent_invocation_id:"",branch_init_state_id:"",current_status_id:"",organization_id:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},eventsByID:{},currentStatus:null,current_status:null,step_invocations:[],step_invocation_states:[],resources:[],outputs:[],statuses:[]}}function we(t,e){let n=t.payload;return {_type:"status",id:new Date().toISOString(),status:n.status,message:{String:n.message,Valid:true},Details:n}}function Lo(t){return {id:t.id,type:"step",created_at:t.created_at,_type:"invocation_event",Output:null,Message:null,Status:null,ResultHandler:null,Step:t}}function gr(t){return {id:t.output.id,type:"output",created_at:t.output.created_at,_type:"invocation_event",Output:t,Message:null,Status:null,ResultHandler:null,Step:null}}function yr(t){return {id:t.id,type:"status",created_at:t.created_at,_type:"invocation_event",Status:t,Output:null,Message:null,ResultHandler:null,Step:null}}function Hl(t){return {id:t.message.id,type:"message",created_at:t.message.created_at,_type:"invocation_event",Output:null,Message:t,Status:null,ResultHandler:null,Step:null}}function Kl(t){return {id:t.id,type:"result_handler",created_at:t.created_at,_type:"invocation_event",Output:null,Message:null,Status:null,ResultHandler:t,Step:null}}var Ql=new Set(["=","("]);function Zl(t){if(!t||t.length===0)return true;let e=t[t.length-1];return !Ql.has(e)}function Uo(t,e){if(t.content||(t.content=""),t.user_visibility!=="visible"||!ge(t.content_type,t.ui_content_type.String))return t.content+=e,{...t};if(t.parsedJson||(t.parsedJson=[]),typeof e=="object")return t.content+=JSON.stringify(e),t.parsedJson=[...t.parsedJson,e],{...t};t._jsonParser||(t._isInJson=false),t._charBuffer||(t._charBuffer="");let n=t.content_type,o=t.ui_content_type.String;for(let r of e){t.content+=r;let s=n==="json"||o==="json";if(!t._isInJson&&s&&!Dt(r)){t._isInJson=true,t._jsonParser=new X;let a={content:{},type:"json"};t.parsedJson=[...t.parsedJson||[],a],t._currentContent=a,t._charBuffer="";}if(!t._isInJson&&!s&&o==="ui_generation"&&r==="{"){let a=t.content.slice(0,-1);if(Zl(a)){t._charBuffer="{";continue}}if(t._charBuffer&&Dt(r)){t._charBuffer+=r;continue}if(!t._isInJson&&!s&&o==="ui_generation"&&t._charBuffer?.match(/^\s*{\s*$/)&&r==='"'){t._isInJson=true,t._jsonParser=new X;let i={content:t._jsonParser.add("{"),type:"json"};t._currentContent?.content?t._currentContent.content.match(/^\s*{$/)?(t._currentContent=i,t.parsedJson=[...t.parsedJson.slice(0,-1),i]):(t._currentContent.content=t._currentContent.content.replace(/{$/,""),t._currentContent=i,t.parsedJson=[...t.parsedJson,i]):(t._currentContent=i,t.parsedJson=[...t.parsedJson,i]);}if(t._isInJson)try{let a=t._jsonParser.add(r);t._currentContent.content=a,t._jsonParser.state==="END"&&(t._isInJson=!1,t._currentContent=void 0);}catch(a){if(console.log("handleIncrementalMixedJsonParsing: content chunk",e),console.log("handleIncrementalMixedJsonParsing: accumulated content",t.content),console.warn("handleIncrementalMixedJsonParsing: JSON parse error, recovering as text",a),t._isInJson=false,t._jsonParser=void 0,t.parsedJson&&t.parsedJson.length>0){let i=t.parsedJson[t.parsedJson.length-1];if(i.type==="json"){let c=t.content.lastIndexOf("{"),l=t.content.slice(c);i.type="text",i.content=l,t._currentContent=i;}}continue}else t._currentContent||(t._currentContent={content:t._charBuffer||"",type:"text"},t.parsedJson=[...t.parsedJson,t._currentContent]),t._currentContent.content+=t._charBuffer+r;t._charBuffer="";}return {...t}}function Yl(t,e){return Uo(t,e)}function Bo(t,e){return Uo(t,e)}function pr(t,e){let n=U(t);switch(n){case "message":return dt(t,e);case "message_content":return hn(t,e);case "step":return tc(t,e);case "output":return ec(t,e);case "output_content":return nc(t,e);case "invocation":return Ie(t,e);case "result_handler":return rc(t,e);default:throw new Error(`Unable to add update entity for entity type ${n}`)}}function Xl(t,e){for(let n of e)t=pr(t,n);return t}function dt(t,e){let n=mr(t);if(!n)throw new Error("Unable to find message to add content to");let o=U(e),r=null;switch(o){case "message_content":if(r=e,!n.contentsByID[r.id])n.contentIDToIdx={...n.contentIDToIdx,[r.id]:n.contents.length},n.contents=[...n.contents,r];else {let i=n.contentIDToIdx[r.id];n.contents=[...n.contents.slice(0,i),r,...n.contents.slice(i+1)];}return n.contentsByID={...n.contentsByID,[r.id]:r},{...n};case "invocation":let s=e;if(n.contents.length===0)throw new Error("Unable to find message content to add invocation to");return r=hn(n.contents[0],s),dt(n,r);case "step":if(n.contents.length===0)throw new Error("Unable to find message content to add content to");if(r=n.contents[0],!r)throw new Error("Unable to find message content to add content to");let a=fr(r);if(!a)throw new Error("Unable to find bot invocation to add content to");return r.botInvocation=Ie(a,e),dt(n,r);case "status":if(n.contents.length>0){let i=n.contents[0];if(i?.botInvocation){let c=hn(i,e);return dt(n,c)}}return {...n};default:throw new Error(`Unable to add update message child for child type ${o}`)}}function hn(t,e){let n=le(t);if(!n)throw new Error("Unable to find message content to add content to");let o=U(e);switch(o){case "invocation":return n.botInvocation=e,{...n};case "step":let r=n.botInvocation;if(!r)throw new Error("Unable to find bot invocation to add content to");return n.botInvocation=Ie(r,e),{...n};case "status":return n.botInvocation&&(n.botInvocation=Ie(n.botInvocation,e)),{...n};default:throw new Error(`Unable to add update message content child for child type ${o}`)}}function tc(t,e){let n=Vo(t);if(!n)throw new Error("Unable to find bot invocation to add step to");let o=U(e),r=null;switch(o){case "output":let s=e;return r=gr(s),n.eventsByID={...n.eventsByID,[s.output.id]:r},{...n};case "message":let a=e;return r=Hl(a),n.eventsByID={...n.eventsByID,[a.message.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID={...n.eventsByID,[i.id]:r},{...n};case "result_handler":let c=e;return r=Kl(c),n.eventsByID={...n.eventsByID,[c.id]:r},{...n};default:throw new Error(`Unable to add update step for entity type ${o}`)}}function ec(t,e){let n=xn(t);if(!n)throw new Error("Unable to find step output to add content to");let o=U(e);switch(o){case "output_content":let r=e;if(!n.contentsByID[r.id])n.contentIDToIdx={...n.contentIDToIdx,[r.id]:n.contents.length},n.contents=[...n.contents,r];else {let s=n.contentIDToIdx[r.id];n.contents=[...n.contents.slice(0,s),r,...n.contents.slice(s+1)];}return n.contentsByID={...n.contentsByID,[r.id]:r},{...n};default:throw new Error(`Unable to add update output for entity type ${o}`)}}function nc(t,e){let n=ce(t);if(!n)throw new Error("Unable to find step output content to add content to");let o=U(e);switch(o){case "invocation":return n.botInvocation=e,{...n};case "step":let r=n.botInvocation;if(!r)throw new Error("Unable to find bot invocation to add content to");return n.botInvocation=Ie(r,e),{...n};default:throw new Error(`Unable to add update step output content for entity type ${o}`)}}function Ie(t,e){let n=fr(t);if(!n)throw new Error("Unable to find bot invocation to add content to");let o=U(e),r;switch(o){case "step":let s=e;return r=Lo(s),n.eventsByID={...n.eventsByID,[s.id]:r},{...n};case "output":let a=e;return r=gr(a),n.eventsByID={...n.eventsByID,[a.output.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID={...n.eventsByID,[i.id]:r},n.currentStatus=i,{...n};default:throw new Error(`Unable to add update invocation for entity type ${o}`)}}function rc(t,e){let n=Mo(t);if(!n)throw new Error("Unable to find result handler to add content to");let o=U(e),r=null;switch(o){case "step":let s=e;return r=Lo(s),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[s.id]:r},{...n};case "output":let a=e;return r=gr(a),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[a.output.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[i.id]:r},{...n};default:throw new Error(`Unable to add update to result handler for entity type ${o}`)}}function oc(t){return t==="bot started"||t==="bot resumed"||t==="message created"||t==="create message content"||t==="message content result"||t==="step started"||t==="result handler started"||t==="state created"||t==="step output created"||t==="create step output content"||t==="step output content result"||t==="log"}function kn(t,e,n,o,r,s=null,a=[],i={}){if(!s&&Object.keys(r).length>0){let p,d;if(n.length>=2&&n[0]==="message"?(d=n[1],p=r[d],p||(p=Object.values(r)[0],d=Object.keys(r)[0])):(p=Object.values(r)[Object.values(r).length-1],d=Object.keys(r)[Object.keys(r).length-1]),i.message=d,n.length<=2&&t==="message finished")return r[d]=Ao(p),null;if(n[0]!=="content"&&Object.keys(p.contentsByID).length>0&&e.metadata.message_content_id){let m=e.metadata.message_content_id,x=p.contentsByID[m];x&&(s=x);}s?a=[p]:s=p;}if(n.length<=2&&oc(t)){let p=n[1],d=[],m,x,y,k,f;switch(t){case "bot started":case "bot resumed":if(!s)throw new Error("Unable to find message to add content to");let g=zl(e);if(s._type==="message_content"){if(x=s,!x.id)throw new Error("Unable to find message content id");if(y=r[x.message_id],!y)throw new Error("Unable to find message to add content to");if(k=le(y,x.id),!k)throw new Error("Unable to find message content to add content to");let v=hn(k,g);r[x.message_id]={...dt(y,v)};}d.push(g);break;case "message created":return r[p]=$o(e,o,p),null;case "create message content":if(!s)throw new Error("Unable to find message to add content to");if(f=Fl(e,i),s._type==="output"){m=s,d.push(Ro(e,p,i,"hidden"));let v=e.payload.message_id;if(v||(v=a[0].message.id),y=r[v],!y)throw new Error("Unable to find message to add content to")}else if(s._type==="message_content"){if(m=s,y=r[m.message_id],!y)throw new Error("Unable to find message to add content to")}else {if(s._type!=="message")throw new Error(`Incorrect path? Cannot add content to non-message entity: ${s._type}`);if(m=s,y=r[m.message.id],!y)throw new Error("Unable to find message to add content to");d.push(f);}r[y.message.id]={...dt(y,f)};break;case "message content result":if(!s)throw new Error("Unable to find message to add content to");let h=null;if(s._type==="output"){d.push(Po(e,p,i,"hidden"));let v=e.payload.message_id||i.message;if(v?h=a.find(T=>T.message.id===v):h=a[0],y=r[v],!y)throw new Error("Unable to find message to add content to")}else if(s._type==="message_content"){if(h=a[0],y=r[h.message.id],!y)throw new Error("Unable to find message to add content to")}else {if(s._type!=="message")throw new Error(`Incorrect path? Cannot add content to non-message entity: ${s._type}`);if(h=s,y=r[h.message.id],!y)throw new Error("Unable to find message to add content to")}let b=e.metadata.message_content_id;if(!b)throw new Error("Unable to find message content id");let S=le(h,b);if(S){S.state="completed";let v=S.content_type||"text",T=pn(v,S.content,e.payload);S.content=T.content,T.parsedJson&&(S.parsedJson=T.parsedJson),r[y.message.id]={...dt(y,S)},(s._type==="message"||s._type==="message_content")&&d.push(S);}else S=Jl(e,i),r[y.message.id]={...dt(y,S)},(s._type==="message"||s._type==="message_content")&&d.push(S);break;case "step started":d.push(Gl(e,p,i));break;case "result handler started":d.push(Wl(e,p));break;case "step output created":d.push(ql(e,p,s));break;case "create step output content":d.push(Ro(e,p,i));break;case "step output content result":d.push(Po(e,p,i));break;case "log":return null;default:throw new Error(`Unable to handle create event type ${t}`)}return d.length?!s||s._type==="message_content"&&d.length===1&&d[0]._type==="message_content"?d[0]:Xl(s,d):null}if(!s)throw new Error("No first message has been created, so cannot handle amend events");if(n.length<=1){let p=null;try{p=Ul(s);}catch{}switch(t){case "message content delta":if(!p)throw new Error("Unable to find message content");let d=null,m=null,x=null;if(s._type==="output_content"){d=Bo(s,e.payload);let g=e.metadata.message_content_id;if(!g)throw new Error("Unable to find message content id from entity ids");let h=i.message;if(x=a.find(b=>b.message.id===h),!x)throw new Error("Unable to find message to add content to");m=le(x,g);}else {if(m=p,x=a[a.length-1],!x)throw new Error("Unable to find message to add content to");if(x._type!=="message")throw new Error("Unable to find message to add content to - not a message")}if(!m)throw new Error("Unable to find message content");let y=r[x.message.id];if(!y)throw new Error("Unable to find message to add content to");let k=Yl(m,e.payload);return r[y.message.id]={...dt(y,k)},s._type==="message_content"&&(d=k),d;case "step output content delta":return Bo(p,e.payload);case "status":if(s._type==="step"&&(s.currentStatus=we(e)),s._type==="invocation"&&(s.currentStatus=we(e)),s._type==="message_content"){let f=s;if(f.botInvocation)return f.botInvocation.currentStatus=we(e),{...f}}if(s._type==="message"){let f=s,g=Oo(f);if(g?.botInvocation)return g.botInvocation.currentStatus=we(e),dt(f,g)}return pr(s,we(e));case "result":return null;case "message finished":if(s._type==="message"){let g=Ao(s);r[g.message.id]=g;}return null;case "step output finished":return null;case "step result":return null;case "error":return null;case "dataset created":return null;case "log":return null;default:throw new Error(`Unable to handle event type ${t}`)}}let c=n.slice(2),l=jl(s,n,i),u=kn(t,e,c,o,r,l,[...a,s],i);return u?pr(s,{...u}):s}function hr(t){if(!t.content)return null;if(typeof t.content=="object")return t.content;if(typeof t.content=="string"){let e=$(t.content);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}return null}function jo(t){let e=t.content_type;if(e==="tool_result")return "result";if(e==="tool_invocation")return "invocation";let n=hr(t);return n&&"action_type"in n&&"name"in n&&"input"in n&&n.action_type!=="bot.invoke"?"result"in n?"result":"invocation":null}function Fo(t){return hr(t)?.id}function Jo(t){let e=hr(t);if(!e?.action_type)return null;let o=e.input?.query;return `${e.action_type}:${o||""}`}function Go(t){let e=t.filter(r=>jo(r)==="result"),n=new Set(e.map(r=>Fo(r)).filter(Boolean)),o=new Set(e.map(r=>Jo(r)).filter(Boolean));return t.filter(r=>{if(jo(r)==="invocation"){let s=Fo(r),a=Jo(r);if(s&&n.has(s)||a&&o.has(a))return false}return true})}function Wo(t,e,n){let o=e;for(;o;){if(o===n)return true;o=t.byStepId[o]?.parentId??null;}return false}function bn(t,e){if(!e||!t.byStepId[e])return t;let n=new Set;for(let i of t.nodes)i.kind==="step"&&Wo(t,i.id,e)&&n.add(i.id);let o=t.nodes.filter(i=>i.kind==="step"?n.has(i.id):i.kind==="content"||i.kind==="status"?!!i.stepId&&n.has(i.stepId):false),r={},s={},a={};for(let i of n){let c=t.byStepId[i];c&&(r[i]=c);}for(let i of o){if(i.kind==="content"){s[i.id]=i;continue}if(i.kind!=="step")continue;let l=(i.parentId&&n.has(i.parentId)?i.parentId:null)??"__root__";a[l]=[...a[l]||[],i.id];}return {...t,nodes:o,byStepId:r,byContentId:s,childrenByParentId:a,rootStepId:e}}function Ne(){return zustand.createStore((t,e)=>({globalState:fn(),invocationStates:{},invocationRootSteps:{},pendingInvocationQueue:[],pushEvent:(n,o)=>{let r=e(),s=ur(r.globalState,n);if(o&&(s=o(s)),s===r.globalState)return;let a=n.metadata?.step_id??n.payload?.step_id??"",i={...r.invocationStates},c=false;for(let[l,u]of Object.entries(r.invocationRootSteps)){let p=r.invocationStates[l];if(a&&!Wo(s,a,u)&&a)continue;let d=bn(s,u);if(!(n.type==="step_finished"||n.type==="step_started"||n.type==="status")&&p&&p.nodes.length===d.nodes.length){let x=p.nodes[p.nodes.length-1],y=d.nodes[d.nodes.length-1];if(x===y&&p.isStreaming===d.isStreaming)continue}i[l]=d,c=true;}t({globalState:s,...c?{invocationStates:i}:{}});},registerInvocation:n=>{let o=e();o.invocationRootSteps[n]||o.pendingInvocationQueue.includes(n)||t({pendingInvocationQueue:[...o.pendingInvocationQueue,n]});},mapInvocationRoot:(n,o)=>{let r=e(),s=bn(r.globalState,o);t({invocationRootSteps:{...r.invocationRootSteps,[n]:o},invocationStates:{...r.invocationStates,[n]:s},pendingInvocationQueue:r.pendingInvocationQueue.filter(a=>a!==n)});},reset:()=>{t({globalState:fn(),invocationStates:{},invocationRootSteps:{},pendingInvocationQueue:[]});}}))}function lc(t){return t.split("/").filter(Boolean)}function qo(t={}){let e=Ct(),[n,o]=gt.useState(null),[r,s]=gt.useState(false),[a,i]=gt.useState(null),[c,l]=gt.useState([]),u=gt.useRef(Ne()),p=zustand.useStore(u.current,g=>g.globalState),d=gt.useRef(null),m=gt.useRef(t.threadId);t.threadId!==m.current&&(m.current=t.threadId);let x=gt.useCallback(()=>{d.current&&(d.current.abort(),d.current=null);},[]),y=gt.useCallback(g=>{o(g),m.current=g.id;},[]),k=gt.useCallback(async g=>{if(!e.client)throw new Error("ErdoClient not configured in provider. Pass a client to ErdoProvider config to use useThread.");if(!e.client.sendMessage)throw new Error("ErdoClient does not support sendMessage. Make sure you are using @erdoai/server client.");if(!e.client.createThread)throw new Error("ErdoClient does not support createThread. Make sure you are using @erdoai/server client.");x(),d.current=new AbortController,s(true),i(null),l([]),u.current.getState().reset();let h={};try{let b=m.current;if(!b){let E=await e.client.createThread();o(E),m.current=E.id,b=E.id;}for await(let E of e.client.sendMessage(b,{content:g,botKey:t.botKey})){if(d.current?.signal.aborted)break;if(t.onEvent?.(E),e.useAgentEvents)u.current.getState().pushEvent(E);else {let z=E.type||"",Q=E.metadata||{},R=lc(Q.path||""),j={payload:E.payload,metadata:{path:Q.path||"",...Q}};try{kn(z,j,R,b,h);}catch(F){console.error("Error handling SSE event:",F,z);}l(Object.values(h));}}let S=Object.values(h);l(S);let v=u.current.getState().globalState,T;v.rootStepId?T=ve(v):T=S.flatMap(E=>E.contents||[]).filter(E=>E.user_visibility==="visible").map(E=>({id:E.id,content_type:E.content_type,ui_content_type:P(E.ui_content_type),content:E.content,parsedJson:E.parsedJson,botInvocation:E.botInvocation})),t.onFinish?.(T);}catch(b){let S=b instanceof Error?b:new Error(String(b));throw i(S),t.onError?.(S),S}finally{s(false),d.current=null;}},[e.client,e.useAgentEvents,t,x]),f=gt.useMemo(()=>{if(p.rootStepId)return ve(p);let g=c.flatMap(b=>b.contents||[]).filter(b=>b.user_visibility==="visible");return Go(g).map(b=>({id:b.id,content_type:b.content_type,ui_content_type:P(b.ui_content_type),content:b.content,parsedJson:b.parsedJson,botInvocation:b.botInvocation}))},[c,p]);return {thread:n,isStreaming:r,error:a,activeMessages:c,agentState:p,streamingContents:f,sendMessage:k,cancel:x,setThread:y,agentStreamStore:u.current}}function cc(t){return t?typeof t=="string"?t:typeof t=="object"&&t!==null&&"String"in t&&t.String||"":""}function zo(t){let e=cc(t.ui_content_type),n=t.content_type,o={id:t.id,content_type:t.content_type,ui_content_type:e,content:t.content,invocation_id:t.created_by_invocation_id};if(typeof t.content=="string"){if((n==="json"||e==="json")&&t.content.trim()){let r=$(t.content);r!=null&&(o.parsedJson=[{type:"json",content:r}]);}else if(e==="ui_generation")try{o.parsedJson=ft(t.content);}catch(r){console.error("Error parsing UI generation content:",r);}}if((t.content_type==="thinking"||t.content_type==="redacted_thinking")&&typeof t.content=="string"){let r=$(t.content);r&&typeof r=="object"&&(o.content=r);}return o}function uc(t){return t.filter(e=>e.user_visibility!=="hidden").map(zo)}var Sn=gt.createContext(null);function Ko({store:t,children:e}){return jsxRuntime.jsx(Sn.Provider,{value:t,children:e})}function Qo(){return gt.useContext(Sn)}function Zo(t){let e=gt.useContext(Sn);return zustand.useStore(e,n=>t?n.invocationStates[t]:void 0)}function Yo(){let t=gt.useContext(Sn);return zustand.useStore(t,e=>e.globalState)}exports.AgentStreamStoreProvider=Ko;exports.BarChart=wt;exports.BotInvocationContent=an;exports.Chart=it;exports.ChartContainer=de;exports.ChartContent=Ge;exports.ChartLegend=Tn;exports.ChartLegendContent=Dn;exports.ChartNode=qn;exports.ChartStyle=wr;exports.ChartTooltip=Nn;exports.ChartTooltipContent=En;exports.CodeexecContent=sn;exports.CodegenContent=rn;exports.CollapsibleCodeBlock=xt;exports.Content=Mt;exports.DatasetChart=Me;exports.DatasetDownload=Kt;exports.DatasetTable=Ve;exports.DownloadButtonNode=Kn;exports.ErdoProvider=Sr;exports.ErdoUI=dl;exports.ErrorBoundary=St;exports.ExecutionStatus=Ln;exports.ExpandableOutputContent=kt;exports.FileDownloadsNode=Zn;exports.HeatmapChart=Gt;exports.InvocationEvent=Fe;exports.InvocationEvents=Tt;exports.InvocationStatus=qr;exports.JSONStreamParser=X;exports.JsonContent=zt;exports.LineChart=jt;exports.Loader=_o;exports.Log=Xn;exports.LogContent=Ke;exports.MarkdownContent=B;exports.MemoryContent=un;exports.Output=$e;exports.PieChart=Ft;exports.ScatterChart=Jt;exports.SqlContent=Xe;exports.StatusSpinner=rt;exports.StderrText=te;exports.StdoutText=Xt;exports.StdwarnText=en;exports.StepInvocation=je;exports.StepInvocationStatus=Ue;exports.StepTreeContent=Do;exports.SuggestionsNode=Qn;exports.TableContent=We;exports.TableNode=zn;exports.TextContent=ye;exports.TextMarkdownNode=Hn;exports.ThinkingContent=He;exports.ToolGroupContent=ne;exports.UIGenerationNodes=qe;exports.WebParseContent=Ze;exports.WebSearchContent=Qe;exports.WritingLoader=ar;exports.agentStateToContents=ve;exports.cn=K;exports.completeStreamingContent=wo;exports.createAgentStreamStore=Ne;exports.createInitialAgentState=fn;exports.extractContentItems=vo;exports.formatValue=at;exports.handleAgentEvent=ur;exports.handleIncrementalMixedJsonParsing=ir;exports.handleSSEEvent=kn;exports.hasRenderableAssistantOutput=Nl;exports.isJsonLike=ge;exports.isNullString=Ur;exports.isParsingComplete=Ta;exports.isParsingInProgress=he;exports.isWhitespaceChar=Dt;exports.nodeComponents=Yn;exports.normalizeContent=zo;exports.normalizeContents=uc;exports.normalizeUIGenerationChunks=Se;exports.normalizeUINodes=Jn;exports.parseCompleteJson=$;exports.parseMixedJson=ft;exports.parseToDate=Ir;exports.resolveKeyFromData=qt;exports.sliceAgentStateToRoot=bn;exports.toSnakeCase=Mr;exports.unwrapNullString=P;exports.unwrapNullStringOr=ra;exports.useAgentStreamGlobalState=Yo;exports.useAgentStreamStoreOptional=Qo;exports.useChartZoom=Ae;exports.useDatasetContents=Pe;exports.useErdoConfig=Ct;exports.useErdoConfigOptional=q;exports.useInvocationState=Zo;exports.useMultipleDatasetContents=Or;exports.useMultipleDatasetRequests=me;exports.useThread=qo;
51
+ `),wrapperType:Ml(o)}),s++,r=[]);}for(let i of t){let c=typeof i.message=="string"?i.message:"";if(!c)continue;let l=typeof i.level=="string"?i.level:"output";l!==o&&r.length>0&&a(),o=l,r.push(c);}return a(),n}function Eo(t,e,n){let o=[];for(let r of t){if(r.contentType==="tool_invocation"||r.contentType==="tool_result")continue;let s=`${e}-content-${r.id}`,a=r.state==="streaming"?"running":"completed";if(r.contentType==="thinking"||r.contentType==="redacted_thinking"){let i=r.result??r.text;if(!i)continue;o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType||r.contentType,content:i,state:r.state==="streaming"?"in_progress":"completed"},status:a});continue}if(r.result){let i=r.result;if(typeof r.result=="string")if(r.contentType==="json"){let c=$(r.result);if(c!=null)i=c;else {let l=Vl(r.result);if(l!==null)i=l;else if(!(r.parsedContent&&r.parsedContent.length>0))if(n){o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType||"ui_generation",content:r.result,state:r.state==="streaming"?"in_progress":"completed"}});continue}else {o.push({id:s,type:"text",content:r.result});continue}}}else {o.push({id:s,type:"text",content:r.result});continue}if(Array.isArray(i)&&i.length>0){o.push(...No(i,s));continue}if(typeof i=="object"&&i!==null){let c=i;if(typeof c.code=="string"){o.push({id:s,type:"codegen",contentData:c,status:a});continue}if(n){o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType,content:i,state:r.state==="streaming"?"in_progress":"completed"}});continue}}}if(r.contentType==="json"&&r.parsedContent){if(r.uiContentType==="codeexec_output"){let i=[];for(let c of r.parsedContent)c.type==="json"&&typeof c.content=="object"&&i.push(c.content);o.push(...No(i,s));continue}for(let i=0;i<r.parsedContent.length;i++){let c=r.parsedContent[i];if(c.type==="text"&&c.content)o.push({id:`${s}-text-${i}`,type:"text",content:String(c.content)});else if(c.type==="json"&&typeof c.content=="object"){let l=c.content;typeof l.code=="string"?o.push({id:`${s}-codegen-${i}`,type:"codegen",contentData:l,status:a}):typeof l.markdown=="string"?o.push({id:`${s}-text-${i}`,type:"text",content:l.markdown}):typeof l.output=="string"?o.push({id:`${s}-text-${i}`,type:"text",content:l.output}):n&&o.push({id:`${s}-content-${i}`,type:"content",contentItem:{id:`${s}-content-${i}`,content_type:"json",ui_content_type:r.uiContentType||"ui_generation",content:l,state:r.state==="streaming"?"in_progress":"completed"}});}}continue}r.text&&r.contentType!=="json"&&o.push({id:s,type:"text",content:r.text});}return o}function $l(t,e){if(!t.rootStepId)return [];let n=[],o={},r={},s=new Set,a={},i={},c={};function l(f){return r[f]||(r[f]=[]),r[f]}function u(f){if(f)return t.byStepId[f]}function p(f){if(!f)return false;if(f in c)return c[f];let g=f,h=[],b=false;for(;g;){if(g in c){b=b||c[g];break}h.push(g);let S=u(g);if(!S)break;if(S.hidden){b=true;break}g=S.parentId;}for(let S of h)c[S]=b;return b}function d(f){return p(f.id)}for(let f of t.nodes){if(f.kind!=="content"||!f.stepId||f.contentType==="tool_invocation"||f.contentType==="tool_result"||f.contentType==="agent_invocation"||!f.text&&!f.result&&!f.parsedContent?.length)continue;let g=u(f.stepId);if(!g||d(g)||g.type==="llm_call"&&gn(t,g,f))continue;let h=f.stepId;for(;h;){i[h]=true;let b=u(h);if(!b)break;h=b.parentId;}}function m(f){return !!i[f]}function x(f){if(!f)return null;if(f in a)return a[f];let g=f;for(;g;){let h=u(g);if(!h)break;let b=g===t.rootStepId,S=h.type==="agent"&&!h.hidden&&(!b||!Io(t,h.id)),v=h.type==="tool_call"&&!h.hidden;if(S||v)return a[f]=g,g;g=h.parentId;}return a[f]=null,null}function y(f,g){if(g.length===0)return;let h=x(f);if(!h){n.push(...g);return}let b=o[h];if(!b){l(h).push(...g);return}b.children||(b.children=[]),b.children.push(...g);}function k(f,g,h){if(!h||typeof h!="object")return [];let b=h,S=typeof b.result=="object"&&b.result!==null?b.result:b,v=[];typeof S.code=="string"&&S.code.trim()&&v.push({id:`${f}-${g}-codegen`,type:"codegen",contentData:S});let T=typeof S.output=="string"?S.output.trim():"";return T&&v.push({id:`${f}-${g}-output`,type:"codeexec",content:T}),v}for(let f of t.nodes){if(f.kind==="step"){let h=t.byStepId[f.id];if(!h||h.hidden||h.type==="llm_call"||h.id===t.rootStepId&&Io(t,h.id)||s.has(h.id))continue;s.add(h.id);let b={id:h.id,type:"step",label:Bl(h),status:h.status},S=r[h.id];S&&S.length>0&&(b.children=S,delete r[h.id]),o[h.id]=b,y(h.parentId,[b]);continue}if(f.kind!=="content"||f.contentType==="tool_invocation")continue;if(f.stepId===null){n.push(...Eo([f],"root",e));continue}let g=t.byStepId[f.stepId];if(g&&!d(g)&&!(g.type==="llm_call"&&gn(t,g,f))){if(g.type==="tool_call"&&f.contentType==="tool_result"){if(m(g.id))continue;y(g.id,k(g.id,f.id,f.result));continue}y(g.id,Eo([f],g.id,e));}}return n}function To({node:t,ContentComponent:e}){let[n,o]=gt.useState(t.status==="running"),r=gt.useRef(t.status==="running");if(gt.useEffect(()=>{r.current&&t.status!=="running"&&o(false),r.current=t.status==="running";},[t.status]),t.type==="text")return jsxRuntime.jsx(B,{content:t.content||"",className:"max-w-none"});if(t.type==="codegen"&&t.contentData){let{code:i,step_by_step:c,thinking:l}=t.contentData;return jsxRuntime.jsxs("div",{className:"space-y-2",children:[c&&jsxRuntime.jsx(B,{content:c,className:"text-sm max-w-none"}),l&&jsxRuntime.jsx(Ce,{content:l,state:t.status==="running"?"in_progress":"completed"}),i&&jsxRuntime.jsx(xt,{language:"python",value:i,defaultOpen:false})]})}if(t.type==="codeexec"&&t.content){let i=t.wrapperType||"standard";return jsxRuntime.jsx(kt,{wrapperType:i,compact:true,children:jsxRuntime.jsx(Xt,{children:t.content})})}if(t.type==="content"&&t.contentItem&&e)return jsxRuntime.jsx(e,{content:t.contentItem});if(t.type==="content"&&t.contentItem)return jsxRuntime.jsx(Mt,{content:t.contentItem});let s=!!t.children?.length,a=t.status==="running"?"text-foreground":"text-muted-foreground";return jsxRuntime.jsxs(ee__namespace.Root,{open:n,onOpenChange:o,className:"w-full",children:[jsxRuntime.jsxs(ee__namespace.Trigger,{className:`flex items-center justify-between w-full text-sm py-0.5 ${a} ${s?"hover:text-foreground cursor-pointer":"cursor-default"}`,disabled:!s,children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(rt,{status:Ol(t.status),size:14}),jsxRuntime.jsx("span",{children:t.label})]}),s&&jsxRuntime.jsx(lucideReact.ChevronDown,{className:`h-4 w-4 shrink-0 text-muted-foreground/50 transition-transform duration-200 ${n?"rotate-180":""}`})]}),s&&jsxRuntime.jsx(ee__namespace.Content,{children:jsxRuntime.jsx("div",{className:"ml-5 mt-1 flex flex-col gap-1",children:t.children?.map(i=>jsxRuntime.jsx(To,{node:i,ContentComponent:e},i.id))})})]})}function Do({agentState:t,ContentComponent:e,className:n}){if(!t.rootStepId)return null;let o=gt.useMemo(()=>$l(t,e),[t,e]);return o.length===0?null:jsxRuntime.jsx("div",{className:`flex flex-col gap-1 ${n||""}`,children:o.map(r=>jsxRuntime.jsx(To,{node:r,ContentComponent:e},r.id))})}function U(t){if(!t)throw new Error("Entity is null");if(!("_type"in t))throw new Error(`Entity ${JSON.stringify(t)} is missing _type`);return t._type}function Ll(t){return t.contents.length===0?null:t.contents[t.contents.length-1]||null}function Oo(t){return t.contents.length===0?null:t.contents[0]||null}function Ao(t){let e=false,n=t.contents.map(r=>r.state!=="in_progress"?r:(e=true,{...r,state:"completed",updated_at:new Date().toISOString()}));if(!e&&t.state==="completed")return t;let o={...t.contentsByID};for(let r of n)o[r.id]=r;return {...t,state:"completed",contents:n,contentsByID:o}}function mr(t,e){let n=U(t);switch(n){case "message":return t;case "step":let o=t;if(e){let a=o.eventsByID[e]?.Message;return a||$o({},"",e)}let s=Object.keys(o.eventsByID).reverse();for(let a of s){let i=o.eventsByID[a];if(i&&i.Message)return i.Message}throw new Error("Unable to find message for step");default:throw new Error(`Unable to have messages on entity type ${n}`)}}function Ul(t,e){switch(U(t)){case "message_content":return t;case "output_content":return t;case "message":return le(t,e);case "output":return ce(t,e);case "step":let o=xn(t,e);return o?ce(o,e):null;default:return null}}function le(t,e){let n=U(t);switch(n){case "message_content":return t;case "message":let o=mr(t);if(!o)throw new Error("Unable to find message to add content to");return e?o.contentsByID[e]:Ll(o);default:throw new Error(`Unable to have message content on entity type ${n}`)}}function ce(t,e){let n=U(t);switch(n){case "output_content":return t;case "output":let o=t;return e?o.contentsByID[e]||null:o.contents.length<=0?null:o.contents[o.contents.length-1]||null;case "step":let s=xn(t,e);return s?ce(s):null;case "invocation":if(!e)return null;let a=t.eventsByID[e];return !a||!a.Output?null:ce(a.Output);default:throw new Error(`Unable to have output content on entity type ${n}`)}}function fr(t,e){let n=U(t),o=null;switch(n){case "invocation":return t;case "message_content":if(o=t.botInvocation||null,!o)throw new Error("Unable to find bot invocation for message content");if(e&&o.bot_invocation.id!==e)throw new Error("Unable to find bot invocation for message content - mismatched ID");return o;case "message":if(o=Oo(t)?.botInvocation||null,!o)throw new Error("Unable to find bot invocation for message");if(e&&o.bot_invocation.id!==e)throw new Error("Unable to find bot invocation for message - mismatched ID");return o;case "output_content":return t.botInvocation||null;default:throw new Error(`Unable to have bot invocation on entity type ${n}`)}}function xn(t,e){let n=U(t);switch(n){case "output":return t;case "step":let o=t;if(e){let i=o.eventsByID[e]?.Output;if(!i)throw new Error("Unable to find output with id "+e);return i}let s=Object.keys(o.eventsByID).reverse();for(let i of s){let c=o.eventsByID[i];if(c&&c.Output)return c.Output}throw new Error("Unable to find output for step");case "invocation":if(!e)throw new Error("Unable to find output for invocation without ID");return t.eventsByID[e]?.Output||null;default:throw new Error(`Unable to have step outputs on entity type ${n}`)}}function Mo(t,e){let n=U(t);switch(n){case "result_handler":return t;case "step":if(!e)throw new Error("Unable to have result handlers on step without ID");let o=t.eventsByID[e];if(!o||!o.type||o.type!=="result_handler"||!o.ResultHandler)throw new Error(`Unable to find result handler with id ${e} on step ${t.id}`);return o.ResultHandler;default:throw new Error(`Unable to have result handlers on entity type ${n}`)}}function Vo(t,e){let n=U(t),o=null;switch(n){case "step":if(t.id===e||!e)return t;throw new Error("Unable to find step on step with id "+e);case "invocation":if(!e)throw new Error("Unable to have steps on bot invocation without ID");o=t;let r=o.eventsByID[e];if(!r)throw new Error("Unable to find step on invocation with id "+e);if(!r.Step)throw new Error("Unable to find step on invocation with id "+e);return r.Step;case "result_handler":if(!e)throw new Error("Unable to have steps on result handler without ID");let a=t.eventsByID[e];if(!a)throw new Error("Unable to find step on result handler with id "+e);if(!a.Step)throw new Error("Unable to find step on result handler with id "+e);return a.Step;default:throw new Error(`Unable to have steps on entity type ${n}`)}}var dr=class extends Error{};function jl(t,e,n){let o=null,r=e[0],s=e[1];n[r]=s;try{switch(r){case "message":o=mr(t,s);break;case "content":o=le(t,s);break;case "step":o=Vo(t,s);break;case "output":o=xn(t,s);break;case "output_content":o=ce(t,s);break;case "invocation":o=fr(t,s);break;case "result_handler":o=Mo(t,s);break}}catch(a){throw console.error("error finding next entity"),console.log("path",e),console.log("currentEntity",t),a}if(!o)throw console.log("path",e),console.log("currentEntity",t),console.log("nextEntity",o),new dr(`Unable to find next entity for path ${e.join("/")}`);return o}function $o(t,e,n,o){let r=t.payload;return {_type:"message",message:{id:n,thread_id:e,author_id:r.author_id||"app",author_entity_type:r.author_entity_type||"app",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),role:r.role||"assistant",avatar:"/teams/erdo-icon.png"},state:"in_progress",contents:[],contentsByID:{},contentIDToIdx:{}}}function Fl(t,e){return {_type:"message_content",id:t.metadata.message_content_id,message_id:e.message,content_type:t.metadata.content_type,created_by_invocation_id:t.metadata.invocation_id,invocation_id:t.metadata.invocation_id,state:"in_progress",user_visibility:t.metadata.user_visibility??"visible",bot_visibility:t.metadata.bot_visibility??"visible",content:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:t.metadata?.ui_content_type?{String:t.metadata.ui_content_type,Valid:true}:{String:"",Valid:false}}}function Jl(t,e){let n=t.metadata.content_type||"text",o=t.metadata?.ui_content_type,r=ae(n,t.payload);return {_type:"message_content",id:t.metadata.message_content_id,message_id:e.message,content:r.content,content_type:n,created_by_invocation_id:t.metadata.invocation_id,invocation_id:t.metadata.invocation_id,state:"completed",user_visibility:t.metadata.visibility||"visible",bot_visibility:"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:o?{String:o,Valid:true}:{String:"",Valid:false},parsedJson:r.parsedJson??null}}function Gl(t,e,n){let o=t.payload;return {_type:"step",id:e,invocation_id:n.invocation||"",step_id:o.step_id||"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_status_id:"",path:{String:"",Valid:false},action_type:{String:o.action_type,Valid:true},key:{String:o.key,Valid:true},bot_id:o.bot_id,result_handler_id:"",step_order:{Int32:o.step_order,Valid:true},output_content_type:{String:o.content_type,Valid:true},execution_mode:{String:o.execution_mode,Valid:true},output_behaviour:{String:o.output_behaviour,Valid:true},user_output_visibility:{String:t.metadata.visibility||"visible",Valid:true},output_channels:o.output_channels||[],running_message:{String:o.running_message||"",Valid:!!o.running_message},finished_message:{String:o.finished_message||"",Valid:!!o.finished_message},depends_on:[],eventsByID:{},currentStatus:null}}function Wl(t,e,n){let o=t.payload;return {_type:"result_handler",id:e,invocation_id:t.metadata.invocation_id||"",result_handler_id:o.result_handler_id||e,step_invocation_id:o.step_invocation_id||"",type:o.type||"",if_conditions:o.if_conditions||{},created_at:new Date().toISOString(),updated_at:new Date().toISOString(),output_content_type:o.output_content_type||"",result_handler_order:o.result_handler_order||0,eventsByID:{}}}function ql(t,e,n){return {_type:"output",id:e,step_id:n.step_id,output:{id:e,invocation_id:t.metadata?.invocation_id,path:t.metadata.path,created_at:new Date().toISOString(),updated_at:new Date().toISOString()},state:"in_progress",contents:[],contentsByID:{},contentIDToIdx:{}}}function Ro(t,e,n,o=null){return {_type:"output_content",id:e,output_id:n.output,content:"",content_type:t.metadata.content_type,state:"in_progress",invocation_id:t.metadata.invocation_id,user_visibility:o??t.metadata.user_visibility??"visible",bot_visibility:t.metadata.bot_visibility??"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:t.metadata.ui_content_type?{String:t.metadata.ui_content_type,Valid:true}:{String:"",Valid:false},output:null}}function Po(t,e,n,o=null){let r=t.metadata.content_type||"text",s=ae(r,t.payload),a=t.metadata?.ui_content_type;return {_type:"output_content",id:e,output_id:n.output,content:s.content,content_type:r,state:"completed",invocation_id:t.metadata.invocation_id,parsedJson:s.parsedJson??null,user_visibility:o||t.metadata.visibility||"visible",bot_visibility:"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:a?{String:a,Valid:true}:{String:"",Valid:false},output:null}}function zl(t,e,n){return {_type:"invocation",bot_invocation:{id:t.payload.invocation_id,bot_id:t.payload.bot_id,bot_name:t.payload.bot_name,created_by_user_id:t.payload.created_by_user_id,current_state_id:"",parent_invocation_id:"",branch_init_state_id:"",current_status_id:"",organization_id:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},eventsByID:{},currentStatus:null,current_status:null,step_invocations:[],step_invocation_states:[],resources:[],outputs:[],statuses:[]}}function we(t,e){let n=t.payload;return {_type:"status",id:new Date().toISOString(),status:n.status,message:{String:n.message,Valid:true},Details:n}}function Lo(t){return {id:t.id,type:"step",created_at:t.created_at,_type:"invocation_event",Output:null,Message:null,Status:null,ResultHandler:null,Step:t}}function gr(t){return {id:t.output.id,type:"output",created_at:t.output.created_at,_type:"invocation_event",Output:t,Message:null,Status:null,ResultHandler:null,Step:null}}function yr(t){return {id:t.id,type:"status",created_at:t.created_at,_type:"invocation_event",Status:t,Output:null,Message:null,ResultHandler:null,Step:null}}function Hl(t){return {id:t.message.id,type:"message",created_at:t.message.created_at,_type:"invocation_event",Output:null,Message:t,Status:null,ResultHandler:null,Step:null}}function Kl(t){return {id:t.id,type:"result_handler",created_at:t.created_at,_type:"invocation_event",Output:null,Message:null,Status:null,ResultHandler:t,Step:null}}var Ql=new Set(["=","("]);function Zl(t){if(!t||t.length===0)return true;let e=t[t.length-1];return !Ql.has(e)}function Uo(t,e){if(t.content||(t.content=""),t.user_visibility!=="visible"||!ge(t.content_type,t.ui_content_type.String))return t.content+=e,{...t};if(t.parsedJson||(t.parsedJson=[]),typeof e=="object")return t.content+=JSON.stringify(e),t.parsedJson=[...t.parsedJson,e],{...t};t._jsonParser||(t._isInJson=false),t._charBuffer||(t._charBuffer="");let n=t.content_type,o=t.ui_content_type.String;for(let r of e){t.content+=r;let s=n==="json"||o==="json";if(!t._isInJson&&s&&!Dt(r)){t._isInJson=true,t._jsonParser=new X;let a={content:{},type:"json"};t.parsedJson=[...t.parsedJson||[],a],t._currentContent=a,t._charBuffer="";}if(!t._isInJson&&!s&&o==="ui_generation"&&r==="{"){let a=t.content.slice(0,-1);if(Zl(a)){t._charBuffer="{";continue}}if(t._charBuffer&&Dt(r)){t._charBuffer+=r;continue}if(!t._isInJson&&!s&&o==="ui_generation"&&t._charBuffer?.match(/^\s*{\s*$/)&&r==='"'){t._isInJson=true,t._jsonParser=new X;let i={content:t._jsonParser.add("{"),type:"json"};t._currentContent?.content?t._currentContent.content.match(/^\s*{$/)?(t._currentContent=i,t.parsedJson=[...t.parsedJson.slice(0,-1),i]):(t._currentContent.content=t._currentContent.content.replace(/{$/,""),t._currentContent=i,t.parsedJson=[...t.parsedJson,i]):(t._currentContent=i,t.parsedJson=[...t.parsedJson,i]);}if(t._isInJson)try{let a=t._jsonParser.add(r);t._currentContent.content=a,t._jsonParser.state==="END"&&(t._isInJson=!1,t._currentContent=void 0);}catch(a){if(console.log("handleIncrementalMixedJsonParsing: content chunk",e),console.log("handleIncrementalMixedJsonParsing: accumulated content",t.content),console.warn("handleIncrementalMixedJsonParsing: JSON parse error, recovering as text",a),t._isInJson=false,t._jsonParser=void 0,t.parsedJson&&t.parsedJson.length>0){let i=t.parsedJson[t.parsedJson.length-1];if(i.type==="json"){let c=t.content.lastIndexOf("{"),l=t.content.slice(c);i.type="text",i.content=l,t._currentContent=i;}}continue}else t._currentContent||(t._currentContent={content:t._charBuffer||"",type:"text"},t.parsedJson=[...t.parsedJson,t._currentContent]),t._currentContent.content+=t._charBuffer+r;t._charBuffer="";}return {...t}}function Yl(t,e){return Uo(t,e)}function Bo(t,e){return Uo(t,e)}function pr(t,e){let n=U(t);switch(n){case "message":return dt(t,e);case "message_content":return hn(t,e);case "step":return tc(t,e);case "output":return ec(t,e);case "output_content":return nc(t,e);case "invocation":return Ie(t,e);case "result_handler":return rc(t,e);default:throw new Error(`Unable to add update entity for entity type ${n}`)}}function Xl(t,e){for(let n of e)t=pr(t,n);return t}function dt(t,e){let n=mr(t);if(!n)throw new Error("Unable to find message to add content to");let o=U(e),r=null;switch(o){case "message_content":if(r=e,!n.contentsByID[r.id])n.contentIDToIdx={...n.contentIDToIdx,[r.id]:n.contents.length},n.contents=[...n.contents,r];else {let i=n.contentIDToIdx[r.id];n.contents=[...n.contents.slice(0,i),r,...n.contents.slice(i+1)];}return n.contentsByID={...n.contentsByID,[r.id]:r},{...n};case "invocation":let s=e;if(n.contents.length===0)throw new Error("Unable to find message content to add invocation to");return r=hn(n.contents[0],s),dt(n,r);case "step":if(n.contents.length===0)throw new Error("Unable to find message content to add content to");if(r=n.contents[0],!r)throw new Error("Unable to find message content to add content to");let a=fr(r);if(!a)throw new Error("Unable to find bot invocation to add content to");return r.botInvocation=Ie(a,e),dt(n,r);case "status":if(n.contents.length>0){let i=n.contents[0];if(i?.botInvocation){let c=hn(i,e);return dt(n,c)}}return {...n};default:throw new Error(`Unable to add update message child for child type ${o}`)}}function hn(t,e){let n=le(t);if(!n)throw new Error("Unable to find message content to add content to");let o=U(e);switch(o){case "invocation":return n.botInvocation=e,{...n};case "step":let r=n.botInvocation;if(!r)throw new Error("Unable to find bot invocation to add content to");return n.botInvocation=Ie(r,e),{...n};case "status":return n.botInvocation&&(n.botInvocation=Ie(n.botInvocation,e)),{...n};default:throw new Error(`Unable to add update message content child for child type ${o}`)}}function tc(t,e){let n=Vo(t);if(!n)throw new Error("Unable to find bot invocation to add step to");let o=U(e),r=null;switch(o){case "output":let s=e;return r=gr(s),n.eventsByID={...n.eventsByID,[s.output.id]:r},{...n};case "message":let a=e;return r=Hl(a),n.eventsByID={...n.eventsByID,[a.message.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID={...n.eventsByID,[i.id]:r},{...n};case "result_handler":let c=e;return r=Kl(c),n.eventsByID={...n.eventsByID,[c.id]:r},{...n};default:throw new Error(`Unable to add update step for entity type ${o}`)}}function ec(t,e){let n=xn(t);if(!n)throw new Error("Unable to find step output to add content to");let o=U(e);switch(o){case "output_content":let r=e;if(!n.contentsByID[r.id])n.contentIDToIdx={...n.contentIDToIdx,[r.id]:n.contents.length},n.contents=[...n.contents,r];else {let s=n.contentIDToIdx[r.id];n.contents=[...n.contents.slice(0,s),r,...n.contents.slice(s+1)];}return n.contentsByID={...n.contentsByID,[r.id]:r},{...n};default:throw new Error(`Unable to add update output for entity type ${o}`)}}function nc(t,e){let n=ce(t);if(!n)throw new Error("Unable to find step output content to add content to");let o=U(e);switch(o){case "invocation":return n.botInvocation=e,{...n};case "step":let r=n.botInvocation;if(!r)throw new Error("Unable to find bot invocation to add content to");return n.botInvocation=Ie(r,e),{...n};default:throw new Error(`Unable to add update step output content for entity type ${o}`)}}function Ie(t,e){let n=fr(t);if(!n)throw new Error("Unable to find bot invocation to add content to");let o=U(e),r;switch(o){case "step":let s=e;return r=Lo(s),n.eventsByID={...n.eventsByID,[s.id]:r},{...n};case "output":let a=e;return r=gr(a),n.eventsByID={...n.eventsByID,[a.output.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID={...n.eventsByID,[i.id]:r},n.currentStatus=i,{...n};default:throw new Error(`Unable to add update invocation for entity type ${o}`)}}function rc(t,e){let n=Mo(t);if(!n)throw new Error("Unable to find result handler to add content to");let o=U(e),r=null;switch(o){case "step":let s=e;return r=Lo(s),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[s.id]:r},{...n};case "output":let a=e;return r=gr(a),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[a.output.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[i.id]:r},{...n};default:throw new Error(`Unable to add update to result handler for entity type ${o}`)}}function oc(t){return t==="bot started"||t==="bot resumed"||t==="message created"||t==="create message content"||t==="message content result"||t==="step started"||t==="result handler started"||t==="state created"||t==="step output created"||t==="create step output content"||t==="step output content result"||t==="log"}function kn(t,e,n,o,r,s=null,a=[],i={}){if(!s&&Object.keys(r).length>0){let p,d;if(n.length>=2&&n[0]==="message"?(d=n[1],p=r[d],p||(p=Object.values(r)[0],d=Object.keys(r)[0])):(p=Object.values(r)[Object.values(r).length-1],d=Object.keys(r)[Object.keys(r).length-1]),i.message=d,n.length<=2&&t==="message finished")return r[d]=Ao(p),null;if(n[0]!=="content"&&Object.keys(p.contentsByID).length>0&&e.metadata.message_content_id){let m=e.metadata.message_content_id,x=p.contentsByID[m];x&&(s=x);}s?a=[p]:s=p;}if(n.length<=2&&oc(t)){let p=n[1],d=[],m,x,y,k,f;switch(t){case "bot started":case "bot resumed":if(!s)throw new Error("Unable to find message to add content to");let g=zl(e);if(s._type==="message_content"){if(x=s,!x.id)throw new Error("Unable to find message content id");if(y=r[x.message_id],!y)throw new Error("Unable to find message to add content to");if(k=le(y,x.id),!k)throw new Error("Unable to find message content to add content to");let v=hn(k,g);r[x.message_id]={...dt(y,v)};}d.push(g);break;case "message created":return r[p]=$o(e,o,p),null;case "create message content":if(!s)throw new Error("Unable to find message to add content to");if(f=Fl(e,i),s._type==="output"){m=s,d.push(Ro(e,p,i,"hidden"));let v=e.payload.message_id;if(v||(v=a[0].message.id),y=r[v],!y)throw new Error("Unable to find message to add content to")}else if(s._type==="message_content"){if(m=s,y=r[m.message_id],!y)throw new Error("Unable to find message to add content to")}else {if(s._type!=="message")throw new Error(`Incorrect path? Cannot add content to non-message entity: ${s._type}`);if(m=s,y=r[m.message.id],!y)throw new Error("Unable to find message to add content to");d.push(f);}r[y.message.id]={...dt(y,f)};break;case "message content result":if(!s)throw new Error("Unable to find message to add content to");let h=null;if(s._type==="output"){d.push(Po(e,p,i,"hidden"));let v=e.payload.message_id||i.message;if(v?h=a.find(T=>T.message.id===v):h=a[0],y=r[v],!y)throw new Error("Unable to find message to add content to")}else if(s._type==="message_content"){if(h=a[0],y=r[h.message.id],!y)throw new Error("Unable to find message to add content to")}else {if(s._type!=="message")throw new Error(`Incorrect path? Cannot add content to non-message entity: ${s._type}`);if(h=s,y=r[h.message.id],!y)throw new Error("Unable to find message to add content to")}let b=e.metadata.message_content_id;if(!b)throw new Error("Unable to find message content id");let S=le(h,b);if(S){S.state="completed";let v=S.content_type||"text",T=pn(v,S.content,e.payload);S.content=T.content,T.parsedJson&&(S.parsedJson=T.parsedJson),r[y.message.id]={...dt(y,S)},(s._type==="message"||s._type==="message_content")&&d.push(S);}else S=Jl(e,i),r[y.message.id]={...dt(y,S)},(s._type==="message"||s._type==="message_content")&&d.push(S);break;case "step started":d.push(Gl(e,p,i));break;case "result handler started":d.push(Wl(e,p));break;case "step output created":d.push(ql(e,p,s));break;case "create step output content":d.push(Ro(e,p,i));break;case "step output content result":d.push(Po(e,p,i));break;case "log":return null;default:throw new Error(`Unable to handle create event type ${t}`)}return d.length?!s||s._type==="message_content"&&d.length===1&&d[0]._type==="message_content"?d[0]:Xl(s,d):null}if(!s)throw new Error("No first message has been created, so cannot handle amend events");if(n.length<=1){let p=null;try{p=Ul(s);}catch{}switch(t){case "message content delta":if(!p)throw new Error("Unable to find message content");let d=null,m=null,x=null;if(s._type==="output_content"){d=Bo(s,e.payload);let g=e.metadata.message_content_id;if(!g)throw new Error("Unable to find message content id from entity ids");let h=i.message;if(x=a.find(b=>b.message.id===h),!x)throw new Error("Unable to find message to add content to");m=le(x,g);}else {if(m=p,x=a[a.length-1],!x)throw new Error("Unable to find message to add content to");if(x._type!=="message")throw new Error("Unable to find message to add content to - not a message")}if(!m)throw new Error("Unable to find message content");let y=r[x.message.id];if(!y)throw new Error("Unable to find message to add content to");let k=Yl(m,e.payload);return r[y.message.id]={...dt(y,k)},s._type==="message_content"&&(d=k),d;case "step output content delta":return Bo(p,e.payload);case "status":if(s._type==="step"&&(s.currentStatus=we(e)),s._type==="invocation"&&(s.currentStatus=we(e)),s._type==="message_content"){let f=s;if(f.botInvocation)return f.botInvocation.currentStatus=we(e),{...f}}if(s._type==="message"){let f=s,g=Oo(f);if(g?.botInvocation)return g.botInvocation.currentStatus=we(e),dt(f,g)}return pr(s,we(e));case "result":return null;case "message finished":if(s._type==="message"){let g=Ao(s);r[g.message.id]=g;}return null;case "step output finished":return null;case "step result":return null;case "error":return null;case "dataset created":return null;case "log":return null;default:throw new Error(`Unable to handle event type ${t}`)}}let c=n.slice(2),l=jl(s,n,i),u=kn(t,e,c,o,r,l,[...a,s],i);return u?pr(s,{...u}):s}function hr(t){if(!t.content)return null;if(typeof t.content=="object")return t.content;if(typeof t.content=="string"){let e=$(t.content);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}return null}function jo(t){let e=t.content_type;if(e==="tool_result")return "result";if(e==="tool_invocation")return "invocation";let n=hr(t);return n&&"action_type"in n&&"name"in n&&"input"in n&&n.action_type!=="bot.invoke"?"result"in n?"result":"invocation":null}function Fo(t){return hr(t)?.id}function Jo(t){let e=hr(t);if(!e?.action_type)return null;let o=e.input?.query;return `${e.action_type}:${o||""}`}function Go(t){let e=t.filter(r=>jo(r)==="result"),n=new Set(e.map(r=>Fo(r)).filter(Boolean)),o=new Set(e.map(r=>Jo(r)).filter(Boolean));return t.filter(r=>{if(jo(r)==="invocation"){let s=Fo(r),a=Jo(r);if(s&&n.has(s)||a&&o.has(a))return false}return true})}function Wo(t,e,n){let o=e;for(;o;){if(o===n)return true;o=t.byStepId[o]?.parentId??null;}return false}function bn(t,e){if(!e||!t.byStepId[e])return t;let n=new Set;for(let i of t.nodes)i.kind==="step"&&Wo(t,i.id,e)&&n.add(i.id);let o=t.nodes.filter(i=>i.kind==="step"?n.has(i.id):i.kind==="content"||i.kind==="status"?!!i.stepId&&n.has(i.stepId):false),r={},s={},a={};for(let i of n){let c=t.byStepId[i];c&&(r[i]=c);}for(let i of o){if(i.kind==="content"){s[i.id]=i;continue}if(i.kind!=="step")continue;let l=(i.parentId&&n.has(i.parentId)?i.parentId:null)??"__root__";a[l]=[...a[l]||[],i.id];}return {...t,nodes:o,byStepId:r,byContentId:s,childrenByParentId:a,rootStepId:e}}function Ne(){return zustand.createStore((t,e)=>({globalState:fn(),invocationStates:{},invocationRootSteps:{},pendingInvocationQueue:[],pushEvent:(n,o)=>{let r=e(),s=ur(r.globalState,n);if(o&&(s=o(s)),s===r.globalState)return;let a=n.metadata?.step_id??n.payload?.step_id??"",i={...r.invocationStates},c=false;for(let[l,u]of Object.entries(r.invocationRootSteps)){let p=r.invocationStates[l];if(a&&!Wo(s,a,u)&&a)continue;let d=bn(s,u);if(!(n.type==="step_finished"||n.type==="step_started"||n.type==="status")&&p&&p.nodes.length===d.nodes.length){let x=p.nodes[p.nodes.length-1],y=d.nodes[d.nodes.length-1];if(x===y&&p.isStreaming===d.isStreaming)continue}i[l]=d,c=true;}t({globalState:s,...c?{invocationStates:i}:{}});},registerInvocation:n=>{let o=e();o.invocationRootSteps[n]||o.pendingInvocationQueue.includes(n)||t({pendingInvocationQueue:[...o.pendingInvocationQueue,n]});},mapInvocationRoot:(n,o)=>{let r=e(),s=bn(r.globalState,o);t({invocationRootSteps:{...r.invocationRootSteps,[n]:o},invocationStates:{...r.invocationStates,[n]:s},pendingInvocationQueue:r.pendingInvocationQueue.filter(a=>a!==n)});},reset:()=>{t({globalState:fn(),invocationStates:{},invocationRootSteps:{},pendingInvocationQueue:[]});}}))}function lc(t){return t.split("/").filter(Boolean)}function qo(t={}){let e=Ct(),[n,o]=gt.useState(null),[r,s]=gt.useState(false),[a,i]=gt.useState(null),[c,l]=gt.useState([]),u=gt.useRef(Ne()),p=zustand.useStore(u.current,g=>g.globalState),d=gt.useRef(null),m=gt.useRef(t.threadId);t.threadId!==m.current&&(m.current=t.threadId);let x=gt.useCallback(()=>{d.current&&(d.current.abort(),d.current=null);},[]),y=gt.useCallback(g=>{o(g),m.current=g.id;},[]),k=gt.useCallback(async g=>{if(!e.client)throw new Error("ErdoClient not configured in provider. Pass a client to ErdoProvider config to use useThread.");if(!e.client.sendMessage)throw new Error("ErdoClient does not support sendMessage. Make sure you are using @erdoai/server client.");if(!e.client.createThread)throw new Error("ErdoClient does not support createThread. Make sure you are using @erdoai/server client.");x(),d.current=new AbortController,s(true),i(null),l([]),u.current.getState().reset();let h={};try{let b=m.current;if(!b){let E=await e.client.createThread();o(E),m.current=E.id,b=E.id;}for await(let E of e.client.sendMessage(b,{content:g,botKey:t.botKey})){if(d.current?.signal.aborted)break;if(t.onEvent?.(E),e.useAgentEvents)u.current.getState().pushEvent(E);else {let z=E.type||"",Q=E.metadata||{},R=lc(Q.path||""),j={payload:E.payload,metadata:{path:Q.path||"",...Q}};try{kn(z,j,R,b,h);}catch(F){console.error("Error handling SSE event:",F,z);}l(Object.values(h));}}let S=Object.values(h);l(S);let v=u.current.getState().globalState,T;v.rootStepId?T=ve(v):T=S.flatMap(E=>E.contents||[]).filter(E=>E.user_visibility==="visible").map(E=>({id:E.id,content_type:E.content_type,ui_content_type:P(E.ui_content_type),content:E.content,parsedJson:E.parsedJson,botInvocation:E.botInvocation})),t.onFinish?.(T);}catch(b){let S=b instanceof Error?b:new Error(String(b));throw i(S),t.onError?.(S),S}finally{s(false),d.current=null;}},[e.client,e.useAgentEvents,t,x]),f=gt.useMemo(()=>{if(p.rootStepId)return ve(p);let g=c.flatMap(b=>b.contents||[]).filter(b=>b.user_visibility==="visible");return Go(g).map(b=>({id:b.id,content_type:b.content_type,ui_content_type:P(b.ui_content_type),content:b.content,parsedJson:b.parsedJson,botInvocation:b.botInvocation}))},[c,p]);return {thread:n,isStreaming:r,error:a,activeMessages:c,agentState:p,streamingContents:f,sendMessage:k,cancel:x,setThread:y,agentStreamStore:u.current}}function cc(t){return t?typeof t=="string"?t:typeof t=="object"&&t!==null&&"String"in t&&t.String||"":""}function zo(t){let e=cc(t.ui_content_type),n=t.content_type,o={id:t.id,content_type:t.content_type,ui_content_type:e,content:t.content,invocation_id:t.created_by_invocation_id};if(typeof t.content=="string"){if(e==="ui_generation")try{o.parsedJson=ft(t.content);}catch(r){console.error("Error parsing UI generation content:",r);}else if((n==="json"||e==="json")&&t.content.trim()){let r=$(t.content);r!=null&&(o.parsedJson=[{type:"json",content:r}]);}}if((t.content_type==="thinking"||t.content_type==="redacted_thinking")&&typeof t.content=="string"){let r=$(t.content);r&&typeof r=="object"&&(o.content=r);}return o}function uc(t){return t.filter(e=>e.user_visibility!=="hidden").map(zo)}var Sn=gt.createContext(null);function Ko({store:t,children:e}){return jsxRuntime.jsx(Sn.Provider,{value:t,children:e})}function Qo(){return gt.useContext(Sn)}function Zo(t){let e=gt.useContext(Sn);return zustand.useStore(e,n=>t?n.invocationStates[t]:void 0)}function Yo(){let t=gt.useContext(Sn);return zustand.useStore(t,e=>e.globalState)}exports.AgentStreamStoreProvider=Ko;exports.BarChart=wt;exports.BotInvocationContent=an;exports.Chart=it;exports.ChartContainer=de;exports.ChartContent=Ge;exports.ChartLegend=Tn;exports.ChartLegendContent=Dn;exports.ChartNode=qn;exports.ChartStyle=wr;exports.ChartTooltip=Nn;exports.ChartTooltipContent=En;exports.CodeexecContent=sn;exports.CodegenContent=rn;exports.CollapsibleCodeBlock=xt;exports.Content=Mt;exports.DatasetChart=Me;exports.DatasetDownload=Kt;exports.DatasetTable=Ve;exports.DownloadButtonNode=Kn;exports.ErdoProvider=Sr;exports.ErdoUI=dl;exports.ErrorBoundary=St;exports.ExecutionStatus=Ln;exports.ExpandableOutputContent=kt;exports.FileDownloadsNode=Zn;exports.HeatmapChart=Gt;exports.InvocationEvent=Fe;exports.InvocationEvents=Tt;exports.InvocationStatus=qr;exports.JSONStreamParser=X;exports.JsonContent=zt;exports.LineChart=jt;exports.Loader=_o;exports.Log=Xn;exports.LogContent=Ke;exports.MarkdownContent=B;exports.MemoryContent=un;exports.Output=$e;exports.PieChart=Ft;exports.ScatterChart=Jt;exports.SqlContent=Xe;exports.StatusSpinner=rt;exports.StderrText=te;exports.StdoutText=Xt;exports.StdwarnText=en;exports.StepInvocation=je;exports.StepInvocationStatus=Ue;exports.StepTreeContent=Do;exports.SuggestionsNode=Qn;exports.TableContent=We;exports.TableNode=zn;exports.TextContent=ye;exports.TextMarkdownNode=Hn;exports.ThinkingContent=He;exports.ToolGroupContent=ne;exports.UIGenerationNodes=qe;exports.WebParseContent=Ze;exports.WebSearchContent=Qe;exports.WritingLoader=ar;exports.agentStateToContents=ve;exports.cn=K;exports.completeStreamingContent=wo;exports.createAgentStreamStore=Ne;exports.createInitialAgentState=fn;exports.extractContentItems=vo;exports.formatValue=at;exports.handleAgentEvent=ur;exports.handleIncrementalMixedJsonParsing=ir;exports.handleSSEEvent=kn;exports.hasRenderableAssistantOutput=Nl;exports.isJsonLike=ge;exports.isNullString=Ur;exports.isParsingComplete=Ta;exports.isParsingInProgress=he;exports.isWhitespaceChar=Dt;exports.nodeComponents=Yn;exports.normalizeContent=zo;exports.normalizeContents=uc;exports.normalizeUIGenerationChunks=Se;exports.normalizeUINodes=Jn;exports.parseCompleteJson=$;exports.parseMixedJson=ft;exports.parseToDate=Ir;exports.resolveKeyFromData=qt;exports.sliceAgentStateToRoot=bn;exports.toSnakeCase=Mr;exports.unwrapNullString=P;exports.unwrapNullStringOr=ra;exports.useAgentStreamGlobalState=Yo;exports.useAgentStreamStoreOptional=Qo;exports.useChartZoom=Ae;exports.useDatasetContents=Pe;exports.useErdoConfig=Ct;exports.useErdoConfigOptional=q;exports.useInvocationState=Zo;exports.useMultipleDatasetContents=Or;exports.useMultipleDatasetRequests=me;exports.useThread=qo;
package/dist/index.js CHANGED
@@ -48,4 +48,4 @@ $bm_rt = comp('system-solid-56-warning').layer('control').effect('primary')('Col
48
48
  color: transparent;
49
49
  }
50
50
  `,document.head.appendChild(t);}function He({item:t,className:e}){let[n,o]=useState(false);useEffect(()=>{Ya();},[]);let r=t.content_type==="redacted_thinking",s="",a=false;if(typeof t.content=="string")s=t.content;else if(t.content&&typeof t.content=="object")if(r)s=t.content.data||"Some of Claude's internal reasoning has been automatically encrypted for safety reasons. This doesn't affect the quality of responses.";else {let p=t.content;s=p.thinking||"",a=typeof p.signature=="string"&&p.signature.length>0;}let i=typeof t.state=="string"?t.state:"",l=(i==="in_progress"||i==="streaming"||i==="running")&&!a;return jsxs("div",{className:e,children:[jsxs("button",{onClick:()=>o(!n),className:"inline-flex items-center gap-1.5 text-left",children:[n?jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground/70"}):jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground/70"}),jsx("span",{className:`text-sm ${l?"erdo-thinking-shimmer":"text-muted-foreground"}`,children:r?"Encrypted thinking":"Thinking"})]}),n&&jsx("div",{className:"mt-1 pl-5 text-sm text-muted-foreground whitespace-pre-wrap",children:s||(l?"Thinking...":"")})]})}function Xa(t){try{return JSON.parse(t)}catch{return t}}function ti(t){if(!t)return "";try{return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return ""}}function Xn({log:t}){let e=typeof t.message=="string"?Xa(t.message):t.message,n=ti(t.timestamp),o="text-xs font-mono py-0.5 px-1.5 rounded flex items-start",r="";switch(t.level){case "error":o+=" bg-red-50/50 dark:bg-red-950/30 text-red-600 dark:text-red-400 border-l-2 border-red-400 dark:border-red-600",r="text-red-500 dark:text-red-400";break;case "requires_info":o+=" bg-yellow-50/50 dark:bg-yellow-950/30 text-yellow-600 dark:text-yellow-400 border-l-2 border-yellow-400 dark:border-yellow-600",r="text-yellow-500 dark:text-yellow-400";break;default:o+=" bg-blue-50/40 dark:bg-blue-900/20 text-blue-500/90 dark:text-blue-300/80 border-l-2 border-blue-300 dark:border-blue-600/50",r="text-blue-400 dark:text-blue-400/70";}return jsx("div",{className:"my-0.5",children:jsx("div",{className:o,children:jsxs("div",{className:"flex items-start gap-2",children:[n&&jsx("span",{className:"text-[10px] opacity-60 whitespace-nowrap w-16 flex-shrink-0 pt-0.5",children:n}),t.level==="error"&&jsx("span",{className:"inline-block mr-1 flex-shrink-0",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`h-3 w-3 ${r}`,viewBox:"0 0 20 20",fill:"currentColor",children:jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM8.28 7.22a.75.75 0 00-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 101.06 1.06L10 11.06l1.72 1.72a.75.75 0 101.06-1.06L11.06 10l1.72-1.72a.75.75 0 00-1.06-1.06L10 8.94 8.28 7.22z",clipRule:"evenodd"})})}),t.level==="requires_info"&&jsx("span",{className:"inline-block mr-1 flex-shrink-0",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`h-3 w-3 ${r}`,viewBox:"0 0 20 20",fill:"currentColor",children:jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})})}),t.level==="info"&&jsx("span",{className:"inline-block mr-1 flex-shrink-0",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:`h-3 w-3 ${r}`,viewBox:"0 0 20 20",fill:"currentColor",children:jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})})}),jsx("div",{className:"flex-1 break-words whitespace-pre-wrap",children:String(e)})]})})})}function Ke({item:t,className:e}){let n=typeof t.content=="object"&&t.content!==null?t.content:{message:String(t.content)},o={level:n.level||"info",message:n.message||String(t.content),timestamp:n.timestamp};return jsx("div",{className:e,children:jsx(Xn,{log:o})})}function ri(t){if(!t||typeof t!="object")return null;let e=t;if(Array.isArray(e.results))return e;if(e.result&&typeof e.result=="object"){let n=e.result;if(Array.isArray(n.results))return n}return null}function Qe({item:t,className:e}){let n=ri(t.content);return n?.results?.length?jsx("div",{className:`rounded-lg border border-border/50 overflow-hidden ${e||""}`,children:jsx("div",{className:"divide-y divide-border/30",children:n.results.map(o=>{let r="";try{r=new URL(o.url).hostname.replace(/^www\./,"");}catch{}return jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:"flex items-start gap-3 px-3 py-2 hover:bg-muted/50 transition-colors group",children:[jsxs("div",{className:"flex-1 min-w-0",children:[jsx("div",{className:"text-sm text-foreground/90 group-hover:text-foreground group-hover:underline truncate",children:o.title}),o.description&&jsx("div",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:o.description})]}),jsxs("div",{className:"flex items-center gap-1 shrink-0 mt-0.5",children:[jsx("span",{className:"text-[10px] text-muted-foreground/60",children:r}),jsx(ExternalLink,{className:"h-3 w-3 text-muted-foreground/40 group-hover:text-muted-foreground"})]})]},o.url)})})}):null}function si(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.content=="string")return e;if(e.result&&typeof e.result=="object"){let n=e.result;if(typeof n.content=="string")return n}return null}function ai(t){if(!t||typeof t!="object")return null;let n=t.input;return typeof n?.url=="string"?n.url:null}function Ze({item:t,className:e}){let n=si(t.content),o=ai(t.content),r=n?.url||o,s=n?.title,a=n?.content,i="";try{r&&(i=new URL(r).hostname.replace(/^www\./,""));}catch{}return !a&&!r?null:jsxs("div",{className:`rounded-lg border border-border/50 overflow-hidden ${e||""}`,children:[r&&jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 px-3 py-2 border-b border-border/30 hover:bg-muted/50 transition-colors group",children:[jsxs("div",{className:"flex-1 min-w-0",children:[jsx("div",{className:"text-sm text-foreground/90 group-hover:text-foreground truncate",children:s?.trim()||i||r}),s&&i&&jsx("div",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:i})]}),jsx(ExternalLink,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/40 group-hover:text-muted-foreground"})]}),a&&jsx("div",{className:"max-h-64 overflow-y-auto px-3 py-2 bg-muted/20",children:jsx(B,{content:a,className:"text-xs"})})]})}var xi=Prism,xt=memo(function({language:e,value:n,defaultOpen:o=false,title:r="View code",closeTitle:s="Hide code",className:a,theme:i="auto"}){let[c,l]=useState(o),[u,p]=useState(false),d=useRef(null);useEffect(()=>{if(!c){let h=d.current;h&&(h.scrollTop=h.scrollHeight);}},[c,n]);let m=useMemo(()=>i!=="auto"?i:typeof window>"u"?"light":document.documentElement.classList.contains("dark")||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",[i]),x=useMemo(()=>m==="dark"?oneDark:oneLight,[m]),y=useCallback(async()=>{try{await navigator.clipboard.writeText(n),p(!0),setTimeout(()=>p(!1),2e3);}catch{let h=document.createElement("textarea");h.value=n,document.body.appendChild(h),h.select(),document.execCommand("copy"),document.body.removeChild(h),p(true),setTimeout(()=>p(false),2e3);}},[n]),k=useMemo(()=>({margin:0,width:"100%",background:"transparent",padding:"1rem 0.5rem",fontSize:"0.825rem",maxWidth:"100vw",overflow:"auto"}),[]),f=useMemo(()=>({userSelect:"none",minWidth:"2.5em",paddingRight:"1em",color:"rgb(161 161 170)",opacity:"0.5"}),[]),g=useMemo(()=>({style:{fontFamily:"var(--font-mono, ui-monospace, monospace)",whiteSpace:"pre",wordBreak:"break-word"}}),[]);return jsx(ee.Root,{open:c,onOpenChange:l,className:a,children:jsxs("div",{className:"relative w-full font-sans rounded-lg overflow-hidden border border-zinc-200 dark:border-zinc-800",children:[jsxs("div",{className:"flex items-center justify-between w-full px-4 py-1.5 bg-white/80 dark:bg-zinc-800/80 text-zinc-600 dark:text-zinc-100 backdrop-blur-sm border-b border-zinc-200 dark:border-zinc-800",children:[jsx("span",{className:"text-xs font-medium lowercase text-zinc-400 dark:text-zinc-500",children:e}),jsx("button",{onClick:y,className:"h-6 w-6 flex items-center justify-center rounded-md hover:bg-zinc-100 dark:hover:bg-zinc-700 transition-colors",children:u?jsx(Check,{className:"h-3 w-3 text-green-500"}):jsx(Copy,{className:"h-3 w-3 text-zinc-400 dark:text-zinc-500"})})]}),jsxs("div",{ref:d,className:`${c?"max-h-96":"max-h-[200px]"} overflow-auto relative`,children:[jsx("div",{className:"bg-zinc-50/50 dark:bg-zinc-950/70",children:jsx(xi,{language:e,style:x,PreTag:"div",showLineNumbers:true,wrapLines:false,wrapLongLines:false,startingLineNumber:1,className:"not-prose",customStyle:k,lineNumberStyle:f,codeTagProps:g,children:n})}),!c&&jsx("div",{className:"absolute bottom-0 inset-x-0 h-24 pointer-events-none bg-gradient-to-t from-zinc-50 dark:from-zinc-950 to-transparent",style:{marginBottom:"1.5rem"}})]}),jsx(ee.Trigger,{className:"absolute bottom-0 inset-x-0 flex items-center gap-2 text-sm text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300 p-2 justify-start bg-zinc-50/80 dark:bg-zinc-950/80 backdrop-blur-sm border-t border-zinc-200 dark:border-zinc-800 cursor-pointer",children:c?jsxs(Fragment,{children:[jsx(ChevronUp,{className:"h-4 w-4"}),s]}):jsxs(Fragment,{children:[jsx(ChevronDown,{className:"h-4 w-4"}),r]})})]})})});function ki(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;return "sql_query"in e||"thinking"in e||"error"in e?{thinking:typeof e.thinking=="string"?e.thinking:void 0,sql_query:typeof e.sql_query=="string"?e.sql_query:void 0,resource_key:typeof e.resource_key=="string"?e.resource_key:void 0,error:typeof e.error=="string"?e.error:void 0}:null}function bi(t){return ki(t.content)}function Xe({item:t,className:e}){let n=bi(t);if(!n)return null;let{thinking:o,sql_query:r,error:s}=n;return s?jsxs("div",{className:`text-destructive text-sm ${e||""}`,children:[jsx("div",{className:"font-medium",children:"Error"}),jsx("div",{children:s})]}):!r&&!o?null:jsxs("div",{className:`text-foreground whitespace-pre-wrap leading-normal ${e||""}`,children:[o&&jsx("div",{className:"mb-2",children:jsx(B,{content:o,className:"text-sm max-w-none"})}),r&&jsx("div",{className:"mb-2",children:jsx(xt,{language:"sql",value:r,defaultOpen:false})})]})}var Si=500,_i=300;function Ce({content:t,className:e}){let[n,o]=useState(false);if(!t?.trim())return null;if(t.length<=Si)return jsx("div",{className:`text-sm text-muted-foreground ${e||""}`,children:jsx(B,{content:t,className:"text-sm max-w-none"})});let s=t.slice(0,_i).trimEnd()+"...";return jsx("div",{className:`text-sm text-muted-foreground ${e||""}`,children:n?jsxs(Fragment,{children:[jsx(B,{content:t,className:"text-sm max-w-none"}),jsx("button",{onClick:()=>o(false),className:"text-xs text-muted-foreground/70 hover:text-muted-foreground mt-1",children:"Show less"})]}):jsxs(Fragment,{children:[jsx("span",{className:"text-sm",children:s}),jsx("button",{onClick:()=>o(true),className:"text-xs text-muted-foreground/70 hover:text-muted-foreground ml-1",children:"Show more"})]})})}function kt({children:t,defaultOpen:e=false,wrapperType:n="standard",compact:o=false,className:r}){let[s,a]=useState(e),[i,c]=useState(false),l=useRef(null);useEffect(()=>{let d=l.current;d&&(s||(d.scrollTop=d.scrollHeight),c(d.scrollHeight>d.clientHeight));},[s,t]);let u={standard:"bg-muted/30 border-border",info:"bg-info/10 border-info/30",warning:"bg-warning/10 border-warning/30"},p={standard:"text-muted-foreground hover:text-foreground",info:"text-info hover:text-info/80",warning:"text-warning hover:text-warning/80"};return jsx("div",{className:`relative text-sm ${o?"":"mb-2"} ${r||""}`,children:jsx(ee.Root,{open:s,onOpenChange:a,className:`border rounded-sm ${u[n]}`,children:jsxs("div",{ref:l,className:`overflow-y-auto ${s?"":"max-h-[200px]"}`,children:[i&&jsx(ee.Trigger,{className:`sticky top-0 text-center text-xs py-1 transition-opacity w-full cursor-pointer ${p[n]}`,children:s?"Less \u2193":"More \u2191"}),jsx("div",{className:`${o?"px-2 py-1":"p-2"} m-0 overflow-x-auto break-words whitespace-pre-wrap`,children:t})]})})})}function nr(t){return new Date(t).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Xt({children:t,timestamp:e}){return jsxs("div",{className:"flex",children:[e&&jsx("span",{className:"text-muted-foreground/60 mr-2 select-none",children:nr(e)}),jsx("span",{className:"text-foreground/80",children:t})]})}function te({children:t,timestamp:e}){return jsxs("div",{className:"flex",children:[e&&jsx("span",{className:"text-info/60 mr-2 select-none",children:nr(e)}),jsx("span",{className:"text-info/90",children:t})]})}function en({children:t,timestamp:e}){return jsxs("div",{className:"flex",children:[e&&jsx("span",{className:"text-warning/60 mr-2 select-none",children:nr(e)}),jsx("span",{className:"text-warning/90",children:t})]})}function rn({item:t,className:e}){if(!t.content)return null;let n=Ii(t.content)??Ni(t.parsedJson);if(!n)return null;let{step_by_step:o,thinking:r,code:s,warnings:a,error:i}=n;return i?jsx(kt,{wrapperType:"info",className:e,children:jsx(te,{children:i})}):!o&&!r&&!s&&!a?null:jsxs("div",{className:`text-foreground whitespace-pre-wrap leading-normal ${e||""}`,children:[o&&jsx(B,{content:o,className:"text-sm max-w-none"}),r&&jsx(Ce,{content:r,state:typeof t.state=="string"?t.state:void 0}),s&&jsx("div",{className:"mb-2",children:jsx(xt,{language:"python",value:s,defaultOpen:false})}),a&&jsxs("div",{className:"text-sm text-warning",children:[jsx("div",{className:"font-medium",children:"Warnings"}),jsx(B,{content:a,className:"text-sm max-w-none"})]})]})}function Ii(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}function Ni(t){if(!Array.isArray(t))return null;let n=t.find(o=>o.type==="json");return n&&typeof n.content=="object"&&n.content!==null?n.content:null}function sn({item:t,className:e}){let n=Ti(t);if(n.sort((a,i)=>a.index-i.index),n.length===0)return null;let o=n.some(a=>a.level==="error"),r=n.some(a=>a.level==="warning"),s=o?"info":r?"warning":"standard";return jsx("div",{className:`text-foreground leading-normal ${e||""}`,children:jsx(kt,{wrapperType:s,compact:true,children:n.map((a,i)=>jsx(Ei,{output:a},`${a.level}-${i}`))})})}function Ei({output:t}){switch(t.level){case "output":return jsx(Xt,{timestamp:t.timestamp,children:t.message});case "error":return jsx(te,{timestamp:t.timestamp,children:t.message});case "warning":return jsx(en,{timestamp:t.timestamp,children:t.message});default:return jsx("div",{className:"text-muted-foreground",children:t.message})}}function Ti(t){let e=yo(t.content);return e.length>0?e:yo(t.parsedJson)}function yo(t){return on(t).map((n,o)=>Di(n,o)).filter(n=>n!==null)}function on(t){if(Array.isArray(t))return t.every(Ai)?t.flatMap(e=>on(e.content)):t;if(typeof t=="string"){let e=$(t);return e!=null?on(e):on(ft(t))}if(t&&typeof t=="object"){let e=t;if(Array.isArray(e.outputs))return e.outputs;if(typeof e.message=="string"||typeof e.stdout=="string"||typeof e.stderr=="string"||typeof e.content=="string")return [e]}return []}function Di(t,e){if(!t||typeof t!="object")return null;let n=t,o=typeof n.message=="string"?n.message:typeof n.stdout=="string"?n.stdout:typeof n.stderr=="string"?n.stderr:typeof n.content=="string"?n.content:"";if(!o.trim())return null;let r=typeof n.level=="string"?n.level:n.stderr?"error":n.warning?"warning":"output";return {level:r==="error"||r==="warning"||r==="output"?r:"output",message:o,timestamp:typeof n.timestamp=="string"?n.timestamp:void 0,index:typeof n.index=="number"?n.index:e}}function Ai(t){return !!(t&&typeof t=="object"&&"type"in t&&"content"in t)}function Bi(t){if(!t?.result||t.status==="error")return false;let e=t.result;return typeof e=="string"?e.trim()!=="":Array.isArray(e)?e.length>0:typeof e=="object"&&e!==null?Object.keys(e).length>0:true}function Oi(t,e,n){if(e?.finished_message)return e.finished_message;if(e?.running_message)return e.running_message;if(!e&&n?.running_message)return n.running_message;let o=t||"tool";return e?`Completed ${o}`:`Running ${o}...`}function ne({toolGroup:t,ContentComponent:e,className:n,fallbackClassName:o}){let[r,s]=useState(false),a=q(),i=e??a?.ContentComponent,c=t.invocation,l=t.result,u=Bi(l),p=c?.name||l?.name,d=Oi(p,l,c),m=l?l.status==="error"?"failed":"finished":"loading",x=l?.status==="error"?"text-gray-500/80 dark:text-gray-400/80":"text-gray-500 dark:text-gray-400";return jsxs(ee.Root,{open:r,onOpenChange:s,className:`relative w-full max-w-4xl space-y-2 leading-normal ${n||""}`,children:[jsxs(ee.Trigger,{className:`flex items-center justify-between text-sm transition-colors w-full ${x} ${u?"hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer":"cursor-default"}`,disabled:!u,children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(rt,{status:m}),jsx("span",{children:d})]}),u&&jsx(ChevronDown,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${r?"rotate-180":""}`})]}),u&&l&&jsx(ee.Content,{children:jsx("div",{className:"pl-6 mt-2",children:i?jsx(i,{content:{content:l.result,content_type:l.ui_content_type||"json"}}):jsx("pre",{className:o||"text-sm bg-gray-100 dark:bg-gray-800 p-2 rounded overflow-x-auto",children:JSON.stringify(l.result,null,2)})})})]})}var Ot={Success:"success",Error:"error",RequiresInfo:"requires info"};function Li(t){return t?t===Ot.Success?"finished":t===Ot.Error||t===Ot.RequiresInfo?"failed":"loading":"loading"}function ko(t){return t?t!==Ot.Success&&t!==Ot.Error&&t!==Ot.RequiresInfo:true}function Ui(t,e){let n=e||"agent",o=P(t?.message);return o||(t?.status===Ot.Success?`Finished ${n}`:`Running ${n}...`)}function an({content:t,botInvocation:e,isLoading:n=false,defaultOpen:o,adminLinkHref:r,adminLinkText:s="Open in Agent Designer",showAdminLink:a=false,onAdminClick:i,onExpand:c,EventsComponent:l,ContentComponent:u,className:p}){let d=()=>o!==void 0?o:ko(e?.currentStatus?.status),[m,x]=useState(d),[y,k]=useState(false),f=useRef(null);if(useEffect(()=>{if(e?.currentStatus){let T=e.currentStatus.status;if(f.current!==T&&(f.current=T,!y)){let E=ko(T);E&&!m?x(true):!E&&m&&x(false);}}},[e,y,m]),useEffect(()=>{m&&e&&c&&c(t.invocation_id,t.bot_id,t.bot_name);},[m,e,c,t]),n&&!e&&!t.transparent)return jsxs("div",{className:`flex items-center gap-2 text-sm text-muted-foreground ${p||""}`,children:[jsx(rt,{status:"loading"}),jsxs("span",{children:["Loading ",t.bot_name,"..."]})]});if(!e)return null;let g=e.eventsByID&&Object.keys(e.eventsByID).length>0;if(t.transparent)return g?l?jsx(l,{eventsByID:e.eventsByID,defaultOpen:true}):jsx(Tt,{eventsByID:e.eventsByID,ContentComponent:u}):null;let h=Li(e.currentStatus?.status),b=Ui(e.currentStatus,t.bot_name),S=T=>{x(T),k(true);},v=T=>{i&&(T.preventDefault(),i(t.invocation_id,t.bot_id));};return jsxs(ee.Root,{open:m,onOpenChange:S,className:`relative w-full max-w-4xl space-y-2 leading-normal bot-invocation-content ${p||""}`,children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs(ee.Trigger,{className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[jsxs("div",{className:"text-sm font-medium flex items-center gap-2",children:[jsx(rt,{status:h}),b]}),jsx(ChevronDown,{className:`h-4 w-4 transition-transform duration-200 ${m?"transform rotate-180":""}`})]}),a&&(r||i)&&jsxs("a",{href:r||"#",onClick:i?v:void 0,target:r?"_blank":void 0,rel:r?"noopener noreferrer":void 0,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[s,jsx(ArrowUpRight,{className:"h-3.5 w-3.5"})]})]}),jsx(ee.Content,{children:jsx("div",{className:"space-y-2 max-w-3xl",children:g?l?jsx(l,{eventsByID:e.eventsByID,defaultOpen:m}):jsx(Tt,{eventsByID:e.eventsByID,ContentComponent:u}):jsx("span",{className:"text-sm text-muted-foreground",children:"No events to display"})})})]})}function or({content:t,isSearching:e=false,className:n}){let o=[];Array.isArray(t)?o=t:typeof t=="object"&&t!==null&&"q"in t?o=t.q:typeof t=="string"&&(o=[t]);let r=o.filter(s=>s&&s.trim()!=="");return r.length===0?null:jsx("div",{className:`flex flex-wrap gap-2 ${n||""}`,children:r.map(s=>jsxs("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg text-sm bg-muted/50 text-foreground border border-border/30",children:[e?jsx(Loader2,{className:"h-3 w-3 mr-2 text-muted-foreground flex-shrink-0 animate-spin"}):jsx(Search,{className:"h-3 w-3 mr-2 text-muted-foreground flex-shrink-0"}),jsx("span",{className:"line-clamp-1",children:s})]},s))})}function sr({content:t,isSearching:e=false,className:n}){let o=[];if(Array.isArray(t))o=t;else if(typeof t=="object"&&t!==null&&"integration_queries"in t)o=t.integration_queries;else if(typeof t=="string")return null;let r=o.filter(s=>s&&s.query&&s.query.trim()!=="");return r.length===0?null:jsx("div",{className:`flex flex-wrap gap-2 ${n||""}`,children:r.map(s=>jsxs("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg text-sm bg-muted/50 text-foreground border border-border/30",children:[e?jsx(Loader2,{className:"h-3 w-3 mr-2 text-muted-foreground flex-shrink-0 animate-spin"}):jsx(Search,{className:"h-3 w-3 mr-2 text-muted-foreground flex-shrink-0"}),jsx("span",{className:"line-clamp-1",children:s.query})]},`${s.integration_config_id}-${s.resource_id}-${s.query}`))})}var Xi=120;function tl(t,e){return !t||t.length<=e?t:t.slice(0,e).trimEnd()+"..."}function el(t){switch(t){case "snippet":return Code;case "learning":return Brain;case "error":return AlertCircle;case "limitation":return AlertCircle;case "optimization":return Zap;default:return Lightbulb}}function nl(t){switch(t){case "snippet":return "Snippet";case "learning":return "Learning";case "error":return "Error";case "limitation":return "Limitation";case "optimization":return "Optimization";default:return t}}function rl({memory:t}){let[e,n]=useState(false),o=el(t.type),r=nl(t.type),s=t.type==="snippet",a=tl(t.description||"",Xi),i=t.content&&t.content.trim()!=="",c=s&&i;return jsxs(ee.Root,{open:e,onOpenChange:n,className:"border border-border/50 rounded-lg overflow-hidden",children:[jsxs(ee.Trigger,{className:`w-full text-left p-3 flex items-start gap-3 ${c?"hover:bg-muted/50 cursor-pointer":"cursor-default"}`,disabled:!c,children:[jsx("div",{className:"flex-shrink-0 mt-0.5",children:jsx(o,{className:"h-4 w-4 text-muted-foreground"})}),jsxs("div",{className:"flex-1 min-w-0",children:[jsxs("div",{className:"flex items-center gap-2 mb-1",children:[jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:r}),t.tags&&t.tags.length>0&&jsxs("div",{className:"flex gap-1 flex-wrap",children:[t.tags.slice(0,3).map((l,u)=>jsx("span",{className:"text-xs px-1.5 py-0.5 bg-muted rounded text-muted-foreground",children:l},u)),t.tags.length>3&&jsxs("span",{className:"text-xs text-muted-foreground",children:["+",t.tags.length-3]})]})]}),jsx("p",{className:"text-sm text-foreground",children:s?a:t.description||t.content})]}),c&&jsx(ChevronDown,{className:`h-4 w-4 text-muted-foreground flex-shrink-0 transition-transform duration-200 ${e?"rotate-180":""}`})]}),c&&jsx(ee.Content,{children:jsx("div",{className:"border-t border-border/50 bg-muted/30",children:jsx("pre",{className:"p-3 text-sm overflow-x-auto whitespace-pre-wrap break-words font-mono",children:t.content})})})]})}function un({content:t,className:e}){let n=Array.isArray(t)?t:t?.memories;return !n||n.length===0?jsx("p",{className:"text-sm text-muted-foreground",children:"No memories found."}):jsx("div",{className:`space-y-2 ${e||""}`,children:n.map(o=>jsx(rl,{memory:o},o.id))})}function ar(){return jsxs("span",{className:"inline-flex gap-1 text-muted-foreground",children:[jsx("span",{className:"animate-bounce",style:{animationDelay:"0ms"},children:"\u25CF"}),jsx("span",{className:"animate-bounce",style:{animationDelay:"150ms"},children:"\u25CF"}),jsx("span",{className:"animate-bounce",style:{animationDelay:"300ms"},children:"\u25CF"})]})}function _o(){return jsx("div",{className:"flex items-center justify-center py-8",children:jsx(Loader2,{className:"animate-spin text-muted-foreground",size:24})})}function il(t){if(t.content_type==="bot_invocation"||t.content_type==="bot_invocation_result")return null;if(t.content&&typeof t.content=="object"){let n=t.content,o=n.tool_invocation_content;if(n.action_type==="bot.invoke"||o?.action_type==="bot.invoke")return null}if(t.content_type==="tool_invocation")return "tool_invocation";if(t.content_type==="tool_result")return "tool_result";if(!t.content||typeof t.content!="object")return null;let e=t.content;return "action_type"in e&&"name"in e&&"input"in e&&e.action_type!=="bot.invoke"?"result"in e?"tool_result":"tool_invocation":null}function Mt({content:t,className:e,components:n}){let r=q()?.onSuggestionClick,s=useMemo(()=>l=>jsx(Mt,{...l,components:n}),[n]);if(!t.content||t.content==="")return null;if(t.content&&typeof t.content=="object"){let l=t.content,u=l.tool_invocation_content;if(l.action_type==="bot.invoke"||u?.action_type==="bot.invoke")return null}let a=il(t),i;a?i=a:i=P(t.ui_content_type)||t.content_type;let c=n?.[i];if(c)return jsx(c,{content:t,className:e});switch(i){case "text":return jsx(ye,{content:Co(t),className:e});case "markdown":return jsx(B,{content:Co(t),className:e});case "thinking":case "redacted_thinking":return jsx(He,{item:t,className:e});case "json":return jsx(zt,{content:t.content,className:e});case "codegen_json":return jsx(rn,{item:t,className:e});case "sql_generation":return jsx(Xe,{item:t,className:e});case "codeexec_output":return jsx(sn,{item:t,className:e});case "log":return jsx(Ke,{item:t,className:e});case "websearch":case "websearch_output":case "web_search":return jsx(Qe,{item:t,className:e});case "search_queries":return jsx(or,{content:t.content,className:e});case "integration_queries":return jsx(sr,{content:t.content,className:e});case "memory":return jsx(un,{content:t.content,className:e});case "webparse":case "webparse_output":case "web_parse":return jsx(Ze,{item:t,className:e});case "tool_group":return jsx(ne,{toolGroup:t.content,ContentComponent:s,className:e});case "bot_invocation":{let l=t.content,u=t.botInvocation;return jsx(an,{content:l,botInvocation:u,ContentComponent:s,className:e})}case "chart":case "ui_generation":{let l=t.invocation_id||t.created_by_invocation_id;if(t.chartConfig&&t.chartData)return jsx(Ge,{config:t.chartConfig,data:t.chartData,className:e});let u=Se(t.content);if(u&&u.length>0)return So(u,e,l,r);let p=Se(t.parsedJson);return p&&p.length>0?So(p,e,l,r):jsx("p",{className:"w-full max-w-4xl text-sm text-muted-foreground",children:"The LLM generated an invalid response. Please try again."})}case "table":return t.tableColumns&&t.tableData?jsx(We,{columns:t.tableColumns,data:t.tableData,className:e}):jsx(zt,{content:t.content,className:e});case "tool_invocation":{let l=t.content,u={invocation:{invocation_id:l.id||"",action:l.action_type||"",params:l.input||{},id:l.id||"",name:l.name||"",input:l.input||{},description:l.description,action_type:l.action_type,running_message:l.running_message}};return jsx(ne,{toolGroup:u,ContentComponent:s,className:e})}case "tool_result":{let l=t.content,u={invocation:{invocation_id:l.id||"",action:l.action_type||"",params:l.input||{}},result:{invocation_id:l.id||"",result:l.result}},p={...u,invocation:{...u.invocation,id:l.id||"",name:l.name||"",input:l.input||{},action_type:l.action_type,description:l.description},result:{...u.result,id:l.id||"",name:l.name||"",input:l.input||{},result:l.result,status:l.status||"success",action_type:l.action_type,description:l.description,ui_content_type:l.ui_content_type||P(t.ui_content_type),running_message:l.running_message||l.running_status,finished_message:l.finished_message||l.finished_status}};return jsx(ne,{toolGroup:p,ContentComponent:s,className:e})}default:return typeof t.content=="string"?jsx(ye,{content:t.content,className:e}):null}}function Co(t){return typeof t.content=="string"?t.content:""}function ll(t){let e=t?.children??t?.blocks;return Array.isArray(e)?e:void 0}function Se(t){if(t==null)return null;if(Array.isArray(t))return t.every(o=>o&&typeof o=="object"&&"type"in o&&"content"in o)?t:t.every(o=>o&&typeof o=="object"&&"_type"in o)?[{type:"json",content:{children:t}}]:null;if(typeof t=="object")return [{type:"json",content:t}];if(typeof t=="string"){let e=ft(t);return Se(e)}return null}function So(t,e,n,o){return jsx(Fragment,{children:t.map((r,s)=>{if(r.type==="text"){let a=r.content;return jsx(B,{content:a,className:e},`${s}-${a.length}`)}if(r.type==="json"){let a=r.content,i=ll(a);return i?jsx(gt__default.Fragment,{children:jsx(qe,{nodes:i,className:e,invocationId:n,onSuggestionClick:o})},`${s}-${i.length}`):he(a)?jsx(ar,{},s):jsx(zt,{content:a,className:e},`${s}-json`)}return null})})}function dl({result:t,isStreaming:e,className:n,components:o,streamingText:r}){let s=t?vo(t):[];return r&&s.length===0?jsxs("div",{className:n?`erdo-ui ${n}`:"erdo-ui space-y-4",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"animate-pulse w-2 h-2 bg-blue-500 rounded-full"}),jsx("span",{className:"text-sm text-gray-500",children:"Streaming response..."})]}),jsx("div",{className:"border rounded-lg p-4 whitespace-pre-wrap",children:r})]}):s.length===0&&!e?null:jsxs("div",{className:n?`erdo-ui ${n}`:"erdo-ui space-y-4",children:[s.map((a,i)=>jsx("div",{children:jsx(Mt,{content:a,components:o})},a.id||i)),e&&s.length===0&&!r&&jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"animate-pulse w-2 h-2 bg-blue-500 rounded-full"}),jsx("span",{className:"text-sm text-gray-500",children:"Processing..."})]})]})}function vo(t){let e=[],n=new Set;if(t.events)for(let o of t.events){let r=o.metadata,s=o.payload;if(r?.user_visibility==="visible"&&s?.status==="success"&&s?.output){let a=s.output;if(a.content&&Array.isArray(a.content))for(let i=0;i<a.content.length;i++){let c=a.content[i],l=c.id||`event-result-${i}`;if(n.has(l))continue;n.add(l);let u=r?.ui_content_type;e.push({id:l,content_type:c.content_type||"text",ui_content_type:u,content:c.content,data:c.data,chartConfig:c.chartConfig,chartData:c.chartData,tableColumns:c.tableColumns,tableData:c.tableData});}}}if(e.length===0&&t.result?.output?.content){let o=t.result.output.content;if(Array.isArray(o))for(let r=0;r<o.length;r++){let s=o[r],a=s.id||`result-${r}`;if(n.has(a))continue;n.add(a);let i=s.ui_content_type;e.push({...s,id:a,ui_content_type:i});}}return e}function pl(t){if(t.length===0)return t;let e=[];for(let n=0;n<t.length;n++){let o=t[n],r=n>0?t[n-1]:null,s=n<t.length-1?t[n+1]:null;if(o.type==="text"&&typeof o.content=="string"){let a=o.content,i=false;if(s?.type==="json"){let c=a;a=a.replace(/```(?:json)?\s*$/,""),c!==a&&(i=true);}if(r?.type==="json"){let c=a;a=a.replace(/^\s*```/,""),c!==a&&(i=true);}(!i||a.trim())&&e.push({...o,content:a});}else e.push(o);}return e}var ml=new Set(["=","("]);function fl(t){if(!t||t.length===0)return true;let e=t[t.length-1];return !ml.has(e)}function ir(t,e){if(t.user_visibility!=="visible"||!ge(t.content_type,t.ui_content_type.String))return typeof t.content=="object"?t:{...t,content:(t.content||"")+e};if(typeof t.content=="object"&&t.content!==null)return t;let n=t.parsedJson?t.parsedJson.map((u,p,d)=>p===d.length-1?{...u}:u):[],o=t.content||"",r=t._isInJson??false,s=t._charBuffer??"",a=t._jsonParser,i=n.length>0&&t._currentContent?n.length-1:-1;if(typeof e=="object")return {...t,content:o+JSON.stringify(e),parsedJson:[...n,e],_isInJson:r,_charBuffer:s,_jsonParser:a,_currentContent:void 0};for(let u of e){if(o+=u,!r&&u==="{"){let p=o.slice(0,-1);if(fl(p)){s="{";continue}}if(s&&Dt(u)){s+=u;continue}if(!r&&s?.match(/^\s*{\s*$/)&&u==='"'){r=true,a=new X;let d={content:a.add("{"),type:"json"},m=i>=0?n[i]:null;if(!m?.content)n=[...n,d],i=n.length-1;else if(typeof m.content=="string"&&m.content.match(/^\s*{$/))n=[...n.slice(0,-1),d],i=n.length-1;else {if(typeof m.content=="string"){let x={...m,content:m.content.replace(/{$/,"")};n=[...n.slice(0,-1),x,d];}else n=[...n,d];i=n.length-1;}}if(r)try{let d={type:"json",content:a.add(u)};n=[...n.slice(0,i),d],a.state==="END"&&(r=!1,i=-1);}catch(p){if(console.log("handleIncrementalMixedJsonParsing: content chunk",e),console.log("handleIncrementalMixedJsonParsing: accumulated content",o),console.warn("handleIncrementalMixedJsonParsing: JSON parse error, recovering as text",p),r=false,a=void 0,n.length>0&&i>=0&&n[i].type==="json"){let m=o.lastIndexOf("{"),y={type:"text",content:o.slice(m)};n=[...n.slice(0,i),y];}continue}else if(i<0||n[i]?.type!=="text"){let p={content:s+u,type:"text"};n=[...n,p],i=n.length-1;}else {let d={type:"text",content:n[i].content+s+u};n=[...n.slice(0,i),d];}s="";}let c=i>=0?n[i]:void 0,l=pl(n);return {...t,content:o,parsedJson:l,_isInJson:r,_charBuffer:s,_jsonParser:a,_currentContent:c}}function _e(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gl(t){if(!_e(t)||!("content"in t))return t;let e=t.content;return e===void 0?t:e}function ae(t,e){let n=gl(e);if((t==="thinking"||t==="redacted_thinking")&&typeof n=="string"){let o=$(n);return _e(o)?{content:o}:{content:n}}if(t==="json"&&typeof n=="string"){let o;try{let s=ft(n);Array.isArray(s)&&(o=s);}catch{}let r=$(n);return r!=null?{content:r,parsedJson:o}:{content:n,parsedJson:o}}return {content:n}}function yl(t,e){return typeof e=="string"?e:_e(e)?t==="redacted_thinking"?typeof e.data=="string"?e.data:"":typeof e.thinking=="string"?e.thinking:"":""}function pn(t,e,n){let o=ae(t,n);if(t!=="thinking"&&t!=="redacted_thinking")return o;let r=yl(t,e);return r?t==="redacted_thinking"?_e(o.content)&&typeof o.content.data!="string"?{...o,content:{...o.content,data:r}}:o:_e(o.content)&&typeof o.content.thinking!="string"?{...o,content:{...o.content,thinking:r}}:o:o}function mn(t){let e=t.metadata?.step_id??t.payload?.step_id;return typeof e=="string"?e:""}function lr(t){let e=t.metadata?.message_content_id??t.payload?.message_content_id;return typeof e=="string"?e:""}function hl(t){let e=t.metadata?.message_id;return typeof e=="string"?e:""}function cr(t,e){if(e.metadata?.content_type==="agent_invocation")return true;let n=hl(e);return !!(n&&n!==t.messageId)}function xl(t){return typeof t=="string"?t:typeof t=="object"&&t!==null&&"content"in t?String(t.content??""):""}function fn(){return {nodes:[],byStepId:{},byContentId:{},childrenByParentId:{},rootStepId:null,messageId:null,isStreaming:false}}function ur(t,e){switch(e.type){case "message created":return kl(t,e);case "message finished":return wo(t);case "step_started":return bl(t,e);case "step_finished":return Cl(t,e);case "create message content":return Sl(t,e);case "message content delta":return _l(t,e);case "message content result":return vl(t,e);case "status":return wl(t,e);default:return t}}function kl(t,e){let n=e.metadata?.message_id??e.payload?.message_id;if(!n)return t;let o=e.payload?.role,r=!!e.metadata?.invocation_id;return o==="assistant"||!o&&r?{...t,messageId:n}:t}function bl(t,e){let n=e.payload;if(!n?.step_id)return t;let o=t.byStepId[n.step_id],r=n.parent_step_id??null,s={kind:"step",id:n.step_id,parentId:r,type:n.type||o?.type||"agent",name:n.name||o?.name||"",key:n.key??o?.key,status:"running",contentType:n.content_type??o?.contentType,runningStatus:n.running_status??o?.runningStatus,finishedStatus:n.finished_status??o?.finishedStatus,hidden:n.hidden??o?.hidden},i=!r&&!t.rootStepId?n.step_id:t.rootStepId,c=r??"__root__",l=t.childrenByParentId[c]??[],u=l.includes(n.step_id)?t.childrenByParentId:{...t.childrenByParentId,[c]:[...l,n.step_id]},p=o?t.nodes.map(d=>d.kind==="step"&&d.id===n.step_id?s:d):[...t.nodes,s];return {...t,nodes:p,byStepId:{...t.byStepId,[n.step_id]:s},childrenByParentId:u,rootStepId:i,isStreaming:true}}function Cl(t,e){let n=e.payload;if(!n?.step_id)return t;let o=t.byStepId[n.step_id];if(!o){let c={kind:"step",id:n.step_id,parentId:null,type:"agent",name:"",status:n.status==="error"?"error":"completed",error:n.error,finishedStatus:n.finished_status};return {...t,nodes:[...t.nodes,c],byStepId:{...t.byStepId,[n.step_id]:c}}}let r={...o,status:n.status==="error"?"error":"completed",error:n.error??o.error,...n.finished_status?{finishedStatus:n.finished_status}:{}},s=n.step_id===t.rootStepId,a=t.nodes.map(c=>c.kind==="step"&&c.id===n.step_id?r:c.kind==="content"&&c.stepId===n.step_id?{...c,state:"completed"}:c),i={...t.byContentId};for(let[c,l]of Object.entries(i))l.stepId===n.step_id&&(i[c]={...l,state:"completed"});return {...t,nodes:a,byStepId:{...t.byStepId,[n.step_id]:r},byContentId:i,isStreaming:s?false:t.isStreaming}}function Sl(t,e){if(cr(t,e))return t;let n=lr(e);if(!n)return t;let o=mn(e)||null,r=typeof e.metadata?.content_type=="string"&&e.metadata.content_type||"text",s=typeof e.metadata?.ui_content_type=="string"&&e.metadata.ui_content_type||r,a=t.byContentId[n];if(a){let c={...a,stepId:a.stepId??o,contentType:a.contentType==="text"?r:a.contentType,uiContentType:a.uiContentType==="text"?s:a.uiContentType};return {...t,nodes:t.nodes.map(l=>l.kind==="content"&&l.id===n?c:l),byContentId:{...t.byContentId,[n]:c}}}let i={kind:"content",id:n,stepId:o,contentType:r,uiContentType:s,text:"",state:"streaming"};return {...t,nodes:[...t.nodes,i],byContentId:{...t.byContentId,[n]:i}}}function _l(t,e){if(cr(t,e))return t;let n=lr(e),o=xl(e.payload);if(!n||!o)return t;let r=t.byContentId[n],s=t;if(!r){let u=mn(e)||null,p=typeof e.metadata?.content_type=="string"&&e.metadata.content_type||"text",d=typeof e.metadata?.ui_content_type=="string"&&e.metadata.ui_content_type||p;r={kind:"content",id:n,stepId:u,contentType:p,uiContentType:d,text:"",state:"streaming"},s={...t,nodes:[...t.nodes,r],byContentId:{...t.byContentId,[n]:r}};}let a=r.text+o,i={},c=r.parsedContent;if(r.contentType==="json"){let u=Il(r,o);c=u.parsedContent,i=u._parserFields;}let l={...r,text:a,...c!==void 0?{parsedContent:c}:{},...i};return {...s,nodes:s.nodes.map(u=>u.kind==="content"&&u.id===n?l:u),byContentId:{...s.byContentId,[n]:l}}}function vl(t,e){if(cr(t,e))return t;let n=lr(e);if(!n)return t;let o=mn(e)||null,r=typeof e.metadata?.content_type=="string"&&e.metadata.content_type||"text",s=typeof e.metadata?.ui_content_type=="string"&&e.metadata.ui_content_type||r,a=t.byContentId[n],i=a?pn(r,a.result??a.text,e.payload):ae(r,e.payload);if(!a){let l={kind:"content",id:n,stepId:o,contentType:r,uiContentType:s,text:"",result:i.content,...i.parsedJson?{parsedContent:i.parsedJson}:{},state:"completed"};return {...t,nodes:[...t.nodes,l],byContentId:{...t.byContentId,[n]:l}}}let c={...a,result:i.content,...i.parsedJson?{parsedContent:i.parsedJson}:{},state:"completed"};return {...t,nodes:t.nodes.map(l=>l.kind==="content"&&l.id===n?c:l),byContentId:{...t.byContentId,[n]:c}}}function wo(t){let e=t.nodes.map(r=>r.kind==="content"&&r.state==="streaming"?{...r,state:"completed"}:r.kind==="step"&&r.status==="running"?{...r,status:"completed"}:r),n={...t.byContentId};for(let[r,s]of Object.entries(n))s.state==="streaming"&&(n[r]={...s,state:"completed"});let o={...t.byStepId};for(let[r,s]of Object.entries(o))s.status==="running"&&(o[r]={...s,status:"completed"});return {...t,nodes:e,byContentId:n,byStepId:o,isStreaming:false}}function wl(t,e){let n=mn(e)||null,o=e.payload,r=typeof o=="string"?o:o?.message||o?.status_message||o?.status||"";if(!r)return t;if(n){let a=t.byStepId[n];if(!a)return t;let i=a.status==="completed"||a.status==="error"?{...a,finishedStatus:r}:{...a,runningStatus:r};return {...t,nodes:t.nodes.map(c=>c.kind==="step"&&c.id===n?i:c),byStepId:{...t.byStepId,[n]:i}}}let s={kind:"status",stepId:null,message:r};return {...t,nodes:[...t.nodes,s]}}function Il(t,e){let n=t,o={content:n._rawText??t.text,user_visibility:"visible",content_type:"json",ui_content_type:{String:t.uiContentType||"json",Valid:true},parsedJson:t.parsedContent?[...t.parsedContent]:[],_jsonParser:n._jsonParser,_isInJson:n._isInJson,_charBuffer:n._charBuffer??"",_currentContent:n._currentContent},r=ir(o,e);return {parsedContent:r.parsedJson,_parserFields:{_rawText:r.content,_jsonParser:r._jsonParser,_isInJson:r._isInJson,_charBuffer:r._charBuffer,_currentContent:r._currentContent}}}function Nl(t){for(let e of t.nodes){if(e.kind==="step"){let n=t.byStepId[e.id];if(n&&n.type==="tool_call"&&!n.hidden)return true;continue}if(e.kind==="content"&&!(e.contentType==="tool_invocation"||e.contentType==="agent_invocation")&&(e.contentType==="tool_result"&&e.result||e.text||e.parsedContent?.length||e.result))return true}return false}function gn(t,e,n){return e.type!=="llm_call"?false:!(e.parentId===t.rootStepId)&&n.contentType==="text"}function ve(t){if(!t.rootStepId)return [];let e=[],n={};function o(s){if(!s)return false;if(s in n)return n[s];let a=s,i=false,c=[];for(;a;){if(a in n){i=i||n[a];break}c.push(a);let l=t.byStepId[a];if(!l)return false;if(l.hidden){i=true;break}a=l.parentId;}for(let l of c)n[l]=i;return i}function r(s){let a=false;if(s.contentType==="thinking"||s.contentType==="redacted_thinking"){let c=s.result??s.text;e.push({id:s.id,content_type:s.contentType,ui_content_type:s.uiContentType||s.contentType,content:c,state:s.state==="streaming"?"in_progress":"completed"}),a=true;}else if(s.contentType==="json"){if(s.parsedContent)for(let c=0;c<s.parsedContent.length;c++){let l=s.parsedContent[c];if(l.type==="text"&&l.content)e.push({id:`${s.id}-text-${c}`,content_type:"text",ui_content_type:"markdown",content:String(l.content)}),a=true;else if(l.type==="json"&&typeof l.content=="object"){let u=l.content;typeof u.output=="string"?e.push({id:`${s.id}-text-${c}`,content_type:"text",ui_content_type:"markdown",content:u.output}):typeof u.markdown=="string"?e.push({id:`${s.id}-text-${c}`,content_type:"text",ui_content_type:"markdown",content:u.markdown}):e.push({id:`${s.id}-json-${c}`,content_type:"json",ui_content_type:s.uiContentType||"ui_generation",content:u,state:s.state==="streaming"?"in_progress":"completed"}),a=true;}}else if(s.result){let c=typeof s.result=="string"?El(s.result):s.result;c&&typeof c=="object"&&(e.push({id:s.id,content_type:"json",ui_content_type:s.uiContentType||"json",content:c,state:s.state==="streaming"?"in_progress":"completed"}),a=true);}}if(a)return;let i=s.result??s.text;i&&e.push({id:s.id,content_type:s.contentType||"text",ui_content_type:s.uiContentType||"markdown",content:i,state:s.state==="streaming"?"in_progress":"completed"});}for(let s of t.nodes){if(s.kind!=="content"||s.contentType==="tool_invocation")continue;if(s.contentType==="tool_result"){s.result&&s.result.action_type!=="bot.invoke"&&e.push({id:s.id,content_type:"tool_result",ui_content_type:s.uiContentType||"tool_result",content:s.result});continue}if(s.stepId===null){r(s);continue}let a=t.byStepId[s.stepId];if(!a){r(s);continue}o(a.id)||a.type!=="tool_call"&&(a.type==="llm_call"&&gn(t,a,s)||r(s));}return e}function El(t){return t?$(t):null}function Bl(t){return (t.status==="completed"||t.status==="error")&&t.finishedStatus?t.finishedStatus:t.runningStatus?t.runningStatus:t.name.replace(/_/g," ")}function Ol(t){return t==="running"?"loading":t==="error"?"failed":"finished"}function Io(t,e){let n=t.byStepId[e];if(!n||n.type!=="agent"||(t.childrenByParentId[e]||[]).some(s=>{let a=t.byStepId[s];return !!a&&a.type==="agent"&&!a.hidden}))return false;for(let s of t.nodes){if(s.kind!=="step")continue;let a=t.byStepId[s.id];if(!a||a.type!=="agent"||a.hidden||a.id===e)continue;let i=a.id;for(;i;){if(i===e)return true;i=t.byStepId[i]?.parentId??null;}}return false}function Ml(t){return t==="info"?"info":t==="warning"?"warning":"standard"}function Vl(t){let e=t.trim();if(!e)return null;let n=new Set;n.add(e);let o=e.match(/^```[a-zA-Z0-9_-]*\n([\s\S]*?)\n```$/);o?.[1]&&n.add(o[1].trim());let r=e.indexOf("{"),s=e.lastIndexOf("}");r>=0&&s>r&&n.add(e.slice(r,s+1).trim());let a=e.indexOf("["),i=e.lastIndexOf("]");a>=0&&i>a&&n.add(e.slice(a,i+1).trim());for(let c of n){if(!c)continue;let l=$(c);if(l!=null)return typeof l=="string"?$(l)??l:l}return null}function No(t,e){let n=[],o="",r=[],s=0;function a(){r.length>0&&(n.push({id:`${e}-exec-${s}`,type:"codeexec",content:r.join(`
51
- `),wrapperType:Ml(o)}),s++,r=[]);}for(let i of t){let c=typeof i.message=="string"?i.message:"";if(!c)continue;let l=typeof i.level=="string"?i.level:"output";l!==o&&r.length>0&&a(),o=l,r.push(c);}return a(),n}function Eo(t,e,n){let o=[];for(let r of t){if(r.contentType==="tool_invocation"||r.contentType==="tool_result")continue;let s=`${e}-content-${r.id}`,a=r.state==="streaming"?"running":"completed";if(r.contentType==="thinking"||r.contentType==="redacted_thinking"){let i=r.result??r.text;if(!i)continue;o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType||r.contentType,content:i,state:r.state==="streaming"?"in_progress":"completed"},status:a});continue}if(r.result){let i=r.result;if(typeof r.result=="string")if(r.contentType==="json"){let c=$(r.result);if(c!=null)i=c;else {let l=Vl(r.result);if(l!==null)i=l;else if(!(r.parsedContent&&r.parsedContent.length>0))if(n){o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType||"ui_generation",content:r.result,state:r.state==="streaming"?"in_progress":"completed"}});continue}else {o.push({id:s,type:"text",content:r.result});continue}}}else {o.push({id:s,type:"text",content:r.result});continue}if(Array.isArray(i)&&i.length>0){o.push(...No(i,s));continue}if(typeof i=="object"&&i!==null){let c=i;if(typeof c.code=="string"){o.push({id:s,type:"codegen",contentData:c,status:a});continue}if(n){o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType,content:i,state:r.state==="streaming"?"in_progress":"completed"}});continue}}}if(r.contentType==="json"&&r.parsedContent){if(r.uiContentType==="codeexec_output"){let i=[];for(let c of r.parsedContent)c.type==="json"&&typeof c.content=="object"&&i.push(c.content);o.push(...No(i,s));continue}for(let i=0;i<r.parsedContent.length;i++){let c=r.parsedContent[i];if(c.type==="text"&&c.content)o.push({id:`${s}-text-${i}`,type:"text",content:String(c.content)});else if(c.type==="json"&&typeof c.content=="object"){let l=c.content;typeof l.code=="string"?o.push({id:`${s}-codegen-${i}`,type:"codegen",contentData:l,status:a}):typeof l.markdown=="string"?o.push({id:`${s}-text-${i}`,type:"text",content:l.markdown}):typeof l.output=="string"?o.push({id:`${s}-text-${i}`,type:"text",content:l.output}):n&&o.push({id:`${s}-content-${i}`,type:"content",contentItem:{id:`${s}-content-${i}`,content_type:"json",ui_content_type:r.uiContentType||"ui_generation",content:l,state:r.state==="streaming"?"in_progress":"completed"}});}}continue}r.text&&r.contentType!=="json"&&o.push({id:s,type:"text",content:r.text});}return o}function $l(t,e){if(!t.rootStepId)return [];let n=[],o={},r={},s=new Set,a={},i={},c={};function l(f){return r[f]||(r[f]=[]),r[f]}function u(f){if(f)return t.byStepId[f]}function p(f){if(!f)return false;if(f in c)return c[f];let g=f,h=[],b=false;for(;g;){if(g in c){b=b||c[g];break}h.push(g);let S=u(g);if(!S)break;if(S.hidden){b=true;break}g=S.parentId;}for(let S of h)c[S]=b;return b}function d(f){return p(f.id)}for(let f of t.nodes){if(f.kind!=="content"||!f.stepId||f.contentType==="tool_invocation"||f.contentType==="tool_result"||f.contentType==="agent_invocation"||!f.text&&!f.result&&!f.parsedContent?.length)continue;let g=u(f.stepId);if(!g||d(g)||g.type==="llm_call"&&gn(t,g,f))continue;let h=f.stepId;for(;h;){i[h]=true;let b=u(h);if(!b)break;h=b.parentId;}}function m(f){return !!i[f]}function x(f){if(!f)return null;if(f in a)return a[f];let g=f;for(;g;){let h=u(g);if(!h)break;let b=g===t.rootStepId,S=h.type==="agent"&&!h.hidden&&(!b||!Io(t,h.id)),v=h.type==="tool_call"&&!h.hidden;if(S||v)return a[f]=g,g;g=h.parentId;}return a[f]=null,null}function y(f,g){if(g.length===0)return;let h=x(f);if(!h){n.push(...g);return}let b=o[h];if(!b){l(h).push(...g);return}b.children||(b.children=[]),b.children.push(...g);}function k(f,g,h){if(!h||typeof h!="object")return [];let b=h,S=typeof b.result=="object"&&b.result!==null?b.result:b,v=[];typeof S.code=="string"&&S.code.trim()&&v.push({id:`${f}-${g}-codegen`,type:"codegen",contentData:S});let T=typeof S.output=="string"?S.output.trim():"";return T&&v.push({id:`${f}-${g}-output`,type:"codeexec",content:T}),v}for(let f of t.nodes){if(f.kind==="step"){let h=t.byStepId[f.id];if(!h||h.hidden||h.type==="llm_call"||h.id===t.rootStepId&&Io(t,h.id)||s.has(h.id))continue;s.add(h.id);let b={id:h.id,type:"step",label:Bl(h),status:h.status},S=r[h.id];S&&S.length>0&&(b.children=S,delete r[h.id]),o[h.id]=b,y(h.parentId,[b]);continue}if(f.kind!=="content"||f.contentType==="tool_invocation")continue;if(f.stepId===null){n.push(...Eo([f],"root",e));continue}let g=t.byStepId[f.stepId];if(g&&!d(g)&&!(g.type==="llm_call"&&gn(t,g,f))){if(g.type==="tool_call"&&f.contentType==="tool_result"){if(m(g.id))continue;y(g.id,k(g.id,f.id,f.result));continue}y(g.id,Eo([f],g.id,e));}}return n}function To({node:t,ContentComponent:e}){let[n,o]=useState(t.status==="running"),r=useRef(t.status==="running");if(useEffect(()=>{r.current&&t.status!=="running"&&o(false),r.current=t.status==="running";},[t.status]),t.type==="text")return jsx(B,{content:t.content||"",className:"max-w-none"});if(t.type==="codegen"&&t.contentData){let{code:i,step_by_step:c,thinking:l}=t.contentData;return jsxs("div",{className:"space-y-2",children:[c&&jsx(B,{content:c,className:"text-sm max-w-none"}),l&&jsx(Ce,{content:l,state:t.status==="running"?"in_progress":"completed"}),i&&jsx(xt,{language:"python",value:i,defaultOpen:false})]})}if(t.type==="codeexec"&&t.content){let i=t.wrapperType||"standard";return jsx(kt,{wrapperType:i,compact:true,children:jsx(Xt,{children:t.content})})}if(t.type==="content"&&t.contentItem&&e)return jsx(e,{content:t.contentItem});if(t.type==="content"&&t.contentItem)return jsx(Mt,{content:t.contentItem});let s=!!t.children?.length,a=t.status==="running"?"text-foreground":"text-muted-foreground";return jsxs(ee.Root,{open:n,onOpenChange:o,className:"w-full",children:[jsxs(ee.Trigger,{className:`flex items-center justify-between w-full text-sm py-0.5 ${a} ${s?"hover:text-foreground cursor-pointer":"cursor-default"}`,disabled:!s,children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(rt,{status:Ol(t.status),size:14}),jsx("span",{children:t.label})]}),s&&jsx(ChevronDown,{className:`h-4 w-4 shrink-0 text-muted-foreground/50 transition-transform duration-200 ${n?"rotate-180":""}`})]}),s&&jsx(ee.Content,{children:jsx("div",{className:"ml-5 mt-1 flex flex-col gap-1",children:t.children?.map(i=>jsx(To,{node:i,ContentComponent:e},i.id))})})]})}function Do({agentState:t,ContentComponent:e,className:n}){if(!t.rootStepId)return null;let o=useMemo(()=>$l(t,e),[t,e]);return o.length===0?null:jsx("div",{className:`flex flex-col gap-1 ${n||""}`,children:o.map(r=>jsx(To,{node:r,ContentComponent:e},r.id))})}function U(t){if(!t)throw new Error("Entity is null");if(!("_type"in t))throw new Error(`Entity ${JSON.stringify(t)} is missing _type`);return t._type}function Ll(t){return t.contents.length===0?null:t.contents[t.contents.length-1]||null}function Oo(t){return t.contents.length===0?null:t.contents[0]||null}function Ao(t){let e=false,n=t.contents.map(r=>r.state!=="in_progress"?r:(e=true,{...r,state:"completed",updated_at:new Date().toISOString()}));if(!e&&t.state==="completed")return t;let o={...t.contentsByID};for(let r of n)o[r.id]=r;return {...t,state:"completed",contents:n,contentsByID:o}}function mr(t,e){let n=U(t);switch(n){case "message":return t;case "step":let o=t;if(e){let a=o.eventsByID[e]?.Message;return a||$o({},"",e)}let s=Object.keys(o.eventsByID).reverse();for(let a of s){let i=o.eventsByID[a];if(i&&i.Message)return i.Message}throw new Error("Unable to find message for step");default:throw new Error(`Unable to have messages on entity type ${n}`)}}function Ul(t,e){switch(U(t)){case "message_content":return t;case "output_content":return t;case "message":return le(t,e);case "output":return ce(t,e);case "step":let o=xn(t,e);return o?ce(o,e):null;default:return null}}function le(t,e){let n=U(t);switch(n){case "message_content":return t;case "message":let o=mr(t);if(!o)throw new Error("Unable to find message to add content to");return e?o.contentsByID[e]:Ll(o);default:throw new Error(`Unable to have message content on entity type ${n}`)}}function ce(t,e){let n=U(t);switch(n){case "output_content":return t;case "output":let o=t;return e?o.contentsByID[e]||null:o.contents.length<=0?null:o.contents[o.contents.length-1]||null;case "step":let s=xn(t,e);return s?ce(s):null;case "invocation":if(!e)return null;let a=t.eventsByID[e];return !a||!a.Output?null:ce(a.Output);default:throw new Error(`Unable to have output content on entity type ${n}`)}}function fr(t,e){let n=U(t),o=null;switch(n){case "invocation":return t;case "message_content":if(o=t.botInvocation||null,!o)throw new Error("Unable to find bot invocation for message content");if(e&&o.bot_invocation.id!==e)throw new Error("Unable to find bot invocation for message content - mismatched ID");return o;case "message":if(o=Oo(t)?.botInvocation||null,!o)throw new Error("Unable to find bot invocation for message");if(e&&o.bot_invocation.id!==e)throw new Error("Unable to find bot invocation for message - mismatched ID");return o;case "output_content":return t.botInvocation||null;default:throw new Error(`Unable to have bot invocation on entity type ${n}`)}}function xn(t,e){let n=U(t);switch(n){case "output":return t;case "step":let o=t;if(e){let i=o.eventsByID[e]?.Output;if(!i)throw new Error("Unable to find output with id "+e);return i}let s=Object.keys(o.eventsByID).reverse();for(let i of s){let c=o.eventsByID[i];if(c&&c.Output)return c.Output}throw new Error("Unable to find output for step");case "invocation":if(!e)throw new Error("Unable to find output for invocation without ID");return t.eventsByID[e]?.Output||null;default:throw new Error(`Unable to have step outputs on entity type ${n}`)}}function Mo(t,e){let n=U(t);switch(n){case "result_handler":return t;case "step":if(!e)throw new Error("Unable to have result handlers on step without ID");let o=t.eventsByID[e];if(!o||!o.type||o.type!=="result_handler"||!o.ResultHandler)throw new Error(`Unable to find result handler with id ${e} on step ${t.id}`);return o.ResultHandler;default:throw new Error(`Unable to have result handlers on entity type ${n}`)}}function Vo(t,e){let n=U(t),o=null;switch(n){case "step":if(t.id===e||!e)return t;throw new Error("Unable to find step on step with id "+e);case "invocation":if(!e)throw new Error("Unable to have steps on bot invocation without ID");o=t;let r=o.eventsByID[e];if(!r)throw new Error("Unable to find step on invocation with id "+e);if(!r.Step)throw new Error("Unable to find step on invocation with id "+e);return r.Step;case "result_handler":if(!e)throw new Error("Unable to have steps on result handler without ID");let a=t.eventsByID[e];if(!a)throw new Error("Unable to find step on result handler with id "+e);if(!a.Step)throw new Error("Unable to find step on result handler with id "+e);return a.Step;default:throw new Error(`Unable to have steps on entity type ${n}`)}}var dr=class extends Error{};function jl(t,e,n){let o=null,r=e[0],s=e[1];n[r]=s;try{switch(r){case "message":o=mr(t,s);break;case "content":o=le(t,s);break;case "step":o=Vo(t,s);break;case "output":o=xn(t,s);break;case "output_content":o=ce(t,s);break;case "invocation":o=fr(t,s);break;case "result_handler":o=Mo(t,s);break}}catch(a){throw console.error("error finding next entity"),console.log("path",e),console.log("currentEntity",t),a}if(!o)throw console.log("path",e),console.log("currentEntity",t),console.log("nextEntity",o),new dr(`Unable to find next entity for path ${e.join("/")}`);return o}function $o(t,e,n,o){let r=t.payload;return {_type:"message",message:{id:n,thread_id:e,author_id:r.author_id||"app",author_entity_type:r.author_entity_type||"app",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),role:r.role||"assistant",avatar:"/teams/erdo-icon.png"},state:"in_progress",contents:[],contentsByID:{},contentIDToIdx:{}}}function Fl(t,e){return {_type:"message_content",id:t.metadata.message_content_id,message_id:e.message,content_type:t.metadata.content_type,created_by_invocation_id:t.metadata.invocation_id,invocation_id:t.metadata.invocation_id,state:"in_progress",user_visibility:t.metadata.user_visibility??"visible",bot_visibility:t.metadata.bot_visibility??"visible",content:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:t.metadata?.ui_content_type?{String:t.metadata.ui_content_type,Valid:true}:{String:"",Valid:false}}}function Jl(t,e){let n=t.metadata.content_type||"text",o=t.metadata?.ui_content_type,r=ae(n,t.payload);return {_type:"message_content",id:t.metadata.message_content_id,message_id:e.message,content:r.content,content_type:n,created_by_invocation_id:t.metadata.invocation_id,invocation_id:t.metadata.invocation_id,state:"completed",user_visibility:t.metadata.visibility||"visible",bot_visibility:"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:o?{String:o,Valid:true}:{String:"",Valid:false},parsedJson:r.parsedJson??null}}function Gl(t,e,n){let o=t.payload;return {_type:"step",id:e,invocation_id:n.invocation||"",step_id:o.step_id||"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_status_id:"",path:{String:"",Valid:false},action_type:{String:o.action_type,Valid:true},key:{String:o.key,Valid:true},bot_id:o.bot_id,result_handler_id:"",step_order:{Int32:o.step_order,Valid:true},output_content_type:{String:o.content_type,Valid:true},execution_mode:{String:o.execution_mode,Valid:true},output_behaviour:{String:o.output_behaviour,Valid:true},user_output_visibility:{String:t.metadata.visibility||"visible",Valid:true},output_channels:o.output_channels||[],running_message:{String:o.running_message||"",Valid:!!o.running_message},finished_message:{String:o.finished_message||"",Valid:!!o.finished_message},depends_on:[],eventsByID:{},currentStatus:null}}function Wl(t,e,n){let o=t.payload;return {_type:"result_handler",id:e,invocation_id:t.metadata.invocation_id||"",result_handler_id:o.result_handler_id||e,step_invocation_id:o.step_invocation_id||"",type:o.type||"",if_conditions:o.if_conditions||{},created_at:new Date().toISOString(),updated_at:new Date().toISOString(),output_content_type:o.output_content_type||"",result_handler_order:o.result_handler_order||0,eventsByID:{}}}function ql(t,e,n){return {_type:"output",id:e,step_id:n.step_id,output:{id:e,invocation_id:t.metadata?.invocation_id,path:t.metadata.path,created_at:new Date().toISOString(),updated_at:new Date().toISOString()},state:"in_progress",contents:[],contentsByID:{},contentIDToIdx:{}}}function Ro(t,e,n,o=null){return {_type:"output_content",id:e,output_id:n.output,content:"",content_type:t.metadata.content_type,state:"in_progress",invocation_id:t.metadata.invocation_id,user_visibility:o??t.metadata.user_visibility??"visible",bot_visibility:t.metadata.bot_visibility??"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:t.metadata.ui_content_type?{String:t.metadata.ui_content_type,Valid:true}:{String:"",Valid:false},output:null}}function Po(t,e,n,o=null){let r=t.metadata.content_type||"text",s=ae(r,t.payload),a=t.metadata?.ui_content_type;return {_type:"output_content",id:e,output_id:n.output,content:s.content,content_type:r,state:"completed",invocation_id:t.metadata.invocation_id,parsedJson:s.parsedJson??null,user_visibility:o||t.metadata.visibility||"visible",bot_visibility:"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:a?{String:a,Valid:true}:{String:"",Valid:false},output:null}}function zl(t,e,n){return {_type:"invocation",bot_invocation:{id:t.payload.invocation_id,bot_id:t.payload.bot_id,bot_name:t.payload.bot_name,created_by_user_id:t.payload.created_by_user_id,current_state_id:"",parent_invocation_id:"",branch_init_state_id:"",current_status_id:"",organization_id:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},eventsByID:{},currentStatus:null,current_status:null,step_invocations:[],step_invocation_states:[],resources:[],outputs:[],statuses:[]}}function we(t,e){let n=t.payload;return {_type:"status",id:new Date().toISOString(),status:n.status,message:{String:n.message,Valid:true},Details:n}}function Lo(t){return {id:t.id,type:"step",created_at:t.created_at,_type:"invocation_event",Output:null,Message:null,Status:null,ResultHandler:null,Step:t}}function gr(t){return {id:t.output.id,type:"output",created_at:t.output.created_at,_type:"invocation_event",Output:t,Message:null,Status:null,ResultHandler:null,Step:null}}function yr(t){return {id:t.id,type:"status",created_at:t.created_at,_type:"invocation_event",Status:t,Output:null,Message:null,ResultHandler:null,Step:null}}function Hl(t){return {id:t.message.id,type:"message",created_at:t.message.created_at,_type:"invocation_event",Output:null,Message:t,Status:null,ResultHandler:null,Step:null}}function Kl(t){return {id:t.id,type:"result_handler",created_at:t.created_at,_type:"invocation_event",Output:null,Message:null,Status:null,ResultHandler:t,Step:null}}var Ql=new Set(["=","("]);function Zl(t){if(!t||t.length===0)return true;let e=t[t.length-1];return !Ql.has(e)}function Uo(t,e){if(t.content||(t.content=""),t.user_visibility!=="visible"||!ge(t.content_type,t.ui_content_type.String))return t.content+=e,{...t};if(t.parsedJson||(t.parsedJson=[]),typeof e=="object")return t.content+=JSON.stringify(e),t.parsedJson=[...t.parsedJson,e],{...t};t._jsonParser||(t._isInJson=false),t._charBuffer||(t._charBuffer="");let n=t.content_type,o=t.ui_content_type.String;for(let r of e){t.content+=r;let s=n==="json"||o==="json";if(!t._isInJson&&s&&!Dt(r)){t._isInJson=true,t._jsonParser=new X;let a={content:{},type:"json"};t.parsedJson=[...t.parsedJson||[],a],t._currentContent=a,t._charBuffer="";}if(!t._isInJson&&!s&&o==="ui_generation"&&r==="{"){let a=t.content.slice(0,-1);if(Zl(a)){t._charBuffer="{";continue}}if(t._charBuffer&&Dt(r)){t._charBuffer+=r;continue}if(!t._isInJson&&!s&&o==="ui_generation"&&t._charBuffer?.match(/^\s*{\s*$/)&&r==='"'){t._isInJson=true,t._jsonParser=new X;let i={content:t._jsonParser.add("{"),type:"json"};t._currentContent?.content?t._currentContent.content.match(/^\s*{$/)?(t._currentContent=i,t.parsedJson=[...t.parsedJson.slice(0,-1),i]):(t._currentContent.content=t._currentContent.content.replace(/{$/,""),t._currentContent=i,t.parsedJson=[...t.parsedJson,i]):(t._currentContent=i,t.parsedJson=[...t.parsedJson,i]);}if(t._isInJson)try{let a=t._jsonParser.add(r);t._currentContent.content=a,t._jsonParser.state==="END"&&(t._isInJson=!1,t._currentContent=void 0);}catch(a){if(console.log("handleIncrementalMixedJsonParsing: content chunk",e),console.log("handleIncrementalMixedJsonParsing: accumulated content",t.content),console.warn("handleIncrementalMixedJsonParsing: JSON parse error, recovering as text",a),t._isInJson=false,t._jsonParser=void 0,t.parsedJson&&t.parsedJson.length>0){let i=t.parsedJson[t.parsedJson.length-1];if(i.type==="json"){let c=t.content.lastIndexOf("{"),l=t.content.slice(c);i.type="text",i.content=l,t._currentContent=i;}}continue}else t._currentContent||(t._currentContent={content:t._charBuffer||"",type:"text"},t.parsedJson=[...t.parsedJson,t._currentContent]),t._currentContent.content+=t._charBuffer+r;t._charBuffer="";}return {...t}}function Yl(t,e){return Uo(t,e)}function Bo(t,e){return Uo(t,e)}function pr(t,e){let n=U(t);switch(n){case "message":return dt(t,e);case "message_content":return hn(t,e);case "step":return tc(t,e);case "output":return ec(t,e);case "output_content":return nc(t,e);case "invocation":return Ie(t,e);case "result_handler":return rc(t,e);default:throw new Error(`Unable to add update entity for entity type ${n}`)}}function Xl(t,e){for(let n of e)t=pr(t,n);return t}function dt(t,e){let n=mr(t);if(!n)throw new Error("Unable to find message to add content to");let o=U(e),r=null;switch(o){case "message_content":if(r=e,!n.contentsByID[r.id])n.contentIDToIdx={...n.contentIDToIdx,[r.id]:n.contents.length},n.contents=[...n.contents,r];else {let i=n.contentIDToIdx[r.id];n.contents=[...n.contents.slice(0,i),r,...n.contents.slice(i+1)];}return n.contentsByID={...n.contentsByID,[r.id]:r},{...n};case "invocation":let s=e;if(n.contents.length===0)throw new Error("Unable to find message content to add invocation to");return r=hn(n.contents[0],s),dt(n,r);case "step":if(n.contents.length===0)throw new Error("Unable to find message content to add content to");if(r=n.contents[0],!r)throw new Error("Unable to find message content to add content to");let a=fr(r);if(!a)throw new Error("Unable to find bot invocation to add content to");return r.botInvocation=Ie(a,e),dt(n,r);case "status":if(n.contents.length>0){let i=n.contents[0];if(i?.botInvocation){let c=hn(i,e);return dt(n,c)}}return {...n};default:throw new Error(`Unable to add update message child for child type ${o}`)}}function hn(t,e){let n=le(t);if(!n)throw new Error("Unable to find message content to add content to");let o=U(e);switch(o){case "invocation":return n.botInvocation=e,{...n};case "step":let r=n.botInvocation;if(!r)throw new Error("Unable to find bot invocation to add content to");return n.botInvocation=Ie(r,e),{...n};case "status":return n.botInvocation&&(n.botInvocation=Ie(n.botInvocation,e)),{...n};default:throw new Error(`Unable to add update message content child for child type ${o}`)}}function tc(t,e){let n=Vo(t);if(!n)throw new Error("Unable to find bot invocation to add step to");let o=U(e),r=null;switch(o){case "output":let s=e;return r=gr(s),n.eventsByID={...n.eventsByID,[s.output.id]:r},{...n};case "message":let a=e;return r=Hl(a),n.eventsByID={...n.eventsByID,[a.message.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID={...n.eventsByID,[i.id]:r},{...n};case "result_handler":let c=e;return r=Kl(c),n.eventsByID={...n.eventsByID,[c.id]:r},{...n};default:throw new Error(`Unable to add update step for entity type ${o}`)}}function ec(t,e){let n=xn(t);if(!n)throw new Error("Unable to find step output to add content to");let o=U(e);switch(o){case "output_content":let r=e;if(!n.contentsByID[r.id])n.contentIDToIdx={...n.contentIDToIdx,[r.id]:n.contents.length},n.contents=[...n.contents,r];else {let s=n.contentIDToIdx[r.id];n.contents=[...n.contents.slice(0,s),r,...n.contents.slice(s+1)];}return n.contentsByID={...n.contentsByID,[r.id]:r},{...n};default:throw new Error(`Unable to add update output for entity type ${o}`)}}function nc(t,e){let n=ce(t);if(!n)throw new Error("Unable to find step output content to add content to");let o=U(e);switch(o){case "invocation":return n.botInvocation=e,{...n};case "step":let r=n.botInvocation;if(!r)throw new Error("Unable to find bot invocation to add content to");return n.botInvocation=Ie(r,e),{...n};default:throw new Error(`Unable to add update step output content for entity type ${o}`)}}function Ie(t,e){let n=fr(t);if(!n)throw new Error("Unable to find bot invocation to add content to");let o=U(e),r;switch(o){case "step":let s=e;return r=Lo(s),n.eventsByID={...n.eventsByID,[s.id]:r},{...n};case "output":let a=e;return r=gr(a),n.eventsByID={...n.eventsByID,[a.output.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID={...n.eventsByID,[i.id]:r},n.currentStatus=i,{...n};default:throw new Error(`Unable to add update invocation for entity type ${o}`)}}function rc(t,e){let n=Mo(t);if(!n)throw new Error("Unable to find result handler to add content to");let o=U(e),r=null;switch(o){case "step":let s=e;return r=Lo(s),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[s.id]:r},{...n};case "output":let a=e;return r=gr(a),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[a.output.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[i.id]:r},{...n};default:throw new Error(`Unable to add update to result handler for entity type ${o}`)}}function oc(t){return t==="bot started"||t==="bot resumed"||t==="message created"||t==="create message content"||t==="message content result"||t==="step started"||t==="result handler started"||t==="state created"||t==="step output created"||t==="create step output content"||t==="step output content result"||t==="log"}function kn(t,e,n,o,r,s=null,a=[],i={}){if(!s&&Object.keys(r).length>0){let p,d;if(n.length>=2&&n[0]==="message"?(d=n[1],p=r[d],p||(p=Object.values(r)[0],d=Object.keys(r)[0])):(p=Object.values(r)[Object.values(r).length-1],d=Object.keys(r)[Object.keys(r).length-1]),i.message=d,n.length<=2&&t==="message finished")return r[d]=Ao(p),null;if(n[0]!=="content"&&Object.keys(p.contentsByID).length>0&&e.metadata.message_content_id){let m=e.metadata.message_content_id,x=p.contentsByID[m];x&&(s=x);}s?a=[p]:s=p;}if(n.length<=2&&oc(t)){let p=n[1],d=[],m,x,y,k,f;switch(t){case "bot started":case "bot resumed":if(!s)throw new Error("Unable to find message to add content to");let g=zl(e);if(s._type==="message_content"){if(x=s,!x.id)throw new Error("Unable to find message content id");if(y=r[x.message_id],!y)throw new Error("Unable to find message to add content to");if(k=le(y,x.id),!k)throw new Error("Unable to find message content to add content to");let v=hn(k,g);r[x.message_id]={...dt(y,v)};}d.push(g);break;case "message created":return r[p]=$o(e,o,p),null;case "create message content":if(!s)throw new Error("Unable to find message to add content to");if(f=Fl(e,i),s._type==="output"){m=s,d.push(Ro(e,p,i,"hidden"));let v=e.payload.message_id;if(v||(v=a[0].message.id),y=r[v],!y)throw new Error("Unable to find message to add content to")}else if(s._type==="message_content"){if(m=s,y=r[m.message_id],!y)throw new Error("Unable to find message to add content to")}else {if(s._type!=="message")throw new Error(`Incorrect path? Cannot add content to non-message entity: ${s._type}`);if(m=s,y=r[m.message.id],!y)throw new Error("Unable to find message to add content to");d.push(f);}r[y.message.id]={...dt(y,f)};break;case "message content result":if(!s)throw new Error("Unable to find message to add content to");let h=null;if(s._type==="output"){d.push(Po(e,p,i,"hidden"));let v=e.payload.message_id||i.message;if(v?h=a.find(T=>T.message.id===v):h=a[0],y=r[v],!y)throw new Error("Unable to find message to add content to")}else if(s._type==="message_content"){if(h=a[0],y=r[h.message.id],!y)throw new Error("Unable to find message to add content to")}else {if(s._type!=="message")throw new Error(`Incorrect path? Cannot add content to non-message entity: ${s._type}`);if(h=s,y=r[h.message.id],!y)throw new Error("Unable to find message to add content to")}let b=e.metadata.message_content_id;if(!b)throw new Error("Unable to find message content id");let S=le(h,b);if(S){S.state="completed";let v=S.content_type||"text",T=pn(v,S.content,e.payload);S.content=T.content,T.parsedJson&&(S.parsedJson=T.parsedJson),r[y.message.id]={...dt(y,S)},(s._type==="message"||s._type==="message_content")&&d.push(S);}else S=Jl(e,i),r[y.message.id]={...dt(y,S)},(s._type==="message"||s._type==="message_content")&&d.push(S);break;case "step started":d.push(Gl(e,p,i));break;case "result handler started":d.push(Wl(e,p));break;case "step output created":d.push(ql(e,p,s));break;case "create step output content":d.push(Ro(e,p,i));break;case "step output content result":d.push(Po(e,p,i));break;case "log":return null;default:throw new Error(`Unable to handle create event type ${t}`)}return d.length?!s||s._type==="message_content"&&d.length===1&&d[0]._type==="message_content"?d[0]:Xl(s,d):null}if(!s)throw new Error("No first message has been created, so cannot handle amend events");if(n.length<=1){let p=null;try{p=Ul(s);}catch{}switch(t){case "message content delta":if(!p)throw new Error("Unable to find message content");let d=null,m=null,x=null;if(s._type==="output_content"){d=Bo(s,e.payload);let g=e.metadata.message_content_id;if(!g)throw new Error("Unable to find message content id from entity ids");let h=i.message;if(x=a.find(b=>b.message.id===h),!x)throw new Error("Unable to find message to add content to");m=le(x,g);}else {if(m=p,x=a[a.length-1],!x)throw new Error("Unable to find message to add content to");if(x._type!=="message")throw new Error("Unable to find message to add content to - not a message")}if(!m)throw new Error("Unable to find message content");let y=r[x.message.id];if(!y)throw new Error("Unable to find message to add content to");let k=Yl(m,e.payload);return r[y.message.id]={...dt(y,k)},s._type==="message_content"&&(d=k),d;case "step output content delta":return Bo(p,e.payload);case "status":if(s._type==="step"&&(s.currentStatus=we(e)),s._type==="invocation"&&(s.currentStatus=we(e)),s._type==="message_content"){let f=s;if(f.botInvocation)return f.botInvocation.currentStatus=we(e),{...f}}if(s._type==="message"){let f=s,g=Oo(f);if(g?.botInvocation)return g.botInvocation.currentStatus=we(e),dt(f,g)}return pr(s,we(e));case "result":return null;case "message finished":if(s._type==="message"){let g=Ao(s);r[g.message.id]=g;}return null;case "step output finished":return null;case "step result":return null;case "error":return null;case "dataset created":return null;case "log":return null;default:throw new Error(`Unable to handle event type ${t}`)}}let c=n.slice(2),l=jl(s,n,i),u=kn(t,e,c,o,r,l,[...a,s],i);return u?pr(s,{...u}):s}function hr(t){if(!t.content)return null;if(typeof t.content=="object")return t.content;if(typeof t.content=="string"){let e=$(t.content);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}return null}function jo(t){let e=t.content_type;if(e==="tool_result")return "result";if(e==="tool_invocation")return "invocation";let n=hr(t);return n&&"action_type"in n&&"name"in n&&"input"in n&&n.action_type!=="bot.invoke"?"result"in n?"result":"invocation":null}function Fo(t){return hr(t)?.id}function Jo(t){let e=hr(t);if(!e?.action_type)return null;let o=e.input?.query;return `${e.action_type}:${o||""}`}function Go(t){let e=t.filter(r=>jo(r)==="result"),n=new Set(e.map(r=>Fo(r)).filter(Boolean)),o=new Set(e.map(r=>Jo(r)).filter(Boolean));return t.filter(r=>{if(jo(r)==="invocation"){let s=Fo(r),a=Jo(r);if(s&&n.has(s)||a&&o.has(a))return false}return true})}function Wo(t,e,n){let o=e;for(;o;){if(o===n)return true;o=t.byStepId[o]?.parentId??null;}return false}function bn(t,e){if(!e||!t.byStepId[e])return t;let n=new Set;for(let i of t.nodes)i.kind==="step"&&Wo(t,i.id,e)&&n.add(i.id);let o=t.nodes.filter(i=>i.kind==="step"?n.has(i.id):i.kind==="content"||i.kind==="status"?!!i.stepId&&n.has(i.stepId):false),r={},s={},a={};for(let i of n){let c=t.byStepId[i];c&&(r[i]=c);}for(let i of o){if(i.kind==="content"){s[i.id]=i;continue}if(i.kind!=="step")continue;let l=(i.parentId&&n.has(i.parentId)?i.parentId:null)??"__root__";a[l]=[...a[l]||[],i.id];}return {...t,nodes:o,byStepId:r,byContentId:s,childrenByParentId:a,rootStepId:e}}function Ne(){return createStore((t,e)=>({globalState:fn(),invocationStates:{},invocationRootSteps:{},pendingInvocationQueue:[],pushEvent:(n,o)=>{let r=e(),s=ur(r.globalState,n);if(o&&(s=o(s)),s===r.globalState)return;let a=n.metadata?.step_id??n.payload?.step_id??"",i={...r.invocationStates},c=false;for(let[l,u]of Object.entries(r.invocationRootSteps)){let p=r.invocationStates[l];if(a&&!Wo(s,a,u)&&a)continue;let d=bn(s,u);if(!(n.type==="step_finished"||n.type==="step_started"||n.type==="status")&&p&&p.nodes.length===d.nodes.length){let x=p.nodes[p.nodes.length-1],y=d.nodes[d.nodes.length-1];if(x===y&&p.isStreaming===d.isStreaming)continue}i[l]=d,c=true;}t({globalState:s,...c?{invocationStates:i}:{}});},registerInvocation:n=>{let o=e();o.invocationRootSteps[n]||o.pendingInvocationQueue.includes(n)||t({pendingInvocationQueue:[...o.pendingInvocationQueue,n]});},mapInvocationRoot:(n,o)=>{let r=e(),s=bn(r.globalState,o);t({invocationRootSteps:{...r.invocationRootSteps,[n]:o},invocationStates:{...r.invocationStates,[n]:s},pendingInvocationQueue:r.pendingInvocationQueue.filter(a=>a!==n)});},reset:()=>{t({globalState:fn(),invocationStates:{},invocationRootSteps:{},pendingInvocationQueue:[]});}}))}function lc(t){return t.split("/").filter(Boolean)}function qo(t={}){let e=Ct(),[n,o]=useState(null),[r,s]=useState(false),[a,i]=useState(null),[c,l]=useState([]),u=useRef(Ne()),p=useStore(u.current,g=>g.globalState),d=useRef(null),m=useRef(t.threadId);t.threadId!==m.current&&(m.current=t.threadId);let x=useCallback(()=>{d.current&&(d.current.abort(),d.current=null);},[]),y=useCallback(g=>{o(g),m.current=g.id;},[]),k=useCallback(async g=>{if(!e.client)throw new Error("ErdoClient not configured in provider. Pass a client to ErdoProvider config to use useThread.");if(!e.client.sendMessage)throw new Error("ErdoClient does not support sendMessage. Make sure you are using @erdoai/server client.");if(!e.client.createThread)throw new Error("ErdoClient does not support createThread. Make sure you are using @erdoai/server client.");x(),d.current=new AbortController,s(true),i(null),l([]),u.current.getState().reset();let h={};try{let b=m.current;if(!b){let E=await e.client.createThread();o(E),m.current=E.id,b=E.id;}for await(let E of e.client.sendMessage(b,{content:g,botKey:t.botKey})){if(d.current?.signal.aborted)break;if(t.onEvent?.(E),e.useAgentEvents)u.current.getState().pushEvent(E);else {let z=E.type||"",Q=E.metadata||{},R=lc(Q.path||""),j={payload:E.payload,metadata:{path:Q.path||"",...Q}};try{kn(z,j,R,b,h);}catch(F){console.error("Error handling SSE event:",F,z);}l(Object.values(h));}}let S=Object.values(h);l(S);let v=u.current.getState().globalState,T;v.rootStepId?T=ve(v):T=S.flatMap(E=>E.contents||[]).filter(E=>E.user_visibility==="visible").map(E=>({id:E.id,content_type:E.content_type,ui_content_type:P(E.ui_content_type),content:E.content,parsedJson:E.parsedJson,botInvocation:E.botInvocation})),t.onFinish?.(T);}catch(b){let S=b instanceof Error?b:new Error(String(b));throw i(S),t.onError?.(S),S}finally{s(false),d.current=null;}},[e.client,e.useAgentEvents,t,x]),f=useMemo(()=>{if(p.rootStepId)return ve(p);let g=c.flatMap(b=>b.contents||[]).filter(b=>b.user_visibility==="visible");return Go(g).map(b=>({id:b.id,content_type:b.content_type,ui_content_type:P(b.ui_content_type),content:b.content,parsedJson:b.parsedJson,botInvocation:b.botInvocation}))},[c,p]);return {thread:n,isStreaming:r,error:a,activeMessages:c,agentState:p,streamingContents:f,sendMessage:k,cancel:x,setThread:y,agentStreamStore:u.current}}function cc(t){return t?typeof t=="string"?t:typeof t=="object"&&t!==null&&"String"in t&&t.String||"":""}function zo(t){let e=cc(t.ui_content_type),n=t.content_type,o={id:t.id,content_type:t.content_type,ui_content_type:e,content:t.content,invocation_id:t.created_by_invocation_id};if(typeof t.content=="string"){if((n==="json"||e==="json")&&t.content.trim()){let r=$(t.content);r!=null&&(o.parsedJson=[{type:"json",content:r}]);}else if(e==="ui_generation")try{o.parsedJson=ft(t.content);}catch(r){console.error("Error parsing UI generation content:",r);}}if((t.content_type==="thinking"||t.content_type==="redacted_thinking")&&typeof t.content=="string"){let r=$(t.content);r&&typeof r=="object"&&(o.content=r);}return o}function uc(t){return t.filter(e=>e.user_visibility!=="hidden").map(zo)}var Sn=createContext(null);function Ko({store:t,children:e}){return jsx(Sn.Provider,{value:t,children:e})}function Qo(){return useContext(Sn)}function Zo(t){let e=useContext(Sn);return useStore(e,n=>t?n.invocationStates[t]:void 0)}function Yo(){let t=useContext(Sn);return useStore(t,e=>e.globalState)}export{Ko as AgentStreamStoreProvider,wt as BarChart,an as BotInvocationContent,it as Chart,de as ChartContainer,Ge as ChartContent,Tn as ChartLegend,Dn as ChartLegendContent,qn as ChartNode,wr as ChartStyle,Nn as ChartTooltip,En as ChartTooltipContent,sn as CodeexecContent,rn as CodegenContent,xt as CollapsibleCodeBlock,Mt as Content,Me as DatasetChart,Kt as DatasetDownload,Ve as DatasetTable,Kn as DownloadButtonNode,Sr as ErdoProvider,dl as ErdoUI,St as ErrorBoundary,Ln as ExecutionStatus,kt as ExpandableOutputContent,Zn as FileDownloadsNode,Gt as HeatmapChart,Fe as InvocationEvent,Tt as InvocationEvents,qr as InvocationStatus,X as JSONStreamParser,zt as JsonContent,jt as LineChart,_o as Loader,Xn as Log,Ke as LogContent,B as MarkdownContent,un as MemoryContent,$e as Output,Ft as PieChart,Jt as ScatterChart,Xe as SqlContent,rt as StatusSpinner,te as StderrText,Xt as StdoutText,en as StdwarnText,je as StepInvocation,Ue as StepInvocationStatus,Do as StepTreeContent,Qn as SuggestionsNode,We as TableContent,zn as TableNode,ye as TextContent,Hn as TextMarkdownNode,He as ThinkingContent,ne as ToolGroupContent,qe as UIGenerationNodes,Ze as WebParseContent,Qe as WebSearchContent,ar as WritingLoader,ve as agentStateToContents,K as cn,wo as completeStreamingContent,Ne as createAgentStreamStore,fn as createInitialAgentState,vo as extractContentItems,at as formatValue,ur as handleAgentEvent,ir as handleIncrementalMixedJsonParsing,kn as handleSSEEvent,Nl as hasRenderableAssistantOutput,ge as isJsonLike,Ur as isNullString,Ta as isParsingComplete,he as isParsingInProgress,Dt as isWhitespaceChar,Yn as nodeComponents,zo as normalizeContent,uc as normalizeContents,Se as normalizeUIGenerationChunks,Jn as normalizeUINodes,$ as parseCompleteJson,ft as parseMixedJson,Ir as parseToDate,qt as resolveKeyFromData,bn as sliceAgentStateToRoot,Mr as toSnakeCase,P as unwrapNullString,ra as unwrapNullStringOr,Yo as useAgentStreamGlobalState,Qo as useAgentStreamStoreOptional,Ae as useChartZoom,Pe as useDatasetContents,Ct as useErdoConfig,q as useErdoConfigOptional,Zo as useInvocationState,Or as useMultipleDatasetContents,me as useMultipleDatasetRequests,qo as useThread};
51
+ `),wrapperType:Ml(o)}),s++,r=[]);}for(let i of t){let c=typeof i.message=="string"?i.message:"";if(!c)continue;let l=typeof i.level=="string"?i.level:"output";l!==o&&r.length>0&&a(),o=l,r.push(c);}return a(),n}function Eo(t,e,n){let o=[];for(let r of t){if(r.contentType==="tool_invocation"||r.contentType==="tool_result")continue;let s=`${e}-content-${r.id}`,a=r.state==="streaming"?"running":"completed";if(r.contentType==="thinking"||r.contentType==="redacted_thinking"){let i=r.result??r.text;if(!i)continue;o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType||r.contentType,content:i,state:r.state==="streaming"?"in_progress":"completed"},status:a});continue}if(r.result){let i=r.result;if(typeof r.result=="string")if(r.contentType==="json"){let c=$(r.result);if(c!=null)i=c;else {let l=Vl(r.result);if(l!==null)i=l;else if(!(r.parsedContent&&r.parsedContent.length>0))if(n){o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType||"ui_generation",content:r.result,state:r.state==="streaming"?"in_progress":"completed"}});continue}else {o.push({id:s,type:"text",content:r.result});continue}}}else {o.push({id:s,type:"text",content:r.result});continue}if(Array.isArray(i)&&i.length>0){o.push(...No(i,s));continue}if(typeof i=="object"&&i!==null){let c=i;if(typeof c.code=="string"){o.push({id:s,type:"codegen",contentData:c,status:a});continue}if(n){o.push({id:s,type:"content",contentItem:{id:s,content_type:r.contentType,ui_content_type:r.uiContentType,content:i,state:r.state==="streaming"?"in_progress":"completed"}});continue}}}if(r.contentType==="json"&&r.parsedContent){if(r.uiContentType==="codeexec_output"){let i=[];for(let c of r.parsedContent)c.type==="json"&&typeof c.content=="object"&&i.push(c.content);o.push(...No(i,s));continue}for(let i=0;i<r.parsedContent.length;i++){let c=r.parsedContent[i];if(c.type==="text"&&c.content)o.push({id:`${s}-text-${i}`,type:"text",content:String(c.content)});else if(c.type==="json"&&typeof c.content=="object"){let l=c.content;typeof l.code=="string"?o.push({id:`${s}-codegen-${i}`,type:"codegen",contentData:l,status:a}):typeof l.markdown=="string"?o.push({id:`${s}-text-${i}`,type:"text",content:l.markdown}):typeof l.output=="string"?o.push({id:`${s}-text-${i}`,type:"text",content:l.output}):n&&o.push({id:`${s}-content-${i}`,type:"content",contentItem:{id:`${s}-content-${i}`,content_type:"json",ui_content_type:r.uiContentType||"ui_generation",content:l,state:r.state==="streaming"?"in_progress":"completed"}});}}continue}r.text&&r.contentType!=="json"&&o.push({id:s,type:"text",content:r.text});}return o}function $l(t,e){if(!t.rootStepId)return [];let n=[],o={},r={},s=new Set,a={},i={},c={};function l(f){return r[f]||(r[f]=[]),r[f]}function u(f){if(f)return t.byStepId[f]}function p(f){if(!f)return false;if(f in c)return c[f];let g=f,h=[],b=false;for(;g;){if(g in c){b=b||c[g];break}h.push(g);let S=u(g);if(!S)break;if(S.hidden){b=true;break}g=S.parentId;}for(let S of h)c[S]=b;return b}function d(f){return p(f.id)}for(let f of t.nodes){if(f.kind!=="content"||!f.stepId||f.contentType==="tool_invocation"||f.contentType==="tool_result"||f.contentType==="agent_invocation"||!f.text&&!f.result&&!f.parsedContent?.length)continue;let g=u(f.stepId);if(!g||d(g)||g.type==="llm_call"&&gn(t,g,f))continue;let h=f.stepId;for(;h;){i[h]=true;let b=u(h);if(!b)break;h=b.parentId;}}function m(f){return !!i[f]}function x(f){if(!f)return null;if(f in a)return a[f];let g=f;for(;g;){let h=u(g);if(!h)break;let b=g===t.rootStepId,S=h.type==="agent"&&!h.hidden&&(!b||!Io(t,h.id)),v=h.type==="tool_call"&&!h.hidden;if(S||v)return a[f]=g,g;g=h.parentId;}return a[f]=null,null}function y(f,g){if(g.length===0)return;let h=x(f);if(!h){n.push(...g);return}let b=o[h];if(!b){l(h).push(...g);return}b.children||(b.children=[]),b.children.push(...g);}function k(f,g,h){if(!h||typeof h!="object")return [];let b=h,S=typeof b.result=="object"&&b.result!==null?b.result:b,v=[];typeof S.code=="string"&&S.code.trim()&&v.push({id:`${f}-${g}-codegen`,type:"codegen",contentData:S});let T=typeof S.output=="string"?S.output.trim():"";return T&&v.push({id:`${f}-${g}-output`,type:"codeexec",content:T}),v}for(let f of t.nodes){if(f.kind==="step"){let h=t.byStepId[f.id];if(!h||h.hidden||h.type==="llm_call"||h.id===t.rootStepId&&Io(t,h.id)||s.has(h.id))continue;s.add(h.id);let b={id:h.id,type:"step",label:Bl(h),status:h.status},S=r[h.id];S&&S.length>0&&(b.children=S,delete r[h.id]),o[h.id]=b,y(h.parentId,[b]);continue}if(f.kind!=="content"||f.contentType==="tool_invocation")continue;if(f.stepId===null){n.push(...Eo([f],"root",e));continue}let g=t.byStepId[f.stepId];if(g&&!d(g)&&!(g.type==="llm_call"&&gn(t,g,f))){if(g.type==="tool_call"&&f.contentType==="tool_result"){if(m(g.id))continue;y(g.id,k(g.id,f.id,f.result));continue}y(g.id,Eo([f],g.id,e));}}return n}function To({node:t,ContentComponent:e}){let[n,o]=useState(t.status==="running"),r=useRef(t.status==="running");if(useEffect(()=>{r.current&&t.status!=="running"&&o(false),r.current=t.status==="running";},[t.status]),t.type==="text")return jsx(B,{content:t.content||"",className:"max-w-none"});if(t.type==="codegen"&&t.contentData){let{code:i,step_by_step:c,thinking:l}=t.contentData;return jsxs("div",{className:"space-y-2",children:[c&&jsx(B,{content:c,className:"text-sm max-w-none"}),l&&jsx(Ce,{content:l,state:t.status==="running"?"in_progress":"completed"}),i&&jsx(xt,{language:"python",value:i,defaultOpen:false})]})}if(t.type==="codeexec"&&t.content){let i=t.wrapperType||"standard";return jsx(kt,{wrapperType:i,compact:true,children:jsx(Xt,{children:t.content})})}if(t.type==="content"&&t.contentItem&&e)return jsx(e,{content:t.contentItem});if(t.type==="content"&&t.contentItem)return jsx(Mt,{content:t.contentItem});let s=!!t.children?.length,a=t.status==="running"?"text-foreground":"text-muted-foreground";return jsxs(ee.Root,{open:n,onOpenChange:o,className:"w-full",children:[jsxs(ee.Trigger,{className:`flex items-center justify-between w-full text-sm py-0.5 ${a} ${s?"hover:text-foreground cursor-pointer":"cursor-default"}`,disabled:!s,children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx(rt,{status:Ol(t.status),size:14}),jsx("span",{children:t.label})]}),s&&jsx(ChevronDown,{className:`h-4 w-4 shrink-0 text-muted-foreground/50 transition-transform duration-200 ${n?"rotate-180":""}`})]}),s&&jsx(ee.Content,{children:jsx("div",{className:"ml-5 mt-1 flex flex-col gap-1",children:t.children?.map(i=>jsx(To,{node:i,ContentComponent:e},i.id))})})]})}function Do({agentState:t,ContentComponent:e,className:n}){if(!t.rootStepId)return null;let o=useMemo(()=>$l(t,e),[t,e]);return o.length===0?null:jsx("div",{className:`flex flex-col gap-1 ${n||""}`,children:o.map(r=>jsx(To,{node:r,ContentComponent:e},r.id))})}function U(t){if(!t)throw new Error("Entity is null");if(!("_type"in t))throw new Error(`Entity ${JSON.stringify(t)} is missing _type`);return t._type}function Ll(t){return t.contents.length===0?null:t.contents[t.contents.length-1]||null}function Oo(t){return t.contents.length===0?null:t.contents[0]||null}function Ao(t){let e=false,n=t.contents.map(r=>r.state!=="in_progress"?r:(e=true,{...r,state:"completed",updated_at:new Date().toISOString()}));if(!e&&t.state==="completed")return t;let o={...t.contentsByID};for(let r of n)o[r.id]=r;return {...t,state:"completed",contents:n,contentsByID:o}}function mr(t,e){let n=U(t);switch(n){case "message":return t;case "step":let o=t;if(e){let a=o.eventsByID[e]?.Message;return a||$o({},"",e)}let s=Object.keys(o.eventsByID).reverse();for(let a of s){let i=o.eventsByID[a];if(i&&i.Message)return i.Message}throw new Error("Unable to find message for step");default:throw new Error(`Unable to have messages on entity type ${n}`)}}function Ul(t,e){switch(U(t)){case "message_content":return t;case "output_content":return t;case "message":return le(t,e);case "output":return ce(t,e);case "step":let o=xn(t,e);return o?ce(o,e):null;default:return null}}function le(t,e){let n=U(t);switch(n){case "message_content":return t;case "message":let o=mr(t);if(!o)throw new Error("Unable to find message to add content to");return e?o.contentsByID[e]:Ll(o);default:throw new Error(`Unable to have message content on entity type ${n}`)}}function ce(t,e){let n=U(t);switch(n){case "output_content":return t;case "output":let o=t;return e?o.contentsByID[e]||null:o.contents.length<=0?null:o.contents[o.contents.length-1]||null;case "step":let s=xn(t,e);return s?ce(s):null;case "invocation":if(!e)return null;let a=t.eventsByID[e];return !a||!a.Output?null:ce(a.Output);default:throw new Error(`Unable to have output content on entity type ${n}`)}}function fr(t,e){let n=U(t),o=null;switch(n){case "invocation":return t;case "message_content":if(o=t.botInvocation||null,!o)throw new Error("Unable to find bot invocation for message content");if(e&&o.bot_invocation.id!==e)throw new Error("Unable to find bot invocation for message content - mismatched ID");return o;case "message":if(o=Oo(t)?.botInvocation||null,!o)throw new Error("Unable to find bot invocation for message");if(e&&o.bot_invocation.id!==e)throw new Error("Unable to find bot invocation for message - mismatched ID");return o;case "output_content":return t.botInvocation||null;default:throw new Error(`Unable to have bot invocation on entity type ${n}`)}}function xn(t,e){let n=U(t);switch(n){case "output":return t;case "step":let o=t;if(e){let i=o.eventsByID[e]?.Output;if(!i)throw new Error("Unable to find output with id "+e);return i}let s=Object.keys(o.eventsByID).reverse();for(let i of s){let c=o.eventsByID[i];if(c&&c.Output)return c.Output}throw new Error("Unable to find output for step");case "invocation":if(!e)throw new Error("Unable to find output for invocation without ID");return t.eventsByID[e]?.Output||null;default:throw new Error(`Unable to have step outputs on entity type ${n}`)}}function Mo(t,e){let n=U(t);switch(n){case "result_handler":return t;case "step":if(!e)throw new Error("Unable to have result handlers on step without ID");let o=t.eventsByID[e];if(!o||!o.type||o.type!=="result_handler"||!o.ResultHandler)throw new Error(`Unable to find result handler with id ${e} on step ${t.id}`);return o.ResultHandler;default:throw new Error(`Unable to have result handlers on entity type ${n}`)}}function Vo(t,e){let n=U(t),o=null;switch(n){case "step":if(t.id===e||!e)return t;throw new Error("Unable to find step on step with id "+e);case "invocation":if(!e)throw new Error("Unable to have steps on bot invocation without ID");o=t;let r=o.eventsByID[e];if(!r)throw new Error("Unable to find step on invocation with id "+e);if(!r.Step)throw new Error("Unable to find step on invocation with id "+e);return r.Step;case "result_handler":if(!e)throw new Error("Unable to have steps on result handler without ID");let a=t.eventsByID[e];if(!a)throw new Error("Unable to find step on result handler with id "+e);if(!a.Step)throw new Error("Unable to find step on result handler with id "+e);return a.Step;default:throw new Error(`Unable to have steps on entity type ${n}`)}}var dr=class extends Error{};function jl(t,e,n){let o=null,r=e[0],s=e[1];n[r]=s;try{switch(r){case "message":o=mr(t,s);break;case "content":o=le(t,s);break;case "step":o=Vo(t,s);break;case "output":o=xn(t,s);break;case "output_content":o=ce(t,s);break;case "invocation":o=fr(t,s);break;case "result_handler":o=Mo(t,s);break}}catch(a){throw console.error("error finding next entity"),console.log("path",e),console.log("currentEntity",t),a}if(!o)throw console.log("path",e),console.log("currentEntity",t),console.log("nextEntity",o),new dr(`Unable to find next entity for path ${e.join("/")}`);return o}function $o(t,e,n,o){let r=t.payload;return {_type:"message",message:{id:n,thread_id:e,author_id:r.author_id||"app",author_entity_type:r.author_entity_type||"app",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),role:r.role||"assistant",avatar:"/teams/erdo-icon.png"},state:"in_progress",contents:[],contentsByID:{},contentIDToIdx:{}}}function Fl(t,e){return {_type:"message_content",id:t.metadata.message_content_id,message_id:e.message,content_type:t.metadata.content_type,created_by_invocation_id:t.metadata.invocation_id,invocation_id:t.metadata.invocation_id,state:"in_progress",user_visibility:t.metadata.user_visibility??"visible",bot_visibility:t.metadata.bot_visibility??"visible",content:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:t.metadata?.ui_content_type?{String:t.metadata.ui_content_type,Valid:true}:{String:"",Valid:false}}}function Jl(t,e){let n=t.metadata.content_type||"text",o=t.metadata?.ui_content_type,r=ae(n,t.payload);return {_type:"message_content",id:t.metadata.message_content_id,message_id:e.message,content:r.content,content_type:n,created_by_invocation_id:t.metadata.invocation_id,invocation_id:t.metadata.invocation_id,state:"completed",user_visibility:t.metadata.visibility||"visible",bot_visibility:"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:o?{String:o,Valid:true}:{String:"",Valid:false},parsedJson:r.parsedJson??null}}function Gl(t,e,n){let o=t.payload;return {_type:"step",id:e,invocation_id:n.invocation||"",step_id:o.step_id||"",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),current_status_id:"",path:{String:"",Valid:false},action_type:{String:o.action_type,Valid:true},key:{String:o.key,Valid:true},bot_id:o.bot_id,result_handler_id:"",step_order:{Int32:o.step_order,Valid:true},output_content_type:{String:o.content_type,Valid:true},execution_mode:{String:o.execution_mode,Valid:true},output_behaviour:{String:o.output_behaviour,Valid:true},user_output_visibility:{String:t.metadata.visibility||"visible",Valid:true},output_channels:o.output_channels||[],running_message:{String:o.running_message||"",Valid:!!o.running_message},finished_message:{String:o.finished_message||"",Valid:!!o.finished_message},depends_on:[],eventsByID:{},currentStatus:null}}function Wl(t,e,n){let o=t.payload;return {_type:"result_handler",id:e,invocation_id:t.metadata.invocation_id||"",result_handler_id:o.result_handler_id||e,step_invocation_id:o.step_invocation_id||"",type:o.type||"",if_conditions:o.if_conditions||{},created_at:new Date().toISOString(),updated_at:new Date().toISOString(),output_content_type:o.output_content_type||"",result_handler_order:o.result_handler_order||0,eventsByID:{}}}function ql(t,e,n){return {_type:"output",id:e,step_id:n.step_id,output:{id:e,invocation_id:t.metadata?.invocation_id,path:t.metadata.path,created_at:new Date().toISOString(),updated_at:new Date().toISOString()},state:"in_progress",contents:[],contentsByID:{},contentIDToIdx:{}}}function Ro(t,e,n,o=null){return {_type:"output_content",id:e,output_id:n.output,content:"",content_type:t.metadata.content_type,state:"in_progress",invocation_id:t.metadata.invocation_id,user_visibility:o??t.metadata.user_visibility??"visible",bot_visibility:t.metadata.bot_visibility??"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:t.metadata.ui_content_type?{String:t.metadata.ui_content_type,Valid:true}:{String:"",Valid:false},output:null}}function Po(t,e,n,o=null){let r=t.metadata.content_type||"text",s=ae(r,t.payload),a=t.metadata?.ui_content_type;return {_type:"output_content",id:e,output_id:n.output,content:s.content,content_type:r,state:"completed",invocation_id:t.metadata.invocation_id,parsedJson:s.parsedJson??null,user_visibility:o||t.metadata.visibility||"visible",bot_visibility:"visible",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),content_params:{RawMessage:null,Valid:false},history_content_type:t.metadata?.history_content_type?{String:t.metadata.history_content_type,Valid:true}:{String:"",Valid:false},ui_content_type:a?{String:a,Valid:true}:{String:"",Valid:false},output:null}}function zl(t,e,n){return {_type:"invocation",bot_invocation:{id:t.payload.invocation_id,bot_id:t.payload.bot_id,bot_name:t.payload.bot_name,created_by_user_id:t.payload.created_by_user_id,current_state_id:"",parent_invocation_id:"",branch_init_state_id:"",current_status_id:"",organization_id:"",created_at:new Date().toISOString(),updated_at:new Date().toISOString()},eventsByID:{},currentStatus:null,current_status:null,step_invocations:[],step_invocation_states:[],resources:[],outputs:[],statuses:[]}}function we(t,e){let n=t.payload;return {_type:"status",id:new Date().toISOString(),status:n.status,message:{String:n.message,Valid:true},Details:n}}function Lo(t){return {id:t.id,type:"step",created_at:t.created_at,_type:"invocation_event",Output:null,Message:null,Status:null,ResultHandler:null,Step:t}}function gr(t){return {id:t.output.id,type:"output",created_at:t.output.created_at,_type:"invocation_event",Output:t,Message:null,Status:null,ResultHandler:null,Step:null}}function yr(t){return {id:t.id,type:"status",created_at:t.created_at,_type:"invocation_event",Status:t,Output:null,Message:null,ResultHandler:null,Step:null}}function Hl(t){return {id:t.message.id,type:"message",created_at:t.message.created_at,_type:"invocation_event",Output:null,Message:t,Status:null,ResultHandler:null,Step:null}}function Kl(t){return {id:t.id,type:"result_handler",created_at:t.created_at,_type:"invocation_event",Output:null,Message:null,Status:null,ResultHandler:t,Step:null}}var Ql=new Set(["=","("]);function Zl(t){if(!t||t.length===0)return true;let e=t[t.length-1];return !Ql.has(e)}function Uo(t,e){if(t.content||(t.content=""),t.user_visibility!=="visible"||!ge(t.content_type,t.ui_content_type.String))return t.content+=e,{...t};if(t.parsedJson||(t.parsedJson=[]),typeof e=="object")return t.content+=JSON.stringify(e),t.parsedJson=[...t.parsedJson,e],{...t};t._jsonParser||(t._isInJson=false),t._charBuffer||(t._charBuffer="");let n=t.content_type,o=t.ui_content_type.String;for(let r of e){t.content+=r;let s=n==="json"||o==="json";if(!t._isInJson&&s&&!Dt(r)){t._isInJson=true,t._jsonParser=new X;let a={content:{},type:"json"};t.parsedJson=[...t.parsedJson||[],a],t._currentContent=a,t._charBuffer="";}if(!t._isInJson&&!s&&o==="ui_generation"&&r==="{"){let a=t.content.slice(0,-1);if(Zl(a)){t._charBuffer="{";continue}}if(t._charBuffer&&Dt(r)){t._charBuffer+=r;continue}if(!t._isInJson&&!s&&o==="ui_generation"&&t._charBuffer?.match(/^\s*{\s*$/)&&r==='"'){t._isInJson=true,t._jsonParser=new X;let i={content:t._jsonParser.add("{"),type:"json"};t._currentContent?.content?t._currentContent.content.match(/^\s*{$/)?(t._currentContent=i,t.parsedJson=[...t.parsedJson.slice(0,-1),i]):(t._currentContent.content=t._currentContent.content.replace(/{$/,""),t._currentContent=i,t.parsedJson=[...t.parsedJson,i]):(t._currentContent=i,t.parsedJson=[...t.parsedJson,i]);}if(t._isInJson)try{let a=t._jsonParser.add(r);t._currentContent.content=a,t._jsonParser.state==="END"&&(t._isInJson=!1,t._currentContent=void 0);}catch(a){if(console.log("handleIncrementalMixedJsonParsing: content chunk",e),console.log("handleIncrementalMixedJsonParsing: accumulated content",t.content),console.warn("handleIncrementalMixedJsonParsing: JSON parse error, recovering as text",a),t._isInJson=false,t._jsonParser=void 0,t.parsedJson&&t.parsedJson.length>0){let i=t.parsedJson[t.parsedJson.length-1];if(i.type==="json"){let c=t.content.lastIndexOf("{"),l=t.content.slice(c);i.type="text",i.content=l,t._currentContent=i;}}continue}else t._currentContent||(t._currentContent={content:t._charBuffer||"",type:"text"},t.parsedJson=[...t.parsedJson,t._currentContent]),t._currentContent.content+=t._charBuffer+r;t._charBuffer="";}return {...t}}function Yl(t,e){return Uo(t,e)}function Bo(t,e){return Uo(t,e)}function pr(t,e){let n=U(t);switch(n){case "message":return dt(t,e);case "message_content":return hn(t,e);case "step":return tc(t,e);case "output":return ec(t,e);case "output_content":return nc(t,e);case "invocation":return Ie(t,e);case "result_handler":return rc(t,e);default:throw new Error(`Unable to add update entity for entity type ${n}`)}}function Xl(t,e){for(let n of e)t=pr(t,n);return t}function dt(t,e){let n=mr(t);if(!n)throw new Error("Unable to find message to add content to");let o=U(e),r=null;switch(o){case "message_content":if(r=e,!n.contentsByID[r.id])n.contentIDToIdx={...n.contentIDToIdx,[r.id]:n.contents.length},n.contents=[...n.contents,r];else {let i=n.contentIDToIdx[r.id];n.contents=[...n.contents.slice(0,i),r,...n.contents.slice(i+1)];}return n.contentsByID={...n.contentsByID,[r.id]:r},{...n};case "invocation":let s=e;if(n.contents.length===0)throw new Error("Unable to find message content to add invocation to");return r=hn(n.contents[0],s),dt(n,r);case "step":if(n.contents.length===0)throw new Error("Unable to find message content to add content to");if(r=n.contents[0],!r)throw new Error("Unable to find message content to add content to");let a=fr(r);if(!a)throw new Error("Unable to find bot invocation to add content to");return r.botInvocation=Ie(a,e),dt(n,r);case "status":if(n.contents.length>0){let i=n.contents[0];if(i?.botInvocation){let c=hn(i,e);return dt(n,c)}}return {...n};default:throw new Error(`Unable to add update message child for child type ${o}`)}}function hn(t,e){let n=le(t);if(!n)throw new Error("Unable to find message content to add content to");let o=U(e);switch(o){case "invocation":return n.botInvocation=e,{...n};case "step":let r=n.botInvocation;if(!r)throw new Error("Unable to find bot invocation to add content to");return n.botInvocation=Ie(r,e),{...n};case "status":return n.botInvocation&&(n.botInvocation=Ie(n.botInvocation,e)),{...n};default:throw new Error(`Unable to add update message content child for child type ${o}`)}}function tc(t,e){let n=Vo(t);if(!n)throw new Error("Unable to find bot invocation to add step to");let o=U(e),r=null;switch(o){case "output":let s=e;return r=gr(s),n.eventsByID={...n.eventsByID,[s.output.id]:r},{...n};case "message":let a=e;return r=Hl(a),n.eventsByID={...n.eventsByID,[a.message.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID={...n.eventsByID,[i.id]:r},{...n};case "result_handler":let c=e;return r=Kl(c),n.eventsByID={...n.eventsByID,[c.id]:r},{...n};default:throw new Error(`Unable to add update step for entity type ${o}`)}}function ec(t,e){let n=xn(t);if(!n)throw new Error("Unable to find step output to add content to");let o=U(e);switch(o){case "output_content":let r=e;if(!n.contentsByID[r.id])n.contentIDToIdx={...n.contentIDToIdx,[r.id]:n.contents.length},n.contents=[...n.contents,r];else {let s=n.contentIDToIdx[r.id];n.contents=[...n.contents.slice(0,s),r,...n.contents.slice(s+1)];}return n.contentsByID={...n.contentsByID,[r.id]:r},{...n};default:throw new Error(`Unable to add update output for entity type ${o}`)}}function nc(t,e){let n=ce(t);if(!n)throw new Error("Unable to find step output content to add content to");let o=U(e);switch(o){case "invocation":return n.botInvocation=e,{...n};case "step":let r=n.botInvocation;if(!r)throw new Error("Unable to find bot invocation to add content to");return n.botInvocation=Ie(r,e),{...n};default:throw new Error(`Unable to add update step output content for entity type ${o}`)}}function Ie(t,e){let n=fr(t);if(!n)throw new Error("Unable to find bot invocation to add content to");let o=U(e),r;switch(o){case "step":let s=e;return r=Lo(s),n.eventsByID={...n.eventsByID,[s.id]:r},{...n};case "output":let a=e;return r=gr(a),n.eventsByID={...n.eventsByID,[a.output.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID={...n.eventsByID,[i.id]:r},n.currentStatus=i,{...n};default:throw new Error(`Unable to add update invocation for entity type ${o}`)}}function rc(t,e){let n=Mo(t);if(!n)throw new Error("Unable to find result handler to add content to");let o=U(e),r=null;switch(o){case "step":let s=e;return r=Lo(s),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[s.id]:r},{...n};case "output":let a=e;return r=gr(a),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[a.output.id]:r},{...n};case "status":let i=e;return r=yr(i),n.eventsByID||(n.eventsByID={}),n.eventsByID={...n.eventsByID,[i.id]:r},{...n};default:throw new Error(`Unable to add update to result handler for entity type ${o}`)}}function oc(t){return t==="bot started"||t==="bot resumed"||t==="message created"||t==="create message content"||t==="message content result"||t==="step started"||t==="result handler started"||t==="state created"||t==="step output created"||t==="create step output content"||t==="step output content result"||t==="log"}function kn(t,e,n,o,r,s=null,a=[],i={}){if(!s&&Object.keys(r).length>0){let p,d;if(n.length>=2&&n[0]==="message"?(d=n[1],p=r[d],p||(p=Object.values(r)[0],d=Object.keys(r)[0])):(p=Object.values(r)[Object.values(r).length-1],d=Object.keys(r)[Object.keys(r).length-1]),i.message=d,n.length<=2&&t==="message finished")return r[d]=Ao(p),null;if(n[0]!=="content"&&Object.keys(p.contentsByID).length>0&&e.metadata.message_content_id){let m=e.metadata.message_content_id,x=p.contentsByID[m];x&&(s=x);}s?a=[p]:s=p;}if(n.length<=2&&oc(t)){let p=n[1],d=[],m,x,y,k,f;switch(t){case "bot started":case "bot resumed":if(!s)throw new Error("Unable to find message to add content to");let g=zl(e);if(s._type==="message_content"){if(x=s,!x.id)throw new Error("Unable to find message content id");if(y=r[x.message_id],!y)throw new Error("Unable to find message to add content to");if(k=le(y,x.id),!k)throw new Error("Unable to find message content to add content to");let v=hn(k,g);r[x.message_id]={...dt(y,v)};}d.push(g);break;case "message created":return r[p]=$o(e,o,p),null;case "create message content":if(!s)throw new Error("Unable to find message to add content to");if(f=Fl(e,i),s._type==="output"){m=s,d.push(Ro(e,p,i,"hidden"));let v=e.payload.message_id;if(v||(v=a[0].message.id),y=r[v],!y)throw new Error("Unable to find message to add content to")}else if(s._type==="message_content"){if(m=s,y=r[m.message_id],!y)throw new Error("Unable to find message to add content to")}else {if(s._type!=="message")throw new Error(`Incorrect path? Cannot add content to non-message entity: ${s._type}`);if(m=s,y=r[m.message.id],!y)throw new Error("Unable to find message to add content to");d.push(f);}r[y.message.id]={...dt(y,f)};break;case "message content result":if(!s)throw new Error("Unable to find message to add content to");let h=null;if(s._type==="output"){d.push(Po(e,p,i,"hidden"));let v=e.payload.message_id||i.message;if(v?h=a.find(T=>T.message.id===v):h=a[0],y=r[v],!y)throw new Error("Unable to find message to add content to")}else if(s._type==="message_content"){if(h=a[0],y=r[h.message.id],!y)throw new Error("Unable to find message to add content to")}else {if(s._type!=="message")throw new Error(`Incorrect path? Cannot add content to non-message entity: ${s._type}`);if(h=s,y=r[h.message.id],!y)throw new Error("Unable to find message to add content to")}let b=e.metadata.message_content_id;if(!b)throw new Error("Unable to find message content id");let S=le(h,b);if(S){S.state="completed";let v=S.content_type||"text",T=pn(v,S.content,e.payload);S.content=T.content,T.parsedJson&&(S.parsedJson=T.parsedJson),r[y.message.id]={...dt(y,S)},(s._type==="message"||s._type==="message_content")&&d.push(S);}else S=Jl(e,i),r[y.message.id]={...dt(y,S)},(s._type==="message"||s._type==="message_content")&&d.push(S);break;case "step started":d.push(Gl(e,p,i));break;case "result handler started":d.push(Wl(e,p));break;case "step output created":d.push(ql(e,p,s));break;case "create step output content":d.push(Ro(e,p,i));break;case "step output content result":d.push(Po(e,p,i));break;case "log":return null;default:throw new Error(`Unable to handle create event type ${t}`)}return d.length?!s||s._type==="message_content"&&d.length===1&&d[0]._type==="message_content"?d[0]:Xl(s,d):null}if(!s)throw new Error("No first message has been created, so cannot handle amend events");if(n.length<=1){let p=null;try{p=Ul(s);}catch{}switch(t){case "message content delta":if(!p)throw new Error("Unable to find message content");let d=null,m=null,x=null;if(s._type==="output_content"){d=Bo(s,e.payload);let g=e.metadata.message_content_id;if(!g)throw new Error("Unable to find message content id from entity ids");let h=i.message;if(x=a.find(b=>b.message.id===h),!x)throw new Error("Unable to find message to add content to");m=le(x,g);}else {if(m=p,x=a[a.length-1],!x)throw new Error("Unable to find message to add content to");if(x._type!=="message")throw new Error("Unable to find message to add content to - not a message")}if(!m)throw new Error("Unable to find message content");let y=r[x.message.id];if(!y)throw new Error("Unable to find message to add content to");let k=Yl(m,e.payload);return r[y.message.id]={...dt(y,k)},s._type==="message_content"&&(d=k),d;case "step output content delta":return Bo(p,e.payload);case "status":if(s._type==="step"&&(s.currentStatus=we(e)),s._type==="invocation"&&(s.currentStatus=we(e)),s._type==="message_content"){let f=s;if(f.botInvocation)return f.botInvocation.currentStatus=we(e),{...f}}if(s._type==="message"){let f=s,g=Oo(f);if(g?.botInvocation)return g.botInvocation.currentStatus=we(e),dt(f,g)}return pr(s,we(e));case "result":return null;case "message finished":if(s._type==="message"){let g=Ao(s);r[g.message.id]=g;}return null;case "step output finished":return null;case "step result":return null;case "error":return null;case "dataset created":return null;case "log":return null;default:throw new Error(`Unable to handle event type ${t}`)}}let c=n.slice(2),l=jl(s,n,i),u=kn(t,e,c,o,r,l,[...a,s],i);return u?pr(s,{...u}):s}function hr(t){if(!t.content)return null;if(typeof t.content=="object")return t.content;if(typeof t.content=="string"){let e=$(t.content);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}return null}function jo(t){let e=t.content_type;if(e==="tool_result")return "result";if(e==="tool_invocation")return "invocation";let n=hr(t);return n&&"action_type"in n&&"name"in n&&"input"in n&&n.action_type!=="bot.invoke"?"result"in n?"result":"invocation":null}function Fo(t){return hr(t)?.id}function Jo(t){let e=hr(t);if(!e?.action_type)return null;let o=e.input?.query;return `${e.action_type}:${o||""}`}function Go(t){let e=t.filter(r=>jo(r)==="result"),n=new Set(e.map(r=>Fo(r)).filter(Boolean)),o=new Set(e.map(r=>Jo(r)).filter(Boolean));return t.filter(r=>{if(jo(r)==="invocation"){let s=Fo(r),a=Jo(r);if(s&&n.has(s)||a&&o.has(a))return false}return true})}function Wo(t,e,n){let o=e;for(;o;){if(o===n)return true;o=t.byStepId[o]?.parentId??null;}return false}function bn(t,e){if(!e||!t.byStepId[e])return t;let n=new Set;for(let i of t.nodes)i.kind==="step"&&Wo(t,i.id,e)&&n.add(i.id);let o=t.nodes.filter(i=>i.kind==="step"?n.has(i.id):i.kind==="content"||i.kind==="status"?!!i.stepId&&n.has(i.stepId):false),r={},s={},a={};for(let i of n){let c=t.byStepId[i];c&&(r[i]=c);}for(let i of o){if(i.kind==="content"){s[i.id]=i;continue}if(i.kind!=="step")continue;let l=(i.parentId&&n.has(i.parentId)?i.parentId:null)??"__root__";a[l]=[...a[l]||[],i.id];}return {...t,nodes:o,byStepId:r,byContentId:s,childrenByParentId:a,rootStepId:e}}function Ne(){return createStore((t,e)=>({globalState:fn(),invocationStates:{},invocationRootSteps:{},pendingInvocationQueue:[],pushEvent:(n,o)=>{let r=e(),s=ur(r.globalState,n);if(o&&(s=o(s)),s===r.globalState)return;let a=n.metadata?.step_id??n.payload?.step_id??"",i={...r.invocationStates},c=false;for(let[l,u]of Object.entries(r.invocationRootSteps)){let p=r.invocationStates[l];if(a&&!Wo(s,a,u)&&a)continue;let d=bn(s,u);if(!(n.type==="step_finished"||n.type==="step_started"||n.type==="status")&&p&&p.nodes.length===d.nodes.length){let x=p.nodes[p.nodes.length-1],y=d.nodes[d.nodes.length-1];if(x===y&&p.isStreaming===d.isStreaming)continue}i[l]=d,c=true;}t({globalState:s,...c?{invocationStates:i}:{}});},registerInvocation:n=>{let o=e();o.invocationRootSteps[n]||o.pendingInvocationQueue.includes(n)||t({pendingInvocationQueue:[...o.pendingInvocationQueue,n]});},mapInvocationRoot:(n,o)=>{let r=e(),s=bn(r.globalState,o);t({invocationRootSteps:{...r.invocationRootSteps,[n]:o},invocationStates:{...r.invocationStates,[n]:s},pendingInvocationQueue:r.pendingInvocationQueue.filter(a=>a!==n)});},reset:()=>{t({globalState:fn(),invocationStates:{},invocationRootSteps:{},pendingInvocationQueue:[]});}}))}function lc(t){return t.split("/").filter(Boolean)}function qo(t={}){let e=Ct(),[n,o]=useState(null),[r,s]=useState(false),[a,i]=useState(null),[c,l]=useState([]),u=useRef(Ne()),p=useStore(u.current,g=>g.globalState),d=useRef(null),m=useRef(t.threadId);t.threadId!==m.current&&(m.current=t.threadId);let x=useCallback(()=>{d.current&&(d.current.abort(),d.current=null);},[]),y=useCallback(g=>{o(g),m.current=g.id;},[]),k=useCallback(async g=>{if(!e.client)throw new Error("ErdoClient not configured in provider. Pass a client to ErdoProvider config to use useThread.");if(!e.client.sendMessage)throw new Error("ErdoClient does not support sendMessage. Make sure you are using @erdoai/server client.");if(!e.client.createThread)throw new Error("ErdoClient does not support createThread. Make sure you are using @erdoai/server client.");x(),d.current=new AbortController,s(true),i(null),l([]),u.current.getState().reset();let h={};try{let b=m.current;if(!b){let E=await e.client.createThread();o(E),m.current=E.id,b=E.id;}for await(let E of e.client.sendMessage(b,{content:g,botKey:t.botKey})){if(d.current?.signal.aborted)break;if(t.onEvent?.(E),e.useAgentEvents)u.current.getState().pushEvent(E);else {let z=E.type||"",Q=E.metadata||{},R=lc(Q.path||""),j={payload:E.payload,metadata:{path:Q.path||"",...Q}};try{kn(z,j,R,b,h);}catch(F){console.error("Error handling SSE event:",F,z);}l(Object.values(h));}}let S=Object.values(h);l(S);let v=u.current.getState().globalState,T;v.rootStepId?T=ve(v):T=S.flatMap(E=>E.contents||[]).filter(E=>E.user_visibility==="visible").map(E=>({id:E.id,content_type:E.content_type,ui_content_type:P(E.ui_content_type),content:E.content,parsedJson:E.parsedJson,botInvocation:E.botInvocation})),t.onFinish?.(T);}catch(b){let S=b instanceof Error?b:new Error(String(b));throw i(S),t.onError?.(S),S}finally{s(false),d.current=null;}},[e.client,e.useAgentEvents,t,x]),f=useMemo(()=>{if(p.rootStepId)return ve(p);let g=c.flatMap(b=>b.contents||[]).filter(b=>b.user_visibility==="visible");return Go(g).map(b=>({id:b.id,content_type:b.content_type,ui_content_type:P(b.ui_content_type),content:b.content,parsedJson:b.parsedJson,botInvocation:b.botInvocation}))},[c,p]);return {thread:n,isStreaming:r,error:a,activeMessages:c,agentState:p,streamingContents:f,sendMessage:k,cancel:x,setThread:y,agentStreamStore:u.current}}function cc(t){return t?typeof t=="string"?t:typeof t=="object"&&t!==null&&"String"in t&&t.String||"":""}function zo(t){let e=cc(t.ui_content_type),n=t.content_type,o={id:t.id,content_type:t.content_type,ui_content_type:e,content:t.content,invocation_id:t.created_by_invocation_id};if(typeof t.content=="string"){if(e==="ui_generation")try{o.parsedJson=ft(t.content);}catch(r){console.error("Error parsing UI generation content:",r);}else if((n==="json"||e==="json")&&t.content.trim()){let r=$(t.content);r!=null&&(o.parsedJson=[{type:"json",content:r}]);}}if((t.content_type==="thinking"||t.content_type==="redacted_thinking")&&typeof t.content=="string"){let r=$(t.content);r&&typeof r=="object"&&(o.content=r);}return o}function uc(t){return t.filter(e=>e.user_visibility!=="hidden").map(zo)}var Sn=createContext(null);function Ko({store:t,children:e}){return jsx(Sn.Provider,{value:t,children:e})}function Qo(){return useContext(Sn)}function Zo(t){let e=useContext(Sn);return useStore(e,n=>t?n.invocationStates[t]:void 0)}function Yo(){let t=useContext(Sn);return useStore(t,e=>e.globalState)}export{Ko as AgentStreamStoreProvider,wt as BarChart,an as BotInvocationContent,it as Chart,de as ChartContainer,Ge as ChartContent,Tn as ChartLegend,Dn as ChartLegendContent,qn as ChartNode,wr as ChartStyle,Nn as ChartTooltip,En as ChartTooltipContent,sn as CodeexecContent,rn as CodegenContent,xt as CollapsibleCodeBlock,Mt as Content,Me as DatasetChart,Kt as DatasetDownload,Ve as DatasetTable,Kn as DownloadButtonNode,Sr as ErdoProvider,dl as ErdoUI,St as ErrorBoundary,Ln as ExecutionStatus,kt as ExpandableOutputContent,Zn as FileDownloadsNode,Gt as HeatmapChart,Fe as InvocationEvent,Tt as InvocationEvents,qr as InvocationStatus,X as JSONStreamParser,zt as JsonContent,jt as LineChart,_o as Loader,Xn as Log,Ke as LogContent,B as MarkdownContent,un as MemoryContent,$e as Output,Ft as PieChart,Jt as ScatterChart,Xe as SqlContent,rt as StatusSpinner,te as StderrText,Xt as StdoutText,en as StdwarnText,je as StepInvocation,Ue as StepInvocationStatus,Do as StepTreeContent,Qn as SuggestionsNode,We as TableContent,zn as TableNode,ye as TextContent,Hn as TextMarkdownNode,He as ThinkingContent,ne as ToolGroupContent,qe as UIGenerationNodes,Ze as WebParseContent,Qe as WebSearchContent,ar as WritingLoader,ve as agentStateToContents,K as cn,wo as completeStreamingContent,Ne as createAgentStreamStore,fn as createInitialAgentState,vo as extractContentItems,at as formatValue,ur as handleAgentEvent,ir as handleIncrementalMixedJsonParsing,kn as handleSSEEvent,Nl as hasRenderableAssistantOutput,ge as isJsonLike,Ur as isNullString,Ta as isParsingComplete,he as isParsingInProgress,Dt as isWhitespaceChar,Yn as nodeComponents,zo as normalizeContent,uc as normalizeContents,Se as normalizeUIGenerationChunks,Jn as normalizeUINodes,$ as parseCompleteJson,ft as parseMixedJson,Ir as parseToDate,qt as resolveKeyFromData,bn as sliceAgentStateToRoot,Mr as toSnakeCase,P as unwrapNullString,ra as unwrapNullStringOr,Yo as useAgentStreamGlobalState,Qo as useAgentStreamStoreOptional,Ae as useChartZoom,Pe as useDatasetContents,Ct as useErdoConfig,q as useErdoConfigOptional,Zo as useInvocationState,Or as useMultipleDatasetContents,me as useMultipleDatasetRequests,qo as useThread};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@erdoai/ui",
3
- "version": "0.1.73",
3
+ "version": "0.1.74",
4
4
  "description": "Erdo UI components for rendering agent results",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",