@arbor-education/agent-view-frontend 0.7.0 → 0.7.2

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
@@ -1,8 +1,8 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),r=require("react"),W=require("classnames"),c=require("@arbor-education/design-system.components"),De=require("@arbor-education/ask-arbor-chat-panel"),A={"generating-a-response":"generating-a-response",hitl:"hitl",paused:"paused",complete:"complete"},$={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},M={briefing:"briefing",running:"running",paused:"paused",complete:"complete"},te={agent:"agent",user:"user",system:"system"},pe={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",user_file:"user_file",link:"link"},ws={user_file:"user_file"},Rt={active:"active",complete:"complete",paused:"paused"},Tt={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},me={[$.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[$.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[$.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[$["generating-a-response"]]:{label:"Generating a response",icon:"sparkles",color:"var(--color-brand-600)"}},ks="var(--color-grey-600)",Ye={[A["generating-a-response"]]:{status:A["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:me["generating-a-response"].icon,color:me["generating-a-response"].color}},[A.hitl]:{status:A.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:me.hitl.icon,color:me.hitl.color}},[A.paused]:{status:A.paused,title:"Paused",dotColour:"green",statusIcon:{name:"circle-x",color:ks}},[A.complete]:{status:A.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:me.complete.icon,color:me.complete.color}}},gn={name:"archive",color:ks},pn=[A["generating-a-response"],A.hitl,A.complete],mn="m4",_n="1",As="msg-opening",gt="Unable to load agent tasks. Please try again.",fn="Unable to load context.",vn="Unable to load the resources for this agent",xn="Unable to load this document. Please try again.",ys="Unable to load the timeline for this agent",wn="Unable to pause the agent. Please try again.",Ut="Unable to archive the agent. Please try again.",kn="Archive this agent?",An="Archiving cannot be undone. This agent will leave the board and cannot be restored or run again. You will not be able to retrieve it as active work. You can still open it from Archived to view the timeline and resources. Chat is not available.",yn="This agent is still in progress.",Nn="Unable to resume the agent. Please try again.",bn="The agent was resumed but could not be woken. Send a message to continue.",is="You have been resumed after being paused. Reassess your current progress and continue your work from where you left off.",Sn="Unable to rename the agent. Please try again.",jn="Something went wrong. Please try again.",Ns="Unable to load agents. Please try again.",Me="Loading tasks…",os="Loading agents…",Cn="Task",En={[M.briefing]:"Briefing",[M.running]:"Working",[M.paused]:"Paused",[M.complete]:"Complete"},Rn=[A["generating-a-response"],A.hitl,A.complete],Tn={[A["generating-a-response"]]:"Agents currently working on tasks for you.",[A.hitl]:"Agents that need your input before they can continue.",[A.paused]:"Agents that are paused until you resume them.",[A.complete]:"Agents that have finished their work."},In=()=>s.jsxs("svg",{className:"agent-view__empty-illustration",viewBox:"0 0 360 240",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Preview of the agents board layout",children:[s.jsx("rect",{x:"0",y:"0",width:"360",height:"240",rx:"12",fill:"var(--color-grey-100)"}),s.jsx("rect",{x:"16",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"130",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"244",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"28",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("rect",{x:"28",y:"96",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("rect",{x:"142",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-semantic-warning-050)"}),s.jsx("rect",{x:"256",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("circle",{cx:"40",cy:"70",r:"4",fill:"var(--color-brand-600)"}),s.jsx("circle",{cx:"40",cy:"114",r:"4",fill:"var(--color-brand-600)"}),s.jsx("circle",{cx:"154",cy:"70",r:"4",fill:"var(--color-semantic-warning-600)"}),s.jsx("circle",{cx:"256",cy:"70",r:"4",fill:"var(--color-grey-400)"})]}),On=({status:e})=>{const t=Ye[e];return t.statusIcon?s.jsx(c.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,screenReaderText:t.title}):s.jsx(c.Dot,{colour:t.dotColour,label:t.title})},Ln=()=>s.jsxs("section",{className:"agent-view__empty","aria-label":"About the agents board",children:[s.jsxs("div",{className:"agent-view__empty-content",children:[s.jsx(c.Heading,{level:4,children:"Your agents board"}),s.jsx("p",{className:"agent-view__empty-lead",children:"When you start an agent, it appears here so you can track progress at a glance. Agents move between columns as their status changes."}),s.jsx("ul",{className:"agent-view__empty-columns",children:Rn.map(e=>{const t=Ye[e];return s.jsxs("li",{className:"agent-view__empty-column",children:[s.jsx("span",{className:"agent-view__empty-column-indicator",children:s.jsx(On,{status:e})}),s.jsxs("span",{className:"agent-view__empty-column-text",children:[s.jsx("span",{className:"agent-view__empty-column-title",children:t.title}),s.jsx("span",{className:"agent-view__empty-column-description",children:Tn[e]})]})]},e)})}),s.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",s.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),s.jsx("div",{className:"agent-view__empty-visual",children:s.jsx(In,{})})]}),Pn=()=>({needsInput:[],complete:[],failed:[],tasks:[]}),Mn=(e,t)=>({...e,...t.length>0?{children:t}:{}}),bs=e=>{const t=[],n=[],a=[],i=[];for(const l of e){const o=l.children?bs(l.children):Pn();if(t.push(...o.needsInput),n.push(...o.complete),a.push(...o.failed),l.status===$.hitl){t.push({...l,children:void 0});continue}if(l.status===$.complete){n.push({...l,children:void 0});continue}if(l.status===$.failed){a.push({...l,children:void 0});continue}i.push(Mn(l,o.tasks))}return{needsInput:t,complete:n,failed:a,tasks:i}},ls=e=>e===$.hitl?0:e===$.complete?1:e===$.failed?2:3,Un=e=>e.map((t,n)=>({item:t,index:n})).sort((t,n)=>{const a=ls(t.item.status)-ls(n.item.status);return a!==0?a:t.index-n.index}).map(({item:t})=>t),It=2,Dn=e=>{if(!e)return{canScrollUp:!1,canScrollDown:!1};const t=e.scrollHeight-e.clientHeight;return t<=It?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:e.scrollTop>It,canScrollDown:e.scrollTop<t-It}},$n=(e,t)=>{if(!e||!t)return null;const n=e.getBoundingClientRect(),a=t.getBoundingClientRect();return{top:a.top-n.top,left:a.left-n.left,width:a.width,height:a.height}},mt=({children:e,className:t,contentClassName:n,scrollSelector:a,style:i,"aria-label":l})=>{const o=r.useRef(null),g=r.useRef(null),[h,w]=r.useState(!1),[p,f]=r.useState(!1),[v,R]=r.useState(null),_=()=>{var y;return a?((y=o.current)==null?void 0:y.querySelector(a))??null:g.current},k=()=>{const y=_(),j=Dn(y);if(w(m=>m===j.canScrollUp?m:j.canScrollUp),f(m=>m===j.canScrollDown?m:j.canScrollDown),a){const m=$n(o.current,y);R(S=>(S==null?void 0:S.top)===(m==null?void 0:m.top)&&(S==null?void 0:S.left)===(m==null?void 0:m.left)&&(S==null?void 0:S.width)===(m==null?void 0:m.width)&&(S==null?void 0:S.height)===(m==null?void 0:m.height)?S:m)}else R(m=>m===null?m:null)};r.useLayoutEffect(()=>{k()}),r.useEffect(()=>{const y=o.current;if(!y)return;let j=null,m=null;const S=()=>{j==null||j.removeEventListener("scroll",k),m==null||m.disconnect(),m=null,j=null},T=K=>{if(K===j){k();return}if(S(),j=K,!j){k();return}j.addEventListener("scroll",k,{passive:!0}),m=new ResizeObserver(()=>k()),m.observe(j),j.firstElementChild instanceof HTMLElement&&m.observe(j.firstElementChild),k()};T(_());const P=new MutationObserver(()=>{T(_())});return P.observe(y,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",k),()=>{window.removeEventListener("resize",k),P.disconnect(),S()}},[a]);const O=y=>{const j=_();if(!j)return;const m=Math.max(j.clientHeight*.75,120);j.scrollBy({top:y==="up"?-m:m,behavior:"smooth"})},E=s.jsxs(s.Fragment,{children:[h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--top","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--top","aria-label":"Scroll up",onClick:()=>O("up"),children:s.jsx(c.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),p&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>O("down"),children:s.jsx(c.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return s.jsx("div",{ref:o,className:W("scrollable-region",t),style:i,"aria-label":l,children:a?s.jsxs(s.Fragment,{children:[e,v&&(h||p)&&s.jsx("div",{className:"scrollable-region__overlay",style:{top:v.top,left:v.left,width:v.width,height:v.height},children:E})]}):s.jsxs(s.Fragment,{children:[E,s.jsx("div",{ref:g,className:W("scrollable-region__viewport",n),children:e})]})})},Hn=48,Bn=({checklist:e})=>{const t=r.useRef(null),n=r.useRef(!1);return r.useLayoutEffect(()=>{const a=t.current;if(!a)return;const i=a.scrollHeight-a.scrollTop-a.clientHeight;(!n.current||i<=Hn)&&(a.scrollTop=a.scrollHeight,n.current=!0)},[e]),e.length===0?s.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):s.jsx(mt,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:s.jsx("ul",{ref:t,className:"agent-view__progress-list","aria-label":"Agent tasks",children:Un(e).map(a=>{const i=me[a.status];return s.jsxs("li",{className:W("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[s.jsx(c.Icon,{name:i.icon,size:16,color:i.color,screenReaderText:`${i.label}:`}),s.jsxs("div",{className:"agent-view__progress-item-content",children:[s.jsx("span",{className:"agent-view__progress-label",children:a.task}),a.status!==$.complete&&s.jsx("span",{className:"agent-view__progress-description",children:a.description})]})]},a.task)})})})},Ss=({open:e,isInProgress:t,isArchiving:n,error:a,onCancel:i,onConfirm:l})=>{const o=r.useId(),g=r.useId();return s.jsxs(c.Modal,{open:e,closeHandler:i,className:"archive-agent-confirm",children:[s.jsx(c.Modal.Header,{className:"archive-agent-confirm__header",children:s.jsx(c.Modal.Title,{id:o,children:kn})}),s.jsxs(c.Modal.Body,{className:"archive-agent-confirm__body",children:[s.jsxs("div",{role:"alertdialog","aria-labelledby":o,"aria-describedby":g,children:[s.jsx("p",{id:g,className:"archive-agent-confirm__lead",children:An}),t?s.jsx("p",{className:"archive-agent-confirm__progress",children:yn}):null,a?s.jsx("p",{className:"archive-agent-confirm__error",role:"alert",children:a}):null]}),s.jsxs("div",{className:"archive-agent-confirm__actions",children:[s.jsx(c.Button,{variant:"secondary",size:"S",disabled:n,onClick:i,children:"Cancel"}),s.jsx(c.Button,{variant:"secondary-destructive",size:"S",disabled:n,onClick:l,children:n?"Archiving…":"Archive"})]})]})]})},Fn=e=>e!==void 0&&e.some(t=>t.status===$.hitl),js=e=>e!==void 0&&e.length>0&&e.every(t=>t.status===$.complete),Ot=(e,t)=>e.status===A.paused?js(t)?A.complete:A["generating-a-response"]:Fn(t)?A.hitl:e.status===A.complete?A.complete:e.status===A.hitl?A.hitl:A["generating-a-response"],Gn=({prompts:e,classNamePrefix:t="agent-workspace",onSelect:n})=>e.length===0?null:s.jsx("div",{className:`${t}__chips`,children:e.map(a=>s.jsx("button",{type:"button",className:`${t}__chip`,onClick:()=>n(a),children:a},a))});class zn{constructor(t,n){this.connector=t,this.canSend=n.canSend,this.onTurn=n.onTurn,this.onAwaitingChange=n.onAwaitingChange}get canRate(){return!1}get canLoadHistory(){return!1}get canListInteractions(){return!1}get canSendNotification(){return!1}get ratingPopupUrls(){return{}}async sendMessage(t){var n,a;if(!this.canSend())return null;(n=this.onAwaitingChange)==null||n.call(this,!0);try{const i=await this.connector.sendMessage(t.userMessage,t.uploadFiles);return this.onTurn(i),{id:i.message.id,text:i.message.text,type:De.CHAT_RESPONSE_TYPE_AGENT,...i.message.followUpPrompts?{followUpPrompts:i.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:jn,type:De.CHAT_RESPONSE_TYPE_ERROR}}finally{(a=this.onAwaitingChange)==null||a.call(this,!1)}}async loadHistory(t){return null}async listInteractions(){return null}async rateMessage(t){}async sendNotification(t){return!1}}const qn=({connector:e,phase:t,chatHistory:n,chatSessionKey:a,startQuery:i,clarificationMessage:l,enableUpload:o=!1,onTurn:g,onAwaitingChange:h,onClarificationPrompt:w,onDismissClarification:p})=>{const f=r.useMemo(()=>new zn(e,{canSend:()=>t===M.running,onTurn:g,onAwaitingChange:h}),[e,t,g,h]),v=t!==M.running,R=t===M.running;return s.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[l&&s.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[s.jsx("p",{className:"agent-workspace__clarification-text",children:l.text}),l.followUpPrompts&&s.jsx(Gn,{prompts:l.followUpPrompts,onSelect:w}),s.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:p,children:"Dismiss"})]}),s.jsx("div",{className:"agent-workspace__ask-arbor",children:s.jsx(mt,{scrollSelector:".chat-panel-message-list",children:s.jsx(De.ChatPanel,{connector:f,chatHistory:n,startQuery:i,lockConversation:v,enableUpload:o,speechEnabled:R,speechLanguage:"en-GB",speechSubmissionDelay:1e3,slashMenuItems:[],menuContent:[],introHeading:"Message your agent",introBody:"Ask questions, share trip details, or paste a link. The agent will update the checklist as it works.",placeholder:R?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)})}),t===M.paused&&s.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[s.jsx(c.Icon,{name:"circle-alert",size:16,color:"var(--color-semantic-warning-600)"}),s.jsx("span",{children:"The agent is paused. Its progress is saved in the checklist."})]}),t===M.complete&&s.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[s.jsx(c.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),s.jsx("span",{children:"The agent has finished."})]})]})},Cs=({item:e,depth:t,canRequestInput:n,onAttentionItemClick:a})=>{const i=me[e.status],l=e.status.replace(/_/g,"-"),o=e.status===$.hitl&&n&&a,g=s.jsxs("div",{className:"agent-workspace__task-row",children:[s.jsx(c.Icon,{name:i.icon,size:16,color:i.color,screenReaderText:`${i.label}:`}),s.jsxs("div",{className:"agent-workspace__task-content",children:[s.jsx("span",{className:"agent-workspace__task-label",children:e.task}),e.status!==$.complete&&e.description&&s.jsx("span",{className:"agent-workspace__task-description",children:e.description})]})]});return s.jsxs("li",{className:W("agent-workspace__task",`agent-workspace__task--${l}`,{"agent-workspace__task--child":t>0}),children:[o?s.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${e.task}`,onClick:()=>a(e),children:g}):g,e.children&&e.children.length>0&&s.jsx("ul",{className:"agent-workspace__task-children",children:e.children.map(h=>s.jsx(Cs,{item:h,depth:t+1,canRequestInput:n,onAttentionItemClick:a},h.task))})]})},ht=({items:e,ariaLabel:t,canRequestInput:n,onAttentionItemClick:a})=>s.jsx("ul",{className:"agent-workspace__task-list","aria-label":t,children:e.map(i=>s.jsx(Cs,{item:i,depth:0,canRequestInput:n,onAttentionItemClick:a},i.task))}),Kn=({checklist:e,isLoading:t,error:n,phase:a,canRequestInput:i,onAttentionItemClick:l,adminMode:o=!1,context:g,contextLoaded:h=!1,contextLoading:w=!1,contextError:p=null,onContextSelect:f})=>{const[v,R]=r.useState("checklist"),_=r.useMemo(()=>e?bs(e):null,[e]),k=()=>{R("context"),f==null||f()};return s.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--checklist","aria-label":"Checklist",children:[s.jsx("div",{className:"agent-workspace__panel-header",children:o?s.jsxs(c.Tabs,{className:"agent-workspace__checklist-tabs","aria-label":"Checklist panel",children:[s.jsx(c.Tabs.Item,{active:v==="checklist",tabElementProps:{id:"agent-checklist-tab-checklist",onClick:()=>R("checklist")},children:"Checklist"}),s.jsx(c.Tabs.Item,{active:v==="context",tabElementProps:{id:"agent-checklist-tab-context",onClick:k},children:"Context"})]}):s.jsx(c.Heading,{level:4,children:"Checklist"})}),s.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:s.jsx(mt,{children:v==="context"?s.jsxs(s.Fragment,{children:[w&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading context"}),s.jsx("span",{children:"Loading context…"})]}),!w&&p&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:p}),!w&&!p&&h&&g==null&&s.jsx("p",{className:"agent-workspace__empty",children:"No context available."}),!w&&!p&&h&&g!==null&&g!==void 0&&s.jsx("pre",{className:"agent-workspace__context-json",children:JSON.stringify(g,null,2)})]}):s.jsxs(s.Fragment,{children:[t&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:Me}),s.jsx("span",{children:Me})]}),!t&&n&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:n}),!t&&!n&&_&&s.jsxs(s.Fragment,{children:[_.needsInput.length>0&&s.jsxs("div",{className:"agent-workspace__task-group",children:[s.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),s.jsx(ht,{items:_.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:i,onAttentionItemClick:l})]}),_.complete.length>0&&s.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":_.needsInput.length>0}),children:[(_.needsInput.length>0||_.failed.length>0||_.tasks.length>0)&&s.jsx("p",{className:"agent-workspace__task-group-label",children:"Completed"}),s.jsx(ht,{items:_.complete,ariaLabel:"Completed tasks",canRequestInput:i,onAttentionItemClick:l})]}),_.failed.length>0&&s.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":_.needsInput.length>0||_.complete.length>0}),children:[(_.needsInput.length>0||_.complete.length>0||_.tasks.length>0)&&s.jsx("p",{className:"agent-workspace__task-group-label",children:"Failed"}),s.jsx(ht,{items:_.failed,ariaLabel:"Failed tasks",canRequestInput:i,onAttentionItemClick:l})]}),_.tasks.length>0&&s.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":_.needsInput.length>0||_.complete.length>0||_.failed.length>0}),children:[(_.needsInput.length>0||_.complete.length>0||_.failed.length>0)&&s.jsx("p",{className:"agent-workspace__task-group-label",children:"Working on"}),s.jsx(ht,{items:_.tasks,ariaLabel:"Agent tasks",canRequestInput:i,onAttentionItemClick:l})]})]}),!t&&!n&&(!_||_.needsInput.length===0&&_.complete.length===0&&_.failed.length===0&&_.tasks.length===0)&&s.jsx("p",{className:"agent-workspace__empty",children:a===M.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})})]})},Jn=({resource:e,html:t,isLoading:n,error:a,onClose:i})=>{r.useEffect(()=>{if(!e)return;const o=c.SlideoverUtils.removeSlideover;return c.SlideoverUtils.removeSlideover=()=>{o(),i()},()=>{c.SlideoverUtils.removeSlideover=o}},[e,i]),r.useEffect(()=>{if(!e)return;const o=g=>{g.key==="Escape"&&c.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[e]);const l=r.useMemo(()=>e?[{centerHeaderText:!1,children:s.jsxs("div",{className:"resource-preview-slideover__body",children:[n&&s.jsxs("div",{className:"resource-preview-slideover__status",children:[s.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading document"}),s.jsx("span",{children:"Loading document…"})]}),!n&&a&&s.jsx("p",{className:"resource-preview-slideover__error",role:"alert",children:a}),!n&&!a&&t!==null&&s.jsx("iframe",{className:"resource-preview-slideover__frame",title:e.title,sandbox:"",srcDoc:t})]})}]:[],[e,t,n,a]);return s.jsx("div",{className:"resource-preview-slideover",children:s.jsx(c.SlideoverManager,{slideovers:l})})},Vn={[pe.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[pe.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[pe.file]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[pe.user_file]:{icon:"upload",label:"File upload",color:"var(--color-semantic-caution-800)"},[pe.workflow]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[pe.link]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},Wn=({resources:e,isLoading:t=!1,error:n=null,onOpenResource:a})=>s.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--documents","aria-label":"Resources",children:[s.jsxs("div",{className:"agent-workspace__panel-header",children:[s.jsx(c.Heading,{level:4,children:"Resources"}),s.jsx("span",{className:"agent-workspace__panel-count",children:e.length})]}),s.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:s.jsxs(mt,{children:[t&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading resources"}),s.jsx("span",{children:"Loading resources…"})]}),!t&&n&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:n}),!t&&!n&&e.length>0&&s.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:e.map(i=>{const l=Vn[i.type],o=i.misRecordUrl;return s.jsx("li",{className:"agent-workspace__resource",children:o?s.jsx("a",{className:"agent-workspace__resource-card",href:o,target:"_blank",rel:"noreferrer",onClick:g=>{g.preventDefault(),a(i)},children:s.jsx(cs,{resource:i,config:l,external:!0})}):s.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>a(i),children:s.jsx(cs,{resource:i,config:l})})},i.id)})}),!t&&!n&&e.length===0&&s.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),cs=({resource:e,config:t,external:n=!1})=>s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${e.type}`,children:s.jsx(c.Icon,{name:t.icon,size:16,color:t.color,screenReaderText:`${t.label}:`})}),s.jsx("span",{className:"agent-workspace__resource-content",children:s.jsxs("span",{className:"agent-workspace__resource-top",children:[s.jsx("span",{className:"agent-workspace__resource-name",children:e.title}),s.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${e.type}`,children:t.label})]})}),n&&s.jsx(c.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]}),Lt=e=>{const t=Date.parse(e);return Number.isFinite(t)?t:0},Yn=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),Pt=e=>{const t=new Date(e);return Number.isFinite(t.getTime())?Yn.format(t):e},ds=e=>e.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,t=>t.split(/[_-]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" ")),us=e=>{const n=e.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,a=>a.split(/[_-]/).map(i=>i.toLowerCase()).join(" ")).toLowerCase();return n&&n.charAt(0).toUpperCase()+n.slice(1)},Xn=60*60*1e3,Es=60*60*1e3,Ve=24*Es,Dt=7*Ve,Zn=e=>e.type!=="message-sent",Qn=e=>{if(e==null||e<=0)return null;if(e%86400===0){const n=e/86400;return n===1?"every day":`every ${n} days`}if(e%3600===0){const n=e/3600;return n===1?"every hour":`every ${n} hours`}if(e%60===0){const n=e/60;return n===1?"every minute":`every ${n} minutes`}const t=Math.max(1,Math.round(e/60));return t===1?"every minute":`every ${t} minutes`},ea=e=>{if(e.recurrence==="one_off")return"Scheduled to run once";const t=Qn(e.repeatIntervalSeconds);return t?`Repeating ${t}`:"Repeating run scheduled"},ta=e=>e.recurrence==="one_off"?"scheduled-one-off":"scheduled-repeating",sa=(e,t,n=[])=>{const a=e.filter(Zn).map((o,g)=>({kind:"action",id:`action-${o.timestamp}-${g}`,timestampMs:Lt(o.timestamp),item:o})),i=t.map(o=>({kind:"chat",id:o.sessionId,timestampMs:Lt(o.timestamp),session:o})),l=n.map(o=>({kind:"scheduled",id:`scheduled-${o.scheduleId}`,timestampMs:Lt(o.dueAt),run:o}));return[...a,...i,...l].sort((o,g)=>o.timestampMs-g.timestampMs||o.id.localeCompare(g.id))},na=e=>e>=Dt?"weeks":e>=Ve?"days":"hours",aa=e=>{if(e<Ve){const a=Math.max(1,Math.round(e/Es));return a===1?"1 hour later":`${a} hours later`}if(e<Dt){const a=Math.max(1,Math.round(e/Ve));return a===1?"1 day later":`${a} days later`}const t=Math.max(1,Math.round(e/Dt));if(t<5)return t===1?"1 week later":`${t} weeks later`;const n=Math.max(1,Math.round(e/(30*Ve)));return n===1?"1 month later":`${n} months later`},ra=(e,t=Xn)=>{if(e.length===0)return[];const n=[e[0]];for(let a=1;a<e.length;a+=1){const i=e[a-1],l=e[a],o=l.timestampMs-i.timestampMs;o>=t&&n.push({kind:"gap",id:`gap-${i.id}-${l.id}`,durationMs:o,label:aa(o),size:na(o)}),n.push(l)}return n},ia=e=>e.type==="checklist-updated"?"checklist":e.type==="status-transition"?"status":"note",oa=({timeline:e,isLoading:t,error:n,onOpenChatSession:a})=>{const i=(e==null?void 0:e.actionLog)??[],l=(e==null?void 0:e.chatSessions)??[],o=(e==null?void 0:e.scheduledRuns)??[],g=sa(i,l,o),h=ra(g),w=!t&&!n&&g.length===0;return s.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[t&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),n&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:n||ys}),w&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!t&&!n&&!w&&s.jsxs("div",{className:"agent-timeline",children:[s.jsx("div",{className:"agent-timeline__track","aria-hidden":"true"}),s.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",children:[s.jsx("span",{className:"agent-timeline__station-rail",children:s.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:s.jsx(c.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})})}),s.jsx("div",{className:"agent-timeline__label",children:s.jsx("strong",{className:"agent-timeline__label-type",children:"Start"})})]}),h.map(p=>{if(p.kind==="gap")return s.jsxs("div",{className:`agent-timeline__gap agent-timeline__gap--${p.size}`,role:"separator","aria-label":p.label,children:[s.jsx("span",{className:"agent-timeline__gap-rail","aria-hidden":"true",children:s.jsx("span",{className:"agent-timeline__gap-dot"})}),s.jsx("span",{className:"agent-timeline__gap-label",children:p.label})]},p.id);if(p.kind==="chat"){const k=Pt(p.session.timestamp),O=s.jsx(c.Icon,{name:"sparkles",size:16,color:"currentColor"});return s.jsxs("div",{className:"agent-timeline__chat-station",children:[a?s.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${k}`,onClick:()=>a(p.session.sessionId),children:O}):s.jsx("span",{className:"agent-timeline__chat-node agent-timeline__chat-node--static","aria-hidden":"true",children:O}),s.jsxs("div",{className:"agent-timeline__label",children:[s.jsx("strong",{className:"agent-timeline__label-type",children:"Chat session"}),s.jsx("span",{className:"agent-timeline__label-time",children:k})]})]},p.id)}if(p.kind==="scheduled"){const k=ta(p.run),O=p.run.recurrence==="one_off"?"One-off run":"Repeating run";return s.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${k}`,children:[s.jsx("span",{className:"agent-timeline__station-rail",children:s.jsx("span",{className:`agent-timeline__station-node agent-timeline__station-node--${k}`,"aria-hidden":"true",children:s.jsx(c.Icon,{name:"date",size:16,color:"currentColor"})})}),s.jsxs("div",{className:"agent-timeline__label",children:[s.jsx("strong",{className:"agent-timeline__label-type",children:O}),s.jsx("span",{className:"agent-timeline__label-entry",children:ea(p.run)}),s.jsx("span",{className:"agent-timeline__label-time",children:Pt(p.run.dueAt)})]})]},p.id)}const{item:f}=p,v=ia(f),R=v==="checklist",_=v==="status";return s.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${v}`,children:[s.jsx("span",{className:"agent-timeline__station-rail",children:s.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${v}`,"aria-label":`${ds(f.type)}: ${us(f.entry)}`,children:[R&&s.jsx(c.Icon,{name:"check-solid",size:16,color:"currentColor"}),_&&s.jsx(c.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]})}),s.jsxs("div",{className:"agent-timeline__label",children:[s.jsx("strong",{className:"agent-timeline__label-type",children:ds(f.type)}),s.jsx("span",{className:"agent-timeline__label-entry",children:us(f.entry)}),s.jsx("span",{className:"agent-timeline__label-time",children:Pt(f.timestamp)})]})]},p.id)}),s.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",children:[s.jsx("span",{className:"agent-timeline__station-rail",children:s.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:s.jsx(c.Icon,{name:"flag",size:16,color:"currentColor"})})}),s.jsx("div",{className:"agent-timeline__label",children:s.jsx("strong",{className:"agent-timeline__label-type",children:"Finish"})})]})]})]})},la=["I'll get the details and come back to you","Skip this for now"],ca=e=>{var n;const t=(n=e.prompt)!=null&&n.trim()?e.prompt.trim():`I need a bit more from you on "${e.task}". ${e.description} What can you tell me?`;return{id:`clarification-${Date.now()}`,author:te.agent,text:t,followUpPrompts:e.clarificationPrompts??la}},da=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),ua=e=>e.kind===ws.user_file?`<strong>${da(e.text)}</strong>`:e.text,ge=e=>({id:e.id,text:ua(e),type:e.author===te.user?De.CHAT_RESPONSE_TYPE_USER:e.author===te.system?De.CHAT_RESPONSE_TYPE_INFO:De.CHAT_RESPONSE_TYPE_AGENT,...e.followUpPrompts?{followUpPrompts:e.followUpPrompts}:{}}),$t="MESSAGE_TYPE_REPOLL",Rs="agentUi:update",Ht="arbor-agent-",_e={all:"ALL",checklist:"CHECKLIST",resources:"RESOURCES",chat:"CHAT",timeline:"TIMELINE"},ha=new Set(Object.values(_e)),Ts=(e,t)=>`${e.endsWith("-")?e:`${e}-`}${t}`,ga=e=>typeof e=="string"&&ha.has(e)?e:_e.all,pa=e=>{if(!e||typeof e!="object")return null;const t=e;return t.type!==$t?null:{type:$t,target:ga(t.target)}},Is=e=>{const t=Array.isArray(e)?e:[e],n=[];for(const a of t){const i=pa(a);i&&n.push(i)}return n},ma=({enabled:e,channelPrefix:t,agentId:n,subscribeToPusher:a,onRepoll:i})=>{const l=r.useRef(i),o=t==null?void 0:t.trim(),g=!!(e&&a&&o&&n.trim());return r.useEffect(()=>{l.current=i},[i]),r.useEffect(()=>{if(!g||!a||!o)return;const h=a(Ts(o,n),Rs,w=>{for(const p of Is(w))l.current(p.target)});return()=>{h()}},[g,o,n,a]),g};class Ue extends Error{constructor(t,n,a){super(a??`Agent service request failed (${t})`),this.name="AgentServiceError",this.status=t,this.detail=n}}const _a="/api/v1",H={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},q={GET:"GET",POST:"POST",PATCH:"PATCH"},fa={error:"error"},va={user:"user"},Se={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},xa=100,Os=e=>{switch(e){case Rt.paused:return A.paused;case Rt.complete:return A.complete;case A.hitl:return A.hitl;case Rt.active:case A["generating-a-response"]:return A["generating-a-response"];default:return A["generating-a-response"]}},Ls=e=>{switch(e){case Tt.requires_attention:return $.hitl;case Tt.in_progress:case Tt.available:return $["generating-a-response"];case $.failed:case $.complete:case $.hitl:case $["generating-a-response"]:return e;default:return $["generating-a-response"]}},Bt=e=>({ref:e.name,display_name:e.display_name,agent_intent:e.agent_intent??"",description:e.description}),wa=e=>({id:e.id,name:e.name,...e.has_run_before?{hasRunBefore:e.has_run_before}:{}}),ka=new Set(Object.values(pe)),Aa=e=>ka.has(e)?e:pe.document_html,Ps=e=>({id:e.id,type:Aa(e.type),title:e.title,createdDatetime:e.created_datetime,lastUpdatedDatetime:e.last_updated_datetime,misRecordUrl:e.mis_record_url}),Ms=e=>({resources:e.resources.map(Ps),pageNumber:e.page_number,pageSize:e.page_size,totalRecords:e.total_records}),Us=e=>({actionLog:(e.action_log??[]).map(t=>({timestamp:t.timestamp,type:t.type,entry:t.entry,origin:t.origin})),chatSessions:(e.chat_sessions??[]).map(t=>({sessionId:t.session_id,timestamp:t.timestamp})),scheduledRuns:(e.scheduled_runs??[]).map(t=>({scheduleId:t.schedule_id,dueAt:t.due_at,recurrence:t.recurrence,repeatIntervalSeconds:t.repeat_interval_seconds,wakePrompt:t.wake_prompt}))}),We=e=>{var n;const t=e.invocation_id??e.id;return{id:e.id,invocation_id:t,agent_definition_ref:e.agent_definition_ref,...e.agent_intent?{agent_intent:e.agent_intent}:{},invocation_name:((n=e.invocation_name)==null?void 0:n.trim())||e.agent_definition_ref,application_id:e.application_id,...e.application_name?{application_name:e.application_name}:{},created_by:e.created_by,status:Os(e.status),archivedAt:e.archived_at??null,context_ref:e.context_ref??null,checklist_ref:e.checklist_ref??null}},Ft=e=>{var t;return{task:e.item??e.task??e.name??e.label??Cn,status:Ls(e.status),description:e.description??"",...e.prompt?{prompt:e.prompt}:{},...(t=e.follow_up_prompts)!=null&&t.length?{clarificationPrompts:e.follow_up_prompts}:{}}},ya=e=>Array.isArray(e)?e:e.checklist_items??e.checklist??e.items??[],Gt=(e,t,n)=>{var l;const a=!Array.isArray(t)&&(t.opening_message||(l=t.opening_follow_up_prompts)!=null&&l.length)?t:n,i=a?Xe(a):void 0;return{invocation_id:e,checklist:ya(t).map(Ft),...i?{openingMessage:i}:{}}},Ds=(e,t)=>{const n=Xe(t);return{invocation_id:t.invocation_id??e,checklist:(t.checklist_items??[]).map(Ft),...n?{openingMessage:n}:{}}},Xe=e=>{var n,a;const t=(n=e.opening_message)==null?void 0:n.trim();if(t)return{id:As,author:te.agent,text:t,...(a=e.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:e.opening_follow_up_prompts}:{}}},Na=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)){const n=t.filter(a=>!!a&&typeof a=="object"&&typeof a.text=="string").map(a=>a.text);if(n.length>0)return n.join(`
2
- `)}}catch{}return e},ba=e=>{const t=e.trim();return t.length>0?`File upload
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),a=require("react"),W=require("classnames"),c=require("@arbor-education/design-system.components"),Ye=require("@arbor-education/ask-arbor-chat-panel"),N={"generating-a-response":"generating-a-response",hitl:"hitl",paused:"paused",complete:"complete"},F={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},$={briefing:"briefing",running:"running",paused:"paused",complete:"complete"},se={agent:"agent",user:"user",system:"system"},Ae={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",user_file:"user_file",link:"link"},qn={user_file:"user_file"},sn={active:"active",complete:"complete",paused:"paused"},an={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},ye={[F.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[F.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[F.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[F["generating-a-response"]]:{label:"Generating a response",icon:"sparkles",color:"var(--color-brand-600)"}},Kn="var(--color-grey-600)",wt={[N["generating-a-response"]]:{status:N["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:ye["generating-a-response"].icon,color:ye["generating-a-response"].color}},[N.hitl]:{status:N.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:ye.hitl.icon,color:ye.hitl.color}},[N.paused]:{status:N.paused,title:"Paused",dotColour:"green",statusIcon:{name:"circle-x",color:Kn}},[N.complete]:{status:N.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:ye.complete.icon,color:ye.complete.color}}},zs={name:"archive",color:Kn},qs=[N["generating-a-response"],N.hitl,N.complete],Ks="m4",Vs="1",Vn="msg-opening",Ht="Unable to load agent tasks. Please try again.",Js="Unable to load context.",Ys="Unable to load the resources for this agent",Ws="Unable to load this document. Please try again.",Jn="Unable to load the timeline for this agent",Xs="Unable to pause the agent. Please try again.",dn="Unable to archive the agent. Please try again.",Zs="Archive this agent?",Qs="Archiving files this agent away and stops its work. You can restore it later as paused; it will not run until you resume it. Chat is not available while it is archived. You can still open it from Archived to view the timeline and resources.",ea="This agent is still in progress.",hn="Unable to unarchive the agent. Please try again.",ta="Restore this agent?",na="Restoring returns this agent to the board as paused. It will not run chats or scheduled work until you resume it.",sa="Unable to delete the agent. Please try again.",aa="You do not have permission to delete this agent.",ra="This agent must be paused or archived before it can be deleted.",ia="This agent could not be found. It may have already been deleted.",la="Delete this agent?",oa="Deleting cannot be undone. This permanently removes the agent and its related data. It will not appear in Archived and cannot be restored.",ca="Unable to resume the agent. Please try again.",ua="The agent was resumed but could not be woken. Send a message to continue.",Tn="You have been resumed after being paused. Reassess your current progress and continue your work from where you left off.",da="Unable to rename the agent. Please try again.",ha="Something went wrong. Please try again.",Yn="Unable to load agents. Please try again.",Je="Loading tasks…",In="Loading agents…",ga="Task",ma={[$.briefing]:"Briefing",[$.running]:"Working",[$.paused]:"Paused",[$.complete]:"Complete"},pa=[N["generating-a-response"],N.hitl,N.complete],_a={[N["generating-a-response"]]:"Agents currently working on tasks for you.",[N.hitl]:"Agents that need your input before they can continue.",[N.paused]:"Agents that are paused until you resume them.",[N.complete]:"Agents that have finished their work."},fa=()=>n.jsxs("svg",{className:"agent-view__empty-illustration",viewBox:"0 0 360 240",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Preview of the agents board layout",children:[n.jsx("rect",{x:"0",y:"0",width:"360",height:"240",rx:"12",fill:"var(--color-grey-100)"}),n.jsx("rect",{x:"16",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"130",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"244",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"28",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),n.jsx("rect",{x:"28",y:"96",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),n.jsx("rect",{x:"142",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-semantic-warning-050)"}),n.jsx("rect",{x:"256",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),n.jsx("circle",{cx:"40",cy:"70",r:"4",fill:"var(--color-brand-600)"}),n.jsx("circle",{cx:"40",cy:"114",r:"4",fill:"var(--color-brand-600)"}),n.jsx("circle",{cx:"154",cy:"70",r:"4",fill:"var(--color-semantic-warning-600)"}),n.jsx("circle",{cx:"256",cy:"70",r:"4",fill:"var(--color-grey-400)"})]}),va=({status:e})=>{const t=wt[e];return t.statusIcon?n.jsx(c.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,screenReaderText:t.title}):n.jsx(c.Dot,{colour:t.dotColour,label:t.title})},xa=()=>n.jsxs("section",{className:"agent-view__empty","aria-label":"About the agents board",children:[n.jsxs("div",{className:"agent-view__empty-content",children:[n.jsx(c.Heading,{level:4,children:"Your agents board"}),n.jsx("p",{className:"agent-view__empty-lead",children:"When you start an agent, it appears here so you can track progress at a glance. Agents move between columns as their status changes."}),n.jsx("ul",{className:"agent-view__empty-columns",children:pa.map(e=>{const t=wt[e];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(va,{status:e})}),n.jsxs("span",{className:"agent-view__empty-column-text",children:[n.jsx("span",{className:"agent-view__empty-column-title",children:t.title}),n.jsx("span",{className:"agent-view__empty-column-description",children:_a[e]})]})]},e)})}),n.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",n.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),n.jsx("div",{className:"agent-view__empty-visual",children:n.jsx(fa,{})})]}),wa=()=>({needsInput:[],complete:[],failed:[],tasks:[]}),Aa=(e,t)=>({...e,...t.length>0?{children:t}:{}}),Wn=e=>{const t=[],s=[],r=[],i=[];for(const o of e){const l=o.children?Wn(o.children):wa();if(t.push(...l.needsInput),s.push(...l.complete),r.push(...l.failed),o.status===F.hitl){t.push({...o,children:void 0});continue}if(o.status===F.complete){s.push({...o,children:void 0});continue}if(o.status===F.failed){r.push({...o,children:void 0});continue}i.push(Aa(o,l.tasks))}return{needsInput:t,complete:s,failed:r,tasks:i}},On=e=>e===F.hitl?0:e===F.complete?1:e===F.failed?2:3,ya=e=>e.map((t,s)=>({item:t,index:s})).sort((t,s)=>{const r=On(t.item.status)-On(s.item.status);return r!==0?r:t.index-s.index}).map(({item:t})=>t),rn=2,ka=e=>{if(!e)return{canScrollUp:!1,canScrollDown:!1};const t=e.scrollHeight-e.clientHeight;return t<=rn?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:e.scrollTop>rn,canScrollDown:e.scrollTop<t-rn}},Na=(e,t)=>{if(!e||!t)return null;const s=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{top:r.top-s.top,left:r.left-s.left,width:r.width,height:r.height}},Ft=({children:e,className:t,contentClassName:s,scrollSelector:r,style:i,"aria-label":o})=>{const l=a.useRef(null),m=a.useRef(null),[h,k]=a.useState(!1),[f,w]=a.useState(!1),[A,E]=a.useState(null),p=()=>{var I;return r?((I=l.current)==null?void 0:I.querySelector(r))??null:m.current},C=()=>{const I=p(),v=ka(I);if(k(g=>g===v.canScrollUp?g:v.canScrollUp),w(g=>g===v.canScrollDown?g:v.canScrollDown),r){const g=Na(l.current,I);E(x=>(x==null?void 0:x.top)===(g==null?void 0:g.top)&&(x==null?void 0:x.left)===(g==null?void 0:g.left)&&(x==null?void 0:x.width)===(g==null?void 0:g.width)&&(x==null?void 0:x.height)===(g==null?void 0:g.height)?x:g)}else E(g=>g===null?g:null)};a.useLayoutEffect(()=>{C()}),a.useEffect(()=>{const I=l.current;if(!I)return;let v=null,g=null;const x=()=>{v==null||v.removeEventListener("scroll",C),g==null||g.disconnect(),g=null,v=null},j=Y=>{if(Y===v){C();return}if(x(),v=Y,!v){C();return}v.addEventListener("scroll",C,{passive:!0}),g=new ResizeObserver(()=>C()),g.observe(v),v.firstElementChild instanceof HTMLElement&&g.observe(v.firstElementChild),C()};j(p());const O=new MutationObserver(()=>{j(p())});return O.observe(I,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",C),()=>{window.removeEventListener("resize",C),O.disconnect(),x()}},[r]);const L=I=>{const v=p();if(!v)return;const g=Math.max(v.clientHeight*.75,120);v.scrollBy({top:I==="up"?-g:g,behavior:"smooth"})},M=n.jsxs(n.Fragment,{children:[h&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--top","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--top","aria-label":"Scroll up",onClick:()=>L("up"),children:n.jsx(c.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),f&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>L("down"),children:n.jsx(c.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return n.jsx("div",{ref:l,className:W("scrollable-region",t),style:i,"aria-label":o,children:r?n.jsxs(n.Fragment,{children:[e,A&&(h||f)&&n.jsx("div",{className:"scrollable-region__overlay",style:{top:A.top,left:A.left,width:A.width,height:A.height},children:M})]}):n.jsxs(n.Fragment,{children:[M,n.jsx("div",{ref:m,className:W("scrollable-region__viewport",s),children:e})]})})},Ca=48,ba=({checklist:e})=>{const t=a.useRef(null),s=a.useRef(!1);return a.useLayoutEffect(()=>{const r=t.current;if(!r)return;const i=r.scrollHeight-r.scrollTop-r.clientHeight;(!s.current||i<=Ca)&&(r.scrollTop=r.scrollHeight,s.current=!0)},[e]),e.length===0?n.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):n.jsx(Ft,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:n.jsx("ul",{ref:t,className:"agent-view__progress-list","aria-label":"Agent tasks",children:ya(e).map(r=>{const i=ye[r.status];return n.jsxs("li",{className:W("agent-view__progress-item",`agent-view__progress-item--${r.status.replace(/_/g,"-")}`),children:[n.jsx(c.Icon,{name:i.icon,size:16,color:i.color,screenReaderText:`${i.label}:`}),n.jsxs("div",{className:"agent-view__progress-item-content",children:[n.jsx("span",{className:"agent-view__progress-label",children:r.task}),r.status!==F.complete&&n.jsx("span",{className:"agent-view__progress-description",children:r.description})]})]},r.task)})})})},Xn=({open:e,isInProgress:t,isArchiving:s,error:r,onCancel:i,onConfirm:o})=>{const l=a.useId(),m=a.useId();return n.jsxs(c.Modal,{open:e,closeHandler:i,className:"archive-agent-confirm",children:[n.jsx(c.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(c.Modal.Title,{id:l,children:Zs})}),n.jsxs(c.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":l,"aria-describedby":m,children:[n.jsx("p",{id:m,className:"archive-agent-confirm__lead",children:Qs}),t?n.jsx("p",{className:"archive-agent-confirm__progress",children:ea}):null,r?n.jsx("p",{className:"archive-agent-confirm__error",role:"alert",children:r}):null]}),n.jsxs("div",{className:"archive-agent-confirm__actions",children:[n.jsx(c.Button,{variant:"secondary",size:"S",disabled:s,onClick:i,children:"Cancel"}),n.jsx(c.Button,{variant:"secondary-destructive",size:"S",disabled:s,onClick:o,children:s?"Archiving…":"Archive"})]})]})]})},Zn=({open:e,isDeleting:t,error:s,onCancel:r,onConfirm:i})=>{const o=a.useId(),l=a.useId();return n.jsxs(c.Modal,{open:e,closeHandler:r,className:"archive-agent-confirm",children:[n.jsx(c.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(c.Modal.Title,{id:o,children:la})}),n.jsxs(c.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":o,"aria-describedby":l,children:[n.jsx("p",{id:l,className:"archive-agent-confirm__lead",children:oa}),s?n.jsx("p",{className:"archive-agent-confirm__error",role:"alert",children:s}):null]}),n.jsxs("div",{className:"archive-agent-confirm__actions",children:[n.jsx(c.Button,{variant:"secondary",size:"S",disabled:t,onClick:r,children:"Cancel"}),n.jsx(c.Button,{variant:"secondary-destructive",size:"S",disabled:t,onClick:i,children:t?"Deleting…":"Delete"})]})]})]})},Qn=({open:e,isUnarchiving:t,error:s,onCancel:r,onConfirm:i})=>{const o=a.useId(),l=a.useId();return n.jsxs(c.Modal,{open:e,closeHandler:r,className:"archive-agent-confirm",children:[n.jsx(c.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(c.Modal.Title,{id:o,children:ta})}),n.jsxs(c.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":o,"aria-describedby":l,children:[n.jsx("p",{id:l,className:"archive-agent-confirm__lead",children:na}),s?n.jsx("p",{className:"archive-agent-confirm__error",role:"alert",children:s}):null]}),n.jsxs("div",{className:"archive-agent-confirm__actions",children:[n.jsx(c.Button,{variant:"secondary",size:"S",disabled:t,onClick:r,children:"Cancel"}),n.jsx(c.Button,{variant:"secondary",size:"S",disabled:t,onClick:i,children:t?"Restoring…":"Restore"})]})]})]})},Sa=e=>e!==void 0&&e.some(t=>t.status===F.hitl),es=e=>e!==void 0&&e.length>0&&e.every(t=>t.status===F.complete),ln=(e,t)=>e.status===N.paused?es(t)?N.complete:N["generating-a-response"]:Sa(t)?N.hitl:e.status===N.complete?N.complete:e.status===N.hitl?N.hitl:N["generating-a-response"],Ea=({prompts:e,classNamePrefix:t="agent-workspace",onSelect:s})=>e.length===0?null:n.jsx("div",{className:`${t}__chips`,children:e.map(r=>n.jsx("button",{type:"button",className:`${t}__chip`,onClick:()=>s(r),children:r},r))});class ja{constructor(t,s){this.connector=t,this.canSend=s.canSend,this.onTurn=s.onTurn,this.onAwaitingChange=s.onAwaitingChange}get canRate(){return!1}get canLoadHistory(){return!1}get canListInteractions(){return!1}get canSendNotification(){return!1}get ratingPopupUrls(){return{}}async sendMessage(t){var s,r;if(!this.canSend())return null;(s=this.onAwaitingChange)==null||s.call(this,!0);try{const i=await this.connector.sendMessage(t.userMessage,t.uploadFiles);return this.onTurn(i),{id:i.message.id,text:i.message.text,type:Ye.CHAT_RESPONSE_TYPE_AGENT,...i.message.followUpPrompts?{followUpPrompts:i.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:ha,type:Ye.CHAT_RESPONSE_TYPE_ERROR}}finally{(r=this.onAwaitingChange)==null||r.call(this,!1)}}async loadHistory(t){return null}async listInteractions(){return null}async rateMessage(t){}async sendNotification(t){return!1}}const Ra=({connector:e,phase:t,chatHistory:s,chatSessionKey:r,startQuery:i,clarificationMessage:o,enableUpload:l=!1,onTurn:m,onAwaitingChange:h,onClarificationPrompt:k,onDismissClarification:f})=>{const w=a.useMemo(()=>new ja(e,{canSend:()=>t===$.running,onTurn:m,onAwaitingChange:h}),[e,t,m,h]),A=t!==$.running,E=t===$.running;return n.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[o&&n.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[n.jsx("p",{className:"agent-workspace__clarification-text",children:o.text}),o.followUpPrompts&&n.jsx(Ea,{prompts:o.followUpPrompts,onSelect:k}),n.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:f,children:"Dismiss"})]}),n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(Ft,{scrollSelector:".chat-panel-message-list",children:n.jsx(Ye.ChatPanel,{connector:w,chatHistory:s,startQuery:i,lockConversation:A,enableUpload:l,speechEnabled:E,speechLanguage:"en-GB",speechSubmissionDelay:1e3,slashMenuItems:[],menuContent:[],introHeading:"Message your agent",introBody:"Ask questions, share trip details, or paste a link. The agent will update the checklist as it works.",placeholder:E?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},r)})}),t===$.paused&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(c.Icon,{name:"circle-alert",size:16,color:"var(--color-semantic-warning-600)"}),n.jsx("span",{children:"The agent is paused. Its progress is saved in the checklist."})]}),t===$.complete&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(c.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),n.jsx("span",{children:"The agent has finished."})]})]})},ts=({item:e,depth:t,canRequestInput:s,onAttentionItemClick:r})=>{const i=ye[e.status],o=e.status.replace(/_/g,"-"),l=e.status===F.hitl&&s&&r,m=n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(c.Icon,{name:i.icon,size:16,color:i.color,screenReaderText:`${i.label}:`}),n.jsxs("div",{className:"agent-workspace__task-content",children:[n.jsx("span",{className:"agent-workspace__task-label",children:e.task}),e.status!==F.complete&&e.description&&n.jsx("span",{className:"agent-workspace__task-description",children:e.description})]})]});return n.jsxs("li",{className:W("agent-workspace__task",`agent-workspace__task--${o}`,{"agent-workspace__task--child":t>0}),children:[l?n.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${e.task}`,onClick:()=>r(e),children:m}):m,e.children&&e.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:e.children.map(h=>n.jsx(ts,{item:h,depth:t+1,canRequestInput:s,onAttentionItemClick:r},h.task))})]})},Dt=({items:e,ariaLabel:t,canRequestInput:s,onAttentionItemClick:r})=>n.jsx("ul",{className:"agent-workspace__task-list","aria-label":t,children:e.map(i=>n.jsx(ts,{item:i,depth:0,canRequestInput:s,onAttentionItemClick:r},i.task))}),Ta=({checklist:e,isLoading:t,error:s,phase:r,canRequestInput:i,onAttentionItemClick:o,adminMode:l=!1,context:m,contextLoaded:h=!1,contextLoading:k=!1,contextError:f=null,onContextSelect:w})=>{const[A,E]=a.useState("checklist"),p=a.useMemo(()=>e?Wn(e):null,[e]),C=()=>{E("context"),w==null||w()};return n.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--checklist","aria-label":"Checklist",children:[n.jsx("div",{className:"agent-workspace__panel-header",children:l?n.jsxs(c.Tabs,{className:"agent-workspace__checklist-tabs","aria-label":"Checklist panel",children:[n.jsx(c.Tabs.Item,{active:A==="checklist",tabElementProps:{id:"agent-checklist-tab-checklist",onClick:()=>E("checklist")},children:"Checklist"}),n.jsx(c.Tabs.Item,{active:A==="context",tabElementProps:{id:"agent-checklist-tab-context",onClick:C},children:"Context"})]}):n.jsx(c.Heading,{level:4,children:"Checklist"})}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsx(Ft,{children:A==="context"?n.jsxs(n.Fragment,{children:[k&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading context"}),n.jsx("span",{children:"Loading context…"})]}),!k&&f&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:f}),!k&&!f&&h&&m==null&&n.jsx("p",{className:"agent-workspace__empty",children:"No context available."}),!k&&!f&&h&&m!==null&&m!==void 0&&n.jsx("pre",{className:"agent-workspace__context-json",children:JSON.stringify(m,null,2)})]}):n.jsxs(n.Fragment,{children:[t&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:Je}),n.jsx("span",{children:Je})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!t&&!s&&p&&n.jsxs(n.Fragment,{children:[p.needsInput.length>0&&n.jsxs("div",{className:"agent-workspace__task-group",children:[n.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),n.jsx(Dt,{items:p.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:i,onAttentionItemClick:o})]}),p.complete.length>0&&n.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":p.needsInput.length>0}),children:[(p.needsInput.length>0||p.failed.length>0||p.tasks.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Completed"}),n.jsx(Dt,{items:p.complete,ariaLabel:"Completed tasks",canRequestInput:i,onAttentionItemClick:o})]}),p.failed.length>0&&n.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":p.needsInput.length>0||p.complete.length>0}),children:[(p.needsInput.length>0||p.complete.length>0||p.tasks.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Failed"}),n.jsx(Dt,{items:p.failed,ariaLabel:"Failed tasks",canRequestInput:i,onAttentionItemClick:o})]}),p.tasks.length>0&&n.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":p.needsInput.length>0||p.complete.length>0||p.failed.length>0}),children:[(p.needsInput.length>0||p.complete.length>0||p.failed.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Working on"}),n.jsx(Dt,{items:p.tasks,ariaLabel:"Agent tasks",canRequestInput:i,onAttentionItemClick:o})]})]}),!t&&!s&&(!p||p.needsInput.length===0&&p.complete.length===0&&p.failed.length===0&&p.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:r===$.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})})]})},Ia=({resource:e,html:t,isLoading:s,error:r,onClose:i})=>{a.useEffect(()=>{if(!e)return;const l=c.SlideoverUtils.removeSlideover;return c.SlideoverUtils.removeSlideover=()=>{l(),i()},()=>{c.SlideoverUtils.removeSlideover=l}},[e,i]),a.useEffect(()=>{if(!e)return;const l=m=>{m.key==="Escape"&&c.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]);const o=a.useMemo(()=>e?[{centerHeaderText:!1,children:n.jsxs("div",{className:"resource-preview-slideover__body",children:[s&&n.jsxs("div",{className:"resource-preview-slideover__status",children:[n.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading document"}),n.jsx("span",{children:"Loading document…"})]}),!s&&r&&n.jsx("p",{className:"resource-preview-slideover__error",role:"alert",children:r}),!s&&!r&&t!==null&&n.jsx("iframe",{className:"resource-preview-slideover__frame",title:e.title,sandbox:"",srcDoc:t})]})}]:[],[e,t,s,r]);return n.jsx("div",{className:"resource-preview-slideover",children:n.jsx(c.SlideoverManager,{slideovers:o})})},Oa={[Ae.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[Ae.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[Ae.file]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[Ae.user_file]:{icon:"upload",label:"File upload",color:"var(--color-semantic-caution-800)"},[Ae.workflow]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[Ae.link]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},La=({resources:e,isLoading:t=!1,error:s=null,onOpenResource:r})=>n.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--documents","aria-label":"Resources",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(c.Heading,{level:4,children:"Resources"}),n.jsx("span",{className:"agent-workspace__panel-count",children:e.length})]}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsxs(Ft,{children:[t&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading resources"}),n.jsx("span",{children:"Loading resources…"})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!t&&!s&&e.length>0&&n.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:e.map(i=>{const o=Oa[i.type],l=i.misRecordUrl;return n.jsx("li",{className:"agent-workspace__resource",children:l?n.jsx("a",{className:"agent-workspace__resource-card",href:l,target:"_blank",rel:"noreferrer",onClick:m=>{m.preventDefault(),r(i)},children:n.jsx(Ln,{resource:i,config:o,external:!0})}):n.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>r(i),children:n.jsx(Ln,{resource:i,config:o})})},i.id)})}),!t&&!s&&e.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),Ln=({resource:e,config:t,external:s=!1})=>n.jsxs(n.Fragment,{children:[n.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${e.type}`,children:n.jsx(c.Icon,{name:t.icon,size:16,color:t.color,screenReaderText:`${t.label}:`})}),n.jsx("span",{className:"agent-workspace__resource-content",children:n.jsxs("span",{className:"agent-workspace__resource-top",children:[n.jsx("span",{className:"agent-workspace__resource-name",children:e.title}),n.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${e.type}`,children:t.label})]})}),s&&n.jsx(c.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]}),on=e=>{const t=Date.parse(e);return Number.isFinite(t)?t:0},Pa=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),cn=e=>{const t=new Date(e);return Number.isFinite(t.getTime())?Pa.format(t):e},Pn=e=>e.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,t=>t.split(/[_-]/).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")),Mn=e=>{const s=e.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,r=>r.split(/[_-]/).map(i=>i.toLowerCase()).join(" ")).toLowerCase();return s&&s.charAt(0).toUpperCase()+s.slice(1)},Ma=60*60*1e3,ns=60*60*1e3,xt=24*ns,gn=7*xt,Ua=e=>e.type!=="message-sent",Da=e=>{if(e==null||e<=0)return null;if(e%86400===0){const s=e/86400;return s===1?"every day":`every ${s} days`}if(e%3600===0){const s=e/3600;return s===1?"every hour":`every ${s} hours`}if(e%60===0){const s=e/60;return s===1?"every minute":`every ${s} minutes`}const t=Math.max(1,Math.round(e/60));return t===1?"every minute":`every ${t} minutes`},$a=e=>{if(e.recurrence==="one_off")return"Scheduled to run once";const t=Da(e.repeatIntervalSeconds);return t?`Repeating ${t}`:"Repeating run scheduled"},Ha=e=>e.recurrence==="one_off"?"scheduled-one-off":"scheduled-repeating",Ba=(e,t,s=[])=>{const r=e.filter(Ua).map((l,m)=>({kind:"action",id:`action-${l.timestamp}-${m}`,timestampMs:on(l.timestamp),item:l})),i=t.map(l=>({kind:"chat",id:l.sessionId,timestampMs:on(l.timestamp),session:l})),o=s.map(l=>({kind:"scheduled",id:`scheduled-${l.scheduleId}`,timestampMs:on(l.dueAt),run:l}));return[...r,...i,...o].sort((l,m)=>l.timestampMs-m.timestampMs||l.id.localeCompare(m.id))},Fa=e=>e>=gn?"weeks":e>=xt?"days":"hours",Ga=e=>{if(e<xt){const r=Math.max(1,Math.round(e/ns));return r===1?"1 hour later":`${r} hours later`}if(e<gn){const r=Math.max(1,Math.round(e/xt));return r===1?"1 day later":`${r} days later`}const t=Math.max(1,Math.round(e/gn));if(t<5)return t===1?"1 week later":`${t} weeks later`;const s=Math.max(1,Math.round(e/(30*xt)));return s===1?"1 month later":`${s} months later`},za=(e,t=Ma)=>{if(e.length===0)return[];const s=[e[0]];for(let r=1;r<e.length;r+=1){const i=e[r-1],o=e[r],l=o.timestampMs-i.timestampMs;l>=t&&s.push({kind:"gap",id:`gap-${i.id}-${o.id}`,durationMs:l,label:Ga(l),size:Fa(l)}),s.push(o)}return s},qa=e=>e.type==="checklist-updated"?"checklist":e.type==="status-transition"?"status":"note",Ka=({timeline:e,isLoading:t,error:s,onOpenChatSession:r})=>{const i=(e==null?void 0:e.actionLog)??[],o=(e==null?void 0:e.chatSessions)??[],l=(e==null?void 0:e.scheduledRuns)??[],m=Ba(i,o,l),h=za(m),k=!t&&!s&&m.length===0;return n.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[t&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),s&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:s||Jn}),k&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!t&&!s&&!k&&n.jsxs("div",{className:"agent-timeline",children:[n.jsx("div",{className:"agent-timeline__track","aria-hidden":"true"}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(c.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})})}),n.jsx("div",{className:"agent-timeline__label",children:n.jsx("strong",{className:"agent-timeline__label-type",children:"Start"})})]}),h.map(f=>{if(f.kind==="gap")return n.jsxs("div",{className:`agent-timeline__gap agent-timeline__gap--${f.size}`,role:"separator","aria-label":f.label,children:[n.jsx("span",{className:"agent-timeline__gap-rail","aria-hidden":"true",children:n.jsx("span",{className:"agent-timeline__gap-dot"})}),n.jsx("span",{className:"agent-timeline__gap-label",children:f.label})]},f.id);if(f.kind==="chat"){const C=cn(f.session.timestamp),L=n.jsx(c.Icon,{name:"sparkles",size:16,color:"currentColor"});return n.jsxs("div",{className:"agent-timeline__chat-station",children:[r?n.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${C}`,onClick:()=>r(f.session.sessionId),children:L}):n.jsx("span",{className:"agent-timeline__chat-node agent-timeline__chat-node--static","aria-hidden":"true",children:L}),n.jsxs("div",{className:"agent-timeline__label",children:[n.jsx("strong",{className:"agent-timeline__label-type",children:"Chat session"}),n.jsx("span",{className:"agent-timeline__label-time",children:C})]})]},f.id)}if(f.kind==="scheduled"){const C=Ha(f.run),L=f.run.recurrence==="one_off"?"One-off run":"Repeating run";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${C}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsx("span",{className:`agent-timeline__station-node agent-timeline__station-node--${C}`,"aria-hidden":"true",children:n.jsx(c.Icon,{name:"date",size:16,color:"currentColor"})})}),n.jsxs("div",{className:"agent-timeline__label",children:[n.jsx("strong",{className:"agent-timeline__label-type",children:L}),n.jsx("span",{className:"agent-timeline__label-entry",children:$a(f.run)}),n.jsx("span",{className:"agent-timeline__label-time",children:cn(f.run.dueAt)})]})]},f.id)}const{item:w}=f,A=qa(w),E=A==="checklist",p=A==="status";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${A}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${A}`,"aria-label":`${Pn(w.type)}: ${Mn(w.entry)}`,children:[E&&n.jsx(c.Icon,{name:"check-solid",size:16,color:"currentColor"}),p&&n.jsx(c.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]})}),n.jsxs("div",{className:"agent-timeline__label",children:[n.jsx("strong",{className:"agent-timeline__label-type",children:Pn(w.type)}),n.jsx("span",{className:"agent-timeline__label-entry",children:Mn(w.entry)}),n.jsx("span",{className:"agent-timeline__label-time",children:cn(w.timestamp)})]})]},f.id)}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(c.Icon,{name:"flag",size:16,color:"currentColor"})})}),n.jsx("div",{className:"agent-timeline__label",children:n.jsx("strong",{className:"agent-timeline__label-type",children:"Finish"})})]})]})]})},Va=["I'll get the details and come back to you","Skip this for now"],Ja=e=>{var s;const t=(s=e.prompt)!=null&&s.trim()?e.prompt.trim():`I need a bit more from you on "${e.task}". ${e.description} What can you tell me?`;return{id:`clarification-${Date.now()}`,author:se.agent,text:t,followUpPrompts:e.clarificationPrompts??Va}},Ya=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Wa=e=>e.kind===qn.user_file?`<strong>${Ya(e.text)}</strong>`:e.text,we=e=>({id:e.id,text:Wa(e),type:e.author===se.user?Ye.CHAT_RESPONSE_TYPE_USER:e.author===se.system?Ye.CHAT_RESPONSE_TYPE_INFO:Ye.CHAT_RESPONSE_TYPE_AGENT,...e.followUpPrompts?{followUpPrompts:e.followUpPrompts}:{}}),mn="MESSAGE_TYPE_REPOLL",ss="agentUi:update",pn="arbor-agent-",ke={all:"ALL",checklist:"CHECKLIST",resources:"RESOURCES",chat:"CHAT",timeline:"TIMELINE"},Xa=new Set(Object.values(ke)),as=(e,t)=>`${e.endsWith("-")?e:`${e}-`}${t}`,Za=e=>typeof e=="string"&&Xa.has(e)?e:ke.all,Qa=e=>{if(!e||typeof e!="object")return null;const t=e;return t.type!==mn?null:{type:mn,target:Za(t.target)}},rs=e=>{const t=Array.isArray(e)?e:[e],s=[];for(const r of t){const i=Qa(r);i&&s.push(i)}return s},er=({enabled:e,channelPrefix:t,agentId:s,subscribeToPusher:r,onRepoll:i})=>{const o=a.useRef(i),l=t==null?void 0:t.trim(),m=!!(e&&r&&l&&s.trim());return a.useEffect(()=>{o.current=i},[i]),a.useEffect(()=>{if(!m||!r||!l)return;const h=r(as(l,s),ss,k=>{for(const f of rs(k))o.current(f.target)});return()=>{h()}},[m,l,s,r]),m};class De extends Error{constructor(t,s,r){super(r??`Agent service request failed (${t})`),this.name="AgentServiceError",this.status=t,this.detail=s}}const tr="/api/v1",B={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},z={GET:"GET",POST:"POST",PATCH:"PATCH",DELETE:"DELETE"},nr={error:"error"},sr={user:"user"},Ue={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},ar=100,is=e=>{switch(e){case sn.paused:return N.paused;case sn.complete:return N.complete;case N.hitl:return N.hitl;case sn.active:case N["generating-a-response"]:return N["generating-a-response"];default:return N["generating-a-response"]}},ls=e=>{switch(e){case an.requires_attention:return F.hitl;case an.in_progress:case an.available:return F["generating-a-response"];case F.failed:case F.complete:case F.hitl:case F["generating-a-response"]:return e;default:return F["generating-a-response"]}},_n=e=>({ref:e.name,display_name:e.display_name,agent_intent:e.agent_intent??"",description:e.description}),rr=e=>({id:e.id,name:e.name,...e.has_run_before?{hasRunBefore:e.has_run_before}:{}}),ir=new Set(Object.values(Ae)),lr=e=>ir.has(e)?e:Ae.document_html,os=e=>({id:e.id,type:lr(e.type),title:e.title,createdDatetime:e.created_datetime,lastUpdatedDatetime:e.last_updated_datetime,misRecordUrl:e.mis_record_url}),cs=e=>({resources:e.resources.map(os),pageNumber:e.page_number,pageSize:e.page_size,totalRecords:e.total_records}),us=e=>({actionLog:(e.action_log??[]).map(t=>({timestamp:t.timestamp,type:t.type,entry:t.entry,origin:t.origin})),chatSessions:(e.chat_sessions??[]).map(t=>({sessionId:t.session_id,timestamp:t.timestamp})),scheduledRuns:(e.scheduled_runs??[]).map(t=>({scheduleId:t.schedule_id,dueAt:t.due_at,recurrence:t.recurrence,repeatIntervalSeconds:t.repeat_interval_seconds,wakePrompt:t.wake_prompt}))}),Ne=e=>{var s;const t=e.invocation_id??e.id;return{id:e.id,invocation_id:t,agent_definition_ref:e.agent_definition_ref,...e.agent_intent?{agent_intent:e.agent_intent}:{},invocation_name:((s=e.invocation_name)==null?void 0:s.trim())||e.agent_definition_ref,application_id:e.application_id,...e.application_name?{application_name:e.application_name}:{},created_by:e.created_by,status:is(e.status),archivedAt:e.archived_at??null,context_ref:e.context_ref??null,checklist_ref:e.checklist_ref??null}},fn=e=>{var t;return{task:e.item??e.task??e.name??e.label??ga,status:ls(e.status),description:e.description??"",...e.prompt?{prompt:e.prompt}:{},...(t=e.follow_up_prompts)!=null&&t.length?{clarificationPrompts:e.follow_up_prompts}:{}}},or=e=>Array.isArray(e)?e:e.checklist_items??e.checklist??e.items??[],vn=(e,t,s)=>{var o;const r=!Array.isArray(t)&&(t.opening_message||(o=t.opening_follow_up_prompts)!=null&&o.length)?t:s,i=r?At(r):void 0;return{invocation_id:e,checklist:or(t).map(fn),...i?{openingMessage:i}:{}}},ds=(e,t)=>{const s=At(t);return{invocation_id:t.invocation_id??e,checklist:(t.checklist_items??[]).map(fn),...s?{openingMessage:s}:{}}},At=e=>{var s,r;const t=(s=e.opening_message)==null?void 0:s.trim();if(t)return{id:Vn,author:se.agent,text:t,...(r=e.opening_follow_up_prompts)!=null&&r.length?{followUpPrompts:e.opening_follow_up_prompts}:{}}},cr=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)){const s=t.filter(r=>!!r&&typeof r=="object"&&typeof r.text=="string").map(r=>r.text);if(s.length>0)return s.join(`
2
+ `)}}catch{}return e},ur=e=>{const t=e.trim();return t.length>0?`File upload
3
3
 
4
- ${t}`:"File upload"},hs=e=>{var n;const t=(n=e.filename)==null?void 0:n.trim();return t||null},$s=e=>e.filter(t=>hs(t)&&t.role==="user"?!0:(t.role==="user"||t.role==="assistant")&&typeof t.content=="string"&&t.content.length>0&&t.message_type!=="tool_request").map(t=>{const n=hs(t);return n&&t.role==="user"?{id:t.message_id,author:te.user,kind:ws.user_file,text:n}:{id:t.message_id,author:t.role==="user"?te.user:te.agent,text:t.content}}),Sa=/:invocationId\b/g,ja=/:resourceId\b/g,Ca=e=>e.trim().replace(/^Bearer\s+/i,""),gs=e=>e.endsWith("/")?e.slice(0,-1):e;class _t{constructor(t){var a;this.baseUrl=gs(t.baseUrl??"");const n=(a=t.token)==null?void 0:a.trim();this.token=n?Ca(n):void 0,this.customHeaders=t.headers,this.urls=t.urls??{},this.fetchImpl=t.fetch??globalThis.fetch.bind(globalThis)}setHeaders(t){this.customHeaders=t}async listAgentDefinitions(){return(await this.request(q.GET,this.resolveUrl("agentDefinitions",H.agentDefinitions))).agent_definitions??[]}getAgentDefinition(t){return this.request(q.GET,this.apiUrl(`${H.agentDefinitions}/${encodeURIComponent(t)}`))}listTripOptions(){return this.request(q.GET,this.apiUrl(H.tripOptions))}getDataset(){return this.request(q.GET,this.apiUrl(H.demoDataset))}setDataset(t){return this.request(q.POST,this.apiUrl(H.demoDataset),{dataset:t})}listAgents(t={}){const n=new URLSearchParams;t.status&&n.set("status",t.status),t.agentDefinitionRef&&n.set("agent_definition_ref",t.agentDefinitionRef);const a=n.toString()?`?${n.toString()}`:"";return this.request(q.GET,`${this.resolveUrl("agents",H.agents)}${a}`)}createAgent(t,n={}){var o,g;const a={agent_definition_ref:t},i=(o=n.invocationName)==null?void 0:o.trim(),l=(g=n.agentIntent)==null?void 0:g.trim();return i&&(a.invocation_name=i),l&&(a.agent_intent=l),this.request(q.POST,this.resolveUrl("agents",H.agents),a)}getAgent(t){return this.request(q.GET,this.resolveUrl("agent",`${H.agents}/${encodeURIComponent(t)}`,t))}updateAgent(t,n){const i={invocation_name:n.invocationName.trim()};return this.request(q.PATCH,this.resolveUrl("agent",`${H.agents}/${encodeURIComponent(t)}`,t),i)}getAgentChecklist(t){return this.request(q.GET,this.resolveUrl("agentChecklist",`${H.agents}/${encodeURIComponent(t)}/checklist`,t))}getAgentResources(t,n={}){const a=new URLSearchParams;n.pageNumber!==void 0&&a.set("page_number",String(n.pageNumber)),n.pageSize!==void 0&&a.set("page_size",String(n.pageSize)),n.type&&a.set("type",n.type);const i=a.toString(),l=this.resolveUrl("agentResources",`${H.agents}/${encodeURIComponent(t)}/resources`,t);return this.request(q.GET,i?`${l}?${i}`:l)}async listAllAgentResources(t){const n=xa;let a=1;const i=[];let l=Number.POSITIVE_INFINITY;for(;i.length<l;){const o=Ms(await this.getAgentResources(t,{pageNumber:a,pageSize:n}));if(l=o.totalRecords,o.resources.length===0||(i.push(...o.resources),i.length>=l))break;a+=1}return i}getAgentResourceHtml(t,n){return this.requestText(q.GET,this.resolveResourceHtmlUrl(t,n))}getAgentTimeline(t){return this.request(q.GET,this.resolveUrl("agentTimeline",`${H.agents}/${encodeURIComponent(t)}/agent-timeline`,t))}getAgentContext(t){const n=this.resolveUrl("agent",`${H.agents}/${encodeURIComponent(t)}`,t);return this.request(q.GET,`${gs(n)}/context`)}pauseAgent(t){return this.request(q.POST,this.resolveUrl("pauseAgent",`${H.agents}/${encodeURIComponent(t)}/pause`,t))}resumeAgent(t){return this.request(q.POST,this.resolveUrl("resumeAgent",`${H.agents}/${encodeURIComponent(t)}/resume`,t))}archiveAgent(t){return this.request(q.POST,this.resolveUrl("archiveAgent",`${H.agents}/${encodeURIComponent(t)}/archive`,t))}getConversation(t){return this.request(q.GET,this.resolveUrl("agentConversation",`${H.conversations}/${encodeURIComponent(t)}`,t))}async chat(t,n,a={}){const i=!!(a.uploadFiles&&a.uploadFiles.length>0),l=await this.fetchImpl(this.resolveUrl("agentChat",`${H.agents}/${encodeURIComponent(t)}/chat`,t),{method:q.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:Se.acceptEventStream,...i?{}:{"Content-Type":Se.contentTypeJson}},body:i?Ra(n,a.uploadFiles??[]):JSON.stringify(n),signal:a.signal});if(!l.ok)throw await this.toError(l);if(!l.body)throw new Ue(l.status,null,"Chat response contained no stream body");return this.consumeSse(l.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(t){return`${this.baseUrl}${_a}${t}`}resolveUrl(t,n,a,i){const l=this.urls[t];if(!l)return this.apiUrl(n);let o=l;return a&&(o=o.replace(Sa,encodeURIComponent(a))),i&&(o=o.replace(ja,encodeURIComponent(i))),o}resolveResourceHtmlUrl(t,n){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${H.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(n)}`,t,n):this.urls.agentResources?`${this.resolveUrl("agentResources",`${H.agents}/${encodeURIComponent(t)}/resources`,t).replace(/\/$/,"")}/${encodeURIComponent(n)}`:this.apiUrl(`${H.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(n)}`)}async request(t,n,a){const i=await this.fetchImpl(n,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:Se.acceptJson,...a===void 0?{}:{"Content-Type":Se.contentTypeJson}},...a===void 0?{}:{body:JSON.stringify(a)}});if(!i.ok)throw await this.toError(i);if(i.status!==204)return await i.json()}async requestText(t,n){const a=await this.fetchImpl(n,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:Se.acceptHtml}});if(!a.ok)throw await this.toError(a);return a.text()}async toError(t){let n=null;try{n=await t.json()}catch{}return new Ue(t.status,n,`Agent service request failed (${t.status} ${t.statusText})`)}async consumeSse(t,n){const a=t.getReader(),i=new TextDecoder;let l="",o;const g=h=>{const{event:w,data:p}=Ea(h);if(p===null)return;if(w===fa.error){const v=ps(p);throw new Ue(502,v,(v==null?void 0:v.message)??"Chat stream error")}const f=ps(p);f&&(o=f,n==null||n(f))};for(;;){const{done:h,value:w}=await a.read();if(h)break;l+=i.decode(w,{stream:!0});const p=l.split(`
4
+ ${t}`:"File upload"},Un=e=>{var s;const t=(s=e.filename)==null?void 0:s.trim();return t||null},hs=e=>e.filter(t=>Un(t)&&t.role==="user"?!0:(t.role==="user"||t.role==="assistant")&&typeof t.content=="string"&&t.content.length>0&&t.message_type!=="tool_request").map(t=>{const s=Un(t);return s&&t.role==="user"?{id:t.message_id,author:se.user,kind:qn.user_file,text:s}:{id:t.message_id,author:t.role==="user"?se.user:se.agent,text:t.content}}),dr=/:invocationId\b/g,hr=/:resourceId\b/g,gr=e=>e.trim().replace(/^Bearer\s+/i,""),Dn=e=>e.endsWith("/")?e.slice(0,-1):e;class Gt{constructor(t){var r;this.baseUrl=Dn(t.baseUrl??"");const s=(r=t.token)==null?void 0:r.trim();this.token=s?gr(s):void 0,this.customHeaders=t.headers,this.urls=t.urls??{},this.fetchImpl=t.fetch??globalThis.fetch.bind(globalThis)}setHeaders(t){this.customHeaders=t}async listAgentDefinitions(){return(await this.request(z.GET,this.resolveUrl("agentDefinitions",B.agentDefinitions))).agent_definitions??[]}getAgentDefinition(t){return this.request(z.GET,this.apiUrl(`${B.agentDefinitions}/${encodeURIComponent(t)}`))}listTripOptions(){return this.request(z.GET,this.apiUrl(B.tripOptions))}getDataset(){return this.request(z.GET,this.apiUrl(B.demoDataset))}setDataset(t){return this.request(z.POST,this.apiUrl(B.demoDataset),{dataset:t})}listAgents(t={}){const s=new URLSearchParams;t.status&&s.set("status",t.status),t.agentDefinitionRef&&s.set("agent_definition_ref",t.agentDefinitionRef);const r=s.toString()?`?${s.toString()}`:"";return this.request(z.GET,`${this.resolveUrl("agents",B.agents)}${r}`)}createAgent(t,s={}){var l,m;const r={agent_definition_ref:t},i=(l=s.invocationName)==null?void 0:l.trim(),o=(m=s.agentIntent)==null?void 0:m.trim();return i&&(r.invocation_name=i),o&&(r.agent_intent=o),this.request(z.POST,this.resolveUrl("agents",B.agents),r)}getAgent(t){return this.request(z.GET,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(t)}`,t))}updateAgent(t,s){const i={invocation_name:s.invocationName.trim()};return this.request(z.PATCH,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(t)}`,t),i)}getAgentChecklist(t){return this.request(z.GET,this.resolveUrl("agentChecklist",`${B.agents}/${encodeURIComponent(t)}/checklist`,t))}getAgentResources(t,s={}){const r=new URLSearchParams;s.pageNumber!==void 0&&r.set("page_number",String(s.pageNumber)),s.pageSize!==void 0&&r.set("page_size",String(s.pageSize)),s.type&&r.set("type",s.type);const i=r.toString(),o=this.resolveUrl("agentResources",`${B.agents}/${encodeURIComponent(t)}/resources`,t);return this.request(z.GET,i?`${o}?${i}`:o)}async listAllAgentResources(t){const s=ar;let r=1;const i=[];let o=Number.POSITIVE_INFINITY;for(;i.length<o;){const l=cs(await this.getAgentResources(t,{pageNumber:r,pageSize:s}));if(o=l.totalRecords,l.resources.length===0||(i.push(...l.resources),i.length>=o))break;r+=1}return i}getAgentResourceHtml(t,s){return this.requestText(z.GET,this.resolveResourceHtmlUrl(t,s))}getAgentTimeline(t){return this.request(z.GET,this.resolveUrl("agentTimeline",`${B.agents}/${encodeURIComponent(t)}/agent-timeline`,t))}getAgentContext(t){const s=this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(t)}`,t);return this.request(z.GET,`${Dn(s)}/context`)}pauseAgent(t){return this.request(z.POST,this.resolveUrl("pauseAgent",`${B.agents}/${encodeURIComponent(t)}/pause`,t))}resumeAgent(t){return this.request(z.POST,this.resolveUrl("resumeAgent",`${B.agents}/${encodeURIComponent(t)}/resume`,t))}archiveAgent(t){return this.request(z.POST,this.resolveUrl("archiveAgent",`${B.agents}/${encodeURIComponent(t)}/archive`,t))}unarchiveAgent(t){return this.request(z.POST,this.resolveUrl("unarchiveAgent",`${B.agents}/${encodeURIComponent(t)}/unarchive`,t))}deleteAgent(t){return this.request(z.DELETE,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(t)}`,t))}getConversation(t){return this.request(z.GET,this.resolveUrl("agentConversation",`${B.conversations}/${encodeURIComponent(t)}`,t))}async chat(t,s,r={}){const i=!!(r.uploadFiles&&r.uploadFiles.length>0),o=await this.fetchImpl(this.resolveUrl("agentChat",`${B.agents}/${encodeURIComponent(t)}/chat`,t),{method:z.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:Ue.acceptEventStream,...i?{}:{"Content-Type":Ue.contentTypeJson}},body:i?pr(s,r.uploadFiles??[]):JSON.stringify(s),signal:r.signal});if(!o.ok)throw await this.toError(o);if(!o.body)throw new De(o.status,null,"Chat response contained no stream body");return this.consumeSse(o.body,r.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(t){return`${this.baseUrl}${tr}${t}`}resolveUrl(t,s,r,i){const o=this.urls[t];if(!o)return this.apiUrl(s);let l=o;return r&&(l=l.replace(dr,encodeURIComponent(r))),i&&(l=l.replace(hr,encodeURIComponent(i))),l}resolveResourceHtmlUrl(t,s){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${B.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(s)}`,t,s):this.urls.agentResources?`${this.resolveUrl("agentResources",`${B.agents}/${encodeURIComponent(t)}/resources`,t).replace(/\/$/,"")}/${encodeURIComponent(s)}`:this.apiUrl(`${B.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(s)}`)}async request(t,s,r){const i=await this.fetchImpl(s,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:Ue.acceptJson,...r===void 0?{}:{"Content-Type":Ue.contentTypeJson}},...r===void 0?{}:{body:JSON.stringify(r)}});if(!i.ok)throw await this.toError(i);if(i.status!==204)return await i.json()}async requestText(t,s){const r=await this.fetchImpl(s,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:Ue.acceptHtml}});if(!r.ok)throw await this.toError(r);return r.text()}async toError(t){let s=null;try{s=await t.json()}catch{}return new De(t.status,s,`Agent service request failed (${t.status} ${t.statusText})`)}async consumeSse(t,s){const r=t.getReader(),i=new TextDecoder;let o="",l;const m=h=>{const{event:k,data:f}=mr(h);if(f===null)return;if(k===nr.error){const A=$n(f);throw new De(502,A,(A==null?void 0:A.message)??"Chat stream error")}const w=$n(f);w&&(l=w,s==null||s(w))};for(;;){const{done:h,value:k}=await r.read();if(h)break;o+=i.decode(k,{stream:!0});const f=o.split(`
5
5
 
6
- `);l=p.pop()??"";for(const f of p)g(f)}if(l.trim()&&g(l),!o)throw new Ue(502,null,"Chat stream ended without any events");return o}}const Ea=e=>{let t=null;const n=[];for(const a of e.split(`
7
- `)){const i=a.trimEnd();i.startsWith("event:")?t=i.slice(6).trim():i.startsWith("data:")&&n.push(i.slice(5).trim())}return{event:t,data:n.length>0?n.join(`
8
- `):null}},ps=e=>{try{return JSON.parse(e)}catch{return}};function Ra(e,t){const n=new FormData;n.append("body",JSON.stringify(e));for(const a of t)n.append("files",a,a.name);return n}const Ta={id:As,author:te.agent,text:"Type a question or upload a file. You can ask it how it's progressing, or send an instruction and it'll act on it."};let ms=0;const Ia=e=>(ms+=1,`${e}-${Date.now()}-${ms}`),Oa=e=>{const t=e.destination?` to ${e.destination}`:"";return`Let's get started on ${e.tripName.trim()||e.destination.trim()||"this task"}${t}. What will you do first?`};class Hs{constructor(t,n,a={}){this.seededChecklist=[],this.client=t,this.agentId=n,this.chatId=a.chatId??n,this.opening=a.openingMessage??Ta,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const t=await this.client.getConversation(this.chatId),n=$s(t.messages);return n.length===0?[this.opening]:n}async start(t){return{...await this.exchange(Oa(t)),phase:M.running}}sendMessage(t,n){return this.exchange(t,n)}async pause(){await this.client.pauseAgent(this.agentId)}async resume(){await this.client.resumeAgent(this.agentId)}seedChecklist(t){this.seededChecklist=t}async exchange(t,n){var o;const a=[{role:va.user,content:t}],i=await this.client.chat(this.agentId,{messages:a,chat_id:this.chatId,...this.model?{model:this.model}:{},moderation_enabled:!0,meta:{feature_id:"agent_view",source:"agent_view_frontend"}},...n&&n.length>0?[{uploadFiles:n}]:[]),l={id:i.event_id||Ia("msg-agent"),author:te.agent,text:i.message.content,...(o=i.follow_up_prompts)!=null&&o.length?{followUpPrompts:i.follow_up_prompts}:{}};try{const g=await this.client.getAgent(this.agentId),{checklist:h}=Ds(this.agentId,g);return this.seededChecklist=h,{message:l,checklist:h}}catch{return{message:l,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const zt=(e,t)=>n=>{var a,i;return new Hs(e,n.invocation_id,{model:t==null?void 0:t.model,chatId:((a=t==null?void 0:t.resolveChatId)==null?void 0:a.call(t,n))??(t==null?void 0:t.chatId)??n.invocation_id,openingMessage:((i=t==null?void 0:t.resolveOpeningMessage)==null?void 0:i.call(t,n))??(t==null?void 0:t.openingMessage)})},Bs=e=>e instanceof Ue?e.message:e instanceof TypeError?"Network error while contacting the agent service.":e instanceof Error&&e.message?e.message:Ns,La=e=>{const t={};for(const n of e){const a=Xe(n);if(!a)continue;const i=n.invocation_id??n.id;t[i]=a,t[n.id]=a}return t},Pa=e=>JSON.stringify(e),Mt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Fs=e=>{const{jwt:t,headers:n,urls:a}=e,i=JSON.stringify(n??{}),l=Pa(a),o=r.useMemo(()=>new _t({token:t,headers:n,urls:a}),[t,l]);r.useLayoutEffect(()=>{o.setHeaders(n)},[o,i]);const[g,h]=r.useState([]),[w,p]=r.useState([]),[f,v]=r.useState({}),[R,_]=r.useState("loading"),[k,O]=r.useState(null),[E,y]=r.useState(0),j=r.useCallback((C,U)=>{const J=C.map(We),V=U.map(Bt),D=La(C);h(B=>Mt(B,J)?B:J),p(B=>Mt(B,V)?B:V),v(B=>Mt(B,D)?B:D),_("idle"),O(null)},[]);r.useEffect(()=>{let C=!1;return _("loading"),O(null),(async()=>{try{const[U,J]=await Promise.all([o.listAgents(),o.listAgentDefinitions()]);if(C)return;j(U,J)}catch(U){if(C)return;h([]),p([]),v({}),_("error"),O(Bs(U))}})(),()=>{C=!0}},[j,o,E]);const m=r.useCallback(()=>{y(C=>C+1)},[]),S=r.useCallback(async()=>{try{const[C,U]=await Promise.all([o.listAgents(),o.listAgentDefinitions()]);j(C,U)}catch{}},[j,o]),T=r.useCallback(async C=>{const[U,J]=await Promise.all([o.getAgentChecklist(C),o.getAgent(C).catch(()=>null)]);return Gt(C,U,J??void 0)},[o]),P=r.useCallback(async C=>o.listAllAgentResources(C),[o]),K=r.useCallback(async({definition:C,invocationName:U})=>{const J=await o.createAgent(C.ref,{invocationName:U}),V=await o.getAgent(J.id),D=We(V),B=Xe(V);return h(ne=>[D,...ne]),B&&v(ne=>({...ne,[D.invocation_id]:B,[D.id]:B})),D},[o]),L=r.useCallback(async C=>{const U=await o.archiveAgent(C),J=We(U);return h(V=>V.map(D=>D.id===J.id||D.id===C||D.invocation_id===C?J:D)),J},[o]),se=r.useMemo(()=>zt(o,{resolveOpeningMessage:C=>f[C.invocation_id]??f[C.id]}),[o,f]);return{agents:g,agentDefinitions:w,loadState:R,loadError:k,reload:m,refresh:S,fetchAgentChecklist:T,fetchAgentResources:P,createAgent:K,archiveAgent:L,chatConnector:se}},Ma=e=>JSON.stringify(e),Gs=e=>{const{agent:t,jwt:n,headers:a,urls:i,chatId:l}=e,o=JSON.stringify(a??{}),g=Ma(i),h=r.useMemo(()=>new _t({token:n,headers:a,urls:{agent:i.agentUrl,agentChecklist:i.agentChecklistUrl,...i.agentResourcesUrl?{agentResources:i.agentResourcesUrl}:{},...i.agentTimelineUrl?{agentTimeline:i.agentTimelineUrl}:{},agentChat:i.agentChatUrl,agentConversation:i.agentConversationUrl,...i.pauseAgentUrl?{pauseAgent:i.pauseAgentUrl}:{},...i.resumeAgentUrl?{resumeAgent:i.resumeAgentUrl}:{},...i.archiveAgentUrl?{archiveAgent:i.archiveAgentUrl}:{}}}),[n,g]);r.useLayoutEffect(()=>{h.setHeaders(a)},[h,o]);const w=r.useCallback(async E=>{const[y,j]=await Promise.all([h.getAgentChecklist(E),h.getAgent(E).catch(()=>null)]);return Gt(E,y,j??void 0)},[h]),p=r.useCallback(async E=>h.listAllAgentResources(E),[h]),f=r.useCallback(async E=>h.getAgentContext(E),[h]),v=r.useCallback(async(E,y)=>h.getAgentResourceHtml(E,y),[h]),R=r.useCallback(async E=>{const y=await h.getAgentTimeline(E);return Us(y)},[h]),_=r.useCallback(async(E,y)=>{await h.updateAgent(E,{invocationName:y})},[h]),k=r.useCallback(async E=>We(await h.archiveAgent(E)),[h]);return{connector:r.useMemo(()=>zt(h,{chatId:l??t.invocation_id})(t),[h,t.invocation_id,l]),fetchAgentChecklist:w,fetchAgentContext:f,fetchAgentResources:p,fetchAgentResourceHtml:v,fetchAgentTimeline:R,updateAgentInvocationName:_,archiveAgent:k}},Ua=3e4,Da=(e,t)=>{const n=e.hasRunBefore?t||"This trip":e.tripName.trim()||"A new trip",a=e.destination?` to ${e.destination}`:"",i=e.hasRunBefore?" It has run before.":"";return`${n}${a}.${i}`.trim()},$a=e=>{switch(e){case A.paused:return M.paused;case A.complete:return M.complete;default:return M.running}},_s=e=>e===A.paused,fs=(e,t)=>{t([ge(e)])},Ha=(e,t)=>e.length===t.length&&e.every((n,a)=>{const i=t[a];return i!==void 0&&n.id===i.id&&n.text===i.text}),zs=({agent:e,invocationId:t,open:n,onClose:a,jwt:i,headers:l,agentUrl:o,agentChecklistUrl:g,agentResourcesUrl:h,agentTimelineUrl:w,agentChatUrl:p,agentConversationUrl:f,pauseAgentUrl:v,resumeAgentUrl:R,archiveAgentUrl:_,chatId:k,enableUpload:O,adminMode:E=!1,initialBrief:y,initialPhase:j,initialChecklist:m,usePusherToRepoll:S=!1,pusherChannelPrefix:T=Ht,subscribeToPusher:P,onArchived:K})=>{const[L,se]=r.useState(k??t),[C,U]=r.useState("chat"),[J,V]=r.useState(!1),{connector:D,fetchAgentChecklist:B,fetchAgentContext:ne,fetchAgentResources:je,fetchAgentResourceHtml:Ce,fetchAgentTimeline:ae,updateAgentInvocationName:fe,archiveAgent:$e}=Gs({agent:{...e,invocation_id:t},jwt:i,headers:l,chatId:L,urls:{agentUrl:o,agentChecklistUrl:g,agentResourcesUrl:h,agentTimelineUrl:w,agentChatUrl:p,agentConversationUrl:f,pauseAgentUrl:v,resumeAgentUrl:R,archiveAgentUrl:_}}),F=r.useRef(D),[Y,Ee]=r.useState(e.invocation_name),[Ze,ce]=r.useState(0),[ve,He]=r.useState(null),[X,Re]=r.useState(j??(y?M.running:$a(e.status))),[ee,Z]=r.useState([]),[Be,xe]=r.useState(0),[ft,Te]=r.useState(),[vt,we]=r.useState(null),[Qe,re]=r.useState([]),[et,ke]=r.useState(!1),[tt,Ie]=r.useState(null),[xt,Fe]=r.useState(null),[st,Ae]=r.useState(null),[nt,Ge]=r.useState(!1),[at,ze]=r.useState(null),[ye,rt]=r.useState(null),[wt,it]=r.useState(!1),[kt,qe]=r.useState(null),[Ne,d]=r.useState(m??null),[N,b]=r.useState(!1),[Q,ie]=r.useState(null),[Oe,de]=r.useState(void 0),[Le,qt]=r.useState(!1),[At,yt]=r.useState(!1),[Vs,Nt]=r.useState(null),[Kt,Jt]=r.useState(!1),[Vt,Wt]=r.useState(!1),[Yt,Xt]=r.useState(!1),[Ws,bt]=r.useState(!1),[Ys,ot]=r.useState(null),[Zt,ue]=r.useState(null),[Xs,St]=r.useState(()=>_s(e.status)),z=!!e.archivedAt,[lt,Ke]=r.useState(!1),[ct,Zs]=r.useState(!1),[dt,Qs]=r.useState(!1),Qt=r.useRef(lt),es=r.useRef(e.invocation_name),ts=r.useRef(0),ss=r.useRef(0),Pe=r.useRef(0);r.useEffect(()=>{F.current=D},[D]),r.useEffect(()=>{es.current=e.invocation_name},[e.invocation_name]),r.useEffect(()=>{Qt.current=lt},[lt]),r.useEffect(()=>{se(k??t),U("chat"),V(!1),Z([]),xe(u=>u+1),He(null)},[t,k]),r.useEffect(()=>(Pe.current+=1,de(void 0),qt(!1),yt(!1),Nt(null),()=>{Pe.current+=1}),[t]),r.useEffect(()=>{St(_s(e.status))},[e.status,t]),r.useEffect(()=>{Ee(e.invocation_name),ce(u=>u+1)},[e.invocation_name]),r.useEffect(()=>{z&&U("timeline")},[z]),r.useEffect(()=>{if(!n||y||z)return;const u=F.current.bootstrapConversation;if(!u){fs(F.current.openingMessage(),Z);return}let x=!1;return Ke(!0),(async()=>{try{const I=await u.call(F.current);if(x)return;Z(I.map(ge))}catch{x||fs(F.current.openingMessage(),Z)}finally{x||Ke(!1)}})(),()=>{x=!0}},[n,y,z,t,L]);const oe=r.useCallback(()=>{const u=++ts.current;(async()=>{var x,I;try{const G=await B(t);if(u!==ts.current)return;d(he=>JSON.stringify(he)===JSON.stringify(G.checklist)?he:G.checklist),ie(null),(I=(x=F.current).seedChecklist)==null||I.call(x,G.checklist)}catch{}})()},[B,t]),be=r.useCallback(()=>{h&&(async()=>{try{const u=await je(t);re(u),Ie(null)}catch{}})()},[h,je,t]),le=r.useCallback(()=>{if(!w)return;const u=++ss.current;(async()=>{try{const x=await ae(t);if(u!==ss.current)return;rt(I=>JSON.stringify(I)===JSON.stringify(x)?I:x),qe(null)}catch{}})()},[w,ae,t]),Je=r.useCallback(u=>{const x=F.current.bootstrapConversation;x&&(async()=>{try{const I=await x.call(F.current);if(Qt.current)return;const G=I.map(ge);let he=!1;Z(rs=>Ha(rs,G)?rs:(he=!0,G)),he&&(u!=null&&u.refreshSidePanelsOnChange)&&(oe(),le())}catch{}})()},[oe,le]),en=r.useCallback(u=>{switch(u){case _e.checklist:oe();return;case _e.resources:be();return;case _e.chat:Je();return;case _e.timeline:le();return;case _e.all:default:oe(),be(),Je(),le()}},[oe,Je,be,le]),ns=ma({enabled:n&&S,channelPrefix:T,agentId:e.id,subscribeToPusher:P,onRepoll:en});r.useEffect(()=>{if(!n||y||z||ns)return;const u=window.setInterval(()=>{Je({refreshSidePanelsOnChange:!0})},Ua);return()=>{window.clearInterval(u)}},[n,y,z,ns,t,L,Je]);const jt=r.useCallback(u=>{var x,I;u.checklist?(d(u.checklist),(I=(x=F.current).seedChecklist)==null||I.call(x,u.checklist)):oe(),u.phase&&Re(u.phase),be(),le()},[oe,be,le]);r.useEffect(()=>{var u,x;!n||y||m&&m.length>0&&((x=(u=F.current).seedChecklist)==null||x.call(u,m))},[n,y,m]),r.useEffect(()=>{if(!n||y)return;let u=!1;return b(x=>m!=null&&m.length?!1:x||Ne===null||Ne.length===0),ie(null),(async()=>{var x,I;try{const G=await B(t);if(u)return;m!=null&&m.length||(d(G.checklist),(I=(x=F.current).seedChecklist)==null||I.call(x,G.checklist))}catch{!u&&!(m!=null&&m.length)&&ie(gt)}finally{u||b(!1)}})(),()=>{u=!0}},[n,t,y,m,B]),r.useEffect(()=>{if(!n||!h)return;let u=!1;return ke(!0),Ie(null),(async()=>{try{const x=await je(t);u||re(x)}catch{u||Ie(vn)}finally{u||ke(!1)}})(),()=>{u=!0}},[n,t,h,je]);const tn=r.useCallback(()=>{Fe(null),Ae(null),ze(null),Ge(!1)},[]),sn=r.useCallback(u=>{if(u.misRecordUrl){window.open(u.misRecordUrl,"_blank","noopener,noreferrer");return}Fe(u),Ae(null),ze(null),Ge(!0),(async()=>{try{const x=await Ce(t,u.id);Ae(x)}catch{ze(xn)}finally{Ge(!1)}})()},[Ce,t]);r.useEffect(()=>{if(!n||!w)return;let u=!1;return it(x=>x||ye===null),qe(null),(async()=>{try{const x=await ae(t);u||rt(x)}catch{u||qe(ys)}finally{u||it(!1)}})(),()=>{u=!0}},[n,t,w,ae]),r.useEffect(()=>{if(!n||!y)return;let u=!1;const x={id:`user-brief-${Date.now()}`,author:te.user,text:Da(y,es.current)};return(async()=>{var G,he;const I=await F.current.start(y);u||(Z([ge(F.current.openingMessage()),ge(x),ge(I.message)]),I.checklist?(d(I.checklist),(he=(G=F.current).seedChecklist)==null||he.call(G,I.checklist)):oe(),Re(I.phase??M.running),be(),le())})(),()=>{u=!0}},[n,y,t,oe,be,le]);const nn=r.useCallback(u=>{we(ca(u))},[]),Ct=k??t,ut=ye==null?void 0:ye.chatSessions,as=ut!=null&&ut.length?ut.reduce((u,x)=>Date.parse(x.timestamp)<Date.parse(u.timestamp)?x:u).sessionId:void 0,Et=r.useCallback(()=>{U("chat"),V(!1),L!==Ct&&(se(Ct),Z([]),xe(u=>u+1))},[L,Ct]),an=r.useCallback(u=>{if(u===as){Et();return}se(u),V(!0),U("chat"),Z([]),xe(x=>x+1)},[as,Et]),rn=r.useCallback(u=>{we(null),Te(u),xe(x=>x+1)},[]),on=r.useCallback(async()=>{ue(null),Jt(!0);try{await F.current.pause(),Re(M.paused),St(!0)}catch{ue(wn)}finally{Jt(!1)}},[]),ln=r.useCallback(async()=>{ue(null),Wt(!0);let u=!1;try{await F.current.resume(),u=!0,Re(M.running),St(!1),Ke(!0);const x={id:`wake-${Date.now()}`,author:te.user,text:is};Z(G=>[...G,ge(x)]);const I=await F.current.sendMessage(is);Z(G=>[...G,ge(I.message)]),jt(I)}catch{ue(u?bn:Nn)}finally{Wt(!1),Ke(!1)}},[jt]),cn=r.useCallback(async()=>{ue(null),ot(null),Xt(!0);try{await $e(t),bt(!1),K==null||K(),a()}catch{ot(Ut),ue(Ut)}finally{Xt(!1)}},[t,$e,K,a]),dn=r.useCallback(u=>{const x=u.trim(),I=Y;if(He(null),!x){ce(G=>G+1);return}x!==I&&(Ee(x),(async()=>{try{await fe(t,x)}catch{Ee(I),ce(G=>G+1),He(Sn)}})())},[Y,t,fe]),un=r.useCallback(()=>{if(!E||Le||At)return;const u=++Pe.current;yt(!0),Nt(null),(async()=>{try{const x=await ne(t);if(Pe.current!==u)return;de(x),qt(!0)}catch{Pe.current===u&&Nt(fn)}finally{Pe.current===u&&yt(!1)}})()},[E,Le,At,ne,t]),hn=Ne;return s.jsxs(s.Fragment,{children:[s.jsxs(c.Modal,{open:n,closeHandler:a,hideCloseButton:!0,className:"agent-workspace",children:[s.jsxs(c.Modal.Header,{className:"agent-workspace__header",children:[s.jsxs("div",{className:"agent-workspace__header-title",children:[s.jsx("span",{className:"agent-workspace__header-avatar","aria-hidden":"true",children:s.jsx(c.Icon,{name:"ask-arbor",size:24})}),s.jsx(c.Modal.Title,{children:z?s.jsx("span",{className:"agent-workspace__header-name",children:Y}):s.jsx(c.EditableText,{className:"agent-workspace__header-name",text:Y,onEditSave:dn},Ze)}),s.jsx("span",{className:W("agent-workspace__phase",`agent-workspace__phase--${X}`),children:En[X]}),z?s.jsx("span",{className:"agent-workspace__phase agent-workspace__phase--archived",children:"Archived"}):null,ve&&s.jsx("p",{className:"agent-workspace__error agent-workspace__name-error",role:"alert",children:ve})]}),s.jsxs("div",{className:"agent-workspace__header-actions",children:[s.jsx(c.Button,{variant:ct?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!ct,onClick:()=>Zs(u=>!u),children:"Checklist"}),s.jsx(c.Button,{variant:dt?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!dt,onClick:()=>Qs(u=>!u),children:"Resources"}),s.jsx(c.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),s.jsxs(c.Modal.Body,{className:W("agent-workspace__body",{"agent-workspace__body--no-checklist":ct,"agent-workspace__body--no-resources":dt}),children:[s.jsxs("section",{className:W("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!w&&(z||C==="timeline")}),"aria-label":"Agent",children:[s.jsxs("div",{className:"agent-workspace__panel-header",children:[s.jsx(c.Heading,{level:4,children:"Agent"}),v&&!z&&X===M.running&&s.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Pause",disabled:Kt,onClick:()=>void on(),children:Kt?"Pausing…":"Pause agent"}),R&&!z&&X===M.paused&&Xs&&s.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"iteration-ccw",iconLeftScreenReaderText:"Resume",disabled:Vt,onClick:()=>void ln(),children:Vt?"Resuming…":"Resume agent"}),_&&!z&&s.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>{ot(null),ue(null),bt(!0)},children:"Archive agent"})]}),Zt&&s.jsx("p",{className:"agent-workspace__error agent-workspace__lifecycle-error",role:"alert",children:Zt}),w&&!z&&s.jsxs(c.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[s.jsx(c.Tabs.Item,{active:C==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>U("chat")},children:"Chat"}),s.jsx(c.Tabs.Item,{active:C==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>U("timeline")},children:"Timeline"})]}),w&&!z&&C==="chat"&&J&&s.jsx("div",{className:"agent-workspace__center-back",children:s.jsx(c.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:Et,children:"Back to main chat"})}),w&&(z||C==="timeline")&&s.jsx(oa,{timeline:ye,isLoading:wt,error:kt,onOpenChatSession:z?void 0:an}),!z&&s.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!w&&C!=="chat",children:s.jsx(qn,{connector:D,phase:X,chatHistory:ee,chatSessionKey:Be,startQuery:ft,clarificationMessage:vt,enableUpload:O,onTurn:jt,onAwaitingChange:Ke,onClarificationPrompt:rn,onDismissClarification:()=>we(null)})}),z&&!w&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Chat is not available for archived agents."})]}),!ct&&s.jsx(Kn,{checklist:hn,isLoading:N,error:Q,phase:X,canRequestInput:!z&&X===M.running&&!lt,onAttentionItemClick:nn,adminMode:E,context:Oe,contextLoaded:Le,contextLoading:At,contextError:Vs,onContextSelect:un},t),!dt&&s.jsx(Wn,{resources:Qe,isLoading:et,error:tt,onOpenResource:sn}),s.jsx(Jn,{resource:xt,html:st,isLoading:nt,error:at,onClose:tn})]})]}),s.jsx(Ss,{open:Ws,isInProgress:X===M.running||X===M.paused&&!js(Ne??void 0),isArchiving:Yt,error:Ys,onCancel:()=>{Yt||(ot(null),bt(!1))},onConfirm:()=>{cn()}})]})},Ba="Unable to load agent definitions. Please try again.",Fa="Unable to start the agent.",vs="Loading agents…",qs=({open:e,onClose:t,onStart:n,agentDefinitions:a,definitionsState:i="idle",definitionsError:l=null,onRetryDefinitions:o,embedded:g=!1})=>{const[h,w]=r.useState(void 0),[p,f]=r.useState(""),[v,R]=r.useState(!1),[_,k]=r.useState(null),O=[...a].sort((T,P)=>T.display_name.localeCompare(P.display_name)).map(T=>({value:T.ref,label:T.display_name}));r.useEffect(()=>{e&&(w(void 0),f(""),R(!1),k(null))},[e]);const E=h!==void 0&&p.trim().length>0,y=r.useCallback(T=>{const P=a.find(K=>K.ref===T[0]);P&&w(P)},[a]),j=r.useCallback(async()=>{if(!(!h||!E||v)){R(!0),k(null);try{await n({definition:h,invocationName:p.trim()})}catch(T){k(T instanceof Error?T.message:Fa)}finally{R(!1)}}},[E,h,p,v,n]);if(i==="idle"&&a.length===0||!e)return null;const m=s.jsxs("div",{className:"new-agent__header-title",children:[s.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:s.jsx(c.Icon,{name:"ask-arbor",size:24})}),g?s.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):s.jsx(c.Modal.Title,{children:"Start an agent"})]});let S;return i==="loading"?S=s.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[s.jsx(c.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:vs}),s.jsx("p",{className:"new-agent__state-message",children:vs})]}):i==="error"?S=s.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[s.jsx(c.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),s.jsx("p",{className:"new-agent__state-message",children:l??Ba}),o?s.jsx(c.Button,{variant:"secondary",size:"S",onClick:o,children:"Try again"}):null]}):S=s.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:T=>{T.preventDefault(),E&&!v&&j()},children:[s.jsxs("div",{className:"new-agent__type-field",children:[s.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:"What would you like your agent to do?"}),s.jsx(c.SelectDropdown,{id:"new-agent-type",placeholder:"Which agent would you like to start?",options:O,selectedValues:h?[h.ref]:[],onSelectionChange:y})]}),s.jsxs("div",{className:"new-agent__type-field",children:[s.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:"Name"}),s.jsx(c.TextInput,{id:"new-agent-invocation-name",value:p,placeholder:"What would you like to call your agent?",onChange:T=>f(T.target.value)})]}),_?s.jsx("p",{className:"new-agent__error",role:"alert",children:_}):null,s.jsx("div",{className:"new-agent__actions",children:s.jsx(c.Button,{type:"submit",variant:"primary",className:W("new-agent__start-button",{"new-agent__start-button--starting":v}),disabled:!E||v,iconLeftName:v?"loader":"sparkles",iconLeftScreenReaderText:v?"Starting":void 0,children:v?"Starting…":"Start"})})]}),g?s.jsxs("div",{className:W("new-agent","new-agent--embedded"),children:[s.jsx("div",{className:"new-agent__header",children:m}),s.jsx("div",{className:"new-agent__body",children:S})]}):s.jsxs(c.Modal,{open:e,closeHandler:t,className:"new-agent",children:[s.jsx(c.Modal.Header,{className:"new-agent__header",children:m}),s.jsx(c.Modal.Body,{className:"new-agent__body",children:S})]})},xs=e=>{window.location.assign(e)},Ga=({open:e,authToken:t,headers:n,agentDefinitionsUrl:a,agentsUrl:i,closeUrl:l,successUrl:o,onClose:g,onStart:h,embedded:w=!1})=>{const p=JSON.stringify(n??{}),f=r.useMemo(()=>new _t({token:t,headers:n,urls:{agentDefinitions:a,agents:i}}),[t,a,i,p]),[v,R]=r.useState([]),[_,k]=r.useState("loading"),[O,E]=r.useState(null),[y,j]=r.useState(0);r.useEffect(()=>{if(!e)return;let P=!1;return k("loading"),E(null),(async()=>{try{const K=await f.listAgentDefinitions();if(P)return;R(K.map(Bt)),k("idle")}catch(K){if(P)return;R([]),E(Bs(K)),k("error")}})(),()=>{P=!0}},[f,e,y]);const m=r.useCallback(()=>{g==null||g(),l&&xs(l)},[l,g]),S=r.useCallback(async P=>{await f.createAgent(P.definition.ref,{invocationName:P.invocationName}),h==null||h(P),o&&xs(o)},[f,h,o]),T=r.useCallback(()=>{j(P=>P+1)},[]);return s.jsx(qs,{open:e,onClose:m,onStart:S,agentDefinitions:v,definitionsState:_,definitionsError:O,onRetryDefinitions:T,embedded:w})},za=e=>"agentDefinitionsUrl"in e,Ks=e=>za(e)?s.jsx(Ga,{...e}):s.jsx(qs,{...e}),qa=e=>e.archivedAt?"archived":e.status===A.paused?"paused":null,Ka=e=>{if(e==="archived")return gn;if(e==="paused")return Ye[A.paused].statusIcon},Ja=({column:e,overlayIcon:t,label:n})=>{const a=t??e.statusIcon;return a?s.jsx("span",{className:"agent-view__status-indicator",children:s.jsx(c.Icon,{name:a.name,size:16,color:a.color,className:W({"agent-view__progress-icon--spinning":a.spin}),screenReaderText:n})}):s.jsx("span",{className:W("agent-view__dot",{[`agent-view__dot--${e.dotModifier}`]:e.dotModifier}),children:s.jsx(c.Dot,{colour:e.dotColour,label:n})})},Js=({agent:e,agentName:t,column:n,isExpanded:a,isLoading:i,checklist:l,error:o,canArchive:g,onToggle:h,onViewAgent:w,onArchive:p})=>{const{id:f,invocation_name:v}=e,R=`agent-card-${f}-header`,_=`agent-card-${f}-progress`,k=qa(e),O=Ka(k);return s.jsx("li",{className:W("agent-view__card",{"agent-view__card--expanded":a,"agent-view__card--paused":k==="paused","agent-view__card--archived":k==="archived"}),children:s.jsxs(c.Card,{spacing:"dense",children:[s.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":_,"aria-label":v,id:R,onClick:()=>h(f),children:s.jsxs("div",{className:"agent-view__card-content",children:[s.jsx(Ja,{column:n,overlayIcon:O}),s.jsx("span",{className:"agent-view__card-invocation-name",children:v}),s.jsx("span",{className:"agent-view__card-agent-name",children:t}),k==="paused"?s.jsx("span",{className:"agent-view__card-state-pill",children:"Paused"}):null,k==="archived"?s.jsx("span",{className:"agent-view__card-state-pill",children:"Archived"}):null,s.jsx(c.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&s.jsxs("div",{id:_,"aria-labelledby":R,className:"agent-view__card-progress",children:[i&&s.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[s.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:Me}),s.jsx("span",{children:Me})]}),!i&&o&&s.jsx("p",{className:"agent-view__progress-error",role:"alert",children:o}),!i&&!o&&l!==null&&s.jsx(Bn,{checklist:l}),!i&&!o&&l===null&&s.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[s.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:Me}),s.jsx("span",{children:Me})]}),s.jsxs("div",{className:"agent-view__card-actions",children:[g?s.jsx(c.Button,{variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>p==null?void 0:p(e),children:"Archive"}):s.jsx("span",{}),s.jsx(c.Button,{variant:"secondary",size:"S",onClick:()=>w==null?void 0:w(e),children:"View agent"})]})]})]})})},Va=({column:e,agents:t,expandedAgentId:n,loadingAgentId:a,checklistByInvocationId:i,errorByAgentId:l,definitionNameByRef:o,onToggleAgent:g,onViewAgent:h,onArchiveAgent:w,canArchive:p})=>s.jsxs("section",{className:"agent-view__column","aria-label":e.title,children:[s.jsxs("div",{className:"agent-view__column-header",children:[s.jsx(c.Heading,{level:4,children:e.title}),s.jsx("span",{className:"agent-view__column-count",children:t.length})]}),s.jsx("ul",{className:"agent-view__card-list",children:t.map(f=>s.jsx(Js,{agent:f,agentName:pt(f,o),column:e,isExpanded:n===f.id,isLoading:a===f.id,checklist:i[f.invocation_id]??null,error:l[f.id]??null,canArchive:p&&!f.archivedAt,onToggle:g,onViewAgent:h,onArchive:w},f.id))})]}),pt=(e,t)=>t.get(e.agent_definition_ref)??e.agent_definition_ref.replace(/_/g," "),Wa=({jwt:e,headers:t,agentDefinitionsUrl:n,agentsUrl:a,agentUrl:i,agentChecklistUrl:l,agentResourcesUrl:o,agentTimelineUrl:g,agentChatUrl:h,agentConversationUrl:w,pauseAgentUrl:p,resumeAgentUrl:f,archiveAgentUrl:v,enableUpload:R,adminMode:_=!1,showHeader:k=!1,institutions:O,usePusherToRepoll:E=!1,pusherChannelPrefix:y=Ht,subscribeToPusher:j})=>{var Ne;const m=r.useMemo(()=>({agentDefinitions:n,agents:a,agent:i,agentChecklist:l,...o?{agentResources:o}:{},...g?{agentTimeline:g}:{},agentChat:h,agentConversation:w,...v?{archiveAgent:v}:{}}),[n,a,i,l,o,g,h,w,v]),[S,T]=r.useState(null),P=S?(Ne=O==null?void 0:O.find(d=>d.applicationId===S.application_id))==null?void 0:Ne.applicationUrl:void 0,K=r.useMemo(()=>{const d={...t??{}};return P?d[Se.arborApplicationUrl]=P:delete d[Se.arborApplicationUrl],d},[t,P]),{agents:L,agentDefinitions:se,loadState:C,loadError:U,reload:J,refresh:V,fetchAgentChecklist:D,createAgent:B,archiveAgent:ne}=Fs({jwt:e,headers:K,urls:m}),[je,Ce]=r.useState(!1),[ae,fe]=r.useState(null),[$e,F]=r.useState(null),[Y,Ee]=r.useState({}),[Ze,ce]=r.useState({}),[ve,He]=r.useState([]),[X,Re]=r.useState([]),[ee,Z]=r.useState(null),[Be,xe]=r.useState(!1),[ft,Te]=r.useState(null),[vt,we]=r.useState(!1);r.useEffect(()=>{T(d=>d?L.find(N=>N.id===d.id)??d:null)},[L]);const Qe=r.useMemo(()=>{const d=new Set(L.map(b=>b.application_id)),N=new Map((O??[]).map(b=>[b.applicationId,b.name]));return[...d].sort((b,Q)=>(N.get(b)??b).localeCompare(N.get(Q)??Q)).map(b=>({value:b,label:N.get(b)??b}))},[L,O]),re=r.useMemo(()=>new Map(se.map(d=>[d.ref,d.display_name])),[se]),et=r.useMemo(()=>[...new Set(L.map(N=>pt(N,re)))].sort((N,b)=>N.localeCompare(b)).map(N=>({value:N,label:N})),[L,re]),ke=r.useMemo(()=>L.filter(d=>!(ve.length>0&&!ve.includes(d.application_id)||X.length>0&&!X.includes(pt(d,re)))),[L,re,X,ve]),tt=Qe.length>1,Ie=et.length>1,xt=tt||Ie;r.useEffect(()=>{const d=window.setInterval(()=>{V()},6e4);return()=>{window.clearInterval(d)}},[V]),r.useEffect(()=>{if(L.length===0)return;let d=!1;return(async()=>{const N=await Promise.allSettled(L.map(async b=>{const Q=await D(b.invocation_id);return{agentId:b.id,invocationId:b.invocation_id,checklist:Q.checklist}}));d||(Ee(b=>{const Q={...b};let ie=!1;for(const Oe of N){if(Oe.status!=="fulfilled")continue;const{invocationId:de,checklist:Le}=Oe.value;JSON.stringify(b[de])!==JSON.stringify(Le)&&(Q[de]=Le,ie=!0)}return ie?Q:b}),ce(b=>{const Q={...b};let ie=!1;return N.forEach((Oe,de)=>{Oe.status==="rejected"&&Q[L[de].id]!==gt&&(Q[L[de].id]=gt,ie=!0)}),ie?Q:b}))})(),()=>{d=!0}},[L,D]);const Fe=r.useCallback(async d=>{if(!Y[d.invocation_id]){F(d.id),ce(N=>{const b={...N};return delete b[d.id],b});try{const N=await D(d.invocation_id);Ee(b=>({...b,[d.invocation_id]:N.checklist}))}catch{ce(N=>({...N,[d.id]:gt}))}finally{F(N=>N===d.id?null:N)}}},[D,Y]),st=r.useCallback(d=>{if(ae===d){fe(null);return}const N=L.find(({id:b})=>b===d);N&&(fe(d),Fe(N))},[L,ae,Fe]),Ae=r.useMemo(()=>ke.filter(d=>!!d.archivedAt),[ke]),nt=r.useMemo(()=>ke.filter(d=>!d.archivedAt),[ke]),Ge=r.useMemo(()=>{const d={};for(const N of nt){const b=Ot(N,Y[N.invocation_id]);(d[b]??(d[b]=[])).push(N)}return d},[nt,Y]),at=r.useCallback(d=>{T(d)},[]),ze=r.useCallback(d=>{Te(null),Z(d)},[]),ye=r.useCallback(()=>{Be||(Te(null),Z(null))},[Be]),rt=r.useCallback(async()=>{if(ee){xe(!0),Te(null),ce(d=>{const N={...d};return delete N[ee.id],N});try{await ne(ee.invocation_id),T(d=>(d==null?void 0:d.id)===ee.id?null:d),fe(ee.id),we(!0),Z(null)}catch{Te(Ut)}finally{xe(!1)}}},[ee,ne]),wt=ee?Ot(ee,Y[ee.invocation_id])!==A.complete:!1,it=r.useCallback(async d=>{const N=await B(d);T(N),Ce(!1)},[B]),kt=r.useCallback(()=>{T(null)},[]),qe={expandedAgentId:ae,loadingAgentId:$e,checklistByInvocationId:Y,errorByAgentId:Ze,definitionNameByRef:re,onToggleAgent:st,onViewAgent:at,onArchiveAgent:ze,canArchive:!!v};return s.jsxs("div",{className:"agent-view-frontend agent-view",children:[k&&s.jsxs("div",{className:"agent-view__header",children:[s.jsx(c.Heading,{level:1,children:"Agents"}),s.jsx(c.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>Ce(!0),children:"Start an agent"})]}),L.length>0&&xt&&s.jsxs("div",{className:"agent-view__filters",children:[tt&&s.jsxs("div",{className:"agent-view__filter",children:[s.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-institution-filter",children:"Institution"}),s.jsx(c.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:Qe,value:ve,onValueChange:He,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Ie&&s.jsxs("div",{className:"agent-view__filter",children:[s.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-agent-filter",children:"Agent"}),s.jsx(c.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:et,value:X,onValueChange:Re,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),C==="error"?s.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[s.jsx(c.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),s.jsx("p",{className:"agent-view__state-message",children:U??Ns}),s.jsx(c.Button,{variant:"secondary",size:"S",onClick:J,children:"Try again"})]}):C==="loading"&&L.length===0?s.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[s.jsx(c.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:os}),s.jsx("p",{className:"agent-view__state-message",children:os})]}):L.length===0?s.jsx(Ln,{}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"agent-view__board",children:pn.map(d=>s.jsx(Va,{column:Ye[d],agents:Ge[d]??[],...qe},d))}),Ae.length>0?s.jsxs("details",{className:"agent-view__archived",open:vt,onToggle:d=>{we(d.currentTarget.open)},children:[s.jsxs("summary",{className:"agent-view__archived-summary",children:[s.jsx(c.Heading,{level:4,children:"Archived"}),s.jsx("span",{className:"agent-view__column-count",children:Ae.length})]}),s.jsx("ul",{className:"agent-view__card-list agent-view__archived-list",children:Ae.map(d=>s.jsx(Js,{agent:d,agentName:pt(d,re),column:Ye[Ot(d,Y[d.invocation_id])],isExpanded:ae===d.id,isLoading:$e===d.id,checklist:Y[d.invocation_id]??null,error:Ze[d.id]??null,canArchive:!1,onToggle:st,onViewAgent:at},d.id))})]}):null]}),S&&s.jsx(zs,{agent:S,invocationId:S.invocation_id,open:!0,jwt:e,headers:K,agentUrl:i,agentChecklistUrl:l,agentResourcesUrl:o,agentTimelineUrl:g,agentChatUrl:h,agentConversationUrl:w,pauseAgentUrl:p,resumeAgentUrl:f,archiveAgentUrl:v,enableUpload:R,adminMode:_,initialChecklist:Y[S.invocation_id]??null,usePusherToRepoll:E,pusherChannelPrefix:y,subscribeToPusher:j,onClose:kt,onArchived:()=>{fe(S.id),we(!0),V()}},S.id),s.jsx(Ss,{open:!!ee,isInProgress:wt,isArchiving:Be,error:ft,onCancel:ye,onConfirm:()=>{rt()}}),s.jsx(Ks,{open:je,onClose:()=>Ce(!1),onStart:it,agentDefinitions:se})]})},Ya=(e,t)=>{const n=Date.now(),a=t.trim()||e.agent_intent;return{id:`agent-${n}`,invocation_id:`inv-${n}`,agent_definition_ref:e.ref,agent_intent:e.agent_intent,invocation_name:a,application_id:mn,created_by:_n,status:A["generating-a-response"],archivedAt:null,context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=Wa;exports.AgentServiceClient=_t;exports.AgentServiceError=Ue;exports.AgentView=zs;exports.DEFAULT_PUSHER_CHANNEL_PREFIX=Ht;exports.HttpChatConnector=Hs;exports.MESSAGE_TYPE_REPOLL=$t;exports.NewAgentModal=Ks;exports.PUSHER_AGENT_MESSAGE_EVENT=Rs;exports.REPOLL_TARGET=_e;exports.buildAgentFromDefinition=Ya;exports.buildAgentPusherChannel=Ts;exports.createHttpChatConnectorFactory=zt;exports.formatUserFileChatCardText=ba;exports.mapApiAgent=We;exports.mapApiAgentDefinition=Bt;exports.mapApiAgentStatus=Os;exports.mapApiAgentTimelineResponse=Us;exports.mapApiChecklistEndpointResponse=Gt;exports.mapApiChecklistItem=Ft;exports.mapApiChecklistResponse=Ds;exports.mapApiChecklistStatus=Ls;exports.mapApiConversationMessages=$s;exports.mapApiOpeningMessage=Xe;exports.mapApiResource=Ps;exports.mapApiResourcesEndpointResponse=Ms;exports.mapApiTripOption=wa;exports.parseConversationContentCaption=Na;exports.parseRepollMessages=Is;exports.useAgentService=Fs;exports.useAgentWorkspace=Gs;
6
+ `);o=f.pop()??"";for(const w of f)m(w)}if(o.trim()&&m(o),!l)throw new De(502,null,"Chat stream ended without any events");return l}}const mr=e=>{let t=null;const s=[];for(const r of e.split(`
7
+ `)){const i=r.trimEnd();i.startsWith("event:")?t=i.slice(6).trim():i.startsWith("data:")&&s.push(i.slice(5).trim())}return{event:t,data:s.length>0?s.join(`
8
+ `):null}},$n=e=>{try{return JSON.parse(e)}catch{return}};function pr(e,t){const s=new FormData;s.append("body",JSON.stringify(e));for(const r of t)s.append("files",r,r.name);return s}const _r={id:Vn,author:se.agent,text:"Type a question or upload a file. You can ask it how it's progressing, or send an instruction and it'll act on it."};let Hn=0;const fr=e=>(Hn+=1,`${e}-${Date.now()}-${Hn}`),vr=e=>{const t=e.destination?` to ${e.destination}`:"";return`Let's get started on ${e.tripName.trim()||e.destination.trim()||"this task"}${t}. What will you do first?`};class gs{constructor(t,s,r={}){this.seededChecklist=[],this.client=t,this.agentId=s,this.chatId=r.chatId??s,this.opening=r.openingMessage??_r,this.model=r.model}openingMessage(){return this.opening}async bootstrapConversation(){const t=await this.client.getConversation(this.chatId),s=hs(t.messages);return s.length===0?[this.opening]:s}async start(t){return{...await this.exchange(vr(t)),phase:$.running}}sendMessage(t,s){return this.exchange(t,s)}async pause(){await this.client.pauseAgent(this.agentId)}async resume(){await this.client.resumeAgent(this.agentId)}seedChecklist(t){this.seededChecklist=t}async exchange(t,s){var l;const r=[{role:sr.user,content:t}],i=await this.client.chat(this.agentId,{messages:r,chat_id:this.chatId,...this.model?{model:this.model}:{},moderation_enabled:!0,meta:{feature_id:"agent_view",source:"agent_view_frontend"}},...s&&s.length>0?[{uploadFiles:s}]:[]),o={id:i.event_id||fr("msg-agent"),author:se.agent,text:i.message.content,...(l=i.follow_up_prompts)!=null&&l.length?{followUpPrompts:i.follow_up_prompts}:{}};try{const m=await this.client.getAgent(this.agentId),{checklist:h}=ds(this.agentId,m);return this.seededChecklist=h,{message:o,checklist:h}}catch{return{message:o,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const xn=(e,t)=>s=>{var r,i;return new gs(e,s.invocation_id,{model:t==null?void 0:t.model,chatId:((r=t==null?void 0:t.resolveChatId)==null?void 0:r.call(t,s))??(t==null?void 0:t.chatId)??s.invocation_id,openingMessage:((i=t==null?void 0:t.resolveOpeningMessage)==null?void 0:i.call(t,s))??(t==null?void 0:t.openingMessage)})},ms=e=>e instanceof De?e.message:e instanceof TypeError?"Network error while contacting the agent service.":e instanceof Error&&e.message?e.message:Yn,ps=e=>{if(e instanceof De){if(e.status===403)return aa;if(e.status===409)return ra;if(e.status===404)return ia}return sa},xr=e=>{const t={};for(const s of e){const r=At(s);if(!r)continue;const i=s.invocation_id??s.id;t[i]=r,t[s.id]=r}return t},wr=e=>JSON.stringify(e),$t=(e,t)=>JSON.stringify(e)===JSON.stringify(t),_s=e=>{const{jwt:t,headers:s,urls:r}=e,i=JSON.stringify(s??{}),o=wr(r),l=a.useMemo(()=>new Gt({token:t,headers:s,urls:r}),[t,o]);a.useLayoutEffect(()=>{l.setHeaders(s)},[l,i]);const[m,h]=a.useState([]),[k,f]=a.useState([]),[w,A]=a.useState({}),[E,p]=a.useState("loading"),[C,L]=a.useState(null),[M,I]=a.useState(0),v=a.useCallback((y,R)=>{const P=y.map(Ne),G=R.map(_n),D=xr(y);h(V=>$t(V,P)?V:P),f(V=>$t(V,G)?V:G),A(V=>$t(V,D)?V:D),p("idle"),L(null)},[]);a.useEffect(()=>{let y=!1;return p("loading"),L(null),(async()=>{try{const[R,P]=await Promise.all([l.listAgents(),l.listAgentDefinitions()]);if(y)return;v(R,P)}catch(R){if(y)return;h([]),f([]),A({}),p("error"),L(ms(R))}})(),()=>{y=!0}},[v,l,M]);const g=a.useCallback(()=>{I(y=>y+1)},[]),x=a.useCallback(async()=>{try{const[y,R]=await Promise.all([l.listAgents(),l.listAgentDefinitions()]);v(y,R)}catch{}},[v,l]),j=a.useCallback(async y=>{const[R,P]=await Promise.all([l.getAgentChecklist(y),l.getAgent(y).catch(()=>null)]);return vn(y,R,P??void 0)},[l]),O=a.useCallback(async y=>l.listAllAgentResources(y),[l]),Y=a.useCallback(async({definition:y,invocationName:R})=>{const P=await l.createAgent(y.ref,{invocationName:R}),G=await l.getAgent(P.id),D=Ne(G),V=At(G);return h(ae=>[D,...ae]),V&&A(ae=>({...ae,[D.invocation_id]:V,[D.id]:V})),D},[l]),ce=a.useCallback(async y=>{const R=await l.archiveAgent(y),P=Ne(R);return h(G=>G.map(D=>D.id===P.id||D.id===y||D.invocation_id===y?P:D)),P},[l]),U=a.useCallback(async y=>{const R=await l.unarchiveAgent(y),P=Ne(R);return h(G=>G.map(D=>D.id===P.id||D.id===y||D.invocation_id===y?P:D)),P},[l]),ee=a.useCallback(y=>{h(R=>R.filter(P=>P.id!==y&&P.invocation_id!==y))},[]),Ce=a.useCallback(y=>{h(R=>{const P=R.map(G=>G.id===y.id||G.invocation_id===y.invocation_id?{...G,...y}:G);return $t(R,P)?R:P})},[]),ue=a.useCallback(async y=>{await l.deleteAgent(y),ee(y)},[l,ee]),be=a.useMemo(()=>xn(l,{resolveOpeningMessage:y=>w[y.invocation_id]??w[y.id]}),[l,w]);return{agents:m,agentDefinitions:k,loadState:E,loadError:C,reload:g,refresh:x,fetchAgentChecklist:j,fetchAgentResources:O,createAgent:Y,archiveAgent:ce,unarchiveAgent:U,deleteAgent:ue,removeAgent:ee,replaceAgent:Ce,chatConnector:be}},Ar=e=>JSON.stringify(e),fs=e=>{const{agent:t,jwt:s,headers:r,urls:i,chatId:o}=e,l=JSON.stringify(r??{}),m=Ar(i),h=a.useMemo(()=>new Gt({token:s,headers:r,urls:{agent:i.agentUrl,agentChecklist:i.agentChecklistUrl,...i.agentResourcesUrl?{agentResources:i.agentResourcesUrl}:{},...i.agentTimelineUrl?{agentTimeline:i.agentTimelineUrl}:{},agentChat:i.agentChatUrl,agentConversation:i.agentConversationUrl,...i.pauseAgentUrl?{pauseAgent:i.pauseAgentUrl}:{},...i.resumeAgentUrl?{resumeAgent:i.resumeAgentUrl}:{},...i.archiveAgentUrl?{archiveAgent:i.archiveAgentUrl}:{},...i.unarchiveAgentUrl?{unarchiveAgent:i.unarchiveAgentUrl}:{}}}),[s,m]);a.useLayoutEffect(()=>{h.setHeaders(r)},[h,l]);const k=a.useCallback(async g=>Ne(await h.getAgent(g)),[h]),f=a.useCallback(async g=>{const[x,j]=await Promise.all([h.getAgentChecklist(g),h.getAgent(g).catch(()=>null)]);return vn(g,x,j??void 0)},[h]),w=a.useCallback(async g=>h.listAllAgentResources(g),[h]),A=a.useCallback(async g=>h.getAgentContext(g),[h]),E=a.useCallback(async(g,x)=>h.getAgentResourceHtml(g,x),[h]),p=a.useCallback(async g=>{const x=await h.getAgentTimeline(g);return us(x)},[h]),C=a.useCallback(async(g,x)=>{await h.updateAgent(g,{invocationName:x})},[h]),L=a.useCallback(async g=>Ne(await h.archiveAgent(g)),[h]),M=a.useCallback(async g=>Ne(await h.unarchiveAgent(g)),[h]),I=a.useCallback(async g=>{await h.deleteAgent(g)},[h]);return{connector:a.useMemo(()=>xn(h,{chatId:o??t.invocation_id})(t),[h,t.invocation_id,o]),fetchAgent:k,fetchAgentChecklist:f,fetchAgentContext:A,fetchAgentResources:w,fetchAgentResourceHtml:E,fetchAgentTimeline:p,updateAgentInvocationName:C,archiveAgent:L,unarchiveAgent:M,deleteAgent:I}},yr=3e4,kr=(e,t)=>{const s=e.hasRunBefore?t||"This trip":e.tripName.trim()||"A new trip",r=e.destination?` to ${e.destination}`:"",i=e.hasRunBefore?" It has run before.":"";return`${s}${r}.${i}`.trim()},Bn=e=>{switch(e){case N.paused:return $.paused;case N.complete:return $.complete;default:return $.running}},un=e=>e===N.paused,Fn=(e,t)=>{t([we(e)])},Nr=(e,t)=>e.length===t.length&&e.every((s,r)=>{const i=t[r];return i!==void 0&&s.id===i.id&&s.text===i.text}),vs=({agent:e,invocationId:t,open:s,onClose:r,jwt:i,headers:o,agentUrl:l,agentChecklistUrl:m,agentResourcesUrl:h,agentTimelineUrl:k,agentChatUrl:f,agentConversationUrl:w,pauseAgentUrl:A,resumeAgentUrl:E,archiveAgentUrl:p,unarchiveAgentUrl:C,chatId:L,enableUpload:M,adminMode:I=!1,initialBrief:v,initialPhase:g,initialChecklist:x,usePusherToRepoll:j=!1,pusherChannelPrefix:O=pn,subscribeToPusher:Y,onArchived:ce,onUnarchived:U,onDeleted:ee,onAgentUpdated:Ce})=>{const[ue,be]=a.useState(L??t),[y,R]=a.useState("chat"),[P,G]=a.useState(!1),{connector:D,fetchAgent:V,fetchAgentChecklist:ae,fetchAgentContext:yt,fetchAgentResources:$e,fetchAgentResourceHtml:He,fetchAgentTimeline:de,updateAgentInvocationName:Se,archiveAgent:We,unarchiveAgent:Xe,deleteAgent:te}=fs({agent:{...e,invocation_id:t},jwt:i,headers:o,chatId:ue,urls:{agentUrl:l,agentChecklistUrl:m,agentResourcesUrl:h,agentTimelineUrl:k,agentChatUrl:f,agentConversationUrl:w,pauseAgentUrl:A,resumeAgentUrl:E,archiveAgentUrl:p,unarchiveAgentUrl:C}}),q=a.useRef(D),[Ee,_e]=a.useState(e.invocation_name),[Be,Ze]=a.useState(0),[je,Qe]=a.useState(null),[K,re]=a.useState(g??(v?$.running:Bn(e.status))),[et,X]=a.useState([]),[zt,he]=a.useState(0),[qt,tt]=a.useState(),[Fe,Re]=a.useState(null),[nt,st]=a.useState([]),[Kt,Te]=a.useState(!1),[Ie,Oe]=a.useState(null),[at,rt]=a.useState(null),[Vt,fe]=a.useState(null),[kt,ie]=a.useState(!1),[Nt,ve]=a.useState(null),[xe,it]=a.useState(null),[Jt,lt]=a.useState(!1),[Ct,Le]=a.useState(null),[Pe,Ge]=a.useState(x??null),[bt,St]=a.useState(!1),[Yt,ot]=a.useState(null),[Wt,Et]=a.useState(void 0),[ct,jt]=a.useState(!1),[ut,dt]=a.useState(!1),[Xt,ht]=a.useState(null),[Rt,Tt]=a.useState(!1),[gt,u]=a.useState(!1),[b,S]=a.useState(!1),[Z,ge]=a.useState(!1),[ze,le]=a.useState(null),[mt,wn]=a.useState(!1),[ys,Zt]=a.useState(!1),[ks,It]=a.useState(null),[An,yn]=a.useState(!1),[Ns,Qt]=a.useState(!1),[Cs,Ot]=a.useState(null),[kn,Q]=a.useState(null),[bs,pt]=a.useState(()=>un(e.status)),[Ss,Nn]=a.useState(e.archivedAt??null),H=!!Ss,[Lt,_t]=a.useState(!1),[Pt,Es]=a.useState(!1),[Mt,js]=a.useState(!1),Cn=a.useRef(Lt),bn=a.useRef(e.invocation_name),qe=a.useRef(e),oe=a.useRef(Ce),Sn=a.useRef(0),En=a.useRef(0),Ke=a.useRef(0),ft=a.useRef(0);oe.current=Ce,a.useEffect(()=>{Nn(e.archivedAt??null)},[e.archivedAt]),a.useEffect(()=>{q.current=D},[D]),a.useEffect(()=>{bn.current=e.invocation_name},[e.invocation_name]),a.useEffect(()=>{qe.current=e},[e]),a.useEffect(()=>{Cn.current=Lt},[Lt]),a.useEffect(()=>{be(L??t),R("chat"),G(!1),X([]),he(d=>d+1),Qe(null)},[t,L]),a.useEffect(()=>(Ke.current+=1,Et(void 0),jt(!1),dt(!1),ht(null),()=>{Ke.current+=1}),[t]),a.useEffect(()=>{pt(un(e.status))},[e.status,t]),a.useEffect(()=>{if(!s||v||H)return;const d=++ft.current;return(async()=>{var _;try{const T=await V(t);if(d!==ft.current)return;re(Bn(T.status)),pt(un(T.status)),qe.current=T,(_=oe.current)==null||_.call(oe,T)}catch{}})(),()=>{ft.current+=1}},[s,t,v,H,V]),a.useEffect(()=>{_e(e.invocation_name),Ze(d=>d+1)},[e.invocation_name]),a.useEffect(()=>{H&&R("timeline")},[H]),a.useEffect(()=>{if(!s||v||H)return;const d=q.current.bootstrapConversation;if(!d){Fn(q.current.openingMessage(),X);return}let _=!1;return _t(!0),(async()=>{try{const T=await d.call(q.current);if(_)return;X(T.map(we))}catch{_||Fn(q.current.openingMessage(),X)}finally{_||_t(!1)}})(),()=>{_=!0}},[s,v,H,t,ue]);const me=a.useCallback(()=>{const d=++Sn.current;(async()=>{var _,T;try{const J=await ae(t);if(d!==Sn.current)return;Ge(ne=>JSON.stringify(ne)===JSON.stringify(J.checklist)?ne:J.checklist),ot(null),(T=(_=q.current).seedChecklist)==null||T.call(_,J.checklist)}catch{}})()},[ae,t]),Me=a.useCallback(()=>{h&&(async()=>{try{const d=await $e(t);st(d),Oe(null)}catch{}})()},[h,$e,t]),pe=a.useCallback(()=>{if(!k)return;const d=++En.current;(async()=>{try{const _=await de(t);if(d!==En.current)return;it(T=>JSON.stringify(T)===JSON.stringify(_)?T:_),Le(null)}catch{}})()},[k,de,t]),vt=a.useCallback(d=>{const _=q.current.bootstrapConversation;_&&(async()=>{try{const T=await _.call(q.current);if(Cn.current)return;const J=T.map(we);let ne=!1;X(Ve=>Nr(Ve,J)?Ve:(ne=!0,J)),ne&&(d!=null&&d.refreshSidePanelsOnChange)&&(me(),pe())}catch{}})()},[me,pe]),Rs=a.useCallback(d=>{switch(d){case ke.checklist:me();return;case ke.resources:Me();return;case ke.chat:vt();return;case ke.timeline:pe();return;case ke.all:default:me(),Me(),vt(),pe()}},[me,vt,Me,pe]),jn=er({enabled:s&&j,channelPrefix:O,agentId:e.id,subscribeToPusher:Y,onRepoll:Rs});a.useEffect(()=>{if(!s||v||H||jn)return;const d=window.setInterval(()=>{vt({refreshSidePanelsOnChange:!0})},yr);return()=>{window.clearInterval(d)}},[s,v,H,jn,t,ue,vt]);const en=a.useCallback(d=>{var _,T;d.checklist?(Ge(d.checklist),(T=(_=q.current).seedChecklist)==null||T.call(_,d.checklist)):me(),d.phase&&re(d.phase),Me(),pe()},[me,Me,pe]);a.useEffect(()=>{var d,_;!s||v||x&&x.length>0&&((_=(d=q.current).seedChecklist)==null||_.call(d,x))},[s,v,x]),a.useEffect(()=>{if(!s||v)return;let d=!1;return St(_=>x!=null&&x.length?!1:_||Pe===null||Pe.length===0),ot(null),(async()=>{var _,T;try{const J=await ae(t);if(d)return;x!=null&&x.length||(Ge(J.checklist),(T=(_=q.current).seedChecklist)==null||T.call(_,J.checklist))}catch{!d&&!(x!=null&&x.length)&&ot(Ht)}finally{d||St(!1)}})(),()=>{d=!0}},[s,t,v,x,ae]),a.useEffect(()=>{if(!s||!h)return;let d=!1;return Te(!0),Oe(null),(async()=>{try{const _=await $e(t);d||st(_)}catch{d||Oe(Ys)}finally{d||Te(!1)}})(),()=>{d=!0}},[s,t,h,$e]);const Ts=a.useCallback(()=>{rt(null),fe(null),ve(null),ie(!1)},[]),Is=a.useCallback(d=>{if(d.misRecordUrl){window.open(d.misRecordUrl,"_blank","noopener,noreferrer");return}rt(d),fe(null),ve(null),ie(!0),(async()=>{try{const _=await He(t,d.id);fe(_)}catch{ve(Ws)}finally{ie(!1)}})()},[He,t]);a.useEffect(()=>{if(!s||!k)return;let d=!1;return lt(_=>_||xe===null),Le(null),(async()=>{try{const _=await de(t);d||it(_)}catch{d||Le(Jn)}finally{d||lt(!1)}})(),()=>{d=!0}},[s,t,k,de]),a.useEffect(()=>{if(!s||!v)return;let d=!1;const _={id:`user-brief-${Date.now()}`,author:se.user,text:kr(v,bn.current)};return(async()=>{var J,ne;const T=await q.current.start(v);d||(X([we(q.current.openingMessage()),we(_),we(T.message)]),T.checklist?(Ge(T.checklist),(ne=(J=q.current).seedChecklist)==null||ne.call(J,T.checklist)):me(),re(T.phase??$.running),Me(),pe())})(),()=>{d=!0}},[s,v,t,me,Me,pe]);const Os=a.useCallback(d=>{Re(Ja(d))},[]),tn=L??t,Ut=xe==null?void 0:xe.chatSessions,Rn=Ut!=null&&Ut.length?Ut.reduce((d,_)=>Date.parse(_.timestamp)<Date.parse(d.timestamp)?_:d).sessionId:void 0,nn=a.useCallback(()=>{R("chat"),G(!1),ue!==tn&&(be(tn),X([]),he(d=>d+1))},[ue,tn]),Ls=a.useCallback(d=>{if(d===Rn){nn();return}be(d),G(!0),R("chat"),X([]),he(_=>_+1)},[Rn,nn]),Ps=a.useCallback(d=>{Re(null),tt(d),he(_=>_+1)},[]),Ms=a.useCallback(async()=>{var d;Q(null),Tt(!0);try{await q.current.pause(),ft.current+=1,re($.paused),pt(!0);const _={...qe.current,status:N.paused};qe.current=_,(d=oe.current)==null||d.call(oe,_)}catch{Q(Xs)}finally{Tt(!1)}},[]),Us=a.useCallback(async()=>{var _;Q(null),u(!0);let d=!1;try{await q.current.resume(),d=!0,ft.current+=1,re($.running),pt(!1);const T={...qe.current,status:N["generating-a-response"]};qe.current=T,(_=oe.current)==null||_.call(oe,T),_t(!0);const J={id:`wake-${Date.now()}`,author:se.user,text:Tn};X(Ve=>[...Ve,we(J)]);const ne=await q.current.sendMessage(Tn);X(Ve=>[...Ve,we(ne.message)]),en(ne)}catch{Q(d?ua:ca)}finally{u(!1),_t(!1)}},[en]),Ds=a.useCallback(async()=>{Q(null),le(null),S(!0);try{await We(t),ge(!1),ce==null||ce(),r()}catch{le(dn),Q(dn)}finally{S(!1)}},[t,We,ce,r]),$s=a.useCallback(async()=>{Q(null),It(null),wn(!0);try{await Xe(t),Nn(null),re($.paused),pt(!0),R("chat"),Zt(!1),U==null||U()}catch{It(hn),Q(hn)}finally{wn(!1)}},[t,Xe,U]),Hs=a.useCallback(async()=>{Q(null),Ot(null),yn(!0);try{await te(t),Qt(!1),ee==null||ee(),r()}catch(d){Ot(ps(d))}finally{yn(!1)}},[t,te,ee,r]),Bs=a.useCallback(d=>{const _=d.trim(),T=Ee;if(Qe(null),!_){Ze(J=>J+1);return}_!==T&&(_e(_),(async()=>{try{await Se(t,_)}catch{_e(T),Ze(J=>J+1),Qe(da)}})())},[Ee,t,Se]),Fs=a.useCallback(()=>{if(!I||ct||ut)return;const d=++Ke.current;dt(!0),ht(null),(async()=>{try{const _=await yt(t);if(Ke.current!==d)return;Et(_),jt(!0)}catch{Ke.current===d&&ht(Js)}finally{Ke.current===d&&dt(!1)}})()},[I,ct,ut,yt,t]),Gs=Pe;return n.jsxs(n.Fragment,{children:[n.jsxs(c.Modal,{open:s,closeHandler:r,hideCloseButton:!0,className:"agent-workspace",children:[n.jsxs(c.Modal.Header,{className:"agent-workspace__header",children:[n.jsxs("div",{className:"agent-workspace__header-title",children:[n.jsx("span",{className:"agent-workspace__header-avatar","aria-hidden":"true",children:n.jsx(c.Icon,{name:"ask-arbor",size:24})}),n.jsx(c.Modal.Title,{children:H?n.jsx("span",{className:"agent-workspace__header-name",children:Ee}):n.jsx(c.EditableText,{className:"agent-workspace__header-name",text:Ee,onEditSave:Bs},Be)}),n.jsx("span",{className:W("agent-workspace__phase",`agent-workspace__phase--${K}`),children:ma[K]}),H?n.jsx("span",{className:"agent-workspace__phase agent-workspace__phase--archived",children:"Archived"}):null,je&&n.jsx("p",{className:"agent-workspace__error agent-workspace__name-error",role:"alert",children:je})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(c.Button,{variant:Pt?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!Pt,onClick:()=>Es(d=>!d),children:"Checklist"}),n.jsx(c.Button,{variant:Mt?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Mt,onClick:()=>js(d=>!d),children:"Resources"}),n.jsx(c.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:r,children:"Close"})]})]}),n.jsxs(c.Modal.Body,{className:W("agent-workspace__body",{"agent-workspace__body--no-checklist":Pt,"agent-workspace__body--no-resources":Mt}),children:[n.jsxs("section",{className:W("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!k&&(H||y==="timeline")}),"aria-label":"Agent",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(c.Heading,{level:4,children:"Agent"}),A&&!H&&K===$.running&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Pause",disabled:Rt,onClick:()=>void Ms(),children:Rt?"Pausing…":"Pause agent"}),E&&!H&&K===$.paused&&bs&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"iteration-ccw",iconLeftScreenReaderText:"Resume",disabled:gt,onClick:()=>void Us(),children:gt?"Resuming…":"Resume agent"}),p&&!H&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>{le(null),Q(null),ge(!0)},children:"Archive agent"}),C&&H&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",onClick:()=>{It(null),Q(null),Zt(!0)},children:"Unarchive agent"}),I&&H&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",onClick:()=>{Ot(null),Q(null),Qt(!0)},children:"Delete agent"})]}),kn&&n.jsx("p",{className:"agent-workspace__error agent-workspace__lifecycle-error",role:"alert",children:kn}),k&&!H&&n.jsxs(c.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(c.Tabs.Item,{active:y==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>R("chat")},children:"Chat"}),n.jsx(c.Tabs.Item,{active:y==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>R("timeline")},children:"Timeline"})]}),k&&!H&&y==="chat"&&P&&n.jsx("div",{className:"agent-workspace__center-back",children:n.jsx(c.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:nn,children:"Back to main chat"})}),k&&(H||y==="timeline")&&n.jsx(Ka,{timeline:xe,isLoading:Jt,error:Ct,onOpenChatSession:H?void 0:Ls}),!H&&n.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!k&&y!=="chat",children:n.jsx(Ra,{connector:D,phase:K,chatHistory:et,chatSessionKey:zt,startQuery:qt,clarificationMessage:Fe,enableUpload:M,onTurn:en,onAwaitingChange:_t,onClarificationPrompt:Ps,onDismissClarification:()=>Re(null)})}),H&&!k&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Chat is not available for archived agents."})]}),!Pt&&n.jsx(Ta,{checklist:Gs,isLoading:bt,error:Yt,phase:K,canRequestInput:!H&&K===$.running&&!Lt,onAttentionItemClick:Os,adminMode:I,context:Wt,contextLoaded:ct,contextLoading:ut,contextError:Xt,onContextSelect:Fs},t),!Mt&&n.jsx(La,{resources:nt,isLoading:Kt,error:Ie,onOpenResource:Is}),n.jsx(Ia,{resource:at,html:Vt,isLoading:kt,error:Nt,onClose:Ts})]})]}),n.jsx(Xn,{open:Z,isInProgress:K===$.running||K===$.paused&&!es(Pe??void 0),isArchiving:b,error:ze,onCancel:()=>{b||(le(null),ge(!1))},onConfirm:()=>{Ds()}}),n.jsx(Qn,{open:ys,isUnarchiving:mt,error:ks,onCancel:()=>{mt||(It(null),Zt(!1))},onConfirm:()=>{$s()}}),n.jsx(Zn,{open:Ns,isDeleting:An,error:Cs,onCancel:()=>{An||(Ot(null),Qt(!1))},onConfirm:()=>{Hs()}})]})},Cr="Unable to load agent definitions. Please try again.",br="Unable to start the agent.",Gn="Loading agents…",xs=({open:e,onClose:t,onStart:s,agentDefinitions:r,definitionsState:i="idle",definitionsError:o=null,onRetryDefinitions:l,embedded:m=!1})=>{const[h,k]=a.useState(void 0),[f,w]=a.useState(""),[A,E]=a.useState(!1),[p,C]=a.useState(null),L=[...r].sort((j,O)=>j.display_name.localeCompare(O.display_name)).map(j=>({value:j.ref,label:j.display_name}));a.useEffect(()=>{e&&(k(void 0),w(""),E(!1),C(null))},[e]);const M=h!==void 0&&f.trim().length>0,I=a.useCallback(j=>{const O=r.find(Y=>Y.ref===j[0]);O&&k(O)},[r]),v=a.useCallback(async()=>{if(!(!h||!M||A)){E(!0),C(null);try{await s({definition:h,invocationName:f.trim()})}catch(j){C(j instanceof Error?j.message:br)}finally{E(!1)}}},[M,h,f,A,s]);if(i==="idle"&&r.length===0||!e)return null;const g=n.jsxs("div",{className:"new-agent__header-title",children:[n.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:n.jsx(c.Icon,{name:"ask-arbor",size:24})}),m?n.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):n.jsx(c.Modal.Title,{children:"Start an agent"})]});let x;return i==="loading"?x=n.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[n.jsx(c.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:Gn}),n.jsx("p",{className:"new-agent__state-message",children:Gn})]}):i==="error"?x=n.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[n.jsx(c.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"new-agent__state-message",children:o??Cr}),l?n.jsx(c.Button,{variant:"secondary",size:"S",onClick:l,children:"Try again"}):null]}):x=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:j=>{j.preventDefault(),M&&!A&&v()},children:[n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:"What would you like your agent to do?"}),n.jsx(c.SelectDropdown,{id:"new-agent-type",placeholder:"Which agent would you like to start?",options:L,selectedValues:h?[h.ref]:[],onSelectionChange:I})]}),n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:"Name"}),n.jsx(c.TextInput,{id:"new-agent-invocation-name",value:f,placeholder:"What would you like to call your agent?",onChange:j=>w(j.target.value)})]}),p?n.jsx("p",{className:"new-agent__error",role:"alert",children:p}):null,n.jsx("div",{className:"new-agent__actions",children:n.jsx(c.Button,{type:"submit",variant:"primary",className:W("new-agent__start-button",{"new-agent__start-button--starting":A}),disabled:!M||A,iconLeftName:A?"loader":"sparkles",iconLeftScreenReaderText:A?"Starting":void 0,children:A?"Starting…":"Start"})})]}),m?n.jsxs("div",{className:W("new-agent","new-agent--embedded"),children:[n.jsx("div",{className:"new-agent__header",children:g}),n.jsx("div",{className:"new-agent__body",children:x})]}):n.jsxs(c.Modal,{open:e,closeHandler:t,className:"new-agent",children:[n.jsx(c.Modal.Header,{className:"new-agent__header",children:g}),n.jsx(c.Modal.Body,{className:"new-agent__body",children:x})]})},zn=e=>{window.location.assign(e)},Sr=({open:e,authToken:t,headers:s,agentDefinitionsUrl:r,agentsUrl:i,closeUrl:o,successUrl:l,onClose:m,onStart:h,embedded:k=!1})=>{const f=JSON.stringify(s??{}),w=a.useMemo(()=>new Gt({token:t,headers:s,urls:{agentDefinitions:r,agents:i}}),[t,r,i,f]),[A,E]=a.useState([]),[p,C]=a.useState("loading"),[L,M]=a.useState(null),[I,v]=a.useState(0);a.useEffect(()=>{if(!e)return;let O=!1;return C("loading"),M(null),(async()=>{try{const Y=await w.listAgentDefinitions();if(O)return;E(Y.map(_n)),C("idle")}catch(Y){if(O)return;E([]),M(ms(Y)),C("error")}})(),()=>{O=!0}},[w,e,I]);const g=a.useCallback(()=>{m==null||m(),o&&zn(o)},[o,m]),x=a.useCallback(async O=>{await w.createAgent(O.definition.ref,{invocationName:O.invocationName}),h==null||h(O),l&&zn(l)},[w,h,l]),j=a.useCallback(()=>{v(O=>O+1)},[]);return n.jsx(xs,{open:e,onClose:g,onStart:x,agentDefinitions:A,definitionsState:p,definitionsError:L,onRetryDefinitions:j,embedded:k})},Er=e=>"agentDefinitionsUrl"in e,ws=e=>Er(e)?n.jsx(Sr,{...e}):n.jsx(xs,{...e}),jr=e=>e.archivedAt?"archived":e.status===N.paused?"paused":null,Rr=e=>{if(e==="archived")return zs;if(e==="paused")return wt[N.paused].statusIcon},Tr=({column:e,overlayIcon:t,label:s})=>{const r=t??e.statusIcon;return r?n.jsx("span",{className:"agent-view__status-indicator",children:n.jsx(c.Icon,{name:r.name,size:16,color:r.color,className:W({"agent-view__progress-icon--spinning":r.spin}),screenReaderText:s})}):n.jsx("span",{className:W("agent-view__dot",{[`agent-view__dot--${e.dotModifier}`]:e.dotModifier}),children:n.jsx(c.Dot,{colour:e.dotColour,label:s})})},As=({agent:e,agentName:t,column:s,isExpanded:r,isLoading:i,checklist:o,error:l,canArchive:m,canUnarchive:h=!1,canDelete:k=!1,onToggle:f,onViewAgent:w,onArchive:A,onUnarchive:E,onDelete:p})=>{const{id:C,invocation_name:L}=e,M=`agent-card-${C}-header`,I=`agent-card-${C}-progress`,v=jr(e),g=Rr(v);return n.jsx("li",{className:W("agent-view__card",{"agent-view__card--expanded":r,"agent-view__card--paused":v==="paused","agent-view__card--archived":v==="archived"}),children:n.jsxs(c.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":r,"aria-controls":I,"aria-label":L,id:M,onClick:()=>f(C),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(Tr,{column:s,overlayIcon:g}),n.jsx("span",{className:"agent-view__card-invocation-name",children:L}),n.jsx("span",{className:"agent-view__card-agent-name",children:t}),v==="paused"?n.jsx("span",{className:"agent-view__card-state-pill",children:"Paused"}):null,v==="archived"?n.jsx("span",{className:"agent-view__card-state-pill",children:"Archived"}):null,n.jsx(c.Icon,{name:r?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),r&&n.jsxs("div",{id:I,"aria-labelledby":M,className:"agent-view__card-progress",children:[i&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:Je}),n.jsx("span",{children:Je})]}),!i&&l&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:l}),!i&&!l&&o!==null&&n.jsx(ba,{checklist:o}),!i&&!l&&o===null&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(c.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:Je}),n.jsx("span",{children:Je})]}),n.jsxs("div",{className:"agent-view__card-actions",children:[m?n.jsx(c.Button,{variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>A==null?void 0:A(e),children:"Archive"}):h?n.jsx(c.Button,{variant:"secondary",size:"S",onClick:()=>E==null?void 0:E(e),children:"Unarchive"}):k?n.jsx(c.Button,{variant:"secondary-destructive",size:"S",onClick:()=>p==null?void 0:p(e),children:"Delete"}):n.jsx("span",{}),h&&k?n.jsx(c.Button,{variant:"secondary-destructive",size:"S",onClick:()=>p==null?void 0:p(e),children:"Delete"}):null,n.jsx(c.Button,{variant:"secondary",size:"S",onClick:()=>w==null?void 0:w(e),children:"View agent"})]})]})]})})},Ir=({column:e,agents:t,expandedAgentId:s,loadingAgentId:r,checklistByInvocationId:i,errorByAgentId:o,definitionNameByRef:l,onToggleAgent:m,onViewAgent:h,onArchiveAgent:k,canArchive:f})=>n.jsxs("section",{className:"agent-view__column","aria-label":e.title,children:[n.jsxs("div",{className:"agent-view__column-header",children:[n.jsx(c.Heading,{level:4,children:e.title}),n.jsx("span",{className:"agent-view__column-count",children:t.length})]}),n.jsx("ul",{className:"agent-view__card-list",children:t.map(w=>n.jsx(As,{agent:w,agentName:Bt(w,l),column:e,isExpanded:s===w.id,isLoading:r===w.id,checklist:i[w.invocation_id]??null,error:o[w.id]??null,canArchive:f&&!w.archivedAt,onToggle:m,onViewAgent:h,onArchive:k},w.id))})]}),Bt=(e,t)=>t.get(e.agent_definition_ref)??e.agent_definition_ref.replace(/_/g," "),Or=({jwt:e,headers:t,agentDefinitionsUrl:s,agentsUrl:r,agentUrl:i,agentChecklistUrl:o,agentResourcesUrl:l,agentTimelineUrl:m,agentChatUrl:h,agentConversationUrl:k,pauseAgentUrl:f,resumeAgentUrl:w,archiveAgentUrl:A,unarchiveAgentUrl:E,enableUpload:p,adminMode:C=!1,showHeader:L=!1,institutions:M,usePusherToRepoll:I=!1,pusherChannelPrefix:v=pn,subscribeToPusher:g})=>{var gt;const x=a.useMemo(()=>({agentDefinitions:s,agents:r,agent:i,agentChecklist:o,...l?{agentResources:l}:{},...m?{agentTimeline:m}:{},agentChat:h,agentConversation:k,...A?{archiveAgent:A}:{},...E?{unarchiveAgent:E}:{}}),[s,r,i,o,l,m,h,k,A,E]),[j,O]=a.useState(null),Y=j?(gt=M==null?void 0:M.find(u=>u.applicationId===j.application_id))==null?void 0:gt.applicationUrl:void 0,ce=a.useMemo(()=>{const u={...t??{}};return Y?u[Ue.arborApplicationUrl]=Y:delete u[Ue.arborApplicationUrl],u},[t,Y]),{agents:U,agentDefinitions:ee,loadState:Ce,loadError:ue,reload:be,refresh:y,fetchAgentChecklist:R,createAgent:P,archiveAgent:G,unarchiveAgent:D,deleteAgent:V,removeAgent:ae,replaceAgent:yt}=_s({jwt:e,headers:ce,urls:x}),[$e,He]=a.useState(!1),[de,Se]=a.useState(null),[We,Xe]=a.useState(null),[te,q]=a.useState({}),[Ee,_e]=a.useState({}),[Be,Ze]=a.useState([]),[je,Qe]=a.useState([]),[K,re]=a.useState(null),[et,X]=a.useState(!1),[zt,he]=a.useState(null),[qt,tt]=a.useState(!1),[Fe,Re]=a.useState(null),[nt,st]=a.useState(!1),[Kt,Te]=a.useState(null),[Ie,Oe]=a.useState(null),[at,rt]=a.useState(!1),[Vt,fe]=a.useState(null);a.useEffect(()=>{O(u=>u?U.find(b=>b.id===u.id)??u:null)},[U]);const kt=a.useMemo(()=>{const u=new Set(U.map(S=>S.application_id)),b=new Map((M??[]).map(S=>[S.applicationId,S.name]));return[...u].sort((S,Z)=>(b.get(S)??S).localeCompare(b.get(Z)??Z)).map(S=>({value:S,label:b.get(S)??S}))},[U,M]),ie=a.useMemo(()=>new Map(ee.map(u=>[u.ref,u.display_name])),[ee]),Nt=a.useMemo(()=>[...new Set(U.map(b=>Bt(b,ie)))].sort((b,S)=>b.localeCompare(S)).map(b=>({value:b,label:b})),[U,ie]),ve=a.useMemo(()=>U.filter(u=>!(Be.length>0&&!Be.includes(u.application_id)||je.length>0&&!je.includes(Bt(u,ie)))),[U,ie,je,Be]),xe=kt.length>1,it=Nt.length>1,Jt=xe||it;a.useEffect(()=>{const u=window.setInterval(()=>{y()},6e4);return()=>{window.clearInterval(u)}},[y]),a.useEffect(()=>{if(U.length===0)return;let u=!1;return(async()=>{const b=await Promise.allSettled(U.map(async S=>{const Z=await R(S.invocation_id);return{agentId:S.id,invocationId:S.invocation_id,checklist:Z.checklist}}));u||(q(S=>{const Z={...S};let ge=!1;for(const ze of b){if(ze.status!=="fulfilled")continue;const{invocationId:le,checklist:mt}=ze.value;JSON.stringify(S[le])!==JSON.stringify(mt)&&(Z[le]=mt,ge=!0)}return ge?Z:S}),_e(S=>{const Z={...S};let ge=!1;return b.forEach((ze,le)=>{ze.status==="rejected"&&Z[U[le].id]!==Ht&&(Z[U[le].id]=Ht,ge=!0)}),ge?Z:S}))})(),()=>{u=!0}},[U,R]);const lt=a.useCallback(async u=>{if(!te[u.invocation_id]){Xe(u.id),_e(b=>{const S={...b};return delete S[u.id],S});try{const b=await R(u.invocation_id);q(S=>({...S,[u.invocation_id]:b.checklist}))}catch{_e(b=>({...b,[u.id]:Ht}))}finally{Xe(b=>b===u.id?null:b)}}},[R,te]),Ct=a.useCallback(u=>{if(de===u){Se(null);return}const b=U.find(({id:S})=>S===u);b&&(Se(u),lt(b))},[U,de,lt]),Le=a.useMemo(()=>ve.filter(u=>!!u.archivedAt),[ve]),Pe=a.useMemo(()=>ve.filter(u=>!u.archivedAt),[ve]),Ge=a.useMemo(()=>{const u={};for(const b of Pe){const S=ln(b,te[b.invocation_id]);(u[S]??(u[S]=[])).push(b)}return u},[Pe,te]),bt=a.useCallback(u=>{O(u)},[]),St=a.useCallback(u=>{he(null),re(u)},[]),Yt=a.useCallback(()=>{et||(he(null),re(null))},[et]),ot=a.useCallback(async()=>{if(K){X(!0),he(null),_e(u=>{const b={...u};return delete b[K.id],b});try{await G(K.invocation_id),O(u=>(u==null?void 0:u.id)===K.id?null:u),Se(K.id),tt(!0),re(null)}catch{he(dn)}finally{X(!1)}}},[K,G]),Wt=a.useCallback(u=>{Te(null),Re(u)},[]),Et=a.useCallback(()=>{nt||(Te(null),Re(null))},[nt]),ct=a.useCallback(async()=>{if(Fe){st(!0),Te(null);try{await D(Fe.invocation_id),Re(null)}catch{Te(hn)}finally{st(!1)}}},[Fe,D]),jt=K?ln(K,te[K.invocation_id])!==N.complete:!1,ut=a.useCallback(async u=>{const b=await P(u);O(b),He(!1)},[P]),dt=a.useCallback(u=>{fe(null),Oe(u)},[]),Xt=a.useCallback(()=>{at||(fe(null),Oe(null))},[at]),ht=a.useCallback(async()=>{if(Ie){rt(!0),fe(null);try{await V(Ie.invocation_id),O(u=>(u==null?void 0:u.id)===Ie.id?null:u),Oe(null)}catch(u){fe(ps(u))}finally{rt(!1)}}},[Ie,V]),Rt=a.useCallback(()=>{O(null)},[]),Tt={expandedAgentId:de,loadingAgentId:We,checklistByInvocationId:te,errorByAgentId:Ee,definitionNameByRef:ie,onToggleAgent:Ct,onViewAgent:bt,onArchiveAgent:St,canArchive:!!A};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[L&&n.jsxs("div",{className:"agent-view__header",children:[n.jsx(c.Heading,{level:1,children:"Agents"}),n.jsx(c.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>He(!0),children:"Start an agent"})]}),U.length>0&&Jt&&n.jsxs("div",{className:"agent-view__filters",children:[xe&&n.jsxs("div",{className:"agent-view__filter",children:[n.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-institution-filter",children:"Institution"}),n.jsx(c.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:kt,value:Be,onValueChange:Ze,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),it&&n.jsxs("div",{className:"agent-view__filter",children:[n.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-agent-filter",children:"Agent"}),n.jsx(c.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:Nt,value:je,onValueChange:Qe,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),Ce==="error"?n.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[n.jsx(c.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"agent-view__state-message",children:ue??Yn}),n.jsx(c.Button,{variant:"secondary",size:"S",onClick:be,children:"Try again"})]}):Ce==="loading"&&U.length===0?n.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[n.jsx(c.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:In}),n.jsx("p",{className:"agent-view__state-message",children:In})]}):U.length===0?n.jsx(xa,{}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"agent-view__board",children:qs.map(u=>n.jsx(Ir,{column:wt[u],agents:Ge[u]??[],...Tt},u))}),Le.length>0?n.jsxs("details",{className:"agent-view__archived",open:qt,onToggle:u=>{tt(u.currentTarget.open)},children:[n.jsxs("summary",{className:"agent-view__archived-summary",children:[n.jsx(c.Heading,{level:4,children:"Archived"}),n.jsx("span",{className:"agent-view__column-count",children:Le.length})]}),n.jsx("ul",{className:"agent-view__card-list agent-view__archived-list",children:Le.map(u=>n.jsx(As,{agent:u,agentName:Bt(u,ie),column:wt[ln(u,te[u.invocation_id])],isExpanded:de===u.id,isLoading:We===u.id,checklist:te[u.invocation_id]??null,error:Ee[u.id]??null,canArchive:!1,canUnarchive:!!E,canDelete:C,onToggle:Ct,onViewAgent:bt,onUnarchive:Wt,onDelete:dt},u.id))})]}):null]}),j&&n.jsx(vs,{agent:j,invocationId:j.invocation_id,open:!0,jwt:e,headers:ce,agentUrl:i,agentChecklistUrl:o,agentResourcesUrl:l,agentTimelineUrl:m,agentChatUrl:h,agentConversationUrl:k,pauseAgentUrl:f,resumeAgentUrl:w,archiveAgentUrl:A,unarchiveAgentUrl:E,enableUpload:p,adminMode:C,initialChecklist:te[j.invocation_id]??null,usePusherToRepoll:I,pusherChannelPrefix:v,subscribeToPusher:g,onClose:Rt,onAgentUpdated:yt,onArchived:()=>{Se(j.id),tt(!0),y()},onUnarchived:()=>{y()},onDeleted:()=>{ae(j.invocation_id)}},j.id),n.jsx(Xn,{open:!!K,isInProgress:jt,isArchiving:et,error:zt,onCancel:Yt,onConfirm:()=>{ot()}}),n.jsx(Qn,{open:!!Fe,isUnarchiving:nt,error:Kt,onCancel:Et,onConfirm:()=>{ct()}}),n.jsx(Zn,{open:!!Ie,isDeleting:at,error:Vt,onCancel:Xt,onConfirm:()=>{ht()}}),n.jsx(ws,{open:$e,onClose:()=>He(!1),onStart:ut,agentDefinitions:ee})]})},Lr=(e,t)=>{const s=Date.now(),r=t.trim()||e.agent_intent;return{id:`agent-${s}`,invocation_id:`inv-${s}`,agent_definition_ref:e.ref,agent_intent:e.agent_intent,invocation_name:r,application_id:Ks,created_by:Vs,status:N["generating-a-response"],archivedAt:null,context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=Or;exports.AgentServiceClient=Gt;exports.AgentServiceError=De;exports.AgentView=vs;exports.DEFAULT_PUSHER_CHANNEL_PREFIX=pn;exports.HttpChatConnector=gs;exports.MESSAGE_TYPE_REPOLL=mn;exports.NewAgentModal=ws;exports.PUSHER_AGENT_MESSAGE_EVENT=ss;exports.REPOLL_TARGET=ke;exports.buildAgentFromDefinition=Lr;exports.buildAgentPusherChannel=as;exports.createHttpChatConnectorFactory=xn;exports.formatUserFileChatCardText=ur;exports.mapApiAgent=Ne;exports.mapApiAgentDefinition=_n;exports.mapApiAgentStatus=is;exports.mapApiAgentTimelineResponse=us;exports.mapApiChecklistEndpointResponse=vn;exports.mapApiChecklistItem=fn;exports.mapApiChecklistResponse=ds;exports.mapApiChecklistStatus=ls;exports.mapApiConversationMessages=hs;exports.mapApiOpeningMessage=At;exports.mapApiResource=os;exports.mapApiResourcesEndpointResponse=cs;exports.mapApiTripOption=rr;exports.parseConversationContentCaption=cr;exports.parseRepollMessages=rs;exports.useAgentService=_s;exports.useAgentWorkspace=fs;
package/dist/index.d.ts CHANGED
@@ -63,7 +63,7 @@ export declare type AgentDefinition = {
63
63
  description: string;
64
64
  };
65
65
 
66
- export declare const AgentMonitorKanban: ({ jwt, headers, agentDefinitionsUrl, agentsUrl, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, pauseAgentUrl, resumeAgentUrl, archiveAgentUrl, enableUpload, adminMode, showHeader, institutions, usePusherToRepoll, pusherChannelPrefix, subscribeToPusher, }: AgentMonitorKanbanProps) => JSX_2.Element;
66
+ export declare const AgentMonitorKanban: ({ jwt, headers, agentDefinitionsUrl, agentsUrl, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, pauseAgentUrl, resumeAgentUrl, archiveAgentUrl, unarchiveAgentUrl, enableUpload, adminMode, showHeader, institutions, usePusherToRepoll, pusherChannelPrefix, subscribeToPusher, }: AgentMonitorKanbanProps) => JSX_2.Element;
67
67
 
68
68
  export declare type AgentMonitorKanbanProps = {
69
69
  jwt?: string;
@@ -81,6 +81,7 @@ export declare type AgentMonitorKanbanProps = {
81
81
  pauseAgentUrl?: string;
82
82
  resumeAgentUrl?: string;
83
83
  archiveAgentUrl?: string;
84
+ unarchiveAgentUrl?: string;
84
85
  enableUpload?: boolean;
85
86
  adminMode?: boolean;
86
87
  showHeader?: boolean;
@@ -143,6 +144,8 @@ export declare class AgentServiceClient {
143
144
  pauseAgent(agentId: string): Promise<ApiAgentInvocation>;
144
145
  resumeAgent(agentId: string): Promise<ApiAgentInvocation>;
145
146
  archiveAgent(agentId: string): Promise<ApiAgentInvocation>;
147
+ unarchiveAgent(agentId: string): Promise<ApiAgentInvocation>;
148
+ deleteAgent(agentId: string): Promise<ApiAgentDeleteResponse>;
146
149
  getConversation(agentId: string): Promise<ApiConversationResponse>;
147
150
  chat(agentId: string, request: ApiChatRequest, options?: ChatOptions): Promise<ApiChatStreamEvent>;
148
151
  private authHeaders;
@@ -190,6 +193,7 @@ export declare type AgentServiceUrlOverrides = {
190
193
  pauseAgent?: string;
191
194
  resumeAgent?: string;
192
195
  archiveAgent?: string;
196
+ unarchiveAgent?: string;
193
197
  };
194
198
 
195
199
  export declare type AgentServiceUrls = AgentServiceUrlOverrides;
@@ -224,7 +228,7 @@ declare type AgentTimelineScheduledRun = {
224
228
 
225
229
  declare type AgentTimelineScheduledRunRecurrence = 'one_off' | 'repeating';
226
230
 
227
- export declare const AgentView: ({ agent, invocationId, open, onClose, jwt, headers, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, pauseAgentUrl, resumeAgentUrl, archiveAgentUrl, chatId, enableUpload, adminMode, initialBrief, initialPhase, initialChecklist, usePusherToRepoll, pusherChannelPrefix, subscribeToPusher, onArchived, }: AgentViewProps) => JSX_2.Element;
231
+ export declare const AgentView: ({ agent, invocationId, open, onClose, jwt, headers, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, pauseAgentUrl, resumeAgentUrl, archiveAgentUrl, unarchiveAgentUrl, chatId, enableUpload, adminMode, initialBrief, initialPhase, initialChecklist, usePusherToRepoll, pusherChannelPrefix, subscribeToPusher, onArchived, onUnarchived, onDeleted, onAgentUpdated, }: AgentViewProps) => JSX_2.Element;
228
232
 
229
233
  export declare type AgentViewProps = {
230
234
  agent: Agent;
@@ -242,7 +246,11 @@ export declare type AgentViewProps = {
242
246
  pauseAgentUrl?: string;
243
247
  resumeAgentUrl?: string;
244
248
  archiveAgentUrl?: string;
249
+ unarchiveAgentUrl?: string;
245
250
  onArchived?: () => void;
251
+ onUnarchived?: () => void;
252
+ onDeleted?: () => void;
253
+ onAgentUpdated?: (agent: Agent) => void;
246
254
  chatId?: string;
247
255
  enableUpload?: boolean;
248
256
  adminMode?: boolean;
@@ -264,6 +272,7 @@ export declare type AgentWorkspaceUrls = {
264
272
  pauseAgentUrl?: string;
265
273
  resumeAgentUrl?: string;
266
274
  archiveAgentUrl?: string;
275
+ unarchiveAgentUrl?: string;
267
276
  };
268
277
 
269
278
  export declare type ApiAgentDefinition = {
@@ -286,6 +295,10 @@ export declare type ApiAgentDefinition = {
286
295
  tags?: string[];
287
296
  };
288
297
 
298
+ export declare type ApiAgentDeleteResponse = {
299
+ status: 'deleted';
300
+ };
301
+
289
302
  export declare type ApiAgentInvocation = {
290
303
  id: string;
291
304
  invocation_id?: string | null;
@@ -674,6 +687,10 @@ export declare type UseAgentServiceResult = {
674
687
  fetchAgentResources: (invocationId: string) => Promise<AgentResource[]>;
675
688
  createAgent: (payload: NewAgentStartPayload) => Promise<Agent>;
676
689
  archiveAgent: (agentId: string) => Promise<Agent>;
690
+ unarchiveAgent: (agentId: string) => Promise<Agent>;
691
+ deleteAgent: (agentId: string) => Promise<void>;
692
+ removeAgent: (agentId: string) => void;
693
+ replaceAgent: (agent: Agent) => void;
677
694
  chatConnector: (agent: Agent) => ChatConnector;
678
695
  };
679
696
 
@@ -689,6 +706,7 @@ export declare type UseAgentWorkspaceConfig = {
689
706
 
690
707
  export declare type UseAgentWorkspaceResult = {
691
708
  connector: ChatConnector;
709
+ fetchAgent: (invocationId: string) => Promise<Agent>;
692
710
  fetchAgentChecklist: (invocationId: string) => Promise<AgentChecklistResponse>;
693
711
  fetchAgentContext: (invocationId: string) => Promise<unknown>;
694
712
  fetchAgentResources: (invocationId: string) => Promise<AgentResource[]>;
@@ -696,6 +714,8 @@ export declare type UseAgentWorkspaceResult = {
696
714
  fetchAgentTimeline: (invocationId: string) => Promise<AgentTimeline>;
697
715
  updateAgentInvocationName: (invocationId: string, invocationName: string) => Promise<void>;
698
716
  archiveAgent: (agentId: string) => Promise<Agent>;
717
+ unarchiveAgent: (agentId: string) => Promise<Agent>;
718
+ deleteAgent: (agentId: string) => Promise<void>;
699
719
  };
700
720
 
701
721
  export declare type WorkspacePhase = 'briefing' | 'running' | 'paused' | 'complete';