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

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