@arbor-education/agent-view-frontend 0.8.4 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),r=require("react"),W=require("classnames"),c=require("@arbor-education/design-system.components"),$e=require("@arbor-education/ask-arbor-chat-panel"),ea=require("pusher-js"),b={"generating-a-response":"generating-a-response",hitl:"hitl",paused:"paused",complete:"complete"},U={"generating-a-response":"generating-a-response",to_do:"to_do",hitl:"hitl",complete:"complete",failed:"failed"},H={briefing:"briefing",running:"running",paused:"paused",complete:"complete"},ae={agent:"agent",user:"user",system:"system"},ke={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",user_file:"user_file",link:"link"},Qn={user_file:"user_file"},dn={active:"active",complete:"complete",paused:"paused"},kt={in_progress:"in_progress",to_do:"to_do",requires_attention:"requires_attention",waiting_on_human:"waiting_on_human",available:"available"},Ue={[U.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[U.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[U.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[U["generating-a-response"]]:{label:"In progress",icon:"loader",color:"var(--color-brand-600)",spin:!0},[U.to_do]:{label:"To do",icon:"sparkles",color:"var(--color-brand-600)"}},es="var(--color-grey-600)",bt={[b["generating-a-response"]]:{status:b["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:"sparkles",color:Ue["generating-a-response"].color}},[b.hitl]:{status:b.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:Ue.hitl.icon,color:Ue.hitl.color}},[b.paused]:{status:b.paused,title:"Paused",dotColour:"green",statusIcon:{name:"circle-x",color:es}},[b.complete]:{status:b.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:Ue.complete.icon,color:Ue.complete.color}}},ta={name:"archive",color:es},na=[b["generating-a-response"],b.hitl,b.complete],sa="m4",aa="1",ts="msg-opening",qt="Unable to load agent tasks. Please try again.",ra="Unable to load context.",ia="Unable to load the resources for this agent",la="Unable to load this document. Please try again.",ns="Unable to load the timeline for this agent",oa="Unable to pause the agent. Please try again.",fn="Unable to archive the agent. Please try again.",ca="Archive this agent?",ua="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.",da="This agent is still in progress.",vn="Unable to unarchive the agent. Please try again.",ha="Restore this agent?",ga="Restoring returns this agent to the board as paused. It will not run chats or scheduled work until you resume it.",pa="Unable to delete the agent. Please try again.",ma="You do not have permission to delete this agent.",_a="This agent must be paused or archived before it can be deleted.",fa="This agent could not be found. It may have already been deleted.",va="Delete this agent?",xa="Deleting cannot be undone. This permanently removes the agent and its related data. It will not appear in Archived and cannot be restored.",wa="Unable to resume the agent. Please try again.",Aa="The agent was resumed but could not be woken. Send a message to continue.",Dn="You have been resumed after being paused. Reassess your current progress and continue your work from where you left off.",ka="Unable to rename the agent. Please try again.",Na="Something went wrong. Please try again.",ss="Unable to load agents. Please try again.",We="Loading tasks…",Hn="Loading agents…",ya="Task",ba={[H.briefing]:"Briefing",[H.running]:"Working",[H.paused]:"Paused",[H.complete]:"Complete"},Ca=[b["generating-a-response"],b.hitl,b.complete],Sa={[b["generating-a-response"]]:"Agents currently working on tasks for you.",[b.hitl]:"Agents that need your input before they can continue.",[b.paused]:"Agents that are paused until you resume them.",[b.complete]:"Agents that have finished their work."},Ea=()=>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)"})]}),ja=({status:e})=>{const t=bt[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})},Ra=()=>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:Ca.map(e=>{const t=bt[e];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(ja,{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:Sa[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(Ea,{})})]}),Ta=()=>({inProgress:[],needsInput:[],complete:[],failed:[],tasks:[]}),Ia=(e,t)=>({...e,children:t.length>0?t:void 0}),as=e=>{const t=[],s=[],a=[],i=[],o=[];for(const l of e){const p=l.children?as(l.children):Ta();if(t.push(...p.inProgress),s.push(...p.needsInput),a.push(...p.complete),i.push(...p.failed),l.status===U.hitl){s.push({...l,children:void 0});continue}if(l.status===U.complete){a.push({...l,children:void 0});continue}if(l.status===U.failed){i.push({...l,children:void 0});continue}if(l.status===U["generating-a-response"]){t.push({...l,children:void 0}),o.push(...p.tasks);continue}o.push(Ia(l,p.tasks))}return{inProgress:t,needsInput:s,complete:a,failed:i,tasks:o}},$n=e=>e===U.hitl?0:e===U.complete?1:e===U.failed?2:3,Oa=e=>e.map((t,s)=>({item:t,index:s})).sort((t,s)=>{const a=$n(t.item.status)-$n(s.item.status);return a!==0?a:t.index-s.index}).map(({item:t})=>t),hn=2,La=e=>{if(!e)return{canScrollUp:!1,canScrollDown:!1};const t=e.scrollHeight-e.clientHeight;return t<=hn?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:e.scrollTop>hn,canScrollDown:e.scrollTop<t-hn}},Pa=(e,t)=>{if(!e||!t)return null;const s=e.getBoundingClientRect(),a=t.getBoundingClientRect();return{top:a.top-s.top,left:a.left-s.left,width:a.width,height:a.height}},Yt=({children:e,className:t,contentClassName:s,scrollSelector:a,style:i,"aria-label":o})=>{const l=r.useRef(null),p=r.useRef(null),[u,A]=r.useState(!1),[f,x]=r.useState(!1),[_,w]=r.useState(null),g=()=>{var O;return a?((O=l.current)==null?void 0:O.querySelector(a))??null:p.current},C=()=>{const O=g(),k=La(O);if(A(m=>m===k.canScrollUp?m:k.canScrollUp),x(m=>m===k.canScrollDown?m:k.canScrollDown),a){const m=Pa(l.current,O);w(N=>(N==null?void 0:N.top)===(m==null?void 0:m.top)&&(N==null?void 0:N.left)===(m==null?void 0:m.left)&&(N==null?void 0:N.width)===(m==null?void 0:m.width)&&(N==null?void 0:N.height)===(m==null?void 0:m.height)?N:m)}else w(m=>m===null?m:null)};r.useLayoutEffect(()=>{C()}),r.useEffect(()=>{const O=l.current;if(!O)return;let k=null,m=null;const N=()=>{k==null||k.removeEventListener("scroll",C),m==null||m.disconnect(),m=null,k=null},L=G=>{if(G===k){C();return}if(N(),k=G,!k){C();return}k.addEventListener("scroll",C,{passive:!0}),m=new ResizeObserver(()=>C()),m.observe(k),k.firstElementChild instanceof HTMLElement&&m.observe(k.firstElementChild),C()};L(g());const $=new MutationObserver(()=>{L(g())});return $.observe(O,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",C),()=>{window.removeEventListener("resize",C),$.disconnect(),N()}},[a]);const T=O=>{const k=g();if(!k)return;const m=Math.max(k.clientHeight*.75,120);k.scrollBy({top:O==="up"?-m:m,behavior:"smooth"})},I=n.jsxs(n.Fragment,{children:[u&&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:()=>T("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:()=>T("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:a?n.jsxs(n.Fragment,{children:[e,_&&(u||f)&&n.jsx("div",{className:"scrollable-region__overlay",style:{top:_.top,left:_.left,width:_.width,height:_.height},children:I})]}):n.jsxs(n.Fragment,{children:[I,n.jsx("div",{ref:p,className:W("scrollable-region__viewport",s),children:e})]})})},Ma=48,Ua=({checklist:e})=>{const t=r.useRef(null),s=r.useRef(!1);return r.useLayoutEffect(()=>{const a=t.current;if(!a)return;const i=a.scrollHeight-a.scrollTop-a.clientHeight;(!s.current||i<=Ma)&&(a.scrollTop=a.scrollHeight,s.current=!0)},[e]),e.length===0?n.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):n.jsx(Yt,{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:Oa(e).map(a=>{const i=Ue[a.status];return n.jsxs("li",{className:W("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[n.jsx(c.Icon,{name:i.icon,size:16,color:i.color,className:i.spin?"agent-view__progress-icon--spinning":void 0,screenReaderText:`${i.label}:`}),n.jsxs("div",{className:"agent-view__progress-item-content",children:[n.jsx("span",{className:"agent-view__progress-label",children:a.task}),a.status!==U.complete&&n.jsx("span",{className:"agent-view__progress-description",children:a.description})]})]},a.task)})})})},rs=({open:e,isInProgress:t,isArchiving:s,error:a,onCancel:i,onConfirm:o})=>{const l=r.useId(),p=r.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:ca})}),n.jsxs(c.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":l,"aria-describedby":p,children:[n.jsx("p",{id:p,className:"archive-agent-confirm__lead",children:ua}),t?n.jsx("p",{className:"archive-agent-confirm__progress",children:da}):null,a?n.jsx("p",{className:"archive-agent-confirm__error",role:"alert",children:a}):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"})]})]})]})},is=({open:e,isDeleting:t,error:s,onCancel:a,onConfirm:i})=>{const o=r.useId(),l=r.useId();return n.jsxs(c.Modal,{open:e,closeHandler:a,className:"archive-agent-confirm",children:[n.jsx(c.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(c.Modal.Title,{id:o,children:va})}),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:xa}),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:a,children:"Cancel"}),n.jsx(c.Button,{variant:"secondary-destructive",size:"S",disabled:t,onClick:i,children:t?"Deleting…":"Delete"})]})]})]})},ls=({open:e,isUnarchiving:t,error:s,onCancel:a,onConfirm:i})=>{const o=r.useId(),l=r.useId();return n.jsxs(c.Modal,{open:e,closeHandler:a,className:"archive-agent-confirm",children:[n.jsx(c.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(c.Modal.Title,{id:o,children:ha})}),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:ga}),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:a,children:"Cancel"}),n.jsx(c.Button,{variant:"secondary",size:"S",disabled:t,onClick:i,children:t?"Restoring…":"Restore"})]})]})]})},Da=e=>e!==void 0&&e.some(t=>t.status===U.hitl),os=e=>e!==void 0&&e.length>0&&e.every(t=>t.status===U.complete),gn=(e,t)=>e.status===b.paused?os(t)?b.complete:b["generating-a-response"]:Da(t)?b.hitl:e.status===b.complete?b.complete:e.status===b.hitl?b.hitl:b["generating-a-response"],Ha=({prompts:e,classNamePrefix:t="agent-workspace",onSelect:s})=>e.length===0?null:n.jsx("div",{className:`${t}__chips`,children:e.map(a=>n.jsx("button",{type:"button",className:`${t}__chip`,onClick:()=>s(a),children:a},a))});class $a{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,a;if(!this.canSend())return null;(s=this.onAwaitingChange)==null||s.call(this,!0);try{const i=await this.connector.sendMessage(t.userMessage,t.uploadFiles,...t.onThinking?[{onThinking:t.onThinking}]:[]);return this.onTurn(i),{id:i.message.id,text:i.message.text,type:$e.CHAT_RESPONSE_TYPE_AGENT,...i.message.followUpPrompts?{followUpPrompts:i.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:Na,type:$e.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 Ba=({connector:e,phase:t,chatHistory:s,chatSessionKey:a,startQuery:i,clarificationMessage:o,enableUpload:l=!1,onTurn:p,onAwaitingChange:u,onClarificationPrompt:A,onDismissClarification:f})=>{const x=r.useMemo(()=>new $a(e,{canSend:()=>t===H.running,onTurn:p,onAwaitingChange:u}),[e,t,p,u]),_=t!==H.running,w=t===H.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(Ha,{prompts:o.followUpPrompts,onSelect:A}),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(Yt,{scrollSelector:".chat-panel-message-list",children:n.jsx($e.ChatPanel,{connector:x,chatHistory:s,startQuery:i,lockConversation:_,enableUpload:l,speechEnabled:w,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:w?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)})}),t===H.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===H.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."})]})]})},cs=({item:e,depth:t,canRequestInput:s,onAttentionItemClick:a})=>{const i=Ue[e.status],o=e.status.replace(/_/g,"-"),l=e.status===U.hitl&&s&&a,p=n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(c.Icon,{name:i.icon,size:16,color:i.color,className:i.spin?"agent-workspace__task-icon--spinning":void 0,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!==U.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:()=>a(e),children:p}):p,e.children&&e.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:e.children.map(u=>n.jsx(cs,{item:u,depth:t+1,canRequestInput:s,onAttentionItemClick:a},u.task))})]})},Nt=({items:e,ariaLabel:t,canRequestInput:s,onAttentionItemClick:a})=>n.jsx("ul",{className:"agent-workspace__task-list","aria-label":t,children:e.map(i=>n.jsx(cs,{item:i,depth:0,canRequestInput:s,onAttentionItemClick:a},i.task))}),Fa=({checklist:e,isLoading:t,error:s,phase:a,canRequestInput:i,onAttentionItemClick:o,adminMode:l=!1,context:p,contextLoaded:u=!1,contextLoading:A=!1,contextError:f=null,onContextSelect:x})=>{const[_,w]=r.useState("checklist"),g=r.useMemo(()=>e?as(e):null,[e]),C=()=>{w("context"),x==null||x()};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:_==="checklist",tabElementProps:{id:"agent-checklist-tab-checklist",onClick:()=>w("checklist")},children:"Checklist"}),n.jsx(c.Tabs.Item,{active:_==="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(Yt,{children:_==="context"?n.jsxs(n.Fragment,{children:[A&&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…"})]}),!A&&f&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:f}),!A&&!f&&u&&p==null&&n.jsx("p",{className:"agent-workspace__empty",children:"No context available."}),!A&&!f&&u&&p!==null&&p!==void 0&&n.jsx("pre",{className:"agent-workspace__context-json",children:JSON.stringify(p,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:We}),n.jsx("span",{children:We})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!t&&!s&&g&&n.jsxs(n.Fragment,{children:[g.inProgress.length>0&&n.jsxs("div",{className:"agent-workspace__task-group",children:[(g.needsInput.length>0||g.tasks.length>0||g.failed.length>0||g.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"In progress"}),n.jsx(Nt,{items:g.inProgress,ariaLabel:"In progress",canRequestInput:i,onAttentionItemClick:o})]}),g.needsInput.length>0&&n.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":g.inProgress.length>0}),children:[n.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),n.jsx(Nt,{items:g.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:i,onAttentionItemClick:o})]}),g.failed.length>0&&n.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":g.inProgress.length>0||g.needsInput.length>0}),children:[(g.inProgress.length>0||g.needsInput.length>0||g.tasks.length>0||g.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Failed"}),n.jsx(Nt,{items:g.failed,ariaLabel:"Failed tasks",canRequestInput:i,onAttentionItemClick:o})]}),g.tasks.length>0&&n.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":g.inProgress.length>0||g.needsInput.length>0||g.failed.length>0}),children:[(g.inProgress.length>0||g.needsInput.length>0||g.failed.length>0||g.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"To Do"}),n.jsx(Nt,{items:g.tasks,ariaLabel:"Upcoming tasks",canRequestInput:i,onAttentionItemClick:o})]}),g.complete.length>0&&n.jsxs("div",{className:W("agent-workspace__task-group",{"agent-workspace__task-group--following":g.inProgress.length>0||g.needsInput.length>0||g.tasks.length>0||g.failed.length>0}),children:[(g.inProgress.length>0||g.needsInput.length>0||g.tasks.length>0||g.failed.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Completed"}),n.jsx(Nt,{items:g.complete,ariaLabel:"Completed tasks",canRequestInput:i,onAttentionItemClick:o})]})]}),!t&&!s&&(!g||g.inProgress.length===0&&g.needsInput.length===0&&g.complete.length===0&&g.failed.length===0&&g.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:a===H.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})})]})},Ga=({resource:e,html:t,isLoading:s,error:a,onClose:i})=>{r.useEffect(()=>{if(!e)return;const l=c.SlideoverUtils.removeSlideover;return c.SlideoverUtils.removeSlideover=()=>{l(),i()},()=>{c.SlideoverUtils.removeSlideover=l}},[e,i]),r.useEffect(()=>{if(!e)return;const l=p=>{p.key==="Escape"&&c.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]);const o=r.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&&a&&n.jsx("p",{className:"resource-preview-slideover__error",role:"alert",children:a}),!s&&!a&&t!==null&&n.jsx("iframe",{className:"resource-preview-slideover__frame",title:e.title,sandbox:"",srcDoc:t})]})}]:[],[e,t,s,a]);return n.jsx("div",{className:"resource-preview-slideover",children:n.jsx(c.SlideoverManager,{slideovers:o})})},za={[ke.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[ke.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[ke.file]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[ke.user_file]:{icon:"upload",label:"File upload",color:"var(--color-semantic-caution-800)"},[ke.workflow]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[ke.link]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},qa=({resources:e,isLoading:t=!1,error:s=null,onOpenResource:a})=>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(Yt,{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=za[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:p=>{p.preventDefault(),a(i)},children:n.jsx(Bn,{resource:i,config:o,external:!0})}):n.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>a(i),children:n.jsx(Bn,{resource:i,config:o})})},i.id)})}),!t&&!s&&e.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),Bn=({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"})]}),pn=e=>{const t=Date.parse(e);return Number.isFinite(t)?t:0},Va=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),mn=e=>{const t=new Date(e);return Number.isFinite(t.getTime())?Va.format(t):e},Fn=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(" ")),Gn=e=>{const s=e.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,a=>a.split(/[_-]/).map(i=>i.toLowerCase()).join(" ")).toLowerCase();return s&&s.charAt(0).toUpperCase()+s.slice(1)},Ka=60*60*1e3,us=60*60*1e3,yt=24*us,xn=7*yt,Ya=e=>e.type!=="message-sent",Ja=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`},Wa=e=>{if(e.recurrence==="one_off")return"Scheduled to run once";const t=Ja(e.repeatIntervalSeconds);return t?`Repeating ${t}`:"Repeating run scheduled"},Xa=e=>e.recurrence==="one_off"?"scheduled-one-off":"scheduled-repeating",Za=(e,t,s=[])=>{const a=e.filter(Ya).map((l,p)=>({kind:"action",id:`action-${l.timestamp}-${p}`,timestampMs:pn(l.timestamp),item:l})),i=t.map(l=>({kind:"chat",id:l.sessionId,timestampMs:pn(l.timestamp),session:l})),o=s.map(l=>({kind:"scheduled",id:`scheduled-${l.scheduleId}`,timestampMs:pn(l.dueAt),run:l}));return[...a,...i,...o].sort((l,p)=>l.timestampMs-p.timestampMs||l.id.localeCompare(p.id))},Qa=e=>e>=xn?"weeks":e>=yt?"days":"hours",er=e=>{if(e<yt){const a=Math.max(1,Math.round(e/us));return a===1?"1 hour later":`${a} hours later`}if(e<xn){const a=Math.max(1,Math.round(e/yt));return a===1?"1 day later":`${a} days later`}const t=Math.max(1,Math.round(e/xn));if(t<5)return t===1?"1 week later":`${t} weeks later`;const s=Math.max(1,Math.round(e/(30*yt)));return s===1?"1 month later":`${s} months later`},tr=(e,t=Ka)=>{if(e.length===0)return[];const s=[e[0]];for(let a=1;a<e.length;a+=1){const i=e[a-1],o=e[a],l=o.timestampMs-i.timestampMs;l>=t&&s.push({kind:"gap",id:`gap-${i.id}-${o.id}`,durationMs:l,label:er(l),size:Qa(l)}),s.push(o)}return s},nr=e=>e.type==="checklist-updated"?"checklist":e.type==="status-transition"?"status":"note",sr=({timeline:e,isLoading:t,error:s,onOpenChatSession:a})=>{const i=(e==null?void 0:e.actionLog)??[],o=(e==null?void 0:e.chatSessions)??[],l=(e==null?void 0:e.scheduledRuns)??[],p=Za(i,o,l),u=tr(p),A=!t&&!s&&p.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||ns}),A&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!t&&!s&&!A&&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"})})]}),u.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=mn(f.session.timestamp),T=n.jsx(c.Icon,{name:"sparkles",size:16,color:"currentColor"});return n.jsxs("div",{className:"agent-timeline__chat-station",children:[a?n.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${C}`,onClick:()=>a(f.session.sessionId),children:T}):n.jsx("span",{className:"agent-timeline__chat-node agent-timeline__chat-node--static","aria-hidden":"true",children:T}),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=Xa(f.run),T=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:T}),n.jsx("span",{className:"agent-timeline__label-entry",children:Wa(f.run)}),n.jsx("span",{className:"agent-timeline__label-time",children:mn(f.run.dueAt)})]})]},f.id)}const{item:x}=f,_=nr(x),w=_==="checklist",g=_==="status";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${_}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${_}`,"aria-label":`${Fn(x.type)}: ${Gn(x.entry)}`,children:[w&&n.jsx(c.Icon,{name:"check-solid",size:16,color:"currentColor"}),g&&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:Fn(x.type)}),n.jsx("span",{className:"agent-timeline__label-entry",children:Gn(x.entry)}),n.jsx("span",{className:"agent-timeline__label-time",children:mn(x.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"})})]})]})]})},ar=["I'll get the details and come back to you","Skip this for now"],rr=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:ae.agent,text:t,followUpPrompts:e.clarificationPrompts??ar}},ir=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),lr=e=>e.kind===Qn.user_file?`<strong>${ir(e.text)}</strong>`:e.text,Ae=e=>({id:e.id,text:lr(e),type:e.author===ae.user?$e.CHAT_RESPONSE_TYPE_USER:e.author===ae.system?$e.CHAT_RESPONSE_TYPE_INFO:$e.CHAT_RESPONSE_TYPE_AGENT,...e.followUpPrompts?{followUpPrompts:e.followUpPrompts}:{}}),wn="MESSAGE_TYPE_REPOLL",ds="agentUi:update",Nn="arbor-agent-",Ne={all:"ALL",checklist:"CHECKLIST",resources:"RESOURCES",chat:"CHAT",timeline:"TIMELINE"},or=new Set(Object.values(Ne)),hs=(e,t)=>`${e.endsWith("-")?e:`${e}-`}${t}`,cr=e=>typeof e=="string"&&or.has(e)?e:Ne.all,ur=e=>{if(!e||typeof e!="object")return null;const t=e;return t.type!==wn?null:{type:wn,target:cr(t.target)}},gs=e=>{const t=Array.isArray(e)?e:[e],s=[];for(const a of t){const i=ur(a);i&&s.push(i)}return s},dr=({enabled:e,channelPrefix:t,agentId:s,subscribeToPusher:a,onRepoll:i})=>{const o=r.useRef(i),l=t==null?void 0:t.trim(),p=!!(e&&a&&l&&s.trim());return r.useEffect(()=>{o.current=i},[i]),r.useEffect(()=>{if(!p||!a||!l)return;const u=a(hs(l,s),ds,A=>{for(const f of gs(A))o.current(f.target)});return()=>{u()}},[p,l,s,a]),p};let de=null,An="",kn="",Kt=0;const hr=()=>{window.setTimeout(()=>{Kt>0||!de||(de.disconnect(),de=null,An="",kn="")},0)},gr=(e,t)=>(de&&(An!==e||kn!==t)&&(de.disconnect(),de=null),de||(de=new ea(e,{cluster:t}),An=e,kn=t),Kt+=1,de),pr=()=>{Kt=Math.max(0,Kt-1),hr()},ps=({enabled:e,key:t,cluster:s,isAdmin:a=!1})=>{const i=r.useRef(null),o=t.trim(),l=s.trim(),p=e&&!!o&&!!l;return r.useEffect(()=>{if(!p){i.current=null;return}const u=gr(o,l);return i.current=u,()=>{i.current=null,pr()}},[p,o,l]),r.useMemo(()=>{if(p)return(u,A,f)=>{const x=i.current??de;if(!x)return a&&console.log(`[pusher] subscribe skipped — client not ready for "${u}"`),()=>{};const _=x.subscribe(u);return _.bind(A,f),()=>{_.unbind(A,f),x.unsubscribe(u)}}},[p,a])};class He extends Error{constructor(t,s,a){super(a??`Agent service request failed (${t})`),this.name="AgentServiceError",this.status=t,this.detail=s}}const mr="/api/v1",F={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},q={GET:"GET",POST:"POST",PATCH:"PATCH",DELETE:"DELETE"},_r={error:"error"},fr={user:"user"},De={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},vr=100,ms=e=>{switch(e){case dn.paused:return b.paused;case dn.complete:return b.complete;case b.hitl:return b.hitl;case dn.active:case b["generating-a-response"]:return b["generating-a-response"];default:return b["generating-a-response"]}},_s=e=>{switch(e){case kt.requires_attention:case kt.waiting_on_human:case U.hitl:return U.hitl;case kt.in_progress:case U["generating-a-response"]:return U["generating-a-response"];case kt.to_do:case kt.available:case U.to_do:return U.to_do;case U.failed:case U.complete:return e;default:return U.to_do}},yn=e=>({ref:e.name,display_name:e.display_name,agent_intent:e.agent_intent??"",description:e.description}),xr=e=>({id:e.id,name:e.name,...e.has_run_before?{hasRunBefore:e.has_run_before}:{}}),wr=new Set(Object.values(ke)),Ar=e=>wr.has(e)?e:ke.document_html,fs=e=>({id:e.id,type:Ar(e.type),title:e.title,createdDatetime:e.created_datetime,lastUpdatedDatetime:e.last_updated_datetime,misRecordUrl:e.mis_record_url}),vs=e=>({resources:e.resources.map(fs),pageNumber:e.page_number,pageSize:e.page_size,totalRecords:e.total_records}),xs=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}))}),ye=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:ms(e.status),archivedAt:e.archived_at??null,context_ref:e.context_ref??null,checklist_ref:e.checklist_ref??null}},bn=e=>{var t;return{task:e.item??e.task??e.name??e.label??ya,status:_s(e.status),description:e.description??"",...e.prompt?{prompt:e.prompt}:{},...(t=e.follow_up_prompts)!=null&&t.length?{clarificationPrompts:e.follow_up_prompts}:{}}},kr=e=>Array.isArray(e)?e:e.checklist_items??e.checklist??e.items??[],Jt=(e,t,s)=>{var o;const a=!Array.isArray(t)&&(t.opening_message||(o=t.opening_follow_up_prompts)!=null&&o.length)?t:s,i=a?Ct(a):void 0;return{invocation_id:e,checklist:kr(t).map(bn),...i?{openingMessage:i}:{}}},Nr=(e,t)=>{const s=Ct(t);return{invocation_id:t.invocation_id??e,checklist:(t.checklist_items??[]).map(bn),...s?{openingMessage:s}:{}}},Ct=e=>{var s,a;const t=(s=e.opening_message)==null?void 0:s.trim();if(t)return{id:ts,author:ae.agent,text:t,...(a=e.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:e.opening_follow_up_prompts}:{}}},yr=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)){const s=t.filter(a=>!!a&&typeof a=="object"&&typeof a.text=="string").map(a=>a.text);if(s.length>0)return s.join(`
2
- `)}}catch{}return e},br=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"),J=require("classnames"),u=require("@arbor-education/design-system.components"),De=require("@arbor-education/ask-arbor-chat-panel"),na=require("pusher-js"),C={"generating-a-response":"generating-a-response",hitl:"hitl",paused:"paused",complete:"complete"},U={"generating-a-response":"generating-a-response",to_do:"to_do",hitl:"hitl",complete:"complete",failed:"failed"},H={briefing:"briefing",running:"running",paused:"paused",complete:"complete"},ae={agent:"agent",user:"user",system:"system"},be={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",user_file:"user_file",link:"link"},es={user_file:"user_file"},gn={active:"active",complete:"complete",paused:"paused"},Nt={in_progress:"in_progress",to_do:"to_do",requires_attention:"requires_attention",waiting_on_human:"waiting_on_human",available:"available"},Pe={[U.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[U.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[U.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[U["generating-a-response"]]:{label:"In progress",icon:"loader",color:"var(--color-brand-600)",spin:!0},[U.to_do]:{label:"To do",icon:"sparkles",color:"var(--color-brand-600)"}},ts="var(--color-grey-600)",Ct={[C["generating-a-response"]]:{status:C["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:"sparkles",color:Pe["generating-a-response"].color}},[C.hitl]:{status:C.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:Pe.hitl.icon,color:Pe.hitl.color}},[C.paused]:{status:C.paused,title:"Paused",dotColour:"green",statusIcon:{name:"circle-x",color:ts}},[C.complete]:{status:C.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:Pe.complete.icon,color:Pe.complete.color}}},sa={name:"archive",color:ts},aa=[C["generating-a-response"],C.hitl,C.complete],ra="m4",ia="1",ns="msg-opening",Wt="Unable to load agent tasks. Please try again.",la="Unable to load context.",oa="Unable to load the resources for this agent",ca="Unable to load this document. Please try again.",ss="Unable to load the timeline for this agent",ua="Unable to pause the agent. Please try again.",xn="Unable to archive the agent. Please try again.",da="Archive this agent?",ha="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.",ga="This agent is still in progress.",wn="Unable to unarchive the agent. Please try again.",pa="Restore this agent?",ma="Restoring returns this agent to the board as paused. It will not run chats or scheduled work until you resume it.",_a="Unable to delete the agent. Please try again.",fa="You do not have permission to delete this agent.",va="This agent must be paused or archived before it can be deleted.",xa="This agent could not be found. It may have already been deleted.",wa="Delete this agent?",Aa="Deleting cannot be undone. This permanently removes the agent and its related data. It will not appear in Archived and cannot be restored.",ka="Unable to resume the agent. Please try again.",Na="The agent was resumed but could not be woken. Send a message to continue.",Hn="You have been resumed after being paused. Reassess your current progress and continue your work from where you left off.",ya="Unable to rename the agent. Please try again.",ba="Something went wrong. Please try again.",as="Unable to load agents. Please try again.",nt="Loading tasks…",$n="Loading agents…",Ca="Task",Ea={[H.briefing]:"Briefing",[H.running]:"Working",[H.paused]:"Paused",[H.complete]:"Complete"},rs="all",Sa=[C["generating-a-response"],C.hitl,C.complete],ja={[C["generating-a-response"]]:"Agents currently working on tasks for you.",[C.hitl]:"Agents that need your input before they can continue.",[C.paused]:"Agents that are paused until you resume them.",[C.complete]:"Agents that have finished their work."},Ra=()=>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)"})]}),Ta=({status:e})=>{const t=Ct[e];return t.statusIcon?n.jsx(u.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,screenReaderText:t.title}):n.jsx(u.Dot,{colour:t.dotColour,label:t.title})},Ia=()=>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(u.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:Sa.map(e=>{const t=Ct[e];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(Ta,{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:ja[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(Ra,{})})]}),Oa=()=>({inProgress:[],needsInput:[],complete:[],failed:[],tasks:[]}),La=(e,t)=>({...e,children:t.length>0?t:void 0}),is=e=>{const t=[],s=[],r=[],i=[],c=[];for(const l of e){const p=l.children?is(l.children):Oa();if(t.push(...p.inProgress),s.push(...p.needsInput),r.push(...p.complete),i.push(...p.failed),l.status===U.hitl){s.push({...l,children:void 0});continue}if(l.status===U.complete){r.push({...l,children:void 0});continue}if(l.status===U.failed){i.push({...l,children:void 0});continue}if(l.status===U["generating-a-response"]){t.push({...l,children:void 0}),c.push(...p.tasks);continue}c.push(La(l,p.tasks))}return{inProgress:t,needsInput:s,complete:r,failed:i,tasks:c}},Bn=e=>e===U.hitl?0:e===U.complete?1:e===U.failed?2:3,Pa=e=>e.map((t,s)=>({item:t,index:s})).sort((t,s)=>{const r=Bn(t.item.status)-Bn(s.item.status);return r!==0?r:t.index-s.index}).map(({item:t})=>t),pn=2,Ma=e=>{if(!e)return{canScrollUp:!1,canScrollDown:!1};const t=e.scrollHeight-e.clientHeight;return t<=pn?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:e.scrollTop>pn,canScrollDown:e.scrollTop<t-pn}},Ua=(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}},Qt=({children:e,className:t,contentClassName:s,scrollSelector:r,style:i,"aria-label":c})=>{const l=a.useRef(null),p=a.useRef(null),[o,A]=a.useState(!1),[_,k]=a.useState(!1),[f,v]=a.useState(null),g=()=>{var j;return r?((j=l.current)==null?void 0:j.querySelector(r))??null:p.current},b=()=>{const j=g(),N=Ma(j);if(A(m=>m===N.canScrollUp?m:N.canScrollUp),k(m=>m===N.canScrollDown?m:N.canScrollDown),r){const m=Ua(l.current,j);v(w=>(w==null?void 0:w.top)===(m==null?void 0:m.top)&&(w==null?void 0:w.left)===(m==null?void 0:m.left)&&(w==null?void 0:w.width)===(m==null?void 0:m.width)&&(w==null?void 0:w.height)===(m==null?void 0:m.height)?w:m)}else v(m=>m===null?m:null)};a.useLayoutEffect(()=>{b()}),a.useEffect(()=>{const j=l.current;if(!j)return;let N=null,m=null;const w=()=>{N==null||N.removeEventListener("scroll",b),m==null||m.disconnect(),m=null,N=null},T=X=>{if(X===N){b();return}if(w(),N=X,!N){b();return}N.addEventListener("scroll",b,{passive:!0}),m=new ResizeObserver(()=>b()),m.observe(N),N.firstElementChild instanceof HTMLElement&&m.observe(N.firstElementChild),b()};T(g());const $=new MutationObserver(()=>{T(g())});return $.observe(j,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",b),()=>{window.removeEventListener("resize",b),$.disconnect(),w()}},[r]);const O=j=>{const N=g();if(!N)return;const m=Math.max(N.clientHeight*.75,120);N.scrollBy({top:j==="up"?-m:m,behavior:"smooth"})},L=n.jsxs(n.Fragment,{children:[o&&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:()=>O("up"),children:n.jsx(u.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),_&&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:()=>O("down"),children:n.jsx(u.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return n.jsx("div",{ref:l,className:J("scrollable-region",t),style:i,"aria-label":c,children:r?n.jsxs(n.Fragment,{children:[e,f&&(o||_)&&n.jsx("div",{className:"scrollable-region__overlay",style:{top:f.top,left:f.left,width:f.width,height:f.height},children:L})]}):n.jsxs(n.Fragment,{children:[L,n.jsx("div",{ref:p,className:J("scrollable-region__viewport",s),children:e})]})})},Da=48,Ha=({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<=Da)&&(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(Qt,{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:Pa(e).map(r=>{const i=Pe[r.status];return n.jsxs("li",{className:J("agent-view__progress-item",`agent-view__progress-item--${r.status.replace(/_/g,"-")}`),children:[n.jsx(u.Icon,{name:i.icon,size:16,color:i.color,className:i.spin?"agent-view__progress-icon--spinning":void 0,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!==U.complete&&n.jsx("span",{className:"agent-view__progress-description",children:r.description})]})]},r.task)})})})},ls=({open:e,isInProgress:t,isArchiving:s,error:r,onCancel:i,onConfirm:c})=>{const l=a.useId(),p=a.useId();return n.jsxs(u.Modal,{open:e,closeHandler:i,className:"archive-agent-confirm",children:[n.jsx(u.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(u.Modal.Title,{id:l,children:da})}),n.jsxs(u.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":l,"aria-describedby":p,children:[n.jsx("p",{id:p,className:"archive-agent-confirm__lead",children:ha}),t?n.jsx("p",{className:"archive-agent-confirm__progress",children:ga}):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(u.Button,{variant:"secondary",size:"S",disabled:s,onClick:i,children:"Cancel"}),n.jsx(u.Button,{variant:"secondary-destructive",size:"S",disabled:s,onClick:c,children:s?"Archiving…":"Archive"})]})]})]})},os=({open:e,isDeleting:t,error:s,onCancel:r,onConfirm:i})=>{const c=a.useId(),l=a.useId();return n.jsxs(u.Modal,{open:e,closeHandler:r,className:"archive-agent-confirm",children:[n.jsx(u.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(u.Modal.Title,{id:c,children:wa})}),n.jsxs(u.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":c,"aria-describedby":l,children:[n.jsx("p",{id:l,className:"archive-agent-confirm__lead",children:Aa}),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(u.Button,{variant:"secondary",size:"S",disabled:t,onClick:r,children:"Cancel"}),n.jsx(u.Button,{variant:"secondary-destructive",size:"S",disabled:t,onClick:i,children:t?"Deleting…":"Delete"})]})]})]})},cs=({open:e,isUnarchiving:t,error:s,onCancel:r,onConfirm:i})=>{const c=a.useId(),l=a.useId();return n.jsxs(u.Modal,{open:e,closeHandler:r,className:"archive-agent-confirm",children:[n.jsx(u.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(u.Modal.Title,{id:c,children:pa})}),n.jsxs(u.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":c,"aria-describedby":l,children:[n.jsx("p",{id:l,className:"archive-agent-confirm__lead",children:ma}),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(u.Button,{variant:"secondary",size:"S",disabled:t,onClick:r,children:"Cancel"}),n.jsx(u.Button,{variant:"secondary",size:"S",disabled:t,onClick:i,children:t?"Restoring…":"Restore"})]})]})]})},$a=e=>e!==void 0&&e.some(t=>t.status===U.hitl),us=e=>e!==void 0&&e.length>0&&e.every(t=>t.status===U.complete),mn=(e,t)=>e.status===C.paused?us(t)?C.complete:C["generating-a-response"]:$a(t)?C.hitl:e.status===C.complete?C.complete:e.status===C.hitl?C.hitl:C["generating-a-response"],Ba=({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 Fa{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,...t.onThinking?[{onThinking:t.onThinking}]:[]);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:ba,type:De.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 Ga=({connector:e,phase:t,chatHistory:s,chatSessionKey:r,startQuery:i,clarificationMessage:c,readOnly:l=!1,enableUpload:p=!1,onTurn:o,onAwaitingChange:A,onClarificationPrompt:_,onDismissClarification:k})=>{const f=a.useMemo(()=>new Fa(e,{canSend:()=>!l&&t===H.running,onTurn:o,onAwaitingChange:A}),[e,t,l,o,A]),v=l||t!==H.running,g=!l&&t===H.running;let b="The agent is not accepting messages.";return g&&(b="Message the agent, paste a link, or attach a file…"),l&&(b="You can view this conversation but cannot send messages."),n.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[c&&n.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[n.jsx("p",{className:"agent-workspace__clarification-text",children:c.text}),c.followUpPrompts&&n.jsx(Ba,{prompts:c.followUpPrompts,onSelect:_}),n.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:k,children:"Dismiss"})]}),n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(Qt,{scrollSelector:".chat-panel-message-list",children:n.jsx(De.ChatPanel,{connector:f,chatHistory:s,startQuery:i,lockConversation:v,enableUpload:p,speechEnabled:g,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:b},r)})}),l&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(u.Icon,{name:"eye",size:16,color:"var(--color-grey-700)"}),n.jsx("span",{children:"View only — you cannot interact with this agent."})]}),t===H.paused&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(u.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===H.complete&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(u.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),n.jsx("span",{children:"The agent has finished."})]})]})},ds=({item:e,depth:t,canRequestInput:s,onAttentionItemClick:r})=>{const i=Pe[e.status],c=e.status.replace(/_/g,"-"),l=e.status===U.hitl&&s&&r,p=n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(u.Icon,{name:i.icon,size:16,color:i.color,className:i.spin?"agent-workspace__task-icon--spinning":void 0,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!==U.complete&&e.description&&n.jsx("span",{className:"agent-workspace__task-description",children:e.description})]})]});return n.jsxs("li",{className:J("agent-workspace__task",`agent-workspace__task--${c}`,{"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:p}):p,e.children&&e.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:e.children.map(o=>n.jsx(ds,{item:o,depth:t+1,canRequestInput:s,onAttentionItemClick:r},o.task))})]})},yt=({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(ds,{item:i,depth:0,canRequestInput:s,onAttentionItemClick:r},i.task))}),za=({checklist:e,isLoading:t,error:s,phase:r,canRequestInput:i,onAttentionItemClick:c,adminMode:l=!1,context:p,contextLoaded:o=!1,contextLoading:A=!1,contextError:_=null,onContextSelect:k})=>{const[f,v]=a.useState("checklist"),g=a.useMemo(()=>e?is(e):null,[e]),b=()=>{v("context"),k==null||k()};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(u.Tabs,{className:"agent-workspace__checklist-tabs","aria-label":"Checklist panel",children:[n.jsx(u.Tabs.Item,{active:f==="checklist",tabElementProps:{id:"agent-checklist-tab-checklist",onClick:()=>v("checklist")},children:"Checklist"}),n.jsx(u.Tabs.Item,{active:f==="context",tabElementProps:{id:"agent-checklist-tab-context",onClick:b},children:"Context"})]}):n.jsx(u.Heading,{level:4,children:"Checklist"})}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsx(Qt,{children:f==="context"?n.jsxs(n.Fragment,{children:[A&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(u.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…"})]}),!A&&_&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:_}),!A&&!_&&o&&p==null&&n.jsx("p",{className:"agent-workspace__empty",children:"No context available."}),!A&&!_&&o&&p!==null&&p!==void 0&&n.jsx("pre",{className:"agent-workspace__context-json",children:JSON.stringify(p,null,2)})]}):n.jsxs(n.Fragment,{children:[t&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:nt}),n.jsx("span",{children:nt})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!t&&!s&&g&&n.jsxs(n.Fragment,{children:[g.inProgress.length>0&&n.jsxs("div",{className:"agent-workspace__task-group",children:[(g.needsInput.length>0||g.tasks.length>0||g.failed.length>0||g.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"In progress"}),n.jsx(yt,{items:g.inProgress,ariaLabel:"In progress",canRequestInput:i,onAttentionItemClick:c})]}),g.needsInput.length>0&&n.jsxs("div",{className:J("agent-workspace__task-group",{"agent-workspace__task-group--following":g.inProgress.length>0}),children:[n.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),n.jsx(yt,{items:g.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:i,onAttentionItemClick:c})]}),g.failed.length>0&&n.jsxs("div",{className:J("agent-workspace__task-group",{"agent-workspace__task-group--following":g.inProgress.length>0||g.needsInput.length>0}),children:[(g.inProgress.length>0||g.needsInput.length>0||g.tasks.length>0||g.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Failed"}),n.jsx(yt,{items:g.failed,ariaLabel:"Failed tasks",canRequestInput:i,onAttentionItemClick:c})]}),g.tasks.length>0&&n.jsxs("div",{className:J("agent-workspace__task-group",{"agent-workspace__task-group--following":g.inProgress.length>0||g.needsInput.length>0||g.failed.length>0}),children:[(g.inProgress.length>0||g.needsInput.length>0||g.failed.length>0||g.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"To Do"}),n.jsx(yt,{items:g.tasks,ariaLabel:"Upcoming tasks",canRequestInput:i,onAttentionItemClick:c})]}),g.complete.length>0&&n.jsxs("div",{className:J("agent-workspace__task-group",{"agent-workspace__task-group--following":g.inProgress.length>0||g.needsInput.length>0||g.tasks.length>0||g.failed.length>0}),children:[(g.inProgress.length>0||g.needsInput.length>0||g.tasks.length>0||g.failed.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Completed"}),n.jsx(yt,{items:g.complete,ariaLabel:"Completed tasks",canRequestInput:i,onAttentionItemClick:c})]})]}),!t&&!s&&(!g||g.inProgress.length===0&&g.needsInput.length===0&&g.complete.length===0&&g.failed.length===0&&g.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:r===H.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})})]})},qa=({resource:e,html:t,isLoading:s,error:r,onClose:i})=>{a.useEffect(()=>{if(!e)return;const l=u.SlideoverUtils.removeSlideover;return u.SlideoverUtils.removeSlideover=()=>{l(),i()},()=>{u.SlideoverUtils.removeSlideover=l}},[e,i]),a.useEffect(()=>{if(!e)return;const l=p=>{p.key==="Escape"&&u.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]);const c=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(u.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(u.SlideoverManager,{slideovers:c})})},Va={[be.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[be.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[be.file]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[be.user_file]:{icon:"upload",label:"File upload",color:"var(--color-semantic-caution-800)"},[be.workflow]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[be.link]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},Ka=({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(u.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(Qt,{children:[t&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(u.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 c=Va[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:p=>{p.preventDefault(),r(i)},children:n.jsx(Fn,{resource:i,config:c,external:!0})}):n.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>r(i),children:n.jsx(Fn,{resource:i,config:c})})},i.id)})}),!t&&!s&&e.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),Fn=({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(u.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(u.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]}),_n=e=>{const t=Date.parse(e);return Number.isFinite(t)?t:0},Ya=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),fn=e=>{const t=new Date(e);return Number.isFinite(t.getTime())?Ya.format(t):e},Gn=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(" ")),zn=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)},Ja=60*60*1e3,hs=60*60*1e3,bt=24*hs,An=7*bt,Wa=e=>e.type!=="message-sent",Xa=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`},Za=e=>{if(e.recurrence==="one_off")return"Scheduled to run once";const t=Xa(e.repeatIntervalSeconds);return t?`Repeating ${t}`:"Repeating run scheduled"},Qa=e=>e.recurrence==="one_off"?"scheduled-one-off":"scheduled-repeating",er=(e,t,s=[])=>{const r=e.filter(Wa).map((l,p)=>({kind:"action",id:`action-${l.timestamp}-${p}`,timestampMs:_n(l.timestamp),item:l})),i=t.map(l=>({kind:"chat",id:l.sessionId,timestampMs:_n(l.timestamp),session:l})),c=s.map(l=>({kind:"scheduled",id:`scheduled-${l.scheduleId}`,timestampMs:_n(l.dueAt),run:l}));return[...r,...i,...c].sort((l,p)=>l.timestampMs-p.timestampMs||l.id.localeCompare(p.id))},tr=e=>e>=An?"weeks":e>=bt?"days":"hours",nr=e=>{if(e<bt){const r=Math.max(1,Math.round(e/hs));return r===1?"1 hour later":`${r} hours later`}if(e<An){const r=Math.max(1,Math.round(e/bt));return r===1?"1 day later":`${r} days later`}const t=Math.max(1,Math.round(e/An));if(t<5)return t===1?"1 week later":`${t} weeks later`;const s=Math.max(1,Math.round(e/(30*bt)));return s===1?"1 month later":`${s} months later`},sr=(e,t=Ja)=>{if(e.length===0)return[];const s=[e[0]];for(let r=1;r<e.length;r+=1){const i=e[r-1],c=e[r],l=c.timestampMs-i.timestampMs;l>=t&&s.push({kind:"gap",id:`gap-${i.id}-${c.id}`,durationMs:l,label:nr(l),size:tr(l)}),s.push(c)}return s},ar=e=>e.type==="checklist-updated"?"checklist":e.type==="status-transition"?"status":"note",rr=({timeline:e,isLoading:t,error:s,onOpenChatSession:r})=>{const i=(e==null?void 0:e.actionLog)??[],c=(e==null?void 0:e.chatSessions)??[],l=(e==null?void 0:e.scheduledRuns)??[],p=er(i,c,l),o=sr(p),A=!t&&!s&&p.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||ss}),A&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!t&&!s&&!A&&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(u.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"})})]}),o.map(_=>{if(_.kind==="gap")return n.jsxs("div",{className:`agent-timeline__gap agent-timeline__gap--${_.size}`,role:"separator","aria-label":_.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:_.label})]},_.id);if(_.kind==="chat"){const b=fn(_.session.timestamp),O=n.jsx(u.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 ${b}`,onClick:()=>r(_.session.sessionId),children:O}):n.jsx("span",{className:"agent-timeline__chat-node agent-timeline__chat-node--static","aria-hidden":"true",children:O}),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:b})]})]},_.id)}if(_.kind==="scheduled"){const b=Qa(_.run),O=_.run.recurrence==="one_off"?"One-off run":"Repeating run";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${b}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsx("span",{className:`agent-timeline__station-node agent-timeline__station-node--${b}`,"aria-hidden":"true",children:n.jsx(u.Icon,{name:"date",size:16,color:"currentColor"})})}),n.jsxs("div",{className:"agent-timeline__label",children:[n.jsx("strong",{className:"agent-timeline__label-type",children:O}),n.jsx("span",{className:"agent-timeline__label-entry",children:Za(_.run)}),n.jsx("span",{className:"agent-timeline__label-time",children:fn(_.run.dueAt)})]})]},_.id)}const{item:k}=_,f=ar(k),v=f==="checklist",g=f==="status";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${f}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${f}`,"aria-label":`${Gn(k.type)}: ${zn(k.entry)}`,children:[v&&n.jsx(u.Icon,{name:"check-solid",size:16,color:"currentColor"}),g&&n.jsx(u.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:Gn(k.type)}),n.jsx("span",{className:"agent-timeline__label-entry",children:zn(k.entry)}),n.jsx("span",{className:"agent-timeline__label-time",children:fn(k.timestamp)})]})]},_.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(u.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"})})]})]})]})},ir=["I'll get the details and come back to you","Skip this for now"],lr=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:ae.agent,text:t,followUpPrompts:e.clarificationPrompts??ir}},or=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),cr=e=>e.kind===es.user_file?`<strong>${or(e.text)}</strong>`:e.text,ye=e=>({id:e.id,text:cr(e),type:e.author===ae.user?De.CHAT_RESPONSE_TYPE_USER:e.author===ae.system?De.CHAT_RESPONSE_TYPE_INFO:De.CHAT_RESPONSE_TYPE_AGENT,...e.followUpPrompts?{followUpPrompts:e.followUpPrompts}:{}}),kn="MESSAGE_TYPE_REPOLL",gs="agentUi:update",bn="arbor-agent-",Ce={all:"ALL",checklist:"CHECKLIST",resources:"RESOURCES",chat:"CHAT",timeline:"TIMELINE"},ur=new Set(Object.values(Ce)),ps=(e,t)=>`${e.endsWith("-")?e:`${e}-`}${t}`,dr=e=>typeof e=="string"&&ur.has(e)?e:Ce.all,hr=e=>{if(!e||typeof e!="object")return null;const t=e;return t.type!==kn?null:{type:kn,target:dr(t.target)}},ms=e=>{const t=Array.isArray(e)?e:[e],s=[];for(const r of t){const i=hr(r);i&&s.push(i)}return s},gr=({enabled:e,channelPrefix:t,agentId:s,subscribeToPusher:r,onRepoll:i})=>{const c=a.useRef(i),l=t==null?void 0:t.trim(),p=!!(e&&r&&l&&s.trim());return a.useEffect(()=>{c.current=i},[i]),a.useEffect(()=>{if(!p||!r||!l)return;const o=r(ps(l,s),gs,A=>{for(const _ of ms(A))c.current(_.target)});return()=>{o()}},[p,l,s,r]),p};let de=null,Nn="",yn="",Zt=0;const pr=()=>{window.setTimeout(()=>{Zt>0||!de||(de.disconnect(),de=null,Nn="",yn="")},0)},mr=(e,t)=>(de&&(Nn!==e||yn!==t)&&(de.disconnect(),de=null),de||(de=new na(e,{cluster:t}),Nn=e,yn=t),Zt+=1,de),_r=()=>{Zt=Math.max(0,Zt-1),pr()},_s=({enabled:e,key:t,cluster:s,isAdmin:r=!1})=>{const i=a.useRef(null),c=t.trim(),l=s.trim(),p=e&&!!c&&!!l;return a.useEffect(()=>{if(!p){i.current=null;return}const o=mr(c,l);return i.current=o,()=>{i.current=null,_r()}},[p,c,l]),a.useMemo(()=>{if(p)return(o,A,_)=>{const k=i.current??de;if(!k)return r&&console.log(`[pusher] subscribe skipped — client not ready for "${o}"`),()=>{};const f=k.subscribe(o);return f.bind(A,_),()=>{f.unbind(A,_),k.unsubscribe(o)}}},[p,r])};class Ue extends Error{constructor(t,s,r){super(r??`Agent service request failed (${t})`),this.name="AgentServiceError",this.status=t,this.detail=s}}const fr="/api/v1",G={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},q={GET:"GET",POST:"POST",PATCH:"PATCH",DELETE:"DELETE"},vr={error:"error"},xr={user:"user"},Me={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},wr=100,fs=e=>{switch(e){case gn.paused:return C.paused;case gn.complete:return C.complete;case C.hitl:return C.hitl;case gn.active:case C["generating-a-response"]:return C["generating-a-response"];default:return C["generating-a-response"]}},vs=e=>{switch(e){case Nt.requires_attention:case Nt.waiting_on_human:case U.hitl:return U.hitl;case Nt.in_progress:case U["generating-a-response"]:return U["generating-a-response"];case Nt.to_do:case Nt.available:case U.to_do:return U.to_do;case U.failed:case U.complete:return e;default:return U.to_do}},Cn=e=>({ref:e.name,display_name:e.display_name,agent_intent:e.agent_intent??"",description:e.description}),Ar=e=>({id:e.id,name:e.name,...e.has_run_before?{hasRunBefore:e.has_run_before}:{}}),kr=new Set(Object.values(be)),Nr=e=>kr.has(e)?e:be.document_html,xs=e=>({id:e.id,type:Nr(e.type),title:e.title,createdDatetime:e.created_datetime,lastUpdatedDatetime:e.last_updated_datetime,misRecordUrl:e.mis_record_url}),ws=e=>({resources:e.resources.map(xs),pageNumber:e.page_number,pageSize:e.page_size,totalRecords:e.total_records}),As=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}))}),Ee=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,usable:e.usable??!1,status:fs(e.status),archivedAt:e.archived_at??null,context_ref:e.context_ref??null,checklist_ref:e.checklist_ref??null}},En=e=>{var t;return{task:e.item??e.task??e.name??e.label??Ca,status:vs(e.status),description:e.description??"",...e.prompt?{prompt:e.prompt}:{},...(t=e.follow_up_prompts)!=null&&t.length?{clarificationPrompts:e.follow_up_prompts}:{}}},yr=e=>Array.isArray(e)?e:e.checklist_items??e.checklist??e.items??[],en=(e,t,s)=>{var c;const r=!Array.isArray(t)&&(t.opening_message||(c=t.opening_follow_up_prompts)!=null&&c.length)?t:s,i=r?Et(r):void 0;return{invocation_id:e,checklist:yr(t).map(En),...i?{openingMessage:i}:{}}},br=(e,t)=>{const s=Et(t);return{invocation_id:t.invocation_id??e,checklist:(t.checklist_items??[]).map(En),...s?{openingMessage:s}:{}}},Et=e=>{var s,r;const t=(s=e.opening_message)==null?void 0:s.trim();if(t)return{id:ns,author:ae.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},Er=e=>{const t=e.trim();return t.length>0?`File upload
3
3
 
4
- ${t}`:"File upload"},zn=e=>{var s;const t=(s=e.filename)==null?void 0:s.trim();return t||null},ws=e=>e.filter(t=>zn(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=zn(t);return s&&t.role==="user"?{id:t.message_id,author:ae.user,kind:Qn.user_file,text:s}:{id:t.message_id,author:t.role==="user"?ae.user:ae.agent,text:t.content}}),Cr=/:invocationId\b/g,Sr=/:resourceId\b/g,Er=e=>e.trim().replace(/^Bearer\s+/i,""),qn=e=>e.endsWith("/")?e.slice(0,-1):e;class Wt{constructor(t){var a;this.baseUrl=qn(t.baseUrl??"");const s=(a=t.token)==null?void 0:a.trim();this.token=s?Er(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(q.GET,this.resolveUrl("agentDefinitions",F.agentDefinitions))).agent_definitions??[]}getAgentDefinition(t){return this.request(q.GET,this.apiUrl(`${F.agentDefinitions}/${encodeURIComponent(t)}`))}listTripOptions(){return this.request(q.GET,this.apiUrl(F.tripOptions))}getDataset(){return this.request(q.GET,this.apiUrl(F.demoDataset))}setDataset(t){return this.request(q.POST,this.apiUrl(F.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 a=s.toString()?`?${s.toString()}`:"";return this.request(q.GET,`${this.resolveUrl("agents",F.agents)}${a}`)}createAgent(t,s={}){var l,p;const a={agent_definition_ref:t},i=(l=s.invocationName)==null?void 0:l.trim(),o=(p=s.agentIntent)==null?void 0:p.trim();return i&&(a.invocation_name=i),o&&(a.agent_intent=o),this.request(q.POST,this.resolveUrl("agents",F.agents),a)}getAgent(t){return this.request(q.GET,this.resolveUrl("agent",`${F.agents}/${encodeURIComponent(t)}`,t))}updateAgent(t,s){const i={invocation_name:s.invocationName.trim()};return this.request(q.PATCH,this.resolveUrl("agent",`${F.agents}/${encodeURIComponent(t)}`,t),i)}getAgentChecklist(t){return this.request(q.GET,this.resolveUrl("agentChecklist",`${F.agents}/${encodeURIComponent(t)}/checklist`,t))}getAgentResources(t,s={}){const a=new URLSearchParams;s.pageNumber!==void 0&&a.set("page_number",String(s.pageNumber)),s.pageSize!==void 0&&a.set("page_size",String(s.pageSize)),s.type&&a.set("type",s.type);const i=a.toString(),o=this.resolveUrl("agentResources",`${F.agents}/${encodeURIComponent(t)}/resources`,t);return this.request(q.GET,i?`${o}?${i}`:o)}async listAllAgentResources(t){const s=vr;let a=1;const i=[];let o=Number.POSITIVE_INFINITY;for(;i.length<o;){const l=vs(await this.getAgentResources(t,{pageNumber:a,pageSize:s}));if(o=l.totalRecords,l.resources.length===0||(i.push(...l.resources),i.length>=o))break;a+=1}return i}getAgentResourceHtml(t,s){return this.requestText(q.GET,this.resolveResourceHtmlUrl(t,s))}getAgentTimeline(t){return this.request(q.GET,this.resolveUrl("agentTimeline",`${F.agents}/${encodeURIComponent(t)}/agent-timeline`,t))}getAgentContext(t){const s=this.resolveUrl("agent",`${F.agents}/${encodeURIComponent(t)}`,t);return this.request(q.GET,`${qn(s)}/context`)}pauseAgent(t){return this.request(q.POST,this.resolveUrl("pauseAgent",`${F.agents}/${encodeURIComponent(t)}/pause`,t))}resumeAgent(t){return this.request(q.POST,this.resolveUrl("resumeAgent",`${F.agents}/${encodeURIComponent(t)}/resume`,t))}archiveAgent(t){return this.request(q.POST,this.resolveUrl("archiveAgent",`${F.agents}/${encodeURIComponent(t)}/archive`,t))}unarchiveAgent(t){return this.request(q.POST,this.resolveUrl("unarchiveAgent",`${F.agents}/${encodeURIComponent(t)}/unarchive`,t))}deleteAgent(t){return this.request(q.DELETE,this.resolveUrl("agent",`${F.agents}/${encodeURIComponent(t)}`,t))}getConversation(t){return this.request(q.GET,this.resolveUrl("agentConversation",`${F.conversations}/${encodeURIComponent(t)}`,t))}async chat(t,s,a={}){const i=!!(a.uploadFiles&&a.uploadFiles.length>0),o=await this.fetchImpl(this.resolveUrl("agentChat",`${F.agents}/${encodeURIComponent(t)}/chat`,t),{method:q.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:De.acceptEventStream,...i?{}:{"Content-Type":De.contentTypeJson}},body:i?Rr(s,a.uploadFiles??[]):JSON.stringify(s),signal:a.signal});if(!o.ok)throw await this.toError(o);if(!o.body)throw new He(o.status,null,"Chat response contained no stream body");return this.consumeSse(o.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(t){return`${this.baseUrl}${mr}${t}`}resolveUrl(t,s,a,i){const o=this.urls[t];if(!o)return this.apiUrl(s);let l=o;return a&&(l=l.replace(Cr,encodeURIComponent(a))),i&&(l=l.replace(Sr,encodeURIComponent(i))),l}resolveResourceHtmlUrl(t,s){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${F.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(s)}`,t,s):this.urls.agentResources?`${this.resolveUrl("agentResources",`${F.agents}/${encodeURIComponent(t)}/resources`,t).replace(/\/$/,"")}/${encodeURIComponent(s)}`:this.apiUrl(`${F.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(s)}`)}async request(t,s,a){const i=await this.fetchImpl(s,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:De.acceptJson,...a===void 0?{}:{"Content-Type":De.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,s){const a=await this.fetchImpl(s,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:De.acceptHtml}});if(!a.ok)throw await this.toError(a);return a.text()}async toError(t){let s=null;try{s=await t.json()}catch{}return new He(t.status,s,`Agent service request failed (${t.status} ${t.statusText})`)}async consumeSse(t,s){const a=t.getReader(),i=new TextDecoder;let o="",l,p;const u=f=>{const{event:x,data:_}=jr(f);if(_===null)return;if(x===_r.error){const g=Vn(_);throw new He(502,g,(g==null?void 0:g.message)??"Chat stream error")}const w=Vn(_);w&&(l=w,s==null||s(w),w.is_final&&(p=w))};try{for(;;){const{done:f,value:x}=await a.read();if(f)break;o+=i.decode(x,{stream:!0});const _=o.split(`
4
+ ${t}`:"File upload"},qn=e=>{var s;const t=(s=e.filename)==null?void 0:s.trim();return t||null},ks=e=>e.filter(t=>qn(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=qn(t);return s&&t.role==="user"?{id:t.message_id,author:ae.user,kind:es.user_file,text:s}:{id:t.message_id,author:t.role==="user"?ae.user:ae.agent,text:t.content}}),Sr=/:invocationId\b/g,jr=/:resourceId\b/g,Rr=e=>e.trim().replace(/^Bearer\s+/i,""),Vn=e=>e.endsWith("/")?e.slice(0,-1):e;class tn{constructor(t){var r;this.baseUrl=Vn(t.baseUrl??"");const s=(r=t.token)==null?void 0:r.trim();this.token=s?Rr(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(q.GET,this.resolveUrl("agentDefinitions",G.agentDefinitions))).agent_definitions??[]}getAgentDefinition(t){return this.request(q.GET,this.apiUrl(`${G.agentDefinitions}/${encodeURIComponent(t)}`))}listTripOptions(){return this.request(q.GET,this.apiUrl(G.tripOptions))}getDataset(){return this.request(q.GET,this.apiUrl(G.demoDataset))}setDataset(t){return this.request(q.POST,this.apiUrl(G.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),t.scope&&s.set("scope",t.scope);const r=s.toString()?`?${s.toString()}`:"";return this.request(q.GET,`${this.resolveUrl("agents",G.agents)}${r}`)}createAgent(t,s={}){var l,p;const r={agent_definition_ref:t},i=(l=s.invocationName)==null?void 0:l.trim(),c=(p=s.agentIntent)==null?void 0:p.trim();return i&&(r.invocation_name=i),c&&(r.agent_intent=c),this.request(q.POST,this.resolveUrl("agents",G.agents),r)}getAgent(t){return this.request(q.GET,this.resolveUrl("agent",`${G.agents}/${encodeURIComponent(t)}`,t))}updateAgent(t,s){const i={invocation_name:s.invocationName.trim()};return this.request(q.PATCH,this.resolveUrl("agent",`${G.agents}/${encodeURIComponent(t)}`,t),i)}getAgentChecklist(t){return this.request(q.GET,this.resolveUrl("agentChecklist",`${G.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(),c=this.resolveUrl("agentResources",`${G.agents}/${encodeURIComponent(t)}/resources`,t);return this.request(q.GET,i?`${c}?${i}`:c)}async listAllAgentResources(t){const s=wr;let r=1;const i=[];let c=Number.POSITIVE_INFINITY;for(;i.length<c;){const l=ws(await this.getAgentResources(t,{pageNumber:r,pageSize:s}));if(c=l.totalRecords,l.resources.length===0||(i.push(...l.resources),i.length>=c))break;r+=1}return i}getAgentResourceHtml(t,s){return this.requestText(q.GET,this.resolveResourceHtmlUrl(t,s))}getAgentTimeline(t){return this.request(q.GET,this.resolveUrl("agentTimeline",`${G.agents}/${encodeURIComponent(t)}/agent-timeline`,t))}getAgentContext(t){const s=this.resolveUrl("agent",`${G.agents}/${encodeURIComponent(t)}`,t);return this.request(q.GET,`${Vn(s)}/context`)}pauseAgent(t){return this.request(q.POST,this.resolveUrl("pauseAgent",`${G.agents}/${encodeURIComponent(t)}/pause`,t))}resumeAgent(t){return this.request(q.POST,this.resolveUrl("resumeAgent",`${G.agents}/${encodeURIComponent(t)}/resume`,t))}archiveAgent(t){return this.request(q.POST,this.resolveUrl("archiveAgent",`${G.agents}/${encodeURIComponent(t)}/archive`,t))}unarchiveAgent(t){return this.request(q.POST,this.resolveUrl("unarchiveAgent",`${G.agents}/${encodeURIComponent(t)}/unarchive`,t))}deleteAgent(t){return this.request(q.DELETE,this.resolveUrl("agent",`${G.agents}/${encodeURIComponent(t)}`,t))}getConversation(t){return this.request(q.GET,this.resolveUrl("agentConversation",`${G.conversations}/${encodeURIComponent(t)}`,t))}async chat(t,s,r={}){const i=!!(r.uploadFiles&&r.uploadFiles.length>0),c=await this.fetchImpl(this.resolveUrl("agentChat",`${G.agents}/${encodeURIComponent(t)}/chat`,t),{method:q.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:Me.acceptEventStream,...i?{}:{"Content-Type":Me.contentTypeJson}},body:i?Ir(s,r.uploadFiles??[]):JSON.stringify(s),signal:r.signal});if(!c.ok)throw await this.toError(c);if(!c.body)throw new Ue(c.status,null,"Chat response contained no stream body");return this.consumeSse(c.body,r.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(t){return`${this.baseUrl}${fr}${t}`}resolveUrl(t,s,r,i){const c=this.urls[t];if(!c)return this.apiUrl(s);let l=c;return r&&(l=l.replace(Sr,encodeURIComponent(r))),i&&(l=l.replace(jr,encodeURIComponent(i))),l}resolveResourceHtmlUrl(t,s){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${G.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(s)}`,t,s):this.urls.agentResources?`${this.resolveUrl("agentResources",`${G.agents}/${encodeURIComponent(t)}/resources`,t).replace(/\/$/,"")}/${encodeURIComponent(s)}`:this.apiUrl(`${G.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:Me.acceptJson,...r===void 0?{}:{"Content-Type":Me.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:Me.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 Ue(t.status,s,`Agent service request failed (${t.status} ${t.statusText})`)}async consumeSse(t,s){const r=t.getReader(),i=new TextDecoder;let c="",l,p;const o=_=>{const{event:k,data:f}=Tr(_);if(f===null)return;if(k===vr.error){const g=Kn(f);throw new Ue(502,g,(g==null?void 0:g.message)??"Chat stream error")}const v=Kn(f);v&&(l=v,s==null||s(v),v.is_final&&(p=v))};try{for(;;){const{done:_,value:k}=await r.read();if(_)break;c+=i.decode(k,{stream:!0});const f=c.split(`
5
5
 
6
- `);o=_.pop()??"";for(const w of _)u(w);if(p){await a.cancel().catch(()=>{});break}}!p&&o.trim()&&u(o)}finally{try{a.releaseLock()}catch{}}const A=p??l;if(!A)throw new He(502,null,"Chat stream ended without any events");return A}}const jr=e=>{let t=null;const s=[];for(const a of e.split(`
7
- `)){const i=a.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}},Vn=e=>{try{return JSON.parse(e)}catch{return}};function Rr(e,t){const s=new FormData;s.append("body",JSON.stringify(e));for(const a of t)s.append("files",a,a.name);return s}const Tr={id:ts,author:ae.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 Kn=0;const Ir=e=>(Kn+=1,`${e}-${Date.now()}-${Kn}`),Or=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 As{constructor(t,s,a={}){this.seededChecklist=[],this.client=t,this.agentId=s,this.chatId=a.chatId??s,this.opening=a.openingMessage??Tr,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const t=await this.client.getConversation(this.chatId),s=ws(t.messages);return s.length===0?[this.opening]:s}async start(t){return{...await this.exchange(Or(t)),phase:H.running}}sendMessage(t,s,a){return this.exchange(t,s,a)}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,a){var x;const i=[{role:fr.user,content:t}];let o="",l=null,p;const u=await this.client.chat(this.agentId,{messages:i,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}:{},onEvent:_=>{var C;const w=_.message;if((w==null?void 0:w.role)==="assistant"&&w.tool_calls&&w.tool_calls.length>0){const T=$e.thinkingPhrasesFromToolCalls(w.tool_calls);for(const I of T)I.phrase!==l&&(l=I.phrase,(C=a==null?void 0:a.onThinking)==null||C.call(a,I))}const g=w==null?void 0:w.content;g&&(o=_.is_final?g:o+g),_.is_final&&(p=_)}}),A=p??u,f={id:A.event_id||Ir("msg-agent"),author:ae.agent,text:o||A.message.content||"",...(x=A.follow_up_prompts)!=null&&x.length?{followUpPrompts:A.follow_up_prompts}:{}};try{const _=await this.client.getAgentChecklist(this.agentId),{checklist:w}=Jt(this.agentId,_);return w.length===0?{message:f}:(this.seededChecklist=w,{message:f,checklist:w})}catch{return{message:f,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const Cn=(e,t)=>s=>{var a,i;return new As(e,s.invocation_id,{model:t==null?void 0:t.model,chatId:((a=t==null?void 0:t.resolveChatId)==null?void 0:a.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)})},ks=e=>e instanceof He?e.message:e instanceof TypeError?"Network error while contacting the agent service.":e instanceof Error&&e.message?e.message:ss,Ns=e=>{if(e instanceof He){if(e.status===403)return ma;if(e.status===409)return _a;if(e.status===404)return fa}return pa},Lr=e=>{const t={};for(const s of e){const a=Ct(s);if(!a)continue;const i=s.invocation_id??s.id;t[i]=a,t[s.id]=a}return t},Pr=e=>JSON.stringify(e),zt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),ys=e=>{const{jwt:t,headers:s,urls:a}=e,i=JSON.stringify(s??{}),o=Pr(a),l=r.useMemo(()=>new Wt({token:t,headers:s,urls:a}),[t,o]);r.useLayoutEffect(()=>{l.setHeaders(s)},[l,i]);const[p,u]=r.useState([]),[A,f]=r.useState([]),[x,_]=r.useState({}),[w,g]=r.useState("loading"),[C,T]=r.useState(null),[I,O]=r.useState(0),k=r.useCallback((y,P)=>{const j=y.map(ye),M=P.map(yn),z=Lr(y);u(K=>zt(K,j)?K:j),f(K=>zt(K,M)?K:M),_(K=>zt(K,z)?K:z),g("idle"),T(null)},[]);r.useEffect(()=>{let y=!1;return g("loading"),T(null),(async()=>{try{const[P,j]=await Promise.all([l.listAgents(),l.listAgentDefinitions()]);if(y)return;k(P,j)}catch(P){if(y)return;u([]),f([]),_({}),g("error"),T(ks(P))}})(),()=>{y=!0}},[k,l,I]);const m=r.useCallback(()=>{O(y=>y+1)},[]),N=r.useCallback(async()=>{try{const[y,P]=await Promise.all([l.listAgents(),l.listAgentDefinitions()]);k(y,P)}catch{}},[k,l]),L=r.useCallback(async y=>{const[P,j]=await Promise.all([l.getAgentChecklist(y),l.getAgent(y).catch(()=>null)]);return Jt(y,P,j??void 0)},[l]),$=r.useCallback(async y=>l.listAllAgentResources(y),[l]),G=r.useCallback(async({definition:y,invocationName:P})=>{const j=await l.createAgent(y.ref,{invocationName:P}),M=await l.getAgent(j.id),z=ye(M),K=Ct(M);return u(ne=>[z,...ne]),K&&_(ne=>({...ne,[z.invocation_id]:K,[z.id]:K})),z},[l]),re=r.useCallback(async y=>{const P=await l.archiveAgent(y),j=ye(P);return u(M=>M.map(z=>z.id===j.id||z.id===y||z.invocation_id===y?j:z)),j},[l]),_e=r.useCallback(async y=>{const P=await l.unarchiveAgent(y),j=ye(P);return u(M=>M.map(z=>z.id===j.id||z.id===y||z.invocation_id===y?j:z)),j},[l]),te=r.useCallback(y=>{u(P=>P.filter(j=>j.id!==y&&j.invocation_id!==y))},[]),D=r.useCallback(y=>{u(P=>{const j=P.map(M=>M.id===y.id||M.invocation_id===y.invocation_id?{...M,...y}:M);return zt(P,j)?P:j})},[]),ie=r.useCallback(async y=>{await l.deleteAgent(y),te(y)},[l,te]),be=r.useMemo(()=>Cn(l,{resolveOpeningMessage:y=>x[y.invocation_id]??x[y.id]}),[l,x]);return{agents:p,agentDefinitions:A,loadState:w,loadError:C,reload:m,refresh:N,fetchAgentChecklist:L,fetchAgentResources:$,createAgent:G,archiveAgent:re,unarchiveAgent:_e,deleteAgent:ie,removeAgent:te,replaceAgent:D,chatConnector:be}},Mr=e=>JSON.stringify(e),bs=e=>{const{agent:t,jwt:s,headers:a,urls:i,chatId:o}=e,l=JSON.stringify(a??{}),p=Mr(i),u=r.useMemo(()=>new Wt({token:s,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}:{},...i.unarchiveAgentUrl?{unarchiveAgent:i.unarchiveAgentUrl}:{}}}),[s,p]);r.useLayoutEffect(()=>{u.setHeaders(a)},[u,l]);const A=r.useCallback(async m=>ye(await u.getAgent(m)),[u]),f=r.useCallback(async m=>{const[N,L]=await Promise.all([u.getAgentChecklist(m),u.getAgent(m).catch(()=>null)]);return Jt(m,N,L??void 0)},[u]),x=r.useCallback(async m=>u.listAllAgentResources(m),[u]),_=r.useCallback(async m=>u.getAgentContext(m),[u]),w=r.useCallback(async(m,N)=>u.getAgentResourceHtml(m,N),[u]),g=r.useCallback(async m=>{const N=await u.getAgentTimeline(m);return xs(N)},[u]),C=r.useCallback(async(m,N)=>{await u.updateAgent(m,{invocationName:N})},[u]),T=r.useCallback(async m=>ye(await u.archiveAgent(m)),[u]),I=r.useCallback(async m=>ye(await u.unarchiveAgent(m)),[u]),O=r.useCallback(async m=>{await u.deleteAgent(m)},[u]);return{connector:r.useMemo(()=>Cn(u,{chatId:o??t.invocation_id})(t),[u,t.invocation_id,o]),fetchAgent:A,fetchAgentChecklist:f,fetchAgentContext:_,fetchAgentResources:x,fetchAgentResourceHtml:w,fetchAgentTimeline:g,updateAgentInvocationName:C,archiveAgent:T,unarchiveAgent:I,deleteAgent:O}},Ur=3e4,Dr=(e,t)=>{const s=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`${s}${a}.${i}`.trim()},Yn=e=>{switch(e){case b.paused:return H.paused;case b.complete:return H.complete;default:return H.running}},_n=e=>e===b.paused,Jn=(e,t)=>{t([Ae(e)])},Hr=(e,t)=>e.length===t.length&&e.every((s,a)=>{const i=t[a];return i!==void 0&&s.id===i.id&&s.text===i.text}),Cs=({agent:e,invocationId:t,open:s,onClose:a,jwt:i,headers:o,agentUrl:l,agentChecklistUrl:p,agentResourcesUrl:u,agentTimelineUrl:A,agentChatUrl:f,agentConversationUrl:x,pauseAgentUrl:_,resumeAgentUrl:w,archiveAgentUrl:g,unarchiveAgentUrl:C,chatId:T,enableUpload:I,adminMode:O=!1,initialBrief:k,initialPhase:m,initialChecklist:N,usePusherToRepoll:L=!1,pusherChannelPrefix:$=Nn,pusherKey:G="",pusherCluster:re="",subscribeToPusher:_e,onArchived:te,onUnarchived:D,onDeleted:ie,onAgentUpdated:be})=>{const[y,P]=r.useState(T??t),[j,M]=r.useState("chat"),[z,K]=r.useState(!1),{connector:ne,fetchAgent:Xe,fetchAgentChecklist:Be,fetchAgentContext:St,fetchAgentResources:Fe,fetchAgentResourceHtml:Ge,fetchAgentTimeline:he,updateAgentInvocationName:Ce,archiveAgent:Ze,unarchiveAgent:Qe,deleteAgent:ee}=bs({agent:{...e,invocation_id:t},jwt:i,headers:o,chatId:y,urls:{agentUrl:l,agentChecklistUrl:p,agentResourcesUrl:u,agentTimelineUrl:A,agentChatUrl:f,agentConversationUrl:x,pauseAgentUrl:_,resumeAgentUrl:w,archiveAgentUrl:g,unarchiveAgentUrl:C}}),Y=r.useRef(ne),[Se,fe]=r.useState(e.invocation_name),[ze,et]=r.useState(0),[Ee,tt]=r.useState(null),[V,le]=r.useState(m??(k?H.running:Yn(e.status))),[nt,X]=r.useState([]),[Xt,ge]=r.useState(0),[Zt,st]=r.useState(),[qe,je]=r.useState(null),[at,rt]=r.useState([]),[Qt,Re]=r.useState(!1),[Te,Ie]=r.useState(null),[it,lt]=r.useState(null),[en,ve]=r.useState(null),[Et,oe]=r.useState(!1),[jt,xe]=r.useState(null),[we,ot]=r.useState(null),[tn,ct]=r.useState(!1),[Rt,Oe]=r.useState(null),[Le,ut]=r.useState(N??null),[Tt,It]=r.useState(!1),[nn,dt]=r.useState(null),[sn,Ot]=r.useState(void 0),[ht,Lt]=r.useState(!1),[gt,pt]=r.useState(!1),[an,mt]=r.useState(null),[Pt,Mt]=r.useState(!1),[_t,d]=r.useState(!1),[S,E]=r.useState(!1),[Z,pe]=r.useState(!1),[Ve,ce]=r.useState(null),[ft,Sn]=r.useState(!1),[Rs,rn]=r.useState(!1),[Ts,Ut]=r.useState(null),[En,jn]=r.useState(!1),[Is,ln]=r.useState(!1),[Os,Dt]=r.useState(null),[Rn,Q]=r.useState(null),[Ls,vt]=r.useState(()=>_n(e.status)),[Ps,Tn]=r.useState(e.archivedAt??null),B=!!Ps,[Ht,xt]=r.useState(!1),[$t,Ms]=r.useState(!1),[Bt,Us]=r.useState(!1),In=r.useRef(Ht),On=r.useRef(e.invocation_name),Ke=r.useRef(e),ue=r.useRef(be),Ln=r.useRef(0),Pn=r.useRef(0),Ye=r.useRef(0),wt=r.useRef(0);ue.current=be,r.useEffect(()=>{Tn(e.archivedAt??null)},[e.archivedAt]),r.useEffect(()=>{Y.current=ne},[ne]),r.useEffect(()=>{On.current=e.invocation_name},[e.invocation_name]),r.useEffect(()=>{Ke.current=e},[e]),r.useEffect(()=>{In.current=Ht},[Ht]),r.useEffect(()=>{P(T??t),M("chat"),K(!1),X([]),ge(h=>h+1),tt(null)},[t,T]),r.useEffect(()=>(Ye.current+=1,Ot(void 0),Lt(!1),pt(!1),mt(null),()=>{Ye.current+=1}),[t]),r.useEffect(()=>{vt(_n(e.status))},[e.status,t]),r.useEffect(()=>{if(!s||k||B)return;const h=++wt.current;return(async()=>{var v;try{const R=await Xe(t);if(h!==wt.current)return;le(Yn(R.status)),vt(_n(R.status)),Ke.current=R,(v=ue.current)==null||v.call(ue,R)}catch{}})(),()=>{wt.current+=1}},[s,t,k,B,Xe]),r.useEffect(()=>{fe(e.invocation_name),et(h=>h+1)},[e.invocation_name]),r.useEffect(()=>{B&&M("timeline")},[B]),r.useEffect(()=>{if(!s||k||B)return;const h=Y.current.bootstrapConversation;if(!h){Jn(Y.current.openingMessage(),X);return}let v=!1;return xt(!0),(async()=>{try{const R=await h.call(Y.current);if(v)return;X(R.map(Ae))}catch{v||Jn(Y.current.openingMessage(),X)}finally{v||xt(!1)}})(),()=>{v=!0}},[s,k,B,t,y]);const Pe=r.useCallback(()=>{const h=++Ln.current;(async()=>{var v,R;try{const J=await Be(t);if(h!==Ln.current)return;ut(se=>J.checklist.length===0&&Array.isArray(se)&&se.length>0||JSON.stringify(se)===JSON.stringify(J.checklist)?se:J.checklist),dt(null),(R=(v=Y.current).seedChecklist)==null||R.call(v,J.checklist)}catch{}})()},[Be,t]),Me=r.useCallback(()=>{u&&(async()=>{try{const h=await Fe(t);rt(h),Ie(null)}catch{}})()},[u,Fe,t]),me=r.useCallback(()=>{if(!A)return;const h=++Pn.current;(async()=>{try{const v=await he(t);if(h!==Pn.current)return;ot(R=>JSON.stringify(R)===JSON.stringify(v)?R:v),Oe(null)}catch{}})()},[A,he,t]),At=r.useCallback(h=>{const v=Y.current.bootstrapConversation;v&&(async()=>{try{const R=await v.call(Y.current);if(In.current)return;const J=R.map(Ae);let se=!1;X(Je=>Hr(Je,J)?Je:(se=!0,J)),se&&(h!=null&&h.refreshSidePanelsOnChange)&&(Pe(),me())}catch{}})()},[Pe,me]),Ds=r.useCallback(h=>{switch(h){case Ne.checklist:Pe();return;case Ne.resources:Me();return;case Ne.chat:At();return;case Ne.timeline:me();return;case Ne.all:default:Pe(),Me(),At(),me()}},[Pe,At,Me,me]),Hs=ps({enabled:!!(s&&L&&!_e),key:G,cluster:re,isAdmin:O}),$s=_e??Hs,Mn=dr({enabled:s&&L,channelPrefix:$,agentId:e.id,subscribeToPusher:$s,onRepoll:Ds});r.useEffect(()=>{if(!s||k||B||Mn)return;const h=window.setInterval(()=>{At({refreshSidePanelsOnChange:!0})},Ur);return()=>{window.clearInterval(h)}},[s,k,B,Mn,t,y,At]);const Ft=r.useCallback(h=>{var v,R;if(h&&h.length>0){ut(h),(R=(v=Y.current).seedChecklist)==null||R.call(v,h);return}Pe()},[Pe]),on=r.useCallback(h=>{Ft(h.checklist),h.phase&&le(h.phase),Me(),me()},[Ft,Me,me]);r.useEffect(()=>{var h,v;!s||k||N&&N.length>0&&((v=(h=Y.current).seedChecklist)==null||v.call(h,N))},[s,k,N]),r.useEffect(()=>{if(!s||k)return;let h=!1;return It(v=>N!=null&&N.length?!1:v||Le===null||Le.length===0),dt(null),(async()=>{var v,R;try{const J=await Be(t);if(h)return;N!=null&&N.length||(ut(J.checklist),(R=(v=Y.current).seedChecklist)==null||R.call(v,J.checklist))}catch{!h&&!(N!=null&&N.length)&&dt(qt)}finally{h||It(!1)}})(),()=>{h=!0}},[s,t,k,N,Be]),r.useEffect(()=>{if(!s||!u)return;let h=!1;return Re(!0),Ie(null),(async()=>{try{const v=await Fe(t);h||rt(v)}catch{h||Ie(ia)}finally{h||Re(!1)}})(),()=>{h=!0}},[s,t,u,Fe]);const Bs=r.useCallback(()=>{lt(null),ve(null),xe(null),oe(!1)},[]),Fs=r.useCallback(h=>{if(h.misRecordUrl){window.open(h.misRecordUrl,"_blank","noopener,noreferrer");return}lt(h),ve(null),xe(null),oe(!0),(async()=>{try{const v=await Ge(t,h.id);ve(v)}catch{xe(la)}finally{oe(!1)}})()},[Ge,t]);r.useEffect(()=>{if(!s||!A)return;let h=!1;return ct(v=>v||we===null),Oe(null),(async()=>{try{const v=await he(t);h||ot(v)}catch{h||Oe(ns)}finally{h||ct(!1)}})(),()=>{h=!0}},[s,t,A,he]),r.useEffect(()=>{if(!s||!k)return;let h=!1;const v={id:`user-brief-${Date.now()}`,author:ae.user,text:Dr(k,On.current)};return(async()=>{const R=await Y.current.start(k);h||(X([Ae(Y.current.openingMessage()),Ae(v),Ae(R.message)]),Ft(R.checklist),le(R.phase??H.running),Me(),me())})(),()=>{h=!0}},[s,k,t,Ft,Me,me]);const Gs=r.useCallback(h=>{je(rr(h))},[]),cn=T??t,Gt=we==null?void 0:we.chatSessions,Un=Gt!=null&&Gt.length?Gt.reduce((h,v)=>Date.parse(v.timestamp)<Date.parse(h.timestamp)?v:h).sessionId:void 0,un=r.useCallback(()=>{M("chat"),K(!1),y!==cn&&(P(cn),X([]),ge(h=>h+1))},[y,cn]),zs=r.useCallback(h=>{if(h===Un){un();return}P(h),K(!0),M("chat"),X([]),ge(v=>v+1)},[Un,un]),qs=r.useCallback(h=>{je(null),st(h),ge(v=>v+1)},[]),Vs=r.useCallback(async()=>{var h;Q(null),Mt(!0);try{await Y.current.pause(),wt.current+=1,le(H.paused),vt(!0);const v={...Ke.current,status:b.paused};Ke.current=v,(h=ue.current)==null||h.call(ue,v)}catch{Q(oa)}finally{Mt(!1)}},[]),Ks=r.useCallback(async()=>{var v;Q(null),d(!0);let h=!1;try{await Y.current.resume(),h=!0,wt.current+=1,le(H.running),vt(!1);const R={...Ke.current,status:b["generating-a-response"]};Ke.current=R,(v=ue.current)==null||v.call(ue,R),xt(!0);const J={id:`wake-${Date.now()}`,author:ae.user,text:Dn};X(Je=>[...Je,Ae(J)]);const se=await Y.current.sendMessage(Dn);X(Je=>[...Je,Ae(se.message)]),on(se)}catch{Q(h?Aa:wa)}finally{d(!1),xt(!1)}},[on]),Ys=r.useCallback(async()=>{Q(null),ce(null),E(!0);try{await Ze(t),pe(!1),te==null||te(),a()}catch{ce(fn),Q(fn)}finally{E(!1)}},[t,Ze,te,a]),Js=r.useCallback(async()=>{Q(null),Ut(null),Sn(!0);try{await Qe(t),Tn(null),le(H.paused),vt(!0),M("chat"),rn(!1),D==null||D()}catch{Ut(vn),Q(vn)}finally{Sn(!1)}},[t,Qe,D]),Ws=r.useCallback(async()=>{Q(null),Dt(null),jn(!0);try{await ee(t),ln(!1),ie==null||ie(),a()}catch(h){Dt(Ns(h))}finally{jn(!1)}},[t,ee,ie,a]),Xs=r.useCallback(h=>{const v=h.trim(),R=Se;if(tt(null),!v){et(J=>J+1);return}v!==R&&(fe(v),(async()=>{try{await Ce(t,v)}catch{fe(R),et(J=>J+1),tt(ka)}})())},[Se,t,Ce]),Zs=r.useCallback(()=>{if(!O||ht||gt)return;const h=++Ye.current;pt(!0),mt(null),(async()=>{try{const v=await St(t);if(Ye.current!==h)return;Ot(v),Lt(!0)}catch{Ye.current===h&&mt(ra)}finally{Ye.current===h&&pt(!1)}})()},[O,ht,gt,St,t]),Qs=Le;return n.jsxs(n.Fragment,{children:[n.jsxs(c.Modal,{open:s,closeHandler:a,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:B?n.jsx("span",{className:"agent-workspace__header-name",children:Se}):n.jsx(c.EditableText,{className:"agent-workspace__header-name",text:Se,onEditSave:Xs},ze)}),n.jsx("span",{className:W("agent-workspace__phase",`agent-workspace__phase--${V}`),children:ba[V]}),B?n.jsx("span",{className:"agent-workspace__phase agent-workspace__phase--archived",children:"Archived"}):null,Ee&&n.jsx("p",{className:"agent-workspace__error agent-workspace__name-error",role:"alert",children:Ee})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(c.Button,{variant:$t?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!$t,onClick:()=>Ms(h=>!h),children:"Checklist"}),n.jsx(c.Button,{variant:Bt?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Bt,onClick:()=>Us(h=>!h),children:"Resources"}),n.jsx(c.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),n.jsxs(c.Modal.Body,{className:W("agent-workspace__body",{"agent-workspace__body--no-checklist":$t,"agent-workspace__body--no-resources":Bt}),children:[n.jsxs("section",{className:W("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!A&&(B||j==="timeline")}),"aria-label":"Agent",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(c.Heading,{level:4,children:"Agent"}),_&&!B&&V===H.running&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Pause",disabled:Pt,onClick:()=>void Vs(),children:Pt?"Pausing…":"Pause agent"}),w&&!B&&V===H.paused&&Ls&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"iteration-ccw",iconLeftScreenReaderText:"Resume",disabled:_t,onClick:()=>void Ks(),children:_t?"Resuming…":"Resume agent"}),g&&!B&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>{ce(null),Q(null),pe(!0)},children:"Archive agent"}),C&&B&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",onClick:()=>{Ut(null),Q(null),rn(!0)},children:"Unarchive agent"}),O&&B&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",onClick:()=>{Dt(null),Q(null),ln(!0)},children:"Delete agent"})]}),Rn&&n.jsx("p",{className:"agent-workspace__error agent-workspace__lifecycle-error",role:"alert",children:Rn}),A&&!B&&n.jsxs(c.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(c.Tabs.Item,{active:j==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>M("chat")},children:"Chat"}),n.jsx(c.Tabs.Item,{active:j==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>M("timeline")},children:"Timeline"})]}),A&&!B&&j==="chat"&&z&&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:un,children:"Back to main chat"})}),A&&(B||j==="timeline")&&n.jsx(sr,{timeline:we,isLoading:tn,error:Rt,onOpenChatSession:B?void 0:zs}),!B&&n.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!A&&j!=="chat",children:n.jsx(Ba,{connector:ne,phase:V,chatHistory:nt,chatSessionKey:Xt,startQuery:Zt,clarificationMessage:qe,enableUpload:I,onTurn:on,onAwaitingChange:xt,onClarificationPrompt:qs,onDismissClarification:()=>je(null)})}),B&&!A&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Chat is not available for archived agents."})]}),!$t&&n.jsx(Fa,{checklist:Qs,isLoading:Tt,error:nn,phase:V,canRequestInput:!B&&V===H.running&&!Ht,onAttentionItemClick:Gs,adminMode:O,context:sn,contextLoaded:ht,contextLoading:gt,contextError:an,onContextSelect:Zs},t),!Bt&&n.jsx(qa,{resources:at,isLoading:Qt,error:Te,onOpenResource:Fs}),n.jsx(Ga,{resource:it,html:en,isLoading:Et,error:jt,onClose:Bs})]})]}),n.jsx(rs,{open:Z,isInProgress:V===H.running||V===H.paused&&!os(Le??void 0),isArchiving:S,error:Ve,onCancel:()=>{S||(ce(null),pe(!1))},onConfirm:()=>{Ys()}}),n.jsx(ls,{open:Rs,isUnarchiving:ft,error:Ts,onCancel:()=>{ft||(Ut(null),rn(!1))},onConfirm:()=>{Js()}}),n.jsx(is,{open:Is,isDeleting:En,error:Os,onCancel:()=>{En||(Dt(null),ln(!1))},onConfirm:()=>{Ws()}})]})},$r="Unable to load agent definitions. Please try again.",Br="Unable to start the agent.",Wn="Loading agents…",Fr="Which agent?",Gr="Select an agent",zr="Name for this run",qr="e.g. Year 6 Science Museum trip",Vr="Shown on the board and in the workspace",Xn="new-agent-invocation-name-hint",Ss=({open:e,onClose:t,onStart:s,agentDefinitions:a,definitionsState:i="idle",definitionsError:o=null,onRetryDefinitions:l,embedded:p=!1})=>{const[u,A]=r.useState(void 0),[f,x]=r.useState(""),[_,w]=r.useState(!1),[g,C]=r.useState(null),T=[...a].sort((L,$)=>L.display_name.localeCompare($.display_name)).map(L=>({value:L.ref,label:L.display_name}));r.useEffect(()=>{e&&(A(void 0),x(""),w(!1),C(null))},[e]);const I=u!==void 0&&f.trim().length>0,O=r.useCallback(L=>{const $=a.find(G=>G.ref===L[0]);$&&A($)},[a]),k=r.useCallback(async()=>{if(!(!u||!I||_)){w(!0),C(null);try{await s({definition:u,invocationName:f.trim()})}catch(L){C(L instanceof Error?L.message:Br)}finally{w(!1)}}},[I,u,f,_,s]);if(i==="idle"&&a.length===0||!e)return null;const m=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})}),p?n.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):n.jsx(c.Modal.Title,{children:"Start an agent"})]});let N;return i==="loading"?N=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:Wn}),n.jsx("p",{className:"new-agent__state-message",children:Wn})]}):i==="error"?N=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??$r}),l?n.jsx(c.Button,{variant:"secondary",size:"S",onClick:l,children:"Try again"}):null]}):N=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:L=>{L.preventDefault(),I&&!_&&k()},children:[n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:Fr}),n.jsx(c.SelectDropdown,{id:"new-agent-type",placeholder:Gr,options:T,selectedValues:u?[u.ref]:[],onSelectionChange:O})]}),n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:zr}),n.jsx(c.TextInput,{id:"new-agent-invocation-name",value:f,placeholder:qr,"aria-describedby":Xn,onChange:L=>x(L.target.value)}),n.jsx("p",{className:"new-agent__field-hint",id:Xn,children:Vr})]}),g?n.jsx("p",{className:"new-agent__error",role:"alert",children:g}):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":_}),disabled:!I||_,iconLeftName:_?"loader":"sparkles",iconLeftScreenReaderText:_?"Starting":void 0,children:_?"Starting…":"Start"})})]}),p?n.jsxs("div",{className:W("new-agent","new-agent--embedded"),children:[n.jsx("div",{className:"new-agent__header",children:m}),n.jsx("div",{className:"new-agent__body",children:N})]}):n.jsxs(c.Modal,{open:e,closeHandler:t,className:"new-agent",children:[n.jsx(c.Modal.Header,{className:"new-agent__header",children:m}),n.jsx(c.Modal.Body,{className:"new-agent__body",children:N})]})},Zn=e=>{window.location.assign(e)},Kr=({open:e,authToken:t,headers:s,agentDefinitionsUrl:a,agentsUrl:i,closeUrl:o,successUrl:l,onClose:p,onStart:u,embedded:A=!1})=>{const f=JSON.stringify(s??{}),x=r.useMemo(()=>new Wt({token:t,headers:s,urls:{agentDefinitions:a,agents:i}}),[t,a,i,f]),[_,w]=r.useState([]),[g,C]=r.useState("loading"),[T,I]=r.useState(null),[O,k]=r.useState(0);r.useEffect(()=>{if(!e)return;let $=!1;return C("loading"),I(null),(async()=>{try{const G=await x.listAgentDefinitions();if($)return;w(G.map(yn)),C("idle")}catch(G){if($)return;w([]),I(ks(G)),C("error")}})(),()=>{$=!0}},[x,e,O]);const m=r.useCallback(()=>{p==null||p(),o&&Zn(o)},[o,p]),N=r.useCallback(async $=>{await x.createAgent($.definition.ref,{invocationName:$.invocationName}),u==null||u($),l&&Zn(l)},[x,u,l]),L=r.useCallback(()=>{k($=>$+1)},[]);return n.jsx(Ss,{open:e,onClose:m,onStart:N,agentDefinitions:_,definitionsState:g,definitionsError:T,onRetryDefinitions:L,embedded:A})},Yr=e=>"agentDefinitionsUrl"in e,Es=e=>Yr(e)?n.jsx(Kr,{...e}):n.jsx(Ss,{...e}),Jr=e=>e.archivedAt?"archived":e.status===b.paused?"paused":null,Wr=e=>{if(e==="archived")return ta;if(e==="paused")return bt[b.paused].statusIcon},Xr=({column:e,overlayIcon:t,label:s})=>{const a=t??e.statusIcon;return a?n.jsx("span",{className:"agent-view__status-indicator",children:n.jsx(c.Icon,{name:a.name,size:16,color:a.color,className:W({"agent-view__progress-icon--spinning":a.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})})},js=({agent:e,agentName:t,column:s,isExpanded:a,isLoading:i,checklist:o,error:l,canArchive:p,canUnarchive:u=!1,canDelete:A=!1,onToggle:f,onViewAgent:x,onArchive:_,onUnarchive:w,onDelete:g})=>{const{id:C,invocation_name:T}=e,I=`agent-card-${C}-header`,O=`agent-card-${C}-progress`,k=Jr(e),m=Wr(k);return n.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:n.jsxs(c.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":O,"aria-label":T,id:I,onClick:()=>f(C),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(Xr,{column:s,overlayIcon:m}),n.jsx("span",{className:"agent-view__card-invocation-name",children:T}),n.jsx("span",{className:"agent-view__card-agent-name",children:t}),k==="paused"?n.jsx("span",{className:"agent-view__card-state-pill",children:"Paused"}):null,k==="archived"?n.jsx("span",{className:"agent-view__card-state-pill",children:"Archived"}):null,n.jsx(c.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&n.jsxs("div",{id:O,"aria-labelledby":I,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:We}),n.jsx("span",{children:We})]}),!i&&l&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:l}),!i&&!l&&o!==null&&n.jsx(Ua,{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:We}),n.jsx("span",{children:We})]}),n.jsxs("div",{className:"agent-view__card-actions",children:[p?n.jsx(c.Button,{variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>_==null?void 0:_(e),children:"Archive"}):u?n.jsx(c.Button,{variant:"secondary",size:"S",onClick:()=>w==null?void 0:w(e),children:"Unarchive"}):A?n.jsx(c.Button,{variant:"secondary-destructive",size:"S",onClick:()=>g==null?void 0:g(e),children:"Delete"}):n.jsx("span",{}),u&&A?n.jsx(c.Button,{variant:"secondary-destructive",size:"S",onClick:()=>g==null?void 0:g(e),children:"Delete"}):null,n.jsx(c.Button,{variant:"secondary",size:"S",onClick:()=>x==null?void 0:x(e),children:"View agent"})]})]})]})})},Zr=({column:e,agents:t,expandedAgentId:s,loadingAgentId:a,checklistByInvocationId:i,errorByAgentId:o,definitionNameByRef:l,onToggleAgent:p,onViewAgent:u,onArchiveAgent:A,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(x=>n.jsx(js,{agent:x,agentName:Vt(x,l),column:e,isExpanded:s===x.id,isLoading:a===x.id,checklist:i[x.invocation_id]??null,error:o[x.id]??null,canArchive:f&&!x.archivedAt,onToggle:p,onViewAgent:u,onArchive:A},x.id))})]}),Vt=(e,t)=>t.get(e.agent_definition_ref)??e.agent_definition_ref.replace(/_/g," "),Qr=({jwt:e,headers:t,agentDefinitionsUrl:s,agentsUrl:a,agentUrl:i,agentChecklistUrl:o,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:u,agentConversationUrl:A,pauseAgentUrl:f,resumeAgentUrl:x,archiveAgentUrl:_,unarchiveAgentUrl:w,enableUpload:g,adminMode:C=!1,showHeader:T=!1,institutions:I,usePusherToRepoll:O=!1,pusherChannelPrefix:k=Nn,pusherKey:m,pusherCluster:N,subscribeToPusher:L})=>{var _t;const $=r.useMemo(()=>({agentDefinitions:s,agents:a,agent:i,agentChecklist:o,...l?{agentResources:l}:{},...p?{agentTimeline:p}:{},agentChat:u,agentConversation:A,..._?{archiveAgent:_}:{},...w?{unarchiveAgent:w}:{}}),[s,a,i,o,l,p,u,A,_,w]),[G,re]=r.useState(null),_e=G?(_t=I==null?void 0:I.find(d=>d.applicationId===G.application_id))==null?void 0:_t.applicationUrl:void 0,te=r.useMemo(()=>{const d={...t??{}};return _e?d[De.arborApplicationUrl]=_e:delete d[De.arborApplicationUrl],d},[t,_e]),{agents:D,agentDefinitions:ie,loadState:be,loadError:y,reload:P,refresh:j,fetchAgentChecklist:M,createAgent:z,archiveAgent:K,unarchiveAgent:ne,deleteAgent:Xe,removeAgent:Be,replaceAgent:St}=ys({jwt:e,headers:te,urls:$}),[Fe,Ge]=r.useState(!1),[he,Ce]=r.useState(null),[Ze,Qe]=r.useState(null),[ee,Y]=r.useState({}),[Se,fe]=r.useState({}),[ze,et]=r.useState([]),[Ee,tt]=r.useState([]),[V,le]=r.useState(null),[nt,X]=r.useState(!1),[Xt,ge]=r.useState(null),[Zt,st]=r.useState(!1),[qe,je]=r.useState(null),[at,rt]=r.useState(!1),[Qt,Re]=r.useState(null),[Te,Ie]=r.useState(null),[it,lt]=r.useState(!1),[en,ve]=r.useState(null);r.useEffect(()=>{re(d=>d?D.find(S=>S.id===d.id)??d:null)},[D]);const Et=r.useMemo(()=>{const d=new Set(D.map(E=>E.application_id)),S=new Map((I??[]).map(E=>[E.applicationId,E.name]));return[...d].sort((E,Z)=>(S.get(E)??E).localeCompare(S.get(Z)??Z)).map(E=>({value:E,label:S.get(E)??E}))},[D,I]),oe=r.useMemo(()=>new Map(ie.map(d=>[d.ref,d.display_name])),[ie]),jt=r.useMemo(()=>[...new Set(D.map(S=>Vt(S,oe)))].sort((S,E)=>S.localeCompare(E)).map(S=>({value:S,label:S})),[D,oe]),xe=r.useMemo(()=>D.filter(d=>!(ze.length>0&&!ze.includes(d.application_id)||Ee.length>0&&!Ee.includes(Vt(d,oe)))),[D,oe,Ee,ze]),we=Et.length>1,ot=jt.length>1,tn=we||ot;r.useEffect(()=>{const d=window.setInterval(()=>{j()},6e4);return()=>{window.clearInterval(d)}},[j]),r.useEffect(()=>{if(D.length===0)return;let d=!1;return(async()=>{const S=await Promise.allSettled(D.map(async E=>{const Z=await M(E.invocation_id);return{agentId:E.id,invocationId:E.invocation_id,checklist:Z.checklist}}));d||(Y(E=>{const Z={...E};let pe=!1;for(const Ve of S){if(Ve.status!=="fulfilled")continue;const{invocationId:ce,checklist:ft}=Ve.value;JSON.stringify(E[ce])!==JSON.stringify(ft)&&(Z[ce]=ft,pe=!0)}return pe?Z:E}),fe(E=>{const Z={...E};let pe=!1;return S.forEach((Ve,ce)=>{Ve.status==="rejected"&&Z[D[ce].id]!==qt&&(Z[D[ce].id]=qt,pe=!0)}),pe?Z:E}))})(),()=>{d=!0}},[D,M]);const ct=r.useCallback(async d=>{if(!ee[d.invocation_id]){Qe(d.id),fe(S=>{const E={...S};return delete E[d.id],E});try{const S=await M(d.invocation_id);Y(E=>({...E,[d.invocation_id]:S.checklist}))}catch{fe(S=>({...S,[d.id]:qt}))}finally{Qe(S=>S===d.id?null:S)}}},[M,ee]),Rt=r.useCallback(d=>{if(he===d){Ce(null);return}const S=D.find(({id:E})=>E===d);S&&(Ce(d),ct(S))},[D,he,ct]),Oe=r.useMemo(()=>xe.filter(d=>!!d.archivedAt),[xe]),Le=r.useMemo(()=>xe.filter(d=>!d.archivedAt),[xe]),ut=r.useMemo(()=>{const d={};for(const S of Le){const E=gn(S,ee[S.invocation_id]);(d[E]??(d[E]=[])).push(S)}return d},[Le,ee]),Tt=r.useCallback(d=>{re(d)},[]),It=r.useCallback(d=>{ge(null),le(d)},[]),nn=r.useCallback(()=>{nt||(ge(null),le(null))},[nt]),dt=r.useCallback(async()=>{if(V){X(!0),ge(null),fe(d=>{const S={...d};return delete S[V.id],S});try{await K(V.invocation_id),re(d=>(d==null?void 0:d.id)===V.id?null:d),Ce(V.id),st(!0),le(null)}catch{ge(fn)}finally{X(!1)}}},[V,K]),sn=r.useCallback(d=>{Re(null),je(d)},[]),Ot=r.useCallback(()=>{at||(Re(null),je(null))},[at]),ht=r.useCallback(async()=>{if(qe){rt(!0),Re(null);try{await ne(qe.invocation_id),je(null)}catch{Re(vn)}finally{rt(!1)}}},[qe,ne]),Lt=V?gn(V,ee[V.invocation_id])!==b.complete:!1,gt=r.useCallback(async d=>{const S=await z(d);re(S),Ge(!1)},[z]),pt=r.useCallback(d=>{ve(null),Ie(d)},[]),an=r.useCallback(()=>{it||(ve(null),Ie(null))},[it]),mt=r.useCallback(async()=>{if(Te){lt(!0),ve(null);try{await Xe(Te.invocation_id),re(d=>(d==null?void 0:d.id)===Te.id?null:d),Ie(null)}catch(d){ve(Ns(d))}finally{lt(!1)}}},[Te,Xe]),Pt=r.useCallback(()=>{re(null)},[]),Mt={expandedAgentId:he,loadingAgentId:Ze,checklistByInvocationId:ee,errorByAgentId:Se,definitionNameByRef:oe,onToggleAgent:Rt,onViewAgent:Tt,onArchiveAgent:It,canArchive:!!_};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[T&&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:()=>Ge(!0),children:"Start an agent"})]}),D.length>0&&tn&&n.jsxs("div",{className:"agent-view__filters",children:[we&&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:Et,value:ze,onValueChange:et,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),ot&&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:jt,value:Ee,onValueChange:tt,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),be==="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:y??ss}),n.jsx(c.Button,{variant:"secondary",size:"S",onClick:P,children:"Try again"})]}):be==="loading"&&D.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:Hn}),n.jsx("p",{className:"agent-view__state-message",children:Hn})]}):D.length===0?n.jsx(Ra,{}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"agent-view__board",children:na.map(d=>n.jsx(Zr,{column:bt[d],agents:ut[d]??[],...Mt},d))}),Oe.length>0?n.jsxs("details",{className:"agent-view__archived",open:Zt,onToggle:d=>{st(d.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:Oe.length})]}),n.jsx("ul",{className:"agent-view__card-list agent-view__archived-list",children:Oe.map(d=>n.jsx(js,{agent:d,agentName:Vt(d,oe),column:bt[gn(d,ee[d.invocation_id])],isExpanded:he===d.id,isLoading:Ze===d.id,checklist:ee[d.invocation_id]??null,error:Se[d.id]??null,canArchive:!1,canUnarchive:!!w,canDelete:C,onToggle:Rt,onViewAgent:Tt,onUnarchive:sn,onDelete:pt},d.id))})]}):null]}),G&&n.jsx(Cs,{agent:G,invocationId:G.invocation_id,open:!0,jwt:e,headers:te,agentUrl:i,agentChecklistUrl:o,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:u,agentConversationUrl:A,pauseAgentUrl:f,resumeAgentUrl:x,archiveAgentUrl:_,unarchiveAgentUrl:w,enableUpload:g,adminMode:C,initialChecklist:ee[G.invocation_id]??null,usePusherToRepoll:O,pusherChannelPrefix:k,pusherKey:m,pusherCluster:N,subscribeToPusher:L,onClose:Pt,onAgentUpdated:St,onArchived:()=>{Ce(G.id),st(!0),j()},onUnarchived:()=>{j()},onDeleted:()=>{Be(G.invocation_id)}},G.id),n.jsx(rs,{open:!!V,isInProgress:Lt,isArchiving:nt,error:Xt,onCancel:nn,onConfirm:()=>{dt()}}),n.jsx(ls,{open:!!qe,isUnarchiving:at,error:Qt,onCancel:Ot,onConfirm:()=>{ht()}}),n.jsx(is,{open:!!Te,isDeleting:it,error:en,onCancel:an,onConfirm:()=>{mt()}}),n.jsx(Es,{open:Fe,onClose:()=>Ge(!1),onStart:gt,agentDefinitions:ie})]})},ei=(e,t)=>{const s=Date.now(),a=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:a,application_id:sa,created_by:aa,status:b["generating-a-response"],archivedAt:null,context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=Qr;exports.AgentServiceClient=Wt;exports.AgentServiceError=He;exports.AgentView=Cs;exports.DEFAULT_PUSHER_CHANNEL_PREFIX=Nn;exports.HttpChatConnector=As;exports.MESSAGE_TYPE_REPOLL=wn;exports.NewAgentModal=Es;exports.PUSHER_AGENT_MESSAGE_EVENT=ds;exports.REPOLL_TARGET=Ne;exports.buildAgentFromDefinition=ei;exports.buildAgentPusherChannel=hs;exports.createHttpChatConnectorFactory=Cn;exports.formatUserFileChatCardText=br;exports.mapApiAgent=ye;exports.mapApiAgentDefinition=yn;exports.mapApiAgentStatus=ms;exports.mapApiAgentTimelineResponse=xs;exports.mapApiChecklistEndpointResponse=Jt;exports.mapApiChecklistItem=bn;exports.mapApiChecklistResponse=Nr;exports.mapApiChecklistStatus=_s;exports.mapApiConversationMessages=ws;exports.mapApiOpeningMessage=Ct;exports.mapApiResource=fs;exports.mapApiResourcesEndpointResponse=vs;exports.mapApiTripOption=xr;exports.parseConversationContentCaption=yr;exports.parseRepollMessages=gs;exports.useAgentService=ys;exports.useAgentWorkspace=bs;exports.useSubscribeToPusher=ps;
6
+ `);c=f.pop()??"";for(const v of f)o(v);if(p){await r.cancel().catch(()=>{});break}}!p&&c.trim()&&o(c)}finally{try{r.releaseLock()}catch{}}const A=p??l;if(!A)throw new Ue(502,null,"Chat stream ended without any events");return A}}const Tr=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}},Kn=e=>{try{return JSON.parse(e)}catch{return}};function Ir(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 Or={id:ns,author:ae.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 Yn=0;const Lr=e=>(Yn+=1,`${e}-${Date.now()}-${Yn}`),Pr=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 Ns{constructor(t,s,r={}){this.seededChecklist=[],this.client=t,this.agentId=s,this.chatId=r.chatId??s,this.opening=r.openingMessage??Or,this.model=r.model}openingMessage(){return this.opening}async bootstrapConversation(){const t=await this.client.getConversation(this.chatId),s=ks(t.messages);return s.length===0?[this.opening]:s}async start(t){return{...await this.exchange(Pr(t)),phase:H.running}}sendMessage(t,s,r){return this.exchange(t,s,r)}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,r){var k;const i=[{role:xr.user,content:t}];let c="",l=null,p;const o=await this.client.chat(this.agentId,{messages:i,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}:{},onEvent:f=>{var b;const v=f.message;if((v==null?void 0:v.role)==="assistant"&&v.tool_calls&&v.tool_calls.length>0){const O=De.thinkingPhrasesFromToolCalls(v.tool_calls);for(const L of O)L.phrase!==l&&(l=L.phrase,(b=r==null?void 0:r.onThinking)==null||b.call(r,L))}const g=v==null?void 0:v.content;g&&(c=f.is_final?g:c+g),f.is_final&&(p=f)}}),A=p??o,_={id:A.event_id||Lr("msg-agent"),author:ae.agent,text:c||A.message.content||"",...(k=A.follow_up_prompts)!=null&&k.length?{followUpPrompts:A.follow_up_prompts}:{}};try{const f=await this.client.getAgentChecklist(this.agentId),{checklist:v}=en(this.agentId,f);return v.length===0?{message:_}:(this.seededChecklist=v,{message:_,checklist:v})}catch{return{message:_,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const Sn=(e,t)=>s=>{var r,i;return new Ns(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)})},ys=e=>e instanceof Ue?e.message:e instanceof TypeError?"Network error while contacting the agent service.":e instanceof Error&&e.message?e.message:as,bs=e=>{if(e instanceof Ue){if(e.status===403)return fa;if(e.status===409)return va;if(e.status===404)return xa}return _a},Mr=e=>{const t={};for(const s of e){const r=Et(s);if(!r)continue;const i=s.invocation_id??s.id;t[i]=r,t[s.id]=r}return t},Ur=e=>JSON.stringify(e),Jt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Cs=e=>{const{jwt:t,headers:s,urls:r,scope:i=rs}=e,c=JSON.stringify(s??{}),l=Ur(r),p=a.useMemo(()=>({scope:i}),[i]),o=a.useMemo(()=>new tn({token:t,headers:s,urls:r}),[t,l]);a.useLayoutEffect(()=>{o.setHeaders(s)},[o,c]);const[A,_]=a.useState([]),[k,f]=a.useState([]),[v,g]=a.useState({}),[b,O]=a.useState("loading"),[L,j]=a.useState(null),[N,m]=a.useState(0),w=a.useRef(0),T=a.useCallback((y,P)=>{const R=y.map(Ee),z=P.map(Cn),B=Mr(y);_(V=>Jt(V,R)?V:R),f(V=>Jt(V,z)?V:z),g(V=>Jt(V,B)?V:B),O("idle"),j(null)},[]);a.useEffect(()=>{const y=++w.current;O("loading"),j(null),(async()=>{try{const[P,R]=await Promise.all([o.listAgents(p),o.listAgentDefinitions()]);if(y!==w.current)return;T(P,R)}catch(P){if(y!==w.current)return;_([]),f([]),g({}),O("error"),j(ys(P))}})()},[T,o,p,N]);const $=a.useCallback(()=>{m(y=>y+1)},[]),X=a.useCallback(async()=>{const y=++w.current;try{const[P,R]=await Promise.all([o.listAgents(p),o.listAgentDefinitions()]);if(y!==w.current)return;T(P,R)}catch{}},[T,o,p]),Q=a.useCallback(async y=>{const[P,R]=await Promise.all([o.getAgentChecklist(y),o.getAgent(y).catch(()=>null)]);return en(y,P,R??void 0)},[o]),te=a.useCallback(async y=>o.listAllAgentResources(y),[o]),re=a.useCallback(async({definition:y,invocationName:P})=>{const R=await o.createAgent(y.ref,{invocationName:P}),z=await o.getAgent(R.id),B=Ee(z),V=Et(z);return _(_e=>[B,..._e]),V&&g(_e=>({..._e,[B.invocation_id]:V,[B.id]:V})),B},[o]),he=a.useCallback(async y=>{const P=await o.archiveAgent(y),R=Ee(P);return _(z=>z.map(B=>B.id===R.id||B.id===y||B.invocation_id===y?R:B)),R},[o]),D=a.useCallback(async y=>{const P=await o.unarchiveAgent(y),R=Ee(P);return _(z=>z.map(B=>B.id===R.id||B.id===y||B.invocation_id===y?R:B)),R},[o]),ie=a.useCallback(y=>{_(P=>P.filter(R=>R.id!==y&&R.invocation_id!==y))},[]),le=a.useCallback(y=>{_(P=>{const R=P.map(z=>z.id===y.id||z.invocation_id===y.invocation_id?{...z,...y}:z);return Jt(P,R)?P:R})},[]),Se=a.useCallback(async y=>{await o.deleteAgent(y),ie(y)},[o,ie]),oe=a.useMemo(()=>Sn(o,{resolveOpeningMessage:y=>v[y.invocation_id]??v[y.id]}),[o,v]);return{agents:A,agentDefinitions:k,loadState:b,loadError:L,reload:$,refresh:X,fetchAgentChecklist:Q,fetchAgentResources:te,createAgent:re,archiveAgent:he,unarchiveAgent:D,deleteAgent:Se,removeAgent:ie,replaceAgent:le,chatConnector:oe}},Dr=e=>JSON.stringify(e),Es=e=>{const{agent:t,jwt:s,headers:r,urls:i,chatId:c}=e,l=JSON.stringify(r??{}),p=Dr(i),o=a.useMemo(()=>new tn({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,p]);a.useLayoutEffect(()=>{o.setHeaders(r)},[o,l]);const A=a.useCallback(async m=>Ee(await o.getAgent(m)),[o]),_=a.useCallback(async m=>{const[w,T]=await Promise.all([o.getAgentChecklist(m),o.getAgent(m).catch(()=>null)]);return en(m,w,T??void 0)},[o]),k=a.useCallback(async m=>o.listAllAgentResources(m),[o]),f=a.useCallback(async m=>o.getAgentContext(m),[o]),v=a.useCallback(async(m,w)=>o.getAgentResourceHtml(m,w),[o]),g=a.useCallback(async m=>{const w=await o.getAgentTimeline(m);return As(w)},[o]),b=a.useCallback(async(m,w)=>{await o.updateAgent(m,{invocationName:w})},[o]),O=a.useCallback(async m=>Ee(await o.archiveAgent(m)),[o]),L=a.useCallback(async m=>Ee(await o.unarchiveAgent(m)),[o]),j=a.useCallback(async m=>{await o.deleteAgent(m)},[o]);return{connector:a.useMemo(()=>Sn(o,{chatId:c??t.invocation_id})(t),[o,t.invocation_id,c]),fetchAgent:A,fetchAgentChecklist:_,fetchAgentContext:f,fetchAgentResources:k,fetchAgentResourceHtml:v,fetchAgentTimeline:g,updateAgentInvocationName:b,archiveAgent:O,unarchiveAgent:L,deleteAgent:j}},Hr=3e4,$r=(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()},Jn=e=>{switch(e){case C.paused:return H.paused;case C.complete:return H.complete;default:return H.running}},vn=e=>e===C.paused,Wn=(e,t)=>{t([ye(e)])},Br=(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}),Ss=({agent:e,invocationId:t,open:s,onClose:r,jwt:i,headers:c,agentUrl:l,agentChecklistUrl:p,agentResourcesUrl:o,agentTimelineUrl:A,agentChatUrl:_,agentConversationUrl:k,pauseAgentUrl:f,resumeAgentUrl:v,archiveAgentUrl:g,unarchiveAgentUrl:b,chatId:O,enableUpload:L,adminMode:j=!1,initialBrief:N,initialPhase:m,initialChecklist:w,usePusherToRepoll:T=!1,pusherChannelPrefix:$=bn,pusherKey:X="",pusherCluster:Q="",subscribeToPusher:te,onArchived:re,onUnarchived:he,onDeleted:D,onAgentUpdated:ie})=>{const[le,Se]=a.useState(O??t),[oe,y]=a.useState("chat"),[P,R]=a.useState(!1),{connector:z,fetchAgent:B,fetchAgentChecklist:V,fetchAgentContext:_e,fetchAgentResources:He,fetchAgentResourceHtml:St,fetchAgentTimeline:fe,updateAgentInvocationName:je,archiveAgent:Re,unarchiveAgent:st,deleteAgent:at}=Es({agent:{...e,invocation_id:t},jwt:i,headers:c,chatId:le,urls:{agentUrl:l,agentChecklistUrl:p,agentResourcesUrl:o,agentTimelineUrl:A,agentChatUrl:_,agentConversationUrl:k,pauseAgentUrl:f,resumeAgentUrl:v,archiveAgentUrl:g,unarchiveAgentUrl:b}}),M=a.useRef(z),[Te,$e]=a.useState(e.invocation_name),[Be,ve]=a.useState(0),[jt,xe]=a.useState(null),[ne,K]=a.useState(m??(N?H.running:Jn(e.status))),[rt,Z]=a.useState([]),[Rt,Fe]=a.useState(0),[Ge,nn]=a.useState(),[it,we]=a.useState(null),[lt,ze]=a.useState([]),[Tt,It]=a.useState(!1),[qe,ge]=a.useState(null),[ot,Ve]=a.useState(null),[Ot,ct]=a.useState(null),[Ke,Ye]=a.useState(!1),[Ae,Je]=a.useState(null),[ce,ut]=a.useState(null),[Lt,Pt]=a.useState(!1),[Mt,We]=a.useState(null),[ke,Xe]=a.useState(w??null),[sn,dt]=a.useState(!1),[an,ht]=a.useState(null),[rn,Ut]=a.useState(void 0),[gt,Dt]=a.useState(!1),[pt,mt]=a.useState(!1),[ln,_t]=a.useState(null),[Ht,$t]=a.useState(!1),[Bt,ft]=a.useState(!1),[d,E]=a.useState(!1),[S,W]=a.useState(!1),[Ie,pe]=a.useState(null),[Ne,vt]=a.useState(!1),[Is,on]=a.useState(!1),[Os,Ft]=a.useState(null),[jn,Rn]=a.useState(!1),[Ls,cn]=a.useState(!1),[Ps,Gt]=a.useState(null),[Tn,ee]=a.useState(null),[Ms,xt]=a.useState(()=>vn(e.status)),[Us,In]=a.useState(e.archivedAt??null),F=!!Us,Ze=!e.usable,[zt,wt]=a.useState(!1),[qt,Ds]=a.useState(!1),[Vt,Hs]=a.useState(!1),On=a.useRef(zt),Ln=a.useRef(e.invocation_name),Qe=a.useRef(e),ue=a.useRef(ie),Pn=a.useRef(0),Mn=a.useRef(0),et=a.useRef(0),At=a.useRef(0);ue.current=ie,a.useEffect(()=>{In(e.archivedAt??null)},[e.archivedAt]),a.useEffect(()=>{M.current=z},[z]),a.useEffect(()=>{Ln.current=e.invocation_name},[e.invocation_name]),a.useEffect(()=>{Qe.current=e},[e]),a.useEffect(()=>{On.current=zt},[zt]),a.useEffect(()=>{Se(O??t),y("chat"),R(!1),Z([]),Fe(h=>h+1),xe(null)},[t,O]),a.useEffect(()=>(et.current+=1,Ut(void 0),Dt(!1),mt(!1),_t(null),()=>{et.current+=1}),[t]),a.useEffect(()=>{xt(vn(e.status))},[e.status,t]),a.useEffect(()=>{if(!s||N||F)return;const h=++At.current;return(async()=>{var x;try{const I=await B(t);if(h!==At.current)return;K(Jn(I.status)),xt(vn(I.status)),Qe.current=I,(x=ue.current)==null||x.call(ue,I)}catch{}})(),()=>{At.current+=1}},[s,t,N,F,B]),a.useEffect(()=>{$e(e.invocation_name),ve(h=>h+1)},[e.invocation_name]),a.useEffect(()=>{F&&y("timeline")},[F]),a.useEffect(()=>{if(!s||N||F)return;const h=M.current.bootstrapConversation;if(!h){Wn(M.current.openingMessage(),Z);return}let x=!1;return wt(!0),(async()=>{try{const I=await h.call(M.current);if(x)return;Z(I.map(ye))}catch{x||Wn(M.current.openingMessage(),Z)}finally{x||wt(!1)}})(),()=>{x=!0}},[s,N,F,t,le]);const Oe=a.useCallback(()=>{const h=++Pn.current;(async()=>{var x,I;try{const Y=await V(t);if(h!==Pn.current)return;Xe(se=>Y.checklist.length===0&&Array.isArray(se)&&se.length>0||JSON.stringify(se)===JSON.stringify(Y.checklist)?se:Y.checklist),ht(null),(I=(x=M.current).seedChecklist)==null||I.call(x,Y.checklist)}catch{}})()},[V,t]),Le=a.useCallback(()=>{o&&(async()=>{try{const h=await He(t);ze(h),ge(null)}catch{}})()},[o,He,t]),me=a.useCallback(()=>{if(!A)return;const h=++Mn.current;(async()=>{try{const x=await fe(t);if(h!==Mn.current)return;ut(I=>JSON.stringify(I)===JSON.stringify(x)?I:x),We(null)}catch{}})()},[A,fe,t]),kt=a.useCallback(h=>{const x=M.current.bootstrapConversation;x&&(async()=>{try{const I=await x.call(M.current);if(On.current)return;const Y=I.map(ye);let se=!1;Z(tt=>Br(tt,Y)?tt:(se=!0,Y)),se&&(h!=null&&h.refreshSidePanelsOnChange)&&(Oe(),me())}catch{}})()},[Oe,me]),$s=a.useCallback(h=>{switch(h){case Ce.checklist:Oe();return;case Ce.resources:Le();return;case Ce.chat:kt();return;case Ce.timeline:me();return;case Ce.all:default:Oe(),Le(),kt(),me()}},[Oe,kt,Le,me]),Bs=_s({enabled:!!(s&&T&&!te),key:X,cluster:Q,isAdmin:j}),Fs=te??Bs,Un=gr({enabled:s&&T,channelPrefix:$,agentId:e.id,subscribeToPusher:Fs,onRepoll:$s});a.useEffect(()=>{if(!s||N||F||Un)return;const h=window.setInterval(()=>{kt({refreshSidePanelsOnChange:!0})},Hr);return()=>{window.clearInterval(h)}},[s,N,F,Un,t,le,kt]);const Kt=a.useCallback(h=>{var x,I;if(h&&h.length>0){Xe(h),(I=(x=M.current).seedChecklist)==null||I.call(x,h);return}Oe()},[Oe]),un=a.useCallback(h=>{Kt(h.checklist),h.phase&&K(h.phase),Le(),me()},[Kt,Le,me]);a.useEffect(()=>{var h,x;!s||N||w&&w.length>0&&((x=(h=M.current).seedChecklist)==null||x.call(h,w))},[s,N,w]),a.useEffect(()=>{if(!s||N)return;let h=!1;return dt(x=>w!=null&&w.length?!1:x||ke===null||ke.length===0),ht(null),(async()=>{var x,I;try{const Y=await V(t);if(h)return;w!=null&&w.length||(Xe(Y.checklist),(I=(x=M.current).seedChecklist)==null||I.call(x,Y.checklist))}catch{!h&&!(w!=null&&w.length)&&ht(Wt)}finally{h||dt(!1)}})(),()=>{h=!0}},[s,t,N,w,V]),a.useEffect(()=>{if(!s||!o)return;let h=!1;return It(!0),ge(null),(async()=>{try{const x=await He(t);h||ze(x)}catch{h||ge(oa)}finally{h||It(!1)}})(),()=>{h=!0}},[s,t,o,He]);const Gs=a.useCallback(()=>{Ve(null),ct(null),Je(null),Ye(!1)},[]),zs=a.useCallback(h=>{if(h.misRecordUrl){window.open(h.misRecordUrl,"_blank","noopener,noreferrer");return}Ve(h),ct(null),Je(null),Ye(!0),(async()=>{try{const x=await St(t,h.id);ct(x)}catch{Je(ca)}finally{Ye(!1)}})()},[St,t]);a.useEffect(()=>{if(!s||!A)return;let h=!1;return Pt(x=>x||ce===null),We(null),(async()=>{try{const x=await fe(t);h||ut(x)}catch{h||We(ss)}finally{h||Pt(!1)}})(),()=>{h=!0}},[s,t,A,fe]),a.useEffect(()=>{if(!s||!N)return;let h=!1;const x={id:`user-brief-${Date.now()}`,author:ae.user,text:$r(N,Ln.current)};return(async()=>{const I=await M.current.start(N);h||(Z([ye(M.current.openingMessage()),ye(x),ye(I.message)]),Kt(I.checklist),K(I.phase??H.running),Le(),me())})(),()=>{h=!0}},[s,N,t,Kt,Le,me]);const qs=a.useCallback(h=>{we(lr(h))},[]),dn=O??t,Yt=ce==null?void 0:ce.chatSessions,Dn=Yt!=null&&Yt.length?Yt.reduce((h,x)=>Date.parse(x.timestamp)<Date.parse(h.timestamp)?x:h).sessionId:void 0,hn=a.useCallback(()=>{y("chat"),R(!1),le!==dn&&(Se(dn),Z([]),Fe(h=>h+1))},[le,dn]),Vs=a.useCallback(h=>{if(h===Dn){hn();return}Se(h),R(!0),y("chat"),Z([]),Fe(x=>x+1)},[Dn,hn]),Ks=a.useCallback(h=>{we(null),nn(h),Fe(x=>x+1)},[]),Ys=a.useCallback(async()=>{var h;ee(null),$t(!0);try{await M.current.pause(),At.current+=1,K(H.paused),xt(!0);const x={...Qe.current,status:C.paused};Qe.current=x,(h=ue.current)==null||h.call(ue,x)}catch{ee(ua)}finally{$t(!1)}},[]),Js=a.useCallback(async()=>{var x;ee(null),ft(!0);let h=!1;try{await M.current.resume(),h=!0,At.current+=1,K(H.running),xt(!1);const I={...Qe.current,status:C["generating-a-response"]};Qe.current=I,(x=ue.current)==null||x.call(ue,I),wt(!0);const Y={id:`wake-${Date.now()}`,author:ae.user,text:Hn};Z(tt=>[...tt,ye(Y)]);const se=await M.current.sendMessage(Hn);Z(tt=>[...tt,ye(se.message)]),un(se)}catch{ee(h?Na:ka)}finally{ft(!1),wt(!1)}},[un]),Ws=a.useCallback(async()=>{ee(null),pe(null),E(!0);try{await Re(t),W(!1),re==null||re(),r()}catch{pe(xn),ee(xn)}finally{E(!1)}},[t,Re,re,r]),Xs=a.useCallback(async()=>{ee(null),Ft(null),vt(!0);try{await st(t),In(null),K(H.paused),xt(!0),y("chat"),on(!1),he==null||he()}catch{Ft(wn),ee(wn)}finally{vt(!1)}},[t,st,he]),Zs=a.useCallback(async()=>{ee(null),Gt(null),Rn(!0);try{await at(t),cn(!1),D==null||D(),r()}catch(h){Gt(bs(h))}finally{Rn(!1)}},[t,at,D,r]),Qs=a.useCallback(h=>{const x=h.trim(),I=Te;if(xe(null),!x){ve(Y=>Y+1);return}x!==I&&($e(x),(async()=>{try{await je(t,x)}catch{$e(I),ve(Y=>Y+1),xe(ya)}})())},[Te,t,je]),ea=a.useCallback(()=>{if(!j||gt||pt)return;const h=++et.current;mt(!0),_t(null),(async()=>{try{const x=await _e(t);if(et.current!==h)return;Ut(x),Dt(!0)}catch{et.current===h&&_t(la)}finally{et.current===h&&mt(!1)}})()},[j,gt,pt,_e,t]),ta=ke;return n.jsxs(n.Fragment,{children:[n.jsxs(u.Modal,{open:s,closeHandler:r,hideCloseButton:!0,className:"agent-workspace",children:[n.jsxs(u.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(u.Icon,{name:"ask-arbor",size:24})}),n.jsx(u.Modal.Title,{children:F?n.jsx("span",{className:"agent-workspace__header-name",children:Te}):n.jsx(u.EditableText,{className:"agent-workspace__header-name",text:Te,onEditSave:Qs},Be)}),n.jsx("span",{className:J("agent-workspace__phase",`agent-workspace__phase--${ne}`),children:Ea[ne]}),F?n.jsx("span",{className:"agent-workspace__phase agent-workspace__phase--archived",children:"Archived"}):null,jt&&n.jsx("p",{className:"agent-workspace__error agent-workspace__name-error",role:"alert",children:jt})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(u.Button,{variant:qt?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!qt,onClick:()=>Ds(h=>!h),children:"Checklist"}),n.jsx(u.Button,{variant:Vt?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Vt,onClick:()=>Hs(h=>!h),children:"Resources"}),n.jsx(u.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:r,children:"Close"})]})]}),n.jsxs(u.Modal.Body,{className:J("agent-workspace__body",{"agent-workspace__body--no-checklist":qt,"agent-workspace__body--no-resources":Vt}),children:[n.jsxs("section",{className:J("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!A&&(F||oe==="timeline")}),"aria-label":"Agent",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(u.Heading,{level:4,children:"Agent"}),f&&!Ze&&!F&&ne===H.running&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Pause",disabled:Ht,onClick:()=>void Ys(),children:Ht?"Pausing…":"Pause agent"}),v&&!Ze&&!F&&ne===H.paused&&Ms&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"iteration-ccw",iconLeftScreenReaderText:"Resume",disabled:Bt,onClick:()=>void Js(),children:Bt?"Resuming…":"Resume agent"}),g&&!Ze&&!F&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>{pe(null),ee(null),W(!0)},children:"Archive agent"}),b&&!Ze&&F&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",onClick:()=>{Ft(null),ee(null),on(!0)},children:"Unarchive agent"}),j&&F&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",onClick:()=>{Gt(null),ee(null),cn(!0)},children:"Delete agent"})]}),Tn&&n.jsx("p",{className:"agent-workspace__error agent-workspace__lifecycle-error",role:"alert",children:Tn}),A&&!F&&n.jsxs(u.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(u.Tabs.Item,{active:oe==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>y("chat")},children:"Chat"}),n.jsx(u.Tabs.Item,{active:oe==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>y("timeline")},children:"Timeline"})]}),A&&!F&&oe==="chat"&&P&&n.jsx("div",{className:"agent-workspace__center-back",children:n.jsx(u.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:hn,children:"Back to main chat"})}),A&&(F||oe==="timeline")&&n.jsx(rr,{timeline:ce,isLoading:Lt,error:Mt,onOpenChatSession:F?void 0:Vs}),!F&&n.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!A&&oe!=="chat",children:n.jsx(Ga,{connector:z,phase:ne,chatHistory:rt,chatSessionKey:Rt,startQuery:Ge,clarificationMessage:it,readOnly:Ze,enableUpload:L,onTurn:un,onAwaitingChange:wt,onClarificationPrompt:Ks,onDismissClarification:()=>we(null)})}),F&&!A&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Chat is not available for archived agents."})]}),!qt&&n.jsx(za,{checklist:ta,isLoading:sn,error:an,phase:ne,canRequestInput:!Ze&&!F&&ne===H.running&&!zt,onAttentionItemClick:qs,adminMode:j,context:rn,contextLoaded:gt,contextLoading:pt,contextError:ln,onContextSelect:ea},t),!Vt&&n.jsx(Ka,{resources:lt,isLoading:Tt,error:qe,onOpenResource:zs}),n.jsx(qa,{resource:ot,html:Ot,isLoading:Ke,error:Ae,onClose:Gs})]})]}),n.jsx(ls,{open:S,isInProgress:ne===H.running||ne===H.paused&&!us(ke??void 0),isArchiving:d,error:Ie,onCancel:()=>{d||(pe(null),W(!1))},onConfirm:()=>{Ws()}}),n.jsx(cs,{open:Is,isUnarchiving:Ne,error:Os,onCancel:()=>{Ne||(Ft(null),on(!1))},onConfirm:()=>{Xs()}}),n.jsx(os,{open:Ls,isDeleting:jn,error:Ps,onCancel:()=>{jn||(Gt(null),cn(!1))},onConfirm:()=>{Zs()}})]})},Fr="Unable to load agent definitions. Please try again.",Gr="Unable to start the agent.",Xn="Loading agents…",zr="Which agent?",qr="Select an agent",Vr="Name for this run",Kr="e.g. Year 6 Science Museum trip",Yr="Shown on the board and in the workspace",Zn="new-agent-invocation-name-hint",js=({open:e,onClose:t,onStart:s,agentDefinitions:r,definitionsState:i="idle",definitionsError:c=null,onRetryDefinitions:l,embedded:p=!1})=>{const[o,A]=a.useState(void 0),[_,k]=a.useState(""),[f,v]=a.useState(!1),[g,b]=a.useState(null),O=[...r].sort((T,$)=>T.display_name.localeCompare($.display_name)).map(T=>({value:T.ref,label:T.display_name}));a.useEffect(()=>{e&&(A(void 0),k(""),v(!1),b(null))},[e]);const L=o!==void 0&&_.trim().length>0,j=a.useCallback(T=>{const $=r.find(X=>X.ref===T[0]);$&&A($)},[r]),N=a.useCallback(async()=>{if(!(!o||!L||f)){v(!0),b(null);try{await s({definition:o,invocationName:_.trim()})}catch(T){b(T instanceof Error?T.message:Gr)}finally{v(!1)}}},[L,o,_,f,s]);if(i==="idle"&&r.length===0||!e)return null;const m=n.jsxs("div",{className:"new-agent__header-title",children:[n.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:n.jsx(u.Icon,{name:"ask-arbor",size:24})}),p?n.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):n.jsx(u.Modal.Title,{children:"Start an agent"})]});let w;return i==="loading"?w=n.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[n.jsx(u.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:Xn}),n.jsx("p",{className:"new-agent__state-message",children:Xn})]}):i==="error"?w=n.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[n.jsx(u.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"new-agent__state-message",children:c??Fr}),l?n.jsx(u.Button,{variant:"secondary",size:"S",onClick:l,children:"Try again"}):null]}):w=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:T=>{T.preventDefault(),L&&!f&&N()},children:[n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:zr}),n.jsx(u.SelectDropdown,{id:"new-agent-type",placeholder:qr,options:O,selectedValues:o?[o.ref]:[],onSelectionChange:j})]}),n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:Vr}),n.jsx(u.TextInput,{id:"new-agent-invocation-name",value:_,placeholder:Kr,"aria-describedby":Zn,onChange:T=>k(T.target.value)}),n.jsx("p",{className:"new-agent__field-hint",id:Zn,children:Yr})]}),g?n.jsx("p",{className:"new-agent__error",role:"alert",children:g}):null,n.jsx("div",{className:"new-agent__actions",children:n.jsx(u.Button,{type:"submit",variant:"primary",className:J("new-agent__start-button",{"new-agent__start-button--starting":f}),disabled:!L||f,iconLeftName:f?"loader":"sparkles",iconLeftScreenReaderText:f?"Starting":void 0,children:f?"Starting…":"Start"})})]}),p?n.jsxs("div",{className:J("new-agent","new-agent--embedded"),children:[n.jsx("div",{className:"new-agent__header",children:m}),n.jsx("div",{className:"new-agent__body",children:w})]}):n.jsxs(u.Modal,{open:e,closeHandler:t,className:"new-agent",children:[n.jsx(u.Modal.Header,{className:"new-agent__header",children:m}),n.jsx(u.Modal.Body,{className:"new-agent__body",children:w})]})},Qn=e=>{window.location.assign(e)},Jr=({open:e,authToken:t,headers:s,agentDefinitionsUrl:r,agentsUrl:i,closeUrl:c,successUrl:l,onClose:p,onStart:o,embedded:A=!1})=>{const _=JSON.stringify(s??{}),k=a.useMemo(()=>new tn({token:t,headers:s,urls:{agentDefinitions:r,agents:i}}),[t,r,i,_]),[f,v]=a.useState([]),[g,b]=a.useState("loading"),[O,L]=a.useState(null),[j,N]=a.useState(0);a.useEffect(()=>{if(!e)return;let $=!1;return b("loading"),L(null),(async()=>{try{const X=await k.listAgentDefinitions();if($)return;v(X.map(Cn)),b("idle")}catch(X){if($)return;v([]),L(ys(X)),b("error")}})(),()=>{$=!0}},[k,e,j]);const m=a.useCallback(()=>{p==null||p(),c&&Qn(c)},[c,p]),w=a.useCallback(async $=>{await k.createAgent($.definition.ref,{invocationName:$.invocationName}),o==null||o($),l&&Qn(l)},[k,o,l]),T=a.useCallback(()=>{N($=>$+1)},[]);return n.jsx(js,{open:e,onClose:m,onStart:w,agentDefinitions:f,definitionsState:g,definitionsError:O,onRetryDefinitions:T,embedded:A})},Wr=e=>"agentDefinitionsUrl"in e,Rs=e=>Wr(e)?n.jsx(Jr,{...e}):n.jsx(js,{...e}),Xr=e=>e.archivedAt?"archived":e.status===C.paused?"paused":null,Zr=e=>{if(e==="archived")return sa;if(e==="paused")return Ct[C.paused].statusIcon},Qr=({column:e,overlayIcon:t,label:s})=>{const r=t??e.statusIcon;return r?n.jsx("span",{className:"agent-view__status-indicator",children:n.jsx(u.Icon,{name:r.name,size:16,color:r.color,className:J({"agent-view__progress-icon--spinning":r.spin}),screenReaderText:s})}):n.jsx("span",{className:J("agent-view__dot",{[`agent-view__dot--${e.dotModifier}`]:e.dotModifier}),children:n.jsx(u.Dot,{colour:e.dotColour,label:s})})},Ts=({agent:e,agentName:t,column:s,isExpanded:r,isLoading:i,checklist:c,error:l,canArchive:p,canUnarchive:o=!1,canDelete:A=!1,onToggle:_,onViewAgent:k,onArchive:f,onUnarchive:v,onDelete:g})=>{const{id:b,invocation_name:O}=e,L=`agent-card-${b}-header`,j=`agent-card-${b}-progress`,N=Xr(e),m=Zr(N);return n.jsx("li",{className:J("agent-view__card",{"agent-view__card--expanded":r,"agent-view__card--paused":N==="paused","agent-view__card--archived":N==="archived","agent-view__card--view-only":!e.usable}),children:n.jsxs(u.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":r,"aria-controls":j,"aria-label":O,id:L,onClick:()=>_(b),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(Qr,{column:s,overlayIcon:m}),n.jsx("span",{className:"agent-view__card-invocation-name",children:O}),n.jsx("span",{className:"agent-view__card-agent-name",children:t}),N==="paused"?n.jsx("span",{className:"agent-view__card-state-pill",children:"Paused"}):null,N==="archived"?n.jsx("span",{className:"agent-view__card-state-pill",children:"Archived"}):null,e.usable?null:n.jsx("span",{className:"agent-view__card-state-pill",children:"View only"}),n.jsx(u.Icon,{name:r?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),r&&n.jsxs("div",{id:j,"aria-labelledby":L,className:"agent-view__card-progress",children:[i&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:nt}),n.jsx("span",{children:nt})]}),!i&&l&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:l}),!i&&!l&&c!==null&&n.jsx(Ha,{checklist:c}),!i&&!l&&c===null&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:nt}),n.jsx("span",{children:nt})]}),n.jsxs("div",{className:"agent-view__card-actions",children:[p?n.jsx(u.Button,{variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>f==null?void 0:f(e),children:"Archive"}):o?n.jsx(u.Button,{variant:"secondary",size:"S",onClick:()=>v==null?void 0:v(e),children:"Unarchive"}):A?n.jsx(u.Button,{variant:"secondary-destructive",size:"S",onClick:()=>g==null?void 0:g(e),children:"Delete"}):n.jsx("span",{}),o&&A?n.jsx(u.Button,{variant:"secondary-destructive",size:"S",onClick:()=>g==null?void 0:g(e),children:"Delete"}):null,n.jsx(u.Button,{variant:"secondary",size:"S",onClick:()=>k==null?void 0:k(e),children:"View agent"})]})]})]})})},ei=({column:e,agents:t,expandedAgentId:s,loadingAgentId:r,checklistByInvocationId:i,errorByAgentId:c,definitionNameByRef:l,onToggleAgent:p,onViewAgent:o,onArchiveAgent:A,canArchive:_})=>n.jsxs("section",{className:"agent-view__column","aria-label":e.title,children:[n.jsxs("div",{className:"agent-view__column-header",children:[n.jsx(u.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(k=>n.jsx(Ts,{agent:k,agentName:Xt(k,l),column:e,isExpanded:s===k.id,isLoading:r===k.id,checklist:i[k.invocation_id]??null,error:c[k.id]??null,canArchive:_&&!k.archivedAt&&k.usable,onToggle:p,onViewAgent:o,onArchive:A},k.id))})]}),Xt=(e,t)=>t.get(e.agent_definition_ref)??e.agent_definition_ref.replace(/_/g," "),ti=({jwt:e,headers:t,agentDefinitionsUrl:s,agentsUrl:r,agentUrl:i,agentChecklistUrl:c,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:o,agentConversationUrl:A,pauseAgentUrl:_,resumeAgentUrl:k,archiveAgentUrl:f,unarchiveAgentUrl:v,enableUpload:g,adminMode:b=!1,showHeader:O=!1,institutions:L,usePusherToRepoll:j=!1,pusherChannelPrefix:N=bn,pusherKey:m,pusherCluster:w,subscribeToPusher:T,scope:$=rs})=>{var ft;const X=a.useMemo(()=>({agentDefinitions:s,agents:r,agent:i,agentChecklist:c,...l?{agentResources:l}:{},...p?{agentTimeline:p}:{},agentChat:o,agentConversation:A,...f?{archiveAgent:f}:{},...v?{unarchiveAgent:v}:{}}),[s,r,i,c,l,p,o,A,f,v]),[Q,te]=a.useState(null),re=Q?(ft=L==null?void 0:L.find(d=>d.applicationId===Q.application_id))==null?void 0:ft.applicationUrl:void 0,he=a.useMemo(()=>{const d={...t??{}};return re?d[Me.arborApplicationUrl]=re:delete d[Me.arborApplicationUrl],d},[t,re]),{agents:D,agentDefinitions:ie,loadState:le,loadError:Se,reload:oe,refresh:y,fetchAgentChecklist:P,createAgent:R,archiveAgent:z,unarchiveAgent:B,deleteAgent:V,removeAgent:_e,replaceAgent:He}=Cs({jwt:e,headers:he,urls:X,scope:$}),[St,fe]=a.useState(!1),[je,Re]=a.useState(null),[st,at]=a.useState(null),[M,Te]=a.useState({}),[$e,Be]=a.useState({}),[ve,jt]=a.useState([]),[xe,ne]=a.useState([]),[K,rt]=a.useState(null),[Z,Rt]=a.useState(!1),[Fe,Ge]=a.useState(null),[nn,it]=a.useState(!1),[we,lt]=a.useState(null),[ze,Tt]=a.useState(!1),[It,qe]=a.useState(null),[ge,ot]=a.useState(null),[Ve,Ot]=a.useState(!1),[ct,Ke]=a.useState(null);a.useEffect(()=>{te(d=>d?D.find(E=>E.id===d.id)??null:null)},[D]);const Ye=a.useMemo(()=>{const d=new Set(D.map(S=>S.application_id)),E=new Map((L??[]).map(S=>[S.applicationId,S.name]));return[...d].sort((S,W)=>(E.get(S)??S).localeCompare(E.get(W)??W)).map(S=>({value:S,label:E.get(S)??S}))},[D,L]),Ae=a.useMemo(()=>new Map(ie.map(d=>[d.ref,d.display_name])),[ie]),Je=a.useMemo(()=>[...new Set(D.map(E=>Xt(E,Ae)))].sort((E,S)=>E.localeCompare(S)).map(E=>({value:E,label:E})),[D,Ae]),ce=a.useMemo(()=>D.filter(d=>!(ve.length>0&&!ve.includes(d.application_id)||xe.length>0&&!xe.includes(Xt(d,Ae)))),[D,Ae,xe,ve]),ut=Ye.length>1,Lt=Je.length>1,Pt=ut||Lt;a.useEffect(()=>{const d=window.setInterval(()=>{y()},6e4);return()=>{window.clearInterval(d)}},[y]),a.useEffect(()=>{if(D.length===0)return;let d=!1;return(async()=>{const E=await Promise.allSettled(D.map(async S=>{const W=await P(S.invocation_id);return{agentId:S.id,invocationId:S.invocation_id,checklist:W.checklist}}));d||(Te(S=>{const W={...S};let Ie=!1;for(const pe of E){if(pe.status!=="fulfilled")continue;const{invocationId:Ne,checklist:vt}=pe.value;JSON.stringify(S[Ne])!==JSON.stringify(vt)&&(W[Ne]=vt,Ie=!0)}return Ie?W:S}),Be(S=>{const W={...S};let Ie=!1;return E.forEach((pe,Ne)=>{pe.status==="rejected"&&W[D[Ne].id]!==Wt&&(W[D[Ne].id]=Wt,Ie=!0)}),Ie?W:S}))})(),()=>{d=!0}},[D,P]);const Mt=a.useCallback(async d=>{if(!M[d.invocation_id]){at(d.id),Be(E=>{const S={...E};return delete S[d.id],S});try{const E=await P(d.invocation_id);Te(S=>({...S,[d.invocation_id]:E.checklist}))}catch{Be(E=>({...E,[d.id]:Wt}))}finally{at(E=>E===d.id?null:E)}}},[P,M]),We=a.useCallback(d=>{if(je===d){Re(null);return}const E=D.find(({id:S})=>S===d);E&&(Re(d),Mt(E))},[D,je,Mt]),ke=a.useMemo(()=>ce.filter(d=>!!d.archivedAt),[ce]),Xe=a.useMemo(()=>ce.filter(d=>!d.archivedAt),[ce]),sn=a.useMemo(()=>{const d={};for(const E of Xe){const S=mn(E,M[E.invocation_id]);(d[S]??(d[S]=[])).push(E)}return d},[Xe,M]),dt=a.useCallback(d=>{te(d)},[]),an=a.useCallback(d=>{Ge(null),rt(d)},[]),ht=a.useCallback(()=>{Z||(Ge(null),rt(null))},[Z]),rn=a.useCallback(async()=>{if(K){Rt(!0),Ge(null),Be(d=>{const E={...d};return delete E[K.id],E});try{await z(K.invocation_id),te(d=>(d==null?void 0:d.id)===K.id?null:d),Re(K.id),it(!0),rt(null)}catch{Ge(xn)}finally{Rt(!1)}}},[K,z]),Ut=a.useCallback(d=>{qe(null),lt(d)},[]),gt=a.useCallback(()=>{ze||(qe(null),lt(null))},[ze]),Dt=a.useCallback(async()=>{if(we){Tt(!0),qe(null);try{await B(we.invocation_id),lt(null)}catch{qe(wn)}finally{Tt(!1)}}},[we,B]),pt=K?mn(K,M[K.invocation_id])!==C.complete:!1,mt=a.useCallback(async d=>{const E=await R(d);te(E),fe(!1)},[R]),ln=a.useCallback(d=>{Ke(null),ot(d)},[]),_t=a.useCallback(()=>{Ve||(Ke(null),ot(null))},[Ve]),Ht=a.useCallback(async()=>{if(ge){Ot(!0),Ke(null);try{await V(ge.invocation_id),te(d=>(d==null?void 0:d.id)===ge.id?null:d),ot(null)}catch(d){Ke(bs(d))}finally{Ot(!1)}}},[ge,V]),$t=a.useCallback(()=>{te(null)},[]),Bt={expandedAgentId:je,loadingAgentId:st,checklistByInvocationId:M,errorByAgentId:$e,definitionNameByRef:Ae,onToggleAgent:We,onViewAgent:dt,onArchiveAgent:an,canArchive:!!f};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[O&&n.jsxs("div",{className:"agent-view__header",children:[n.jsx(u.Heading,{level:1,children:"Agents"}),n.jsx(u.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>fe(!0),children:"Start an agent"})]}),D.length>0&&Pt&&n.jsxs("div",{className:"agent-view__filters",children:[ut&&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(u.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:Ye,value:ve,onValueChange:jt,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Lt&&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(u.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:Je,value:xe,onValueChange:ne,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),le==="error"?n.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[n.jsx(u.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"agent-view__state-message",children:Se??as}),n.jsx(u.Button,{variant:"secondary",size:"S",onClick:oe,children:"Try again"})]}):le==="loading"&&D.length===0?n.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[n.jsx(u.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:$n}),n.jsx("p",{className:"agent-view__state-message",children:$n})]}):D.length===0?n.jsx(Ia,{}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"agent-view__board",children:aa.map(d=>n.jsx(ei,{column:Ct[d],agents:sn[d]??[],...Bt},d))}),ke.length>0?n.jsxs("details",{className:"agent-view__archived",open:nn,onToggle:d=>{it(d.currentTarget.open)},children:[n.jsxs("summary",{className:"agent-view__archived-summary",children:[n.jsx(u.Heading,{level:4,children:"Archived"}),n.jsx("span",{className:"agent-view__column-count",children:ke.length})]}),n.jsx("ul",{className:"agent-view__card-list agent-view__archived-list",children:ke.map(d=>n.jsx(Ts,{agent:d,agentName:Xt(d,Ae),column:Ct[mn(d,M[d.invocation_id])],isExpanded:je===d.id,isLoading:st===d.id,checklist:M[d.invocation_id]??null,error:$e[d.id]??null,canArchive:!1,canUnarchive:!!v&&d.usable,canDelete:b&&d.usable,onToggle:We,onViewAgent:dt,onUnarchive:Ut,onDelete:ln},d.id))})]}):null]}),Q&&n.jsx(Ss,{agent:Q,invocationId:Q.invocation_id,open:!0,jwt:e,headers:he,agentUrl:i,agentChecklistUrl:c,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:o,agentConversationUrl:A,pauseAgentUrl:_,resumeAgentUrl:k,archiveAgentUrl:f,unarchiveAgentUrl:v,enableUpload:g,adminMode:b,initialChecklist:M[Q.invocation_id]??null,usePusherToRepoll:j,pusherChannelPrefix:N,pusherKey:m,pusherCluster:w,subscribeToPusher:T,onClose:$t,onAgentUpdated:He,onArchived:()=>{Re(Q.id),it(!0),y()},onUnarchived:()=>{y()},onDeleted:()=>{_e(Q.invocation_id)}},Q.id),n.jsx(ls,{open:!!K,isInProgress:pt,isArchiving:Z,error:Fe,onCancel:ht,onConfirm:()=>{rn()}}),n.jsx(cs,{open:!!we,isUnarchiving:ze,error:It,onCancel:gt,onConfirm:()=>{Dt()}}),n.jsx(os,{open:!!ge,isDeleting:Ve,error:ct,onCancel:_t,onConfirm:()=>{Ht()}}),n.jsx(Rs,{open:St,onClose:()=>fe(!1),onStart:mt,agentDefinitions:ie})]})},ni=(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:ra,created_by:ia,usable:!0,status:C["generating-a-response"],archivedAt:null,context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=ti;exports.AgentServiceClient=tn;exports.AgentServiceError=Ue;exports.AgentView=Ss;exports.DEFAULT_PUSHER_CHANNEL_PREFIX=bn;exports.HttpChatConnector=Ns;exports.MESSAGE_TYPE_REPOLL=kn;exports.NewAgentModal=Rs;exports.PUSHER_AGENT_MESSAGE_EVENT=gs;exports.REPOLL_TARGET=Ce;exports.buildAgentFromDefinition=ni;exports.buildAgentPusherChannel=ps;exports.createHttpChatConnectorFactory=Sn;exports.formatUserFileChatCardText=Er;exports.mapApiAgent=Ee;exports.mapApiAgentDefinition=Cn;exports.mapApiAgentStatus=fs;exports.mapApiAgentTimelineResponse=As;exports.mapApiChecklistEndpointResponse=en;exports.mapApiChecklistItem=En;exports.mapApiChecklistResponse=br;exports.mapApiChecklistStatus=vs;exports.mapApiConversationMessages=ks;exports.mapApiOpeningMessage=Et;exports.mapApiResource=xs;exports.mapApiResourcesEndpointResponse=ws;exports.mapApiTripOption=Ar;exports.parseConversationContentCaption=Cr;exports.parseRepollMessages=ms;exports.useAgentService=Cs;exports.useAgentWorkspace=Es;exports.useSubscribeToPusher=_s;
package/dist/index.d.ts CHANGED
@@ -11,6 +11,7 @@ export declare type Agent = {
11
11
  application_id: string;
12
12
  application_name?: string;
13
13
  created_by: string;
14
+ usable: boolean;
14
15
  status: AgentStatus;
15
16
  archivedAt?: string | null;
16
17
  context_ref: string | null;
@@ -65,7 +66,7 @@ export declare type AgentDefinition = {
65
66
  description: string;
66
67
  };
67
68
 
68
- export declare const AgentMonitorKanban: ({ jwt, headers, agentDefinitionsUrl, agentsUrl, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, pauseAgentUrl, resumeAgentUrl, archiveAgentUrl, unarchiveAgentUrl, enableUpload, adminMode, showHeader, institutions, usePusherToRepoll, pusherChannelPrefix, pusherKey, pusherCluster, subscribeToPusher, }: AgentMonitorKanbanProps) => JSX_2.Element;
69
+ export declare const AgentMonitorKanban: ({ jwt, headers, agentDefinitionsUrl, agentsUrl, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, pauseAgentUrl, resumeAgentUrl, archiveAgentUrl, unarchiveAgentUrl, enableUpload, adminMode, showHeader, institutions, usePusherToRepoll, pusherChannelPrefix, pusherKey, pusherCluster, subscribeToPusher, scope, }: AgentMonitorKanbanProps) => JSX_2.Element;
69
70
 
70
71
  export declare type AgentMonitorKanbanProps = {
71
72
  jwt?: string;
@@ -91,6 +92,7 @@ export declare type AgentMonitorKanbanProps = {
91
92
  pusherKey?: string;
92
93
  pusherCluster?: string;
93
94
  subscribeToPusher?: SubscribeToPusher;
95
+ scope?: AgentScope;
94
96
  };
95
97
 
96
98
  export declare type AgentResource = {
@@ -111,6 +113,8 @@ export declare type AgentResourcesPage = {
111
113
 
112
114
  export declare type AgentResourceType = 'document_html' | 'mis_record' | 'workflow' | 'file' | 'user_file' | 'link';
113
115
 
116
+ export declare type AgentScope = 'my' | 'all';
117
+
114
118
  export declare class AgentServiceClient {
115
119
  private readonly baseUrl;
116
120
  private readonly token?;
@@ -172,6 +176,7 @@ export declare type AgentServiceConfig = {
172
176
  jwt?: string;
173
177
  headers?: Record<string, string>;
174
178
  urls: AgentServiceUrls;
179
+ scope?: AgentScope;
175
180
  };
176
181
 
177
182
  export declare class AgentServiceError extends Error {
@@ -313,6 +318,7 @@ export declare type ApiAgentInvocation = {
313
318
  application_id: string;
314
319
  application_name?: string;
315
320
  created_by: string;
321
+ usable?: boolean;
316
322
  status: ApiAgentInvocationStatus;
317
323
  archived_at?: string | null;
318
324
  context_ref?: string | null;
@@ -585,6 +591,7 @@ export declare type InstitutionConfig = {
585
591
  export declare type ListAgentsParams = {
586
592
  status?: ApiAgentInvocationStatus;
587
593
  agentDefinitionRef?: string;
594
+ scope?: 'my' | 'all';
588
595
  };
589
596
 
590
597
  export declare const mapApiAgent: (record: ApiAgentInvocation) => Agent;