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