@arbor-education/agent-view-frontend 0.9.4-alpha.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -200,7 +200,7 @@ second design-system Modal (which portals to `document.body`):
200
200
  | `closeUrl` | `close-url` | no | Page navigated to when the modal is closed. |
201
201
  | `successUrl` | `success-url` | no | Page navigated to after a successful start when `viewAgentUrlPrefix` is unset. |
202
202
  | `viewAgentUrlPrefix` | `view-agent-url-prefix` | no | After create, navigate to `{prefix}/{id}` using the new agent `id`. |
203
- | `preselectAgent` | `preselect-agent` | no | Pre-select a definition. **Temporary:** matches definition `ref`, which is mapped from API `name`. Switch to API `code` when the backend adds it. All definitions remain listed. |
203
+ | `preselectAgent` | `preselect-agent` | no | Pre-select a definition. **Temporary:** matches definition `ref`, which is mapped from API `name`. Switch to API `code` when the backend adds it. When matched, the select step shows `Start the {display_name}` instead of the dropdown. |
204
204
 
205
205
  Navigation uses `window.location.assign`. `closeUrl`/`successUrl`/`viewAgentUrlPrefix` are optional —
206
206
  omit them (and pass `onClose`/`onStart`) to keep the modal fully controlled.
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),r=require("react"),Y=require("classnames"),u=require("@arbor-education/design-system.components"),Ee=require("@arbor-education/ask-arbor-chat-panel"),Qs=require("pusher-js"),k={"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"},me={agent:"agent",user:"user",system:"system"},Ne={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",user_file:"user_file",link:"link"},ns={user_file:"user_file"},_n={active:"active",complete:"complete",paused:"paused"},Rt={in_progress:"in_progress",to_do:"to_do",requires_attention:"requires_attention",waiting_on_human:"waiting_on_human",available:"available"},ke={[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",color:"var(--color-brand-600)"}},ss="var(--color-grey-600)",lt={[k["generating-a-response"]]:{status:k["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:"sparkles",color:ke["generating-a-response"].color}},[k.hitl]:{status:k.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:ke.hitl.icon,color:ke.hitl.color}},[k.paused]:{status:k.paused,title:"Paused",dotColour:"green",statusIcon:{name:"circle-x",color:ss}},[k.complete]:{status:k.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:ke.complete.icon,color:ke.complete.color}}},ea={name:"archive",color:ss},$n=[k["generating-a-response"],k.hitl,k.complete],ta="m4",na="1",as="msg-opening",Xt="Unable to load agent tasks. Please try again.",sa="Unable to load context.",aa="Unable to load the resources for this agent",ra="Unable to load this document. Please try again.",rs="Unable to load the timeline for this agent",ia="Unable to pause the agent. Please try again.",Nn="Unable to archive the agent. Please try again.",la="Archive this agent?",oa="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.",ca="This agent is still in progress.",kn="Unable to unarchive the agent. Please try again.",ua="Restore this agent?",da="Restoring returns this agent to the board as paused. It will not run chats or scheduled work until you resume it.",ha="Unable to delete the agent. Please try again.",ga="You do not have permission to delete this agent.",ma="This agent must be paused or archived before it can be deleted.",pa="This agent could not be found. It may have already been deleted.",_a="Delete this agent?",fa="Deleting cannot be undone. This permanently removes the agent and its related data. It will not appear in Archived and cannot be restored.",va="Unable to resume the agent. Please try again.",xa="The agent was resumed but could not be woken. Send a message to continue.",Bn="You have been resumed after being paused. Reassess your current progress and continue your work from where you left off.",wa="Unable to rename the agent. Please try again.",ya="Something went wrong. Please try again.",Aa="Unable to send the message. Please try again.",is="Unable to load agents. Please try again.",Na="Agent not found",ka="Agent not found",it="Loading tasks…",ba="Task",Ca={[$.briefing]:"Briefing",[$.running]:"Working",[$.paused]:"Paused",[$.complete]:"Complete"},ls="all",Ea=[k["generating-a-response"],k.hitl,k.complete],Sa={[k["generating-a-response"]]:"Agents currently working on tasks for you.",[k.hitl]:"Agents that need your input before they can continue.",[k.paused]:"Agents that are paused until you resume them.",[k.complete]:"Agents that have finished their work."},ja=()=>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)"})]}),Ra=({status:e})=>{const t=lt[e];return t.statusIcon?n.jsx(u.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,screenReaderText:t.title}):n.jsx(u.Dot,{colour:t.dotColour,label:t.title})},Ta=()=>n.jsxs("section",{className:"agent-view__empty","aria-label":"About the agents board",children:[n.jsxs("div",{className:"agent-view__empty-content",children:[n.jsx(u.Heading,{level:4,children:"Your agents board"}),n.jsx("p",{className:"agent-view__empty-lead",children:"When you start an agent, it appears here so you can track progress at a glance. Agents move between columns as their status changes."}),n.jsx("ul",{className:"agent-view__empty-columns",children:Ea.map(e=>{const t=lt[e];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(Ra,{status:e})}),n.jsxs("span",{className:"agent-view__empty-column-text",children:[n.jsx("span",{className:"agent-view__empty-column-title",children:t.title}),n.jsx("span",{className:"agent-view__empty-column-description",children:Sa[e]})]})]},e)})}),n.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",n.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),n.jsx("div",{className:"agent-view__empty-visual",children:n.jsx(ja,{})})]}),Ia=()=>({inProgress:[],needsInput:[],complete:[],failed:[],tasks:[]}),Oa=(e,t)=>({...e,children:t.length>0?t:void 0}),os=e=>{const t=[],s=[],a=[],i=[],d=[];for(const l of e){const m=l.children?os(l.children):Ia();if(t.push(...m.inProgress),s.push(...m.needsInput),a.push(...m.complete),i.push(...m.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}),d.push(...m.tasks);continue}d.push(Oa(l,m.tasks))}return{inProgress:t,needsInput:s,complete:a,failed:i,tasks:d}},Fn=e=>e===U.hitl?0:e===U.complete?1:e===U.failed?2:3,La=e=>e.map((t,s)=>({item:t,index:s})).sort((t,s)=>{const a=Fn(t.item.status)-Fn(s.item.status);return a!==0?a:t.index-s.index}).map(({item:t})=>t),cs=({status:e,className:t})=>{const s=ke[e];return e===U.to_do||!s.icon?n.jsxs(n.Fragment,{children:[n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:s.color,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:Y("ds-icon","ds-icon-circle",t),role:"img","aria-hidden":!0,children:n.jsx("circle",{cx:12,cy:12,r:10})}),n.jsx("span",{className:"sr-only",children:`${s.label}:`})]}):n.jsx(u.Icon,{name:s.icon,size:16,color:s.color,className:t,screenReaderText:`${s.label}:`})},fn=2,Pa=e=>{if(!e)return{canScrollUp:!1,canScrollDown:!1};const t=e.scrollHeight-e.clientHeight;return t<=fn?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:e.scrollTop>fn,canScrollDown:e.scrollTop<t-fn}},Ma=(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}},en=({children:e,className:t,contentClassName:s,scrollSelector:a,style:i,"aria-label":d})=>{const l=r.useRef(null),m=r.useRef(null),[h,p]=r.useState(!1),[_,A]=r.useState(!1),[o,v]=r.useState(null),E=()=>{var j;return a?((j=l.current)==null?void 0:j.querySelector(a))??null:m.current},S=()=>{const j=E(),y=Pa(j);if(p(f=>f===y.canScrollUp?f:y.canScrollUp),A(f=>f===y.canScrollDown?f:y.canScrollDown),a){const f=Ma(l.current,j);v(x=>(x==null?void 0:x.top)===(f==null?void 0:f.top)&&(x==null?void 0:x.left)===(f==null?void 0:f.left)&&(x==null?void 0:x.width)===(f==null?void 0:f.width)&&(x==null?void 0:x.height)===(f==null?void 0:f.height)?x:f)}else v(f=>f===null?f:null)};r.useLayoutEffect(()=>{S()}),r.useEffect(()=>{const j=l.current;if(!j)return;let y=null,f=null;const x=()=>{y==null||y.removeEventListener("scroll",S),f==null||f.disconnect(),f=null,y=null},R=ae=>{if(ae===y){S();return}if(x(),y=ae,!y){S();return}y.addEventListener("scroll",S,{passive:!0}),f=new ResizeObserver(()=>S()),f.observe(y),y.firstElementChild instanceof HTMLElement&&f.observe(y.firstElementChild),S()};R(E());const V=new MutationObserver(()=>{R(E())});return V.observe(j,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",S),()=>{window.removeEventListener("resize",S),V.disconnect(),x()}},[a]);const I=j=>{const y=E();if(!y)return;const f=Math.max(y.clientHeight*.75,120);y.scrollBy({top:j==="up"?-f:f,behavior:"smooth"})},P=n.jsxs(n.Fragment,{children:[h&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--top","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--top","aria-label":"Scroll up",onClick:()=>I("up"),children:n.jsx(u.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),_&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>I("down"),children:n.jsx(u.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return n.jsx("div",{ref:l,className:Y("scrollable-region",t),style:i,"aria-label":d,children:a?n.jsxs(n.Fragment,{children:[e,o&&(h||_)&&n.jsx("div",{className:"scrollable-region__overlay",style:{top:o.top,left:o.left,width:o.width,height:o.height},children:P})]}):n.jsxs(n.Fragment,{children:[P,n.jsx("div",{ref:m,className:Y("scrollable-region__viewport",s),children:e})]})})},Ua=48,Da=({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<=Ua)&&(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(en,{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:La(e).map(a=>{const i=ke[a.status];return n.jsxs("li",{className:Y("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[n.jsx(cs,{status:a.status,className:i.spin?"agent-view__progress-icon--spinning":void 0}),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)})})})},us=({open:e,isInProgress:t,isArchiving:s,error:a,onCancel:i,onConfirm:d})=>{const l=r.useId(),m=r.useId();return n.jsxs(u.Modal,{open:e,closeHandler:i,className:"archive-agent-confirm",children:[n.jsx(u.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(u.Modal.Title,{id:l,children:la})}),n.jsxs(u.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":l,"aria-describedby":m,children:[n.jsx("p",{id:m,className:"archive-agent-confirm__lead",children:oa}),t?n.jsx("p",{className:"archive-agent-confirm__progress",children:ca}):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(u.Button,{variant:"secondary",size:"S",disabled:s,onClick:i,children:"Cancel"}),n.jsx(u.Button,{variant:"secondary-destructive",size:"S",disabled:s,onClick:d,children:s?"Archiving…":"Archive"})]})]})]})},ds=({open:e,isDeleting:t,error:s,onCancel:a,onConfirm:i})=>{const d=r.useId(),l=r.useId();return n.jsxs(u.Modal,{open:e,closeHandler:a,className:"archive-agent-confirm",children:[n.jsx(u.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(u.Modal.Title,{id:d,children:_a})}),n.jsxs(u.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":d,"aria-describedby":l,children:[n.jsx("p",{id:l,className:"archive-agent-confirm__lead",children:fa}),s?n.jsx("p",{className:"archive-agent-confirm__error",role:"alert",children:s}):null]}),n.jsxs("div",{className:"archive-agent-confirm__actions",children:[n.jsx(u.Button,{variant:"secondary",size:"S",disabled:t,onClick:a,children:"Cancel"}),n.jsx(u.Button,{variant:"secondary-destructive",size:"S",disabled:t,onClick:i,children:t?"Deleting…":"Delete"})]})]})]})},hs=({open:e,isUnarchiving:t,error:s,onCancel:a,onConfirm:i})=>{const d=r.useId(),l=r.useId();return n.jsxs(u.Modal,{open:e,closeHandler:a,className:"archive-agent-confirm",children:[n.jsx(u.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(u.Modal.Title,{id:d,children:ua})}),n.jsxs(u.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":d,"aria-describedby":l,children:[n.jsx("p",{id:l,className:"archive-agent-confirm__lead",children:da}),s?n.jsx("p",{className:"archive-agent-confirm__error",role:"alert",children:s}):null]}),n.jsxs("div",{className:"archive-agent-confirm__actions",children:[n.jsx(u.Button,{variant:"secondary",size:"S",disabled:t,onClick:a,children:"Cancel"}),n.jsx(u.Button,{variant:"secondary",size:"S",disabled:t,onClick:i,children:t?"Restoring…":"Restore"})]})]})]})},Ha=e=>e!==void 0&&e.some(t=>t.status===U.hitl),gs=e=>e!==void 0&&e.length>0&&e.every(t=>t.status===U.complete),vn=(e,t)=>e.status===k.paused?gs(t)?k.complete:k["generating-a-response"]:Ha(t)?k.hitl:e.status===k.complete?k.complete:e.status===k.hitl?k.hitl:k["generating-a-response"];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{id:`error-${Date.now()}`,text:Aa,type:Ee.CHAT_RESPONSE_TYPE_ERROR};(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:Ee.CHAT_RESPONSE_TYPE_AGENT,...i.message.followUpPrompts?{followUpPrompts:i.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:ya,type:Ee.CHAT_RESPONSE_TYPE_ERROR}}finally{(a=this.onAwaitingChange)==null||a.call(this,!1)}}async loadHistory(t){return null}async listInteractions(){return null}async rateMessage(t){}async sendNotification(t){return!1}}const Ba=({connector:e,phase:t,chatHistory:s,chatSessionKey:a,readOnly:i=!1,enableUpload:d=!1,onTurn:l,onAwaitingChange:m})=>{const h=r.useMemo(()=>new $a(e,{canSend:()=>!i&&t===$.running,onTurn:l,onAwaitingChange:m}),[e,t,i,l,m]),p=i||t!==$.running,_=!i&&t===$.running;let A="The agent is not accepting messages.";return _&&(A="Message the agent, paste a link, or attach a file…"),i&&(A="You can view this conversation but cannot send messages."),n.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(en,{scrollSelector:".chat-panel-message-list",children:n.jsx(Ee.ChatPanel,{connector:h,chatHistory:s,lockConversation:p,enableUpload:d,speechEnabled:_,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:A},a)})}),i&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(u.Icon,{name:"eye",size:16,color:"var(--color-grey-700)"}),n.jsx("span",{children:"View only — you cannot interact with this agent."})]}),t===$.paused&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(u.Icon,{name:"circle-alert",size:16,color:"var(--color-semantic-warning-600)"}),n.jsx("span",{children:"The agent is paused. Its progress is saved in the checklist."})]}),t===$.complete&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(u.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),n.jsx("span",{children:"The agent has finished."})]})]})},ms=({item:e,depth:t})=>{const s=ke[e.status],a=e.status.replace(/_/g,"-");return n.jsxs("li",{className:Y("agent-workspace__task",`agent-workspace__task--${a}`,{"agent-workspace__task--child":t>0}),children:[n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(cs,{status:e.status,className:s.spin?"agent-workspace__task-icon--spinning":void 0}),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})]})]}),e.children&&e.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:e.children.map(i=>n.jsx(ms,{item:i,depth:t+1},i.task))})]})},Tt=({items:e,ariaLabel:t})=>n.jsx("ul",{className:"agent-workspace__task-list","aria-label":t,children:e.map(s=>n.jsx(ms,{item:s,depth:0},s.task))}),Fa=({checklist:e,isLoading:t,error:s,phase:a,adminMode:i=!1,context:d,contextLoaded:l=!1,contextLoading:m=!1,contextError:h=null,onContextSelect:p})=>{const[_,A]=r.useState("checklist"),o=r.useMemo(()=>e?os(e):null,[e]),v=()=>{A("context"),p==null||p()};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:i?n.jsxs(u.Tabs,{className:"agent-workspace__checklist-tabs","aria-label":"Checklist panel",children:[n.jsx(u.Tabs.Item,{active:_==="checklist",tabElementProps:{id:"agent-checklist-tab-checklist",onClick:()=>A("checklist")},children:"Checklist"}),n.jsx(u.Tabs.Item,{active:_==="context",tabElementProps:{id:"agent-checklist-tab-context",onClick:v},children:"Context"})]}):n.jsx(u.Heading,{level:4,children:"Checklist"})}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsx(en,{children:_==="context"?n.jsxs(n.Fragment,{children:[m&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading context"}),n.jsx("span",{children:"Loading context…"})]}),!m&&h&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:h}),!m&&!h&&l&&d==null&&n.jsx("p",{className:"agent-workspace__empty",children:"No context available."}),!m&&!h&&l&&d!==null&&d!==void 0&&n.jsx("pre",{className:"agent-workspace__context-json",children:JSON.stringify(d,null,2)})]}):n.jsxs(n.Fragment,{children:[t&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:it}),n.jsx("span",{children:it})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!t&&!s&&o&&n.jsxs(n.Fragment,{children:[o.inProgress.length>0&&n.jsxs("div",{className:"agent-workspace__task-group",children:[(o.needsInput.length>0||o.tasks.length>0||o.failed.length>0||o.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"In progress"}),n.jsx(Tt,{items:o.inProgress,ariaLabel:"In progress"})]}),o.needsInput.length>0&&n.jsxs("div",{className:Y("agent-workspace__task-group",{"agent-workspace__task-group--following":o.inProgress.length>0}),children:[n.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),n.jsx(Tt,{items:o.needsInput,ariaLabel:"Tasks needing your input"})]}),o.failed.length>0&&n.jsxs("div",{className:Y("agent-workspace__task-group",{"agent-workspace__task-group--following":o.inProgress.length>0||o.needsInput.length>0}),children:[(o.inProgress.length>0||o.needsInput.length>0||o.tasks.length>0||o.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Failed"}),n.jsx(Tt,{items:o.failed,ariaLabel:"Failed tasks"})]}),o.tasks.length>0&&n.jsxs("div",{className:Y("agent-workspace__task-group",{"agent-workspace__task-group--following":o.inProgress.length>0||o.needsInput.length>0||o.failed.length>0}),children:[(o.inProgress.length>0||o.needsInput.length>0||o.failed.length>0||o.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"To Do"}),n.jsx(Tt,{items:o.tasks,ariaLabel:"Upcoming tasks"})]}),o.complete.length>0&&n.jsxs("div",{className:Y("agent-workspace__task-group",{"agent-workspace__task-group--following":o.inProgress.length>0||o.needsInput.length>0||o.tasks.length>0||o.failed.length>0}),children:[(o.inProgress.length>0||o.needsInput.length>0||o.tasks.length>0||o.failed.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Completed"}),n.jsx(Tt,{items:o.complete,ariaLabel:"Completed tasks"})]})]}),!t&&!s&&(!o||o.inProgress.length===0&&o.needsInput.length===0&&o.complete.length===0&&o.failed.length===0&&o.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."})]})})})]})},Ga=({resource:e,html:t,isLoading:s,error:a,onClose:i})=>{r.useEffect(()=>{if(!e)return;const l=u.SlideoverUtils.removeSlideover;return u.SlideoverUtils.removeSlideover=()=>{l(),i()},()=>{u.SlideoverUtils.removeSlideover=l}},[e,i]),r.useEffect(()=>{if(!e)return;const l=m=>{m.key==="Escape"&&u.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]);const d=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(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading document"}),n.jsx("span",{children:"Loading document…"})]}),!s&&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(u.SlideoverManager,{slideovers:d})})},za={[Ne.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[Ne.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[Ne.file]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[Ne.user_file]:{icon:"upload",label:"File upload",color:"var(--color-semantic-caution-800)"},[Ne.workflow]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[Ne.link]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},qa=({resources:e,isLoading:t=!1,error:s=null,onOpenResource:a})=>n.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--documents","aria-label":"Resources",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(u.Heading,{level:4,children:"Resources"}),n.jsx("span",{className:"agent-workspace__panel-count",children:e.length})]}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsxs(en,{children:[t&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading resources"}),n.jsx("span",{children:"Loading resources…"})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!t&&!s&&e.length>0&&n.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:e.map(i=>{const d=za[i.type],l=i.misRecordUrl;return n.jsx("li",{className:"agent-workspace__resource",children:l?n.jsx("a",{className:"agent-workspace__resource-card",href:l,target:"_blank",rel:"noreferrer",onClick:m=>{m.preventDefault(),a(i)},children:n.jsx(Gn,{resource:i,config:d,external:!0})}):n.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>a(i),children:n.jsx(Gn,{resource:i,config:d})})},i.id)})}),!t&&!s&&e.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),Gn=({resource:e,config:t,external:s=!1})=>n.jsxs(n.Fragment,{children:[n.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${e.type}`,children:n.jsx(u.Icon,{name:t.icon,size:16,color:t.color,screenReaderText:`${t.label}:`})}),n.jsx("span",{className:"agent-workspace__resource-content",children:n.jsxs("span",{className:"agent-workspace__resource-top",children:[n.jsx("span",{className:"agent-workspace__resource-name",children:e.title}),n.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${e.type}`,children:t.label})]})}),s&&n.jsx(u.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]}),xn=e=>{const t=Date.parse(e);return Number.isFinite(t)?t:0},Va=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),wn=e=>{const t=new Date(e);return Number.isFinite(t.getTime())?Va.format(t):e},zn=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(" ")),qn=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,ps=60*60*1e3,It=24*ps,bn=7*It,Ya=e=>e.type!=="message-sent",Ja=e=>{if(e==null||e<=0)return null;if(e%86400===0){const s=e/86400;return s===1?"every day":`every ${s} days`}if(e%3600===0){const s=e/3600;return s===1?"every hour":`every ${s} hours`}if(e%60===0){const s=e/60;return s===1?"every minute":`every ${s} minutes`}const t=Math.max(1,Math.round(e/60));return t===1?"every minute":`every ${t} minutes`},Wa=e=>{if(e.recurrence==="one_off")return"Scheduled to run once";const t=Ja(e.repeatIntervalSeconds);return t?`Repeating ${t}`:"Repeating run scheduled"},Xa=e=>e.recurrence==="one_off"?"scheduled-one-off":"scheduled-repeating",Za=(e,t,s=[])=>{const a=e.filter(Ya).map((l,m)=>({kind:"action",id:`action-${l.timestamp}-${m}`,timestampMs:xn(l.timestamp),item:l})),i=t.map(l=>({kind:"chat",id:l.sessionId,timestampMs:xn(l.timestamp),session:l})),d=s.map(l=>({kind:"scheduled",id:`scheduled-${l.scheduleId}`,timestampMs:xn(l.dueAt),run:l}));return[...a,...i,...d].sort((l,m)=>l.timestampMs-m.timestampMs||l.id.localeCompare(m.id))},Qa=e=>e>=bn?"weeks":e>=It?"days":"hours",er=e=>{if(e<It){const a=Math.max(1,Math.round(e/ps));return a===1?"1 hour later":`${a} hours later`}if(e<bn){const a=Math.max(1,Math.round(e/It));return a===1?"1 day later":`${a} days later`}const t=Math.max(1,Math.round(e/bn));if(t<5)return t===1?"1 week later":`${t} weeks later`;const s=Math.max(1,Math.round(e/(30*It)));return s===1?"1 month later":`${s} months later`},tr=(e,t=Ka)=>{if(e.length===0)return[];const s=[e[0]];for(let a=1;a<e.length;a+=1){const i=e[a-1],d=e[a],l=d.timestampMs-i.timestampMs;l>=t&&s.push({kind:"gap",id:`gap-${i.id}-${d.id}`,durationMs:l,label:er(l),size:Qa(l)}),s.push(d)}return s},nr=e=>e.type==="checklist-updated"?"checklist":e.type==="status-transition"?"status":"note",sr=({timeline:e,isLoading:t,error:s,onOpenChatSession:a})=>{const i=(e==null?void 0:e.actionLog)??[],d=(e==null?void 0:e.chatSessions)??[],l=(e==null?void 0:e.scheduledRuns)??[],m=Za(i,d,l),h=tr(m),p=!t&&!s&&m.length===0;return n.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[t&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),s&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:s||rs}),p&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!t&&!s&&!p&&n.jsxs("div",{className:"agent-timeline",children:[n.jsx("div",{className:"agent-timeline__track","aria-hidden":"true"}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(u.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})})}),n.jsx("div",{className:"agent-timeline__label",children:n.jsx("strong",{className:"agent-timeline__label-type",children:"Start"})})]}),h.map(_=>{if(_.kind==="gap")return n.jsxs("div",{className:`agent-timeline__gap agent-timeline__gap--${_.size}`,role:"separator","aria-label":_.label,children:[n.jsx("span",{className:"agent-timeline__gap-rail","aria-hidden":"true",children:n.jsx("span",{className:"agent-timeline__gap-dot"})}),n.jsx("span",{className:"agent-timeline__gap-label",children:_.label})]},_.id);if(_.kind==="chat"){const S=wn(_.session.timestamp),I=n.jsx(u.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 ${S}`,onClick:()=>a(_.session.sessionId),children:I}):n.jsx("span",{className:"agent-timeline__chat-node agent-timeline__chat-node--static","aria-hidden":"true",children:I}),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:S})]})]},_.id)}if(_.kind==="scheduled"){const S=Xa(_.run),I=_.run.recurrence==="one_off"?"One-off run":"Repeating run";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${S}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsx("span",{className:`agent-timeline__station-node agent-timeline__station-node--${S}`,"aria-hidden":"true",children:n.jsx(u.Icon,{name:"date",size:16,color:"currentColor"})})}),n.jsxs("div",{className:"agent-timeline__label",children:[n.jsx("strong",{className:"agent-timeline__label-type",children:I}),n.jsx("span",{className:"agent-timeline__label-entry",children:Wa(_.run)}),n.jsx("span",{className:"agent-timeline__label-time",children:wn(_.run.dueAt)})]})]},_.id)}const{item:A}=_,o=nr(A),v=o==="checklist",E=o==="status";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${o}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${o}`,"aria-label":`${zn(A.type)}: ${qn(A.entry)}`,children:[v&&n.jsx(u.Icon,{name:"check-solid",size:16,color:"currentColor"}),E&&n.jsx(u.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]})}),n.jsxs("div",{className:"agent-timeline__label",children:[n.jsx("strong",{className:"agent-timeline__label-type",children:zn(A.type)}),n.jsx("span",{className:"agent-timeline__label-entry",children:qn(A.entry)}),n.jsx("span",{className:"agent-timeline__label-time",children:wn(A.timestamp)})]})]},_.id)}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(u.Icon,{name:"flag",size:16,color:"currentColor"})})}),n.jsx("div",{className:"agent-timeline__label",children:n.jsx("strong",{className:"agent-timeline__label-type",children:"Finish"})})]})]})]})},ar=(e,t)=>({id:t,contentType:"WIDGET",editedOrCreatedByUser:!0,visible:!0,content:{type:"FILE",header:e}}),Ae=e=>{const t=e.kind===ns.user_file;return{id:e.id,text:t?"":e.text,type:e.author===me.user?Ee.CHAT_RESPONSE_TYPE_USER:e.author===me.system?Ee.CHAT_RESPONSE_TYPE_INFO:Ee.CHAT_RESPONSE_TYPE_AGENT,...t?{element:ar(e.text,`${e.id}-file`)}:{},...e.followUpPrompts?{followUpPrompts:e.followUpPrompts}:{}}},Cn="MESSAGE_TYPE_REPOLL",_s="agentUi:update",jn="arbor-agent-",be={all:"ALL",checklist:"CHECKLIST",resources:"RESOURCES",chat:"CHAT",timeline:"TIMELINE"},rr=new Set(Object.values(be)),fs=(e,t)=>`${e.endsWith("-")?e:`${e}-`}${t}`,ir=e=>typeof e=="string"&&rr.has(e)?e:be.all,lr=e=>{if(!e||typeof e!="object")return null;const t=e;return t.type!==Cn?null:{type:Cn,target:ir(t.target)}},vs=e=>{const t=Array.isArray(e)?e:[e],s=[];for(const a of t){const i=lr(a);i&&s.push(i)}return s},or=({enabled:e,channelPrefix:t,agentId:s,subscribeToPusher:a,onRepoll:i})=>{const d=r.useRef(i),l=t==null?void 0:t.trim(),m=!!(e&&a&&l&&(s!=null&&s.trim()));return r.useEffect(()=>{d.current=i},[i]),r.useEffect(()=>{if(!m||!a||!l)return;const h=a(fs(l,s),_s,p=>{for(const _ of vs(p))d.current(_.target)});return()=>{h()}},[m,l,s,a]),m};let ge=null,En="",Sn="",Qt=0;const cr=()=>{window.setTimeout(()=>{Qt>0||!ge||(ge.disconnect(),ge=null,En="",Sn="")},0)},ur=(e,t)=>(ge&&(En!==e||Sn!==t)&&(ge.disconnect(),ge=null),ge||(ge=new Qs(e,{cluster:t}),En=e,Sn=t),Qt+=1,ge),dr=()=>{Qt=Math.max(0,Qt-1),cr()},xs=({enabled:e,key:t,cluster:s,isAdmin:a=!1})=>{const i=r.useRef(null),d=t.trim(),l=s.trim(),m=e&&!!d&&!!l;return r.useEffect(()=>{if(!m){i.current=null;return}const h=ur(d,l);return i.current=h,()=>{i.current=null,dr()}},[m,d,l]),r.useMemo(()=>{if(m)return(h,p,_)=>{const A=i.current??ge;if(!A)return a&&console.log(`[pusher] subscribe skipped — client not ready for "${h}"`),()=>{};const o=A.subscribe(h);return o.bind(p,_),()=>{o.unbind(p,_),A.unsubscribe(h)}}},[m,a])};class Fe extends Error{constructor(t,s,a){super(a??`Agent service request failed (${t})`),this.name="AgentServiceError",this.status=t,this.detail=s}}const hr="/api/v1",H={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},z={GET:"GET",POST:"POST",PATCH:"PATCH",DELETE:"DELETE"},gr={error:"error"},mr={user:"user"},Be={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},pr=100,ws=e=>{switch(e){case _n.paused:return k.paused;case _n.complete:return k.complete;case k.hitl:return k.hitl;case _n.active:case k["generating-a-response"]:return k["generating-a-response"];default:return k["generating-a-response"]}},ys=e=>{switch(e){case Rt.requires_attention:case Rt.waiting_on_human:case U.hitl:return U.hitl;case Rt.in_progress:case U["generating-a-response"]:return U["generating-a-response"];case Rt.to_do:case Rt.available:case U.to_do:return U.to_do;case U.failed:case U.complete:return e;default:return U.to_do}},Rn=e=>({ref:e.name,display_name:e.display_name,agent_intent:e.agent_intent??"",description:e.description}),_r=e=>({id:e.id,name:e.name,...e.has_run_before?{hasRunBefore:e.has_run_before}:{}}),fr=new Set(Object.values(Ne)),vr=e=>fr.has(e)?e:Ne.document_html,As=e=>({id:e.id,type:vr(e.type),title:e.title,createdDatetime:e.created_datetime,lastUpdatedDatetime:e.last_updated_datetime,misRecordUrl:e.mis_record_url}),Ns=e=>({resources:e.resources.map(As),pageNumber:e.page_number,pageSize:e.page_size,totalRecords:e.total_records}),ks=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}))}),Ce=e=>{var s;const t=e.invocation_id??e.id;return{id:e.id,invocation_id:t,agent_definition_ref:e.agent_definition_ref,...e.agent_intent?{agent_intent:e.agent_intent}:{},invocation_name:((s=e.invocation_name)==null?void 0:s.trim())||e.agent_definition_ref,application_id:e.application_id,...e.application_name?{application_name:e.application_name}:{},created_by:e.created_by,usable:e.usable??!1,status:ws(e.status),archivedAt:e.archived_at??null,context_ref:e.context_ref??null,checklist_ref:e.checklist_ref??null}},Tn=e=>({task:e.item??e.task??e.name??e.label??ba,status:ys(e.status),description:e.description??""}),xr=e=>Array.isArray(e)?e:e.checklist_items??e.checklist??e.items??[],tn=(e,t,s)=>{var d;const a=!Array.isArray(t)&&(t.opening_message||(d=t.opening_follow_up_prompts)!=null&&d.length)?t:s,i=a?Ot(a):void 0;return{invocation_id:e,checklist:xr(t).map(Tn),...i?{openingMessage:i}:{}}},wr=(e,t)=>{const s=Ot(t);return{invocation_id:t.invocation_id??e,checklist:(t.checklist_items??[]).map(Tn),...s?{openingMessage:s}:{}}},Ot=e=>{var s,a;const t=(s=e.opening_message)==null?void 0:s.trim();if(t)return{id:as,author:me.agent,text:t,...(a=e.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:e.opening_follow_up_prompts}:{}}},yr=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)){const s=t.filter(a=>!!a&&typeof a=="object"&&typeof a.text=="string").map(a=>a.text);if(s.length>0)return s.join(`
2
- `)}}catch{}return e},Ar=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"),V=require("classnames"),c=require("@arbor-education/design-system.components"),Te=require("@arbor-education/ask-arbor-chat-panel"),ea=require("pusher-js"),C={"generating-a-response":"generating-a-response",hitl:"hitl",paused:"paused",complete:"complete"},U={"generating-a-response":"generating-a-response",to_do:"to_do",hitl:"hitl",complete:"complete",failed:"failed"},F={briefing:"briefing",running:"running",paused:"paused",complete:"complete"},pe={agent:"agent",user:"user",system:"system"},Se={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",user_file:"user_file",link:"link"},ss={user_file:"user_file"},fn={active:"active",complete:"complete",paused:"paused"},Ct={in_progress:"in_progress",to_do:"to_do",requires_attention:"requires_attention",waiting_on_human:"waiting_on_human",available:"available"},Ee={[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",color:"var(--color-brand-600)"}},as="var(--color-grey-600)",lt={[C["generating-a-response"]]:{status:C["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:"sparkles",color:Ee["generating-a-response"].color}},[C.hitl]:{status:C.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:Ee.hitl.icon,color:Ee.hitl.color}},[C.paused]:{status:C.paused,title:"Paused",dotColour:"green",statusIcon:{name:"circle-x",color:as}},[C.complete]:{status:C.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:Ee.complete.icon,color:Ee.complete.color}}},ta={name:"archive",color:as},Fn=[C["generating-a-response"],C.hitl,C.complete],na="m4",sa="1",rs="msg-opening",en="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.",is="Unable to load the timeline for this agent",la="Unable to pause the agent. Please try again.",Cn="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.",bn="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.",ma="You do not have permission to delete this agent.",pa="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.",Gn="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.",Na="Unable to send the message. Please try again.",ls="Unable to load agents. Please try again.",Aa="Agent not found",Ca="Agent not found",it="Loading tasks…",ba="Task",Sa={[F.briefing]:"Briefing",[F.running]:"Working",[F.paused]:"Paused",[F.complete]:"Complete"},os="all",Ea=[C["generating-a-response"],C.hitl,C.complete],ja={[C["generating-a-response"]]:"Agents currently working on tasks for you.",[C.hitl]:"Agents that need your input before they can continue.",[C.paused]:"Agents that are paused until you resume them.",[C.complete]:"Agents that have finished their work."},Ra=()=>n.jsxs("svg",{className:"agent-view__empty-illustration",viewBox:"0 0 360 240",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Preview of the agents board layout",children:[n.jsx("rect",{x:"0",y:"0",width:"360",height:"240",rx:"12",fill:"var(--color-grey-100)"}),n.jsx("rect",{x:"16",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"130",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"244",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"28",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),n.jsx("rect",{x:"28",y:"96",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),n.jsx("rect",{x:"142",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-semantic-warning-050)"}),n.jsx("rect",{x:"256",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),n.jsx("circle",{cx:"40",cy:"70",r:"4",fill:"var(--color-brand-600)"}),n.jsx("circle",{cx:"40",cy:"114",r:"4",fill:"var(--color-brand-600)"}),n.jsx("circle",{cx:"154",cy:"70",r:"4",fill:"var(--color-semantic-warning-600)"}),n.jsx("circle",{cx:"256",cy:"70",r:"4",fill:"var(--color-grey-400)"})]}),Ta=({status:e})=>{const t=lt[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})},Ia=()=>n.jsxs("section",{className:"agent-view__empty","aria-label":"About the agents board",children:[n.jsxs("div",{className:"agent-view__empty-content",children:[n.jsx(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:Ea.map(e=>{const t=lt[e];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(Ta,{status:e})}),n.jsxs("span",{className:"agent-view__empty-column-text",children:[n.jsx("span",{className:"agent-view__empty-column-title",children:t.title}),n.jsx("span",{className:"agent-view__empty-column-description",children:ja[e]})]})]},e)})}),n.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",n.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),n.jsx("div",{className:"agent-view__empty-visual",children:n.jsx(Ra,{})})]}),Oa=()=>({inProgress:[],needsInput:[],complete:[],failed:[],tasks:[]}),La=(e,t)=>({...e,children:t.length>0?t:void 0}),cs=e=>{const t=[],s=[],a=[],i=[],h=[];for(const l of e){const m=l.children?cs(l.children):Oa();if(t.push(...m.inProgress),s.push(...m.needsInput),a.push(...m.complete),i.push(...m.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}),h.push(...m.tasks);continue}h.push(La(l,m.tasks))}return{inProgress:t,needsInput:s,complete:a,failed:i,tasks:h}},zn=e=>e===U.hitl?0:e===U.complete?1:e===U.failed?2:3,Pa=e=>e.map((t,s)=>({item:t,index:s})).sort((t,s)=>{const a=zn(t.item.status)-zn(s.item.status);return a!==0?a:t.index-s.index}).map(({item:t})=>t),us=({status:e,className:t})=>{const s=Ee[e];return e===U.to_do||!s.icon?n.jsxs(n.Fragment,{children:[n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:s.color,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:V("ds-icon","ds-icon-circle",t),role:"img","aria-hidden":!0,children:n.jsx("circle",{cx:12,cy:12,r:10})}),n.jsx("span",{className:"sr-only",children:`${s.label}:`})]}):n.jsx(c.Icon,{name:s.icon,size:16,color:s.color,className:t,screenReaderText:`${s.label}:`})},vn=2,Ma=e=>{if(!e)return{canScrollUp:!1,canScrollDown:!1};const t=e.scrollHeight-e.clientHeight;return t<=vn?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:e.scrollTop>vn,canScrollDown:e.scrollTop<t-vn}},Ua=(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}},sn=({children:e,className:t,contentClassName:s,scrollSelector:a,style:i,"aria-label":h})=>{const l=r.useRef(null),m=r.useRef(null),[d,v]=r.useState(!1),[f,N]=r.useState(!1),[o,x]=r.useState(null),j=()=>{var I;return a?((I=l.current)==null?void 0:I.querySelector(a))??null:m.current},y=()=>{const I=j(),k=Ma(I);if(v(p=>p===k.canScrollUp?p:k.canScrollUp),N(p=>p===k.canScrollDown?p:k.canScrollDown),a){const p=Ua(l.current,I);x(A=>(A==null?void 0:A.top)===(p==null?void 0:p.top)&&(A==null?void 0:A.left)===(p==null?void 0:p.left)&&(A==null?void 0:A.width)===(p==null?void 0:p.width)&&(A==null?void 0:A.height)===(p==null?void 0:p.height)?A:p)}else x(p=>p===null?p:null)};r.useLayoutEffect(()=>{y()}),r.useEffect(()=>{const I=l.current;if(!I)return;let k=null,p=null;const A=()=>{k==null||k.removeEventListener("scroll",y),p==null||p.disconnect(),p=null,k=null},G=ne=>{if(ne===k){y();return}if(A(),k=ne,!k){y();return}k.addEventListener("scroll",y,{passive:!0}),p=new ResizeObserver(()=>y()),p.observe(k),k.firstElementChild instanceof HTMLElement&&p.observe(k.firstElementChild),y()};G(j());const ae=new MutationObserver(()=>{G(j())});return ae.observe(I,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",y),()=>{window.removeEventListener("resize",y),ae.disconnect(),A()}},[a]);const O=I=>{const k=j();if(!k)return;const p=Math.max(k.clientHeight*.75,120);k.scrollBy({top:I==="up"?-p:p,behavior:"smooth"})},P=n.jsxs(n.Fragment,{children:[d&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--top","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--top","aria-label":"Scroll up",onClick:()=>O("up"),children:n.jsx(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:()=>O("down"),children:n.jsx(c.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return n.jsx("div",{ref:l,className:V("scrollable-region",t),style:i,"aria-label":h,children:a?n.jsxs(n.Fragment,{children:[e,o&&(d||f)&&n.jsx("div",{className:"scrollable-region__overlay",style:{top:o.top,left:o.left,width:o.width,height:o.height},children:P})]}):n.jsxs(n.Fragment,{children:[P,n.jsx("div",{ref:m,className:V("scrollable-region__viewport",s),children:e})]})})},Da=48,Ha=({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<=Da)&&(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(sn,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:n.jsx("ul",{ref:t,className:"agent-view__progress-list","aria-label":"Agent tasks",children:Pa(e).map(a=>{const i=Ee[a.status];return n.jsxs("li",{className:V("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[n.jsx(us,{status:a.status,className:i.spin?"agent-view__progress-icon--spinning":void 0}),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)})})})},ds=({open:e,isInProgress:t,isArchiving:s,error:a,onCancel:i,onConfirm:h})=>{const l=r.useId(),m=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":m,children:[n.jsx("p",{id:m,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:h,children:s?"Archiving…":"Archive"})]})]})]})},hs=({open:e,isDeleting:t,error:s,onCancel:a,onConfirm:i})=>{const h=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:h,children:fa})}),n.jsxs(c.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":h,"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"})]})]})]})},gs=({open:e,isUnarchiving:t,error:s,onCancel:a,onConfirm:i})=>{const h=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:h,children:da})}),n.jsxs(c.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsxs("div",{role:"alertdialog","aria-labelledby":h,"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"})]})]})]})},$a=e=>e!==void 0&&e.some(t=>t.status===U.hitl),ms=e=>e!==void 0&&e.length>0&&e.every(t=>t.status===U.complete),xn=(e,t)=>e.status===C.paused?ms(t)?C.complete:C["generating-a-response"]:$a(t)?C.hitl:e.status===C.complete?C.complete:e.status===C.hitl?C.hitl:C["generating-a-response"];class Ba{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{id:`error-${Date.now()}`,text:Na,type:Te.CHAT_RESPONSE_TYPE_ERROR};(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:Te.CHAT_RESPONSE_TYPE_AGENT,...i.message.followUpPrompts?{followUpPrompts:i.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:ya,type:Te.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 Fa=({connector:e,phase:t,chatHistory:s,chatSessionKey:a,readOnly:i=!1,enableUpload:h=!1,onTurn:l,onAwaitingChange:m})=>{const d=r.useMemo(()=>new Ba(e,{canSend:()=>!i&&t===F.running,onTurn:l,onAwaitingChange:m}),[e,t,i,l,m]),v=i||t!==F.running,f=!i&&t===F.running;let N="The agent is not accepting messages.";return f&&(N="Message the agent, paste a link, or attach a file…"),i&&(N="You can view this conversation but cannot send messages."),n.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(sn,{scrollSelector:".chat-panel-message-list",children:n.jsx(Te.ChatPanel,{connector:d,chatHistory:s,lockConversation:v,enableUpload:h,speechEnabled:f,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:N},a)})}),i&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(c.Icon,{name:"eye",size:16,color:"var(--color-grey-700)"}),n.jsx("span",{children:"View only — you cannot interact with this agent."})]}),t===F.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===F.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."})]})]})},ps=({item:e,depth:t})=>{const s=Ee[e.status],a=e.status.replace(/_/g,"-");return n.jsxs("li",{className:V("agent-workspace__task",`agent-workspace__task--${a}`,{"agent-workspace__task--child":t>0}),children:[n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(us,{status:e.status,className:s.spin?"agent-workspace__task-icon--spinning":void 0}),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})]})]}),e.children&&e.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:e.children.map(i=>n.jsx(ps,{item:i,depth:t+1},i.task))})]})},bt=({items:e,ariaLabel:t})=>n.jsx("ul",{className:"agent-workspace__task-list","aria-label":t,children:e.map(s=>n.jsx(ps,{item:s,depth:0},s.task))}),Ga=({checklist:e,isLoading:t,error:s,phase:a,adminMode:i=!1,context:h,contextLoaded:l=!1,contextLoading:m=!1,contextError:d=null,onContextSelect:v})=>{const[f,N]=r.useState("checklist"),o=r.useMemo(()=>e?cs(e):null,[e]),x=()=>{N("context"),v==null||v()};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:i?n.jsxs(c.Tabs,{className:"agent-workspace__checklist-tabs","aria-label":"Checklist panel",children:[n.jsx(c.Tabs.Item,{active:f==="checklist",tabElementProps:{id:"agent-checklist-tab-checklist",onClick:()=>N("checklist")},children:"Checklist"}),n.jsx(c.Tabs.Item,{active:f==="context",tabElementProps:{id:"agent-checklist-tab-context",onClick:x},children:"Context"})]}):n.jsx(c.Heading,{level:4,children:"Checklist"})}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsx(sn,{children:f==="context"?n.jsxs(n.Fragment,{children:[m&&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…"})]}),!m&&d&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:d}),!m&&!d&&l&&h==null&&n.jsx("p",{className:"agent-workspace__empty",children:"No context available."}),!m&&!d&&l&&h!==null&&h!==void 0&&n.jsx("pre",{className:"agent-workspace__context-json",children:JSON.stringify(h,null,2)})]}):n.jsxs(n.Fragment,{children:[t&&!o&&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:it}),n.jsx("span",{children:it})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!s&&o&&n.jsxs(n.Fragment,{children:[o.inProgress.length>0&&n.jsxs("div",{className:"agent-workspace__task-group",children:[(o.needsInput.length>0||o.tasks.length>0||o.failed.length>0||o.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"In progress"}),n.jsx(bt,{items:o.inProgress,ariaLabel:"In progress"})]}),o.needsInput.length>0&&n.jsxs("div",{className:V("agent-workspace__task-group",{"agent-workspace__task-group--following":o.inProgress.length>0}),children:[n.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),n.jsx(bt,{items:o.needsInput,ariaLabel:"Tasks needing your input"})]}),o.failed.length>0&&n.jsxs("div",{className:V("agent-workspace__task-group",{"agent-workspace__task-group--following":o.inProgress.length>0||o.needsInput.length>0}),children:[(o.inProgress.length>0||o.needsInput.length>0||o.tasks.length>0||o.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Failed"}),n.jsx(bt,{items:o.failed,ariaLabel:"Failed tasks"})]}),o.tasks.length>0&&n.jsxs("div",{className:V("agent-workspace__task-group",{"agent-workspace__task-group--following":o.inProgress.length>0||o.needsInput.length>0||o.failed.length>0}),children:[(o.inProgress.length>0||o.needsInput.length>0||o.failed.length>0||o.complete.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"To Do"}),n.jsx(bt,{items:o.tasks,ariaLabel:"Upcoming tasks"})]}),o.complete.length>0&&n.jsxs("div",{className:V("agent-workspace__task-group",{"agent-workspace__task-group--following":o.inProgress.length>0||o.needsInput.length>0||o.tasks.length>0||o.failed.length>0}),children:[(o.inProgress.length>0||o.needsInput.length>0||o.tasks.length>0||o.failed.length>0)&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Completed"}),n.jsx(bt,{items:o.complete,ariaLabel:"Completed tasks"})]})]}),!t&&!s&&(!o||o.inProgress.length===0&&o.needsInput.length===0&&o.complete.length===0&&o.failed.length===0&&o.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:a===F.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})})]})},za=({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=m=>{m.key==="Escape"&&c.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]);const h=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:h})})},qa={[Se.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[Se.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[Se.file]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[Se.user_file]:{icon:"upload",label:"File upload",color:"var(--color-semantic-caution-800)"},[Se.workflow]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[Se.link]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},Va=({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(sn,{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 h=qa[i.type],l=i.misRecordUrl;return n.jsx("li",{className:"agent-workspace__resource",children:l?n.jsx("a",{className:"agent-workspace__resource-card",href:l,target:"_blank",rel:"noreferrer",onClick:m=>{m.preventDefault(),a(i)},children:n.jsx(qn,{resource:i,config:h,external:!0})}):n.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>a(i),children:n.jsx(qn,{resource:i,config:h})})},i.id)})}),!t&&!s&&e.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),qn=({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"})]}),wn=e=>{const t=Date.parse(e);return Number.isFinite(t)?t:0},Ka=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),kn=e=>{const t=new Date(e);return Number.isFinite(t.getTime())?Ka.format(t):e},Vn=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(" ")),Kn=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)},Ya=60*60*1e3,_s=60*60*1e3,St=24*_s,Sn=7*St,Ja=e=>e.type!=="message-sent",Wa=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`},Xa=e=>{if(e.recurrence==="one_off")return"Scheduled to run once";const t=Wa(e.repeatIntervalSeconds);return t?`Repeating ${t}`:"Repeating run scheduled"},Za=e=>e.recurrence==="one_off"?"scheduled-one-off":"scheduled-repeating",Qa=(e,t,s=[])=>{const a=e.filter(Ja).map((l,m)=>({kind:"action",id:`action-${l.timestamp}-${m}`,timestampMs:wn(l.timestamp),item:l})),i=t.map(l=>({kind:"chat",id:l.sessionId,timestampMs:wn(l.timestamp),session:l})),h=s.map(l=>({kind:"scheduled",id:`scheduled-${l.scheduleId}`,timestampMs:wn(l.dueAt),run:l}));return[...a,...i,...h].sort((l,m)=>l.timestampMs-m.timestampMs||l.id.localeCompare(m.id))},er=e=>e>=Sn?"weeks":e>=St?"days":"hours",tr=e=>{if(e<St){const a=Math.max(1,Math.round(e/_s));return a===1?"1 hour later":`${a} hours later`}if(e<Sn){const a=Math.max(1,Math.round(e/St));return a===1?"1 day later":`${a} days later`}const t=Math.max(1,Math.round(e/Sn));if(t<5)return t===1?"1 week later":`${t} weeks later`;const s=Math.max(1,Math.round(e/(30*St)));return s===1?"1 month later":`${s} months later`},nr=(e,t=Ya)=>{if(e.length===0)return[];const s=[e[0]];for(let a=1;a<e.length;a+=1){const i=e[a-1],h=e[a],l=h.timestampMs-i.timestampMs;l>=t&&s.push({kind:"gap",id:`gap-${i.id}-${h.id}`,durationMs:l,label:tr(l),size:er(l)}),s.push(h)}return s},sr=e=>e.type==="checklist-updated"?"checklist":e.type==="status-transition"?"status":"note",ar=({timeline:e,isLoading:t,error:s,onOpenChatSession:a})=>{const i=(e==null?void 0:e.actionLog)??[],h=(e==null?void 0:e.chatSessions)??[],l=(e==null?void 0:e.scheduledRuns)??[],m=Qa(i,h,l),d=nr(m),v=!t&&!s&&m.length===0;return n.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[t&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),s&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:s||is}),v&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!t&&!s&&!v&&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"})})]}),d.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 y=kn(f.session.timestamp),O=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 ${y}`,onClick:()=>a(f.session.sessionId),children:O}):n.jsx("span",{className:"agent-timeline__chat-node agent-timeline__chat-node--static","aria-hidden":"true",children:O}),n.jsxs("div",{className:"agent-timeline__label",children:[n.jsx("strong",{className:"agent-timeline__label-type",children:"Chat session"}),n.jsx("span",{className:"agent-timeline__label-time",children:y})]})]},f.id)}if(f.kind==="scheduled"){const y=Za(f.run),O=f.run.recurrence==="one_off"?"One-off run":"Repeating run";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${y}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsx("span",{className:`agent-timeline__station-node agent-timeline__station-node--${y}`,"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:O}),n.jsx("span",{className:"agent-timeline__label-entry",children:Xa(f.run)}),n.jsx("span",{className:"agent-timeline__label-time",children:kn(f.run.dueAt)})]})]},f.id)}const{item:N}=f,o=sr(N),x=o==="checklist",j=o==="status";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${o}`,children:[n.jsx("span",{className:"agent-timeline__station-rail",children:n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${o}`,"aria-label":`${Vn(N.type)}: ${Kn(N.entry)}`,children:[x&&n.jsx(c.Icon,{name:"check-solid",size:16,color:"currentColor"}),j&&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:Vn(N.type)}),n.jsx("span",{className:"agent-timeline__label-entry",children:Kn(N.entry)}),n.jsx("span",{className:"agent-timeline__label-time",children:kn(N.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"})})]})]})]})},rr=(e,t)=>({id:t,contentType:"WIDGET",editedOrCreatedByUser:!0,visible:!0,content:{type:"FILE",header:e}}),be=e=>{const t=e.kind===ss.user_file;return{id:e.id,text:t?"":e.text,type:e.author===pe.user?Te.CHAT_RESPONSE_TYPE_USER:e.author===pe.system?Te.CHAT_RESPONSE_TYPE_INFO:Te.CHAT_RESPONSE_TYPE_AGENT,...t?{element:rr(e.text,`${e.id}-file`)}:{},...e.followUpPrompts?{followUpPrompts:e.followUpPrompts}:{}}},En="MESSAGE_TYPE_REPOLL",fs="agentUi:update",Tn="arbor-agent-",je={all:"ALL",checklist:"CHECKLIST",resources:"RESOURCES",chat:"CHAT",timeline:"TIMELINE"},ir=new Set(Object.values(je)),vs=(e,t)=>`${e.endsWith("-")?e:`${e}-`}${t}`,lr=e=>typeof e=="string"&&ir.has(e)?e:je.all,or=e=>{if(!e||typeof e!="object")return null;const t=e;return t.type!==En?null:{type:En,target:lr(t.target)}},xs=e=>{const t=Array.isArray(e)?e:[e],s=[];for(const a of t){const i=or(a);i&&s.push(i)}return s},cr=({enabled:e,channelPrefix:t,agentId:s,subscribeToPusher:a,onRepoll:i})=>{const h=r.useRef(i),l=t==null?void 0:t.trim(),m=!!(e&&a&&l&&(s!=null&&s.trim()));return r.useEffect(()=>{h.current=i},[i]),r.useEffect(()=>{if(!m||!a||!l)return;const d=a(vs(l,s),fs,v=>{for(const f of xs(v))h.current(f.target)});return()=>{d()}},[m,l,s,a]),m};let me=null,jn="",Rn="",nn=0;const ur=()=>{window.setTimeout(()=>{nn>0||!me||(me.disconnect(),me=null,jn="",Rn="")},0)},dr=(e,t)=>(me&&(jn!==e||Rn!==t)&&(me.disconnect(),me=null),me||(me=new ea(e,{cluster:t}),jn=e,Rn=t),nn+=1,me),hr=()=>{nn=Math.max(0,nn-1),ur()},ws=({enabled:e,key:t,cluster:s,isAdmin:a=!1})=>{const i=r.useRef(null),h=t.trim(),l=s.trim(),m=e&&!!h&&!!l;return r.useEffect(()=>{if(!m){i.current=null;return}const d=dr(h,l);return i.current=d,()=>{i.current=null,hr()}},[m,h,l]),r.useMemo(()=>{if(m)return(d,v,f)=>{const N=i.current??me;if(!N)return a&&console.log(`[pusher] subscribe skipped — client not ready for "${d}"`),()=>{};const o=N.subscribe(d);return o.bind(v,f),()=>{o.unbind(v,f),N.unsubscribe(d)}}},[m,a])};class Ve extends Error{constructor(t,s,a){super(a??`Agent service request failed (${t})`),this.name="AgentServiceError",this.status=t,this.detail=s}}const gr="/api/v1",B={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},J={GET:"GET",POST:"POST",PATCH:"PATCH",DELETE:"DELETE"},mr={error:"error"},pr={user:"user"},qe={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},_r=100,ks=e=>{switch(e){case fn.paused:return C.paused;case fn.complete:return C.complete;case C.hitl:return C.hitl;case fn.active:case C["generating-a-response"]:return C["generating-a-response"];default:return C["generating-a-response"]}},ys=e=>{switch(e){case Ct.requires_attention:case Ct.waiting_on_human:case U.hitl:return U.hitl;case Ct.in_progress:case U["generating-a-response"]:return U["generating-a-response"];case Ct.to_do:case Ct.available:case U.to_do:return U.to_do;case U.failed:case U.complete:return e;default:return U.to_do}},In=e=>({ref:e.name,display_name:e.display_name,agent_intent:e.agent_intent??"",description:e.description}),fr=e=>({id:e.id,name:e.name,...e.has_run_before?{hasRunBefore:e.has_run_before}:{}}),vr=new Set(Object.values(Se)),xr=e=>vr.has(e)?e:Se.document_html,Ns=e=>({id:e.id,type:xr(e.type),title:e.title,createdDatetime:e.created_datetime,lastUpdatedDatetime:e.last_updated_datetime,misRecordUrl:e.mis_record_url}),As=e=>({resources:e.resources.map(Ns),pageNumber:e.page_number,pageSize:e.page_size,totalRecords:e.total_records}),Cs=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}))}),Re=e=>{var s;const t=e.invocation_id??e.id;return{id:e.id,invocation_id:t,agent_definition_ref:e.agent_definition_ref,...e.agent_intent?{agent_intent:e.agent_intent}:{},invocation_name:((s=e.invocation_name)==null?void 0:s.trim())||e.agent_definition_ref,application_id:e.application_id,...e.application_name?{application_name:e.application_name}:{},created_by:e.created_by,usable:e.usable??!1,status:ks(e.status),archivedAt:e.archived_at??null,context_ref:e.context_ref??null,checklist_ref:e.checklist_ref??null}},On=e=>({task:e.item??e.task??e.name??e.label??ba,status:ys(e.status),description:e.description??""}),wr=e=>Array.isArray(e)?e:e.checklist_items??e.checklist??e.items??[],an=(e,t,s)=>{var h;const a=!Array.isArray(t)&&(t.opening_message||(h=t.opening_follow_up_prompts)!=null&&h.length)?t:s,i=a?Et(a):void 0;return{invocation_id:e,checklist:wr(t).map(On),...i?{openingMessage:i}:{}}},kr=(e,t)=>{const s=Et(t);return{invocation_id:t.invocation_id??e,checklist:(t.checklist_items??[]).map(On),...s?{openingMessage:s}:{}}},Et=e=>{var s,a;const t=(s=e.opening_message)==null?void 0:s.trim();if(t)return{id:rs,author:pe.agent,text:t,...(a=e.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:e.opening_follow_up_prompts}:{}}},yr=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)){const s=t.filter(a=>!!a&&typeof a=="object"&&typeof a.text=="string").map(a=>a.text);if(s.length>0)return s.join(`
2
+ `)}}catch{}return e},Nr=e=>{const t=e.trim();return t.length>0?`File upload
3
3
 
4
- ${t}`:"File upload"},Nr=e=>!e.includes(`
5
- `)&&e.length>0&&e.length<=240&&/\.[A-Za-z0-9]{2,5}$/.test(e),Vn=e=>{var s,a;const t=(s=e.filename)==null?void 0:s.trim();if(t)return t;if(e.message_type==="user_file"&&e.role==="user"){const i=(a=e.content)==null?void 0:a.trim();return i&&Nr(i)?i:i?"File upload":null}return null},bs=e=>e.filter(t=>Vn(t)&&t.role==="user"?!0:(t.role==="user"||t.role==="assistant")&&typeof t.content=="string"&&t.content.length>0&&t.message_type!=="tool_request"&&t.message_type!=="user_file").map(t=>{const s=Vn(t);return s&&t.role==="user"?{id:t.message_id,author:me.user,kind:ns.user_file,text:s}:{id:t.message_id,author:t.role==="user"?me.user:me.agent,text:t.content}}),kr=/:invocationId\b/g,br=/:resourceId\b/g,Cr=e=>e.trim().replace(/^Bearer\s+/i,""),Kn=e=>e.endsWith("/")?e.slice(0,-1):e;class nn{constructor(t){var a;this.baseUrl=Kn(t.baseUrl??"");const s=(a=t.token)==null?void 0:a.trim();this.token=s?Cr(s):void 0,this.customHeaders=t.headers,this.urls=t.urls??{},this.fetchImpl=t.fetch??globalThis.fetch.bind(globalThis)}setHeaders(t){this.customHeaders=t}async listAgentDefinitions(){return(await this.request(z.GET,this.resolveUrl("agentDefinitions",H.agentDefinitions))).agent_definitions??[]}getAgentDefinition(t){return this.request(z.GET,this.apiUrl(`${H.agentDefinitions}/${encodeURIComponent(t)}`))}listTripOptions(){return this.request(z.GET,this.apiUrl(H.tripOptions))}getDataset(){return this.request(z.GET,this.apiUrl(H.demoDataset))}setDataset(t){return this.request(z.POST,this.apiUrl(H.demoDataset),{dataset:t})}listAgents(t={}){const s=new URLSearchParams;t.status&&s.set("status",t.status),t.agentDefinitionRef&&s.set("agent_definition_ref",t.agentDefinitionRef),t.scope&&s.set("scope",t.scope);const a=s.toString()?`?${s.toString()}`:"";return this.request(z.GET,`${this.resolveUrl("agents",H.agents)}${a}`)}createAgent(t,s={}){var l,m;const a={agent_definition_ref:t},i=(l=s.invocationName)==null?void 0:l.trim(),d=(m=s.agentIntent)==null?void 0:m.trim();return i&&(a.invocation_name=i),d&&(a.agent_intent=d),this.request(z.POST,this.resolveUrl("agents",H.agents),a)}getAgent(t){return this.request(z.GET,this.resolveUrl("agent",`${H.agents}/${encodeURIComponent(t)}`,t))}updateAgent(t,s){const i={invocation_name:s.invocationName.trim()};return this.request(z.PATCH,this.resolveUrl("agent",`${H.agents}/${encodeURIComponent(t)}`,t),i)}getAgentChecklist(t){return this.request(z.GET,this.resolveUrl("agentChecklist",`${H.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(),d=this.resolveUrl("agentResources",`${H.agents}/${encodeURIComponent(t)}/resources`,t);return this.request(z.GET,i?`${d}?${i}`:d)}async listAllAgentResources(t){const s=pr;let a=1;const i=[];let d=Number.POSITIVE_INFINITY;for(;i.length<d;){const l=Ns(await this.getAgentResources(t,{pageNumber:a,pageSize:s}));if(d=l.totalRecords,l.resources.length===0||(i.push(...l.resources),i.length>=d))break;a+=1}return i}getAgentResourceHtml(t,s){return this.requestText(z.GET,this.resolveResourceHtmlUrl(t,s))}getAgentTimeline(t){return this.request(z.GET,this.resolveUrl("agentTimeline",`${H.agents}/${encodeURIComponent(t)}/agent-timeline`,t))}getAgentContext(t){const s=this.resolveUrl("agent",`${H.agents}/${encodeURIComponent(t)}`,t);return this.request(z.GET,`${Kn(s)}/context`)}pauseAgent(t){return this.request(z.POST,this.resolveUrl("pauseAgent",`${H.agents}/${encodeURIComponent(t)}/pause`,t))}resumeAgent(t){return this.request(z.POST,this.resolveUrl("resumeAgent",`${H.agents}/${encodeURIComponent(t)}/resume`,t))}archiveAgent(t){return this.request(z.POST,this.resolveUrl("archiveAgent",`${H.agents}/${encodeURIComponent(t)}/archive`,t))}unarchiveAgent(t){return this.request(z.POST,this.resolveUrl("unarchiveAgent",`${H.agents}/${encodeURIComponent(t)}/unarchive`,t))}deleteAgent(t){return this.request(z.DELETE,this.resolveUrl("agent",`${H.agents}/${encodeURIComponent(t)}`,t))}getConversation(t){return this.request(z.GET,this.resolveUrl("agentConversation",`${H.conversations}/${encodeURIComponent(t)}`,t))}async chat(t,s,a={}){const i=!!(a.uploadFiles&&a.uploadFiles.length>0),d=await this.fetchImpl(this.resolveUrl("agentChat",`${H.agents}/${encodeURIComponent(t)}/chat`,t),{method:z.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:Be.acceptEventStream,...i?{}:{"Content-Type":Be.contentTypeJson}},body:i?Sr(s,a.uploadFiles??[]):JSON.stringify(s),signal:a.signal});if(!d.ok)throw await this.toError(d);if(!d.body)throw new Fe(d.status,null,"Chat response contained no stream body");return this.consumeSse(d.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(t){return`${this.baseUrl}${hr}${t}`}resolveUrl(t,s,a,i){const d=this.urls[t];if(!d)return this.apiUrl(s);let l=d;return a&&(l=l.replace(kr,encodeURIComponent(a))),i&&(l=l.replace(br,encodeURIComponent(i))),l}resolveResourceHtmlUrl(t,s){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${H.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(s)}`,t,s):this.urls.agentResources?`${this.resolveUrl("agentResources",`${H.agents}/${encodeURIComponent(t)}/resources`,t).replace(/\/$/,"")}/${encodeURIComponent(s)}`:this.apiUrl(`${H.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:Be.acceptJson,...a===void 0?{}:{"Content-Type":Be.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:Be.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 Fe(t.status,s,`Agent service request failed (${t.status} ${t.statusText})`)}async consumeSse(t,s){const a=t.getReader(),i=new TextDecoder;let d="",l,m;const h=_=>{const{event:A,data:o}=Er(_);if(o===null)return;if(A===gr.error){const E=Yn(o);throw new Fe(502,E,(E==null?void 0:E.message)??"Chat stream error")}const v=Yn(o);v&&(l=v,s==null||s(v),v.is_final&&(m=v))};try{for(;;){const{done:_,value:A}=await a.read();if(_)break;d+=i.decode(A,{stream:!0});const o=d.split(`
4
+ ${t}`:"File upload"},Ar=e=>!e.includes(`
5
+ `)&&e.length>0&&e.length<=240&&/\.[A-Za-z0-9]{2,5}$/.test(e),Yn=e=>{var s,a;const t=(s=e.filename)==null?void 0:s.trim();if(t)return t;if(e.message_type==="user_file"&&e.role==="user"){const i=(a=e.content)==null?void 0:a.trim();return i&&Ar(i)?i:i?"File upload":null}return null},bs=e=>e.filter(t=>Yn(t)&&t.role==="user"?!0:(t.role==="user"||t.role==="assistant")&&typeof t.content=="string"&&t.content.length>0&&t.message_type!=="tool_request"&&t.message_type!=="user_file").map(t=>{const s=Yn(t);return s&&t.role==="user"?{id:t.message_id,author:pe.user,kind:ss.user_file,text:s}:{id:t.message_id,author:t.role==="user"?pe.user:pe.agent,text:t.content}}),Cr=/:invocationId\b/g,br=/:resourceId\b/g,Sr=e=>e.trim().replace(/^Bearer\s+/i,""),Jn=e=>e.endsWith("/")?e.slice(0,-1):e;class rn{constructor(t){var a;this.baseUrl=Jn(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(J.GET,this.resolveUrl("agentDefinitions",B.agentDefinitions))).agent_definitions??[]}getAgentDefinition(t){return this.request(J.GET,this.apiUrl(`${B.agentDefinitions}/${encodeURIComponent(t)}`))}listTripOptions(){return this.request(J.GET,this.apiUrl(B.tripOptions))}getDataset(){return this.request(J.GET,this.apiUrl(B.demoDataset))}setDataset(t){return this.request(J.POST,this.apiUrl(B.demoDataset),{dataset:t})}listAgents(t={}){const s=new URLSearchParams;t.status&&s.set("status",t.status),t.agentDefinitionRef&&s.set("agent_definition_ref",t.agentDefinitionRef),t.scope&&s.set("scope",t.scope);const a=s.toString()?`?${s.toString()}`:"";return this.request(J.GET,`${this.resolveUrl("agents",B.agents)}${a}`)}createAgent(t,s={}){var l,m;const a={agent_definition_ref:t},i=(l=s.invocationName)==null?void 0:l.trim(),h=(m=s.agentIntent)==null?void 0:m.trim();return i&&(a.invocation_name=i),h&&(a.agent_intent=h),this.request(J.POST,this.resolveUrl("agents",B.agents),a)}getAgent(t){return this.request(J.GET,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(t)}`,t))}updateAgent(t,s){const i={invocation_name:s.invocationName.trim()};return this.request(J.PATCH,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(t)}`,t),i)}getAgentChecklist(t){return this.request(J.GET,this.resolveUrl("agentChecklist",`${B.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(),h=this.resolveUrl("agentResources",`${B.agents}/${encodeURIComponent(t)}/resources`,t);return this.request(J.GET,i?`${h}?${i}`:h)}async listAllAgentResources(t){const s=_r;let a=1;const i=[];let h=Number.POSITIVE_INFINITY;for(;i.length<h;){const l=As(await this.getAgentResources(t,{pageNumber:a,pageSize:s}));if(h=l.totalRecords,l.resources.length===0||(i.push(...l.resources),i.length>=h))break;a+=1}return i}getAgentResourceHtml(t,s){return this.requestText(J.GET,this.resolveResourceHtmlUrl(t,s))}getAgentTimeline(t){return this.request(J.GET,this.resolveUrl("agentTimeline",`${B.agents}/${encodeURIComponent(t)}/agent-timeline`,t))}getAgentContext(t){const s=this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(t)}`,t);return this.request(J.GET,`${Jn(s)}/context`)}pauseAgent(t){return this.request(J.POST,this.resolveUrl("pauseAgent",`${B.agents}/${encodeURIComponent(t)}/pause`,t))}resumeAgent(t){return this.request(J.POST,this.resolveUrl("resumeAgent",`${B.agents}/${encodeURIComponent(t)}/resume`,t))}archiveAgent(t){return this.request(J.POST,this.resolveUrl("archiveAgent",`${B.agents}/${encodeURIComponent(t)}/archive`,t))}unarchiveAgent(t){return this.request(J.POST,this.resolveUrl("unarchiveAgent",`${B.agents}/${encodeURIComponent(t)}/unarchive`,t))}deleteAgent(t){return this.request(J.DELETE,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(t)}`,t))}getConversation(t){return this.request(J.GET,this.resolveUrl("agentConversation",`${B.conversations}/${encodeURIComponent(t)}`,t))}async chat(t,s,a={}){const i=!!(a.uploadFiles&&a.uploadFiles.length>0),h=await this.fetchImpl(this.resolveUrl("agentChat",`${B.agents}/${encodeURIComponent(t)}/chat`,t),{method:J.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:qe.acceptEventStream,...i?{}:{"Content-Type":qe.contentTypeJson}},body:i?jr(s,a.uploadFiles??[]):JSON.stringify(s),signal:a.signal});if(!h.ok)throw await this.toError(h);if(!h.body)throw new Ve(h.status,null,"Chat response contained no stream body");return this.consumeSse(h.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(t){return`${this.baseUrl}${gr}${t}`}resolveUrl(t,s,a,i){const h=this.urls[t];if(!h)return this.apiUrl(s);let l=h;return a&&(l=l.replace(Cr,encodeURIComponent(a))),i&&(l=l.replace(br,encodeURIComponent(i))),l}resolveResourceHtmlUrl(t,s){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${B.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(s)}`,t,s):this.urls.agentResources?`${this.resolveUrl("agentResources",`${B.agents}/${encodeURIComponent(t)}/resources`,t).replace(/\/$/,"")}/${encodeURIComponent(s)}`:this.apiUrl(`${B.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(s)}`)}async request(t,s,a){const i=await this.fetchImpl(s,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:qe.acceptJson,...a===void 0?{}:{"Content-Type":qe.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:qe.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 Ve(t.status,s,`Agent service request failed (${t.status} ${t.statusText})`)}async consumeSse(t,s){const a=t.getReader(),i=new TextDecoder;let h="",l,m;const d=f=>{const{event:N,data:o}=Er(f);if(o===null)return;if(N===mr.error){const j=Wn(o);throw new Ve(502,j,(j==null?void 0:j.message)??"Chat stream error")}const x=Wn(o);x&&(l=x,s==null||s(x),x.is_final&&(m=x))};try{for(;;){const{done:f,value:N}=await a.read();if(f)break;h+=i.decode(N,{stream:!0});const o=h.split(`
6
6
 
7
- `);d=o.pop()??"";for(const v of o)h(v);if(m){await a.cancel().catch(()=>{});break}}!m&&d.trim()&&h(d)}finally{try{a.releaseLock()}catch{}}const p=m??l;if(!p)throw new Fe(502,null,"Chat stream ended without any events");return p}}const Er=e=>{let t=null;const s=[];for(const a of e.split(`
7
+ `);h=o.pop()??"";for(const x of o)d(x);if(m){await a.cancel().catch(()=>{});break}}!m&&h.trim()&&d(h)}finally{try{a.releaseLock()}catch{}}const v=m??l;if(!v)throw new Ve(502,null,"Chat stream ended without any events");return v}}const Er=e=>{let t=null;const s=[];for(const a of e.split(`
8
8
  `)){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(`
9
- `):null}},Yn=e=>{try{return JSON.parse(e)}catch{return}};function Sr(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 jr={id:as,author:me.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 Jn=0;const Rr=e=>(Jn+=1,`${e}-${Date.now()}-${Jn}`),Tr=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 Cs{constructor(t,s,a={}){this.seededChecklist=[],this.client=t,this.agentId=s,this.chatId=a.chatId??s,this.opening=a.openingMessage??jr,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const t=await this.client.getConversation(this.chatId),s=bs(t.messages);return s.length===0?[this.opening]:s}async start(t){return{...await this.exchange(Tr(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 A;const i=[{role:mr.user,content:t}];let d="",l=null,m;const h=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:o=>{var S;const v=o.message;if((v==null?void 0:v.role)==="assistant"&&v.tool_calls&&v.tool_calls.length>0){const I=Ee.thinkingPhrasesFromToolCalls(v.tool_calls);for(const P of I)P.phrase!==l&&(l=P.phrase,(S=a==null?void 0:a.onThinking)==null||S.call(a,P))}const E=v==null?void 0:v.content;E&&(d=o.is_final?E:d+E),o.is_final&&(m=o)}}),p=m??h,_={id:p.event_id||Rr("msg-agent"),author:me.agent,text:d||p.message.content||"",...(A=p.follow_up_prompts)!=null&&A.length?{followUpPrompts:p.follow_up_prompts}:{}};try{const o=await this.client.getAgentChecklist(this.agentId),{checklist:v}=tn(this.agentId,o);return v.length===0?{message:_}:(this.seededChecklist=v,{message:_,checklist:v})}catch{return{message:_,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const In=(e,t)=>s=>{var a,i;return new Cs(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)})},Es=e=>e instanceof Fe?e.message:e instanceof TypeError?"Network error while contacting the agent service.":e instanceof Error&&e.message?e.message:is,Ss=e=>{if(e instanceof Fe){if(e.status===403)return ga;if(e.status===409)return ma;if(e.status===404)return pa}return ha},Ir=e=>{const t={};for(const s of e){const a=Ot(s);if(!a)continue;const i=s.invocation_id??s.id;t[i]=a,t[s.id]=a}return t},Or=e=>JSON.stringify(e),Wt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),js=e=>{const{jwt:t,headers:s,urls:a,scope:i=ls}=e,d=JSON.stringify(s??{}),l=Or(a),m=r.useMemo(()=>({scope:i}),[i]),h=r.useMemo(()=>new nn({token:t,headers:s,urls:a}),[t,l]);r.useLayoutEffect(()=>{h.setHeaders(s)},[h,d]);const[p,_]=r.useState([]),[A,o]=r.useState([]),[v,E]=r.useState({}),[S,I]=r.useState("loading"),[P,j]=r.useState(null),[y,f]=r.useState(0),x=r.useRef(0),R=r.useCallback((N,L)=>{const T=N.map(Ce),F=L.map(Rn),D=Ir(N);_(q=>Wt(q,T)?q:T),o(q=>Wt(q,F)?q:F),E(q=>Wt(q,D)?q:D),I("idle"),j(null)},[]);r.useEffect(()=>{const N=++x.current;I("loading"),j(null),(async()=>{try{const[L,T]=await Promise.all([h.listAgents(m),h.listAgentDefinitions()]);if(N!==x.current)return;R(L,T)}catch(L){if(N!==x.current)return;_([]),o([]),E({}),I("error"),j(Es(L))}})()},[R,h,m,y]);const V=r.useCallback(()=>{f(N=>N+1)},[]),ae=r.useCallback(async()=>{const N=++x.current;try{const[L,T]=await Promise.all([h.listAgents(m),h.listAgentDefinitions()]);if(N!==x.current)return;R(L,T)}catch{}},[R,h,m]),X=r.useCallback(async N=>{const[L,T]=await Promise.all([h.getAgentChecklist(N),h.getAgent(N).catch(()=>null)]);return tn(N,L,T??void 0)},[h]),B=r.useCallback(async N=>h.listAllAgentResources(N),[h]),J=r.useCallback(async({definition:N,invocationName:L})=>{const T=await h.createAgent(N.ref,{invocationName:L}),F=await h.getAgent(T.id),D=Ce(F),q=Ot(F);return _(_e=>[D,..._e]),q&&E(_e=>({..._e,[D.invocation_id]:q,[D.id]:q})),D},[h]),ee=r.useCallback(async N=>{const L=await h.archiveAgent(N),T=Ce(L);return _(F=>F.map(D=>D.id===T.id||D.id===N||D.invocation_id===N?T:D)),T},[h]),pe=r.useCallback(async N=>{const L=await h.unarchiveAgent(N),T=Ce(L);return _(F=>F.map(D=>D.id===T.id||D.id===N||D.invocation_id===N?T:D)),T},[h]),M=r.useCallback(N=>{_(L=>L.filter(T=>T.id!==N&&T.invocation_id!==N))},[]),le=r.useCallback(N=>{_(L=>{const T=L.map(F=>F.id===N.id||F.invocation_id===N.invocation_id?{...F,...N}:F);return Wt(L,T)?L:T})},[]),re=r.useCallback(async N=>{await h.deleteAgent(N),M(N)},[h,M]),ue=r.useMemo(()=>In(h,{resolveOpeningMessage:N=>v[N.invocation_id]??v[N.id]}),[h,v]);return{agents:p,agentDefinitions:A,loadState:S,loadError:P,reload:V,refresh:ae,fetchAgentChecklist:X,fetchAgentResources:B,createAgent:J,archiveAgent:ee,unarchiveAgent:pe,deleteAgent:re,removeAgent:M,replaceAgent:le,chatConnector:ue}},Lr=e=>JSON.stringify(e),Rs=e=>{const{agent:t,jwt:s,headers:a,urls:i,chatId:d}=e,l=JSON.stringify(a??{}),m=Lr(i),h=r.useMemo(()=>new nn({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,m]);r.useLayoutEffect(()=>{h.setHeaders(a)},[h,l]);const p=r.useCallback(async f=>Ce(await h.getAgent(f)),[h]),_=r.useCallback(async f=>{const[x,R]=await Promise.all([h.getAgentChecklist(f),h.getAgent(f).catch(()=>null)]);return tn(f,x,R??void 0)},[h]),A=r.useCallback(async f=>h.listAllAgentResources(f),[h]),o=r.useCallback(async f=>h.getAgentContext(f),[h]),v=r.useCallback(async(f,x)=>h.getAgentResourceHtml(f,x),[h]),E=r.useCallback(async f=>{const x=await h.getAgentTimeline(f);return ks(x)},[h]),S=r.useCallback(async(f,x)=>{await h.updateAgent(f,{invocationName:x})},[h]),I=r.useCallback(async f=>Ce(await h.archiveAgent(f)),[h]),P=r.useCallback(async f=>Ce(await h.unarchiveAgent(f)),[h]),j=r.useCallback(async f=>{await h.deleteAgent(f)},[h]);return{connector:r.useMemo(()=>In(h,{chatId:d??t.invocation_id})(t),[h,t.invocation_id,d]),fetchAgent:p,fetchAgentChecklist:_,fetchAgentContext:o,fetchAgentResources:A,fetchAgentResourceHtml:v,fetchAgentTimeline:E,updateAgentInvocationName:S,archiveAgent:I,unarchiveAgent:P,deleteAgent:j}},Pr=3e4,Mr=(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()},Wn=e=>{switch(e){case k.paused:return $.paused;case k.complete:return $.complete;default:return $.running}},yn=e=>e===k.paused,Xn=(e,t)=>{t([Ae(e)])},Ur=(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}),Ts=({agent:e,invocationId:t,open:s,onClose:a,jwt:i,headers:d,agentUrl:l,agentChecklistUrl:m,agentResourcesUrl:h,agentTimelineUrl:p,agentChatUrl:_,agentConversationUrl:A,pauseAgentUrl:o,resumeAgentUrl:v,archiveAgentUrl:E,unarchiveAgentUrl:S,chatId:I,enableUpload:P,adminMode:j=!1,initialBrief:y,initialPhase:f,initialChecklist:x,usePusherToRepoll:R=!1,pusherChannelPrefix:V=jn,pusherKey:ae="",pusherCluster:X="",subscribeToPusher:B,onArchived:J,onUnarchived:ee,onDeleted:pe,onAgentUpdated:M})=>{const[le,re]=r.useState(I??t),[ue,N]=r.useState("chat"),[L,T]=r.useState(!1),{connector:F,fetchAgent:D,fetchAgentChecklist:q,fetchAgentContext:_e,fetchAgentResources:Ge,fetchAgentResourceHtml:Lt,fetchAgentTimeline:ze,updateAgentInvocationName:qe,archiveAgent:Se,unarchiveAgent:je,deleteAgent:ot}=Rs({agent:{...e,invocation_id:t},jwt:i,headers:d,chatId:le,urls:{agentUrl:l,agentChecklistUrl:m,agentResourcesUrl:h,agentTimelineUrl:p,agentChatUrl:_,agentConversationUrl:A,pauseAgentUrl:o,resumeAgentUrl:v,archiveAgentUrl:E,unarchiveAgentUrl:S}}),K=r.useRef(F),[Z,Ve]=r.useState(e.invocation_name),[ct,xe]=r.useState(0),[Re,ut]=r.useState(null),[te,we]=r.useState(f??(y?$.running:Wn(e.status))),[ie,Q]=r.useState([]),[dt,Ke]=r.useState(0),[sn,Te]=r.useState([]),[an,Ye]=r.useState(!1),[Je,Ie]=r.useState(null),[ht,gt]=r.useState(null),[rn,ye]=r.useState(null),[Oe,Le]=r.useState(!1),[mt,We]=r.useState(null),[Pe,Me]=r.useState(null),[ln,pt]=r.useState(!1),[Pt,Xe]=r.useState(null),[oe,Ze]=r.useState(x??null),[Qe,_t]=r.useState(!1),[Mt,ft]=r.useState(null),[Ut,vt]=r.useState(void 0),[Ue,De]=r.useState(!1),[xt,wt]=r.useState(!1),[on,yt]=r.useState(null),[At,Dt]=r.useState(!1),[Ht,$t]=r.useState(!1),[Bt,Ft]=r.useState(!1),[cn,Nt]=r.useState(!1),[un,et]=r.useState(null),[Gt,zt]=r.useState(!1),[dn,tt]=r.useState(!1),[qt,c]=r.useState(null),[b,C]=r.useState(!1),[ne,fe]=r.useState(!1),[nt,de]=r.useState(null),[kt,se]=r.useState(null),[Ps,bt]=r.useState(()=>yn(e.status)),[Ms,On]=r.useState(e.archivedAt??null),G=!!Ms,Ct=!e.usable,[hn,Et]=r.useState(!1),[Vt,Us]=r.useState(!1),[Kt,Ds]=r.useState(!1),Ln=r.useRef(hn),Pn=r.useRef(e.invocation_name),st=r.useRef(e),he=r.useRef(M),Mn=r.useRef(0),Un=r.useRef(0),at=r.useRef(0),St=r.useRef(0);he.current=M,r.useEffect(()=>{On(e.archivedAt??null)},[e.archivedAt]),r.useEffect(()=>{K.current=F},[F]),r.useEffect(()=>{Pn.current=e.invocation_name},[e.invocation_name]),r.useEffect(()=>{st.current=e},[e]),r.useEffect(()=>{Ln.current=hn},[hn]),r.useEffect(()=>{re(I??t),N("chat"),T(!1),Q([]),Ke(g=>g+1),ut(null)},[t,I]),r.useEffect(()=>(at.current+=1,vt(void 0),De(!1),wt(!1),yt(null),()=>{at.current+=1}),[t]),r.useEffect(()=>{bt(yn(e.status))},[e.status,t]),r.useEffect(()=>{if(!s||y||G)return;const g=++St.current;return(async()=>{var w;try{const O=await D(t);if(g!==St.current)return;we(Wn(O.status)),bt(yn(O.status)),st.current=O,(w=he.current)==null||w.call(he,O)}catch{}})(),()=>{St.current+=1}},[s,t,y,G,D]),r.useEffect(()=>{Ve(e.invocation_name),xe(g=>g+1)},[e.invocation_name]),r.useEffect(()=>{G&&N("timeline")},[G]),r.useEffect(()=>{if(!s||y||G)return;const g=K.current.bootstrapConversation;if(!g){Xn(K.current.openingMessage(),Q);return}let w=!1;return Et(!0),(async()=>{try{const O=await g.call(K.current);if(w)return;Q(O.map(Ae))}catch{w||Xn(K.current.openingMessage(),Q)}finally{w||Et(!1)}})(),()=>{w=!0}},[s,y,G,t,le]);const He=r.useCallback(()=>{const g=++Mn.current;(async()=>{var w,O;try{const W=await q(t);if(g!==Mn.current)return;Ze(ce=>W.checklist.length===0&&Array.isArray(ce)&&ce.length>0||JSON.stringify(ce)===JSON.stringify(W.checklist)?ce:W.checklist),ft(null),(O=(w=K.current).seedChecklist)==null||O.call(w,W.checklist)}catch{}})()},[q,t]),$e=r.useCallback(()=>{h&&(async()=>{try{const g=await Ge(t);Te(g),Ie(null)}catch{}})()},[h,Ge,t]),ve=r.useCallback(()=>{if(!p)return;const g=++Un.current;(async()=>{try{const w=await ze(t);if(g!==Un.current)return;Me(O=>JSON.stringify(O)===JSON.stringify(w)?O:w),Xe(null)}catch{}})()},[p,ze,t]),jt=r.useCallback(g=>{const w=K.current.bootstrapConversation;w&&(async()=>{try{const O=await w.call(K.current);if(Ln.current)return;const W=O.map(Ae);let ce=!1;Q(rt=>Ur(rt,W)?rt:(ce=!0,W)),ce&&(g!=null&&g.refreshSidePanelsOnChange)&&(He(),ve())}catch{}})()},[He,ve]),Hs=r.useCallback(g=>{switch(g){case be.checklist:He();return;case be.resources:$e();return;case be.chat:jt();return;case be.timeline:ve();return;case be.all:default:He(),$e(),jt(),ve()}},[He,jt,$e,ve]),$s=xs({enabled:!!(s&&R&&!B),key:ae,cluster:X,isAdmin:j}),Bs=B??$s,Dn=or({enabled:s&&R,channelPrefix:V,agentId:e.id||t,subscribeToPusher:Bs,onRepoll:Hs});r.useEffect(()=>{if(!s||y||G||Dn)return;const g=window.setInterval(()=>{jt({refreshSidePanelsOnChange:!0})},Pr);return()=>{window.clearInterval(g)}},[s,y,G,Dn,t,le,jt]);const Yt=r.useCallback(g=>{var w,O;if(g&&g.length>0){Ze(g),(O=(w=K.current).seedChecklist)==null||O.call(w,g);return}He()},[He]),gn=r.useCallback(g=>{Yt(g.checklist),g.phase&&we(g.phase),$e(),ve()},[Yt,$e,ve]);r.useEffect(()=>{var g,w;!s||y||x&&x.length>0&&((w=(g=K.current).seedChecklist)==null||w.call(g,x))},[s,y,x]),r.useEffect(()=>{if(!s||y)return;let g=!1;return _t(w=>x!=null&&x.length?!1:w||oe===null||oe.length===0),ft(null),(async()=>{var w,O;try{const W=await q(t);if(g)return;x!=null&&x.length||(Ze(W.checklist),(O=(w=K.current).seedChecklist)==null||O.call(w,W.checklist))}catch{!g&&!(x!=null&&x.length)&&ft(Xt)}finally{g||_t(!1)}})(),()=>{g=!0}},[s,t,y,x,q]),r.useEffect(()=>{if(!s||!h)return;let g=!1;return Ye(!0),Ie(null),(async()=>{try{const w=await Ge(t);g||Te(w)}catch{g||Ie(aa)}finally{g||Ye(!1)}})(),()=>{g=!0}},[s,t,h,Ge]);const Fs=r.useCallback(()=>{gt(null),ye(null),We(null),Le(!1)},[]),Gs=r.useCallback(g=>{if(g.misRecordUrl){window.open(g.misRecordUrl,"_blank","noopener,noreferrer");return}gt(g),ye(null),We(null),Le(!0),(async()=>{try{const w=await Lt(t,g.id);ye(w)}catch{We(ra)}finally{Le(!1)}})()},[Lt,t]);r.useEffect(()=>{if(!s||!p)return;let g=!1;return pt(w=>w||Pe===null),Xe(null),(async()=>{try{const w=await ze(t);g||Me(w)}catch{g||Xe(rs)}finally{g||pt(!1)}})(),()=>{g=!0}},[s,t,p,ze]),r.useEffect(()=>{if(!s||!y)return;let g=!1;const w={id:`user-brief-${Date.now()}`,author:me.user,text:Mr(y,Pn.current)};return(async()=>{const O=await K.current.start(y);g||(Q([Ae(K.current.openingMessage()),Ae(w),Ae(O.message)]),Yt(O.checklist),we(O.phase??$.running),$e(),ve())})(),()=>{g=!0}},[s,y,t,Yt,$e,ve]);const mn=I??t,Jt=Pe==null?void 0:Pe.chatSessions,Hn=Jt!=null&&Jt.length?Jt.reduce((g,w)=>Date.parse(w.timestamp)<Date.parse(g.timestamp)?w:g).sessionId:void 0,pn=r.useCallback(()=>{N("chat"),T(!1),le!==mn&&(re(mn),Q([]),Ke(g=>g+1))},[le,mn]),zs=r.useCallback(g=>{if(g===Hn){pn();return}re(g),T(!0),N("chat"),Q([]),Ke(w=>w+1)},[Hn,pn]),qs=r.useCallback(async()=>{var g;se(null),Dt(!0);try{await K.current.pause(),St.current+=1,we($.paused),bt(!0);const w={...st.current,status:k.paused};st.current=w,(g=he.current)==null||g.call(he,w)}catch{se(ia)}finally{Dt(!1)}},[]),Vs=r.useCallback(async()=>{var w;se(null),$t(!0);let g=!1;try{await K.current.resume(),g=!0,St.current+=1,we($.running),bt(!1);const O={...st.current,status:k["generating-a-response"]};st.current=O,(w=he.current)==null||w.call(he,O),Et(!0);const W={id:`wake-${Date.now()}`,author:me.user,text:Bn};Q(rt=>[...rt,Ae(W)]);const ce=await K.current.sendMessage(Bn);Q(rt=>[...rt,Ae(ce.message)]),gn(ce)}catch{se(g?xa:va)}finally{$t(!1),Et(!1)}},[gn]),Ks=r.useCallback(async()=>{se(null),et(null),Ft(!0);try{await Se(t),Nt(!1),J==null||J(),a()}catch{et(Nn),se(Nn)}finally{Ft(!1)}},[t,Se,J,a]),Ys=r.useCallback(async()=>{se(null),c(null),zt(!0);try{await je(t),On(null),we($.paused),bt(!0),N("chat"),tt(!1),ee==null||ee()}catch{c(kn),se(kn)}finally{zt(!1)}},[t,je,ee]),Js=r.useCallback(async()=>{se(null),de(null),C(!0);try{await ot(t),fe(!1),pe==null||pe(),a()}catch(g){de(Ss(g))}finally{C(!1)}},[t,ot,pe,a]),Ws=r.useCallback(g=>{const w=g.trim(),O=Z;if(ut(null),!w){xe(W=>W+1);return}w!==O&&(Ve(w),(async()=>{try{await qe(t,w)}catch{Ve(O),xe(W=>W+1),ut(wa)}})())},[Z,t,qe]),Xs=r.useCallback(()=>{if(!j||Ue||xt)return;const g=++at.current;wt(!0),yt(null),(async()=>{try{const w=await _e(t);if(at.current!==g)return;vt(w),De(!0)}catch{at.current===g&&yt(sa)}finally{at.current===g&&wt(!1)}})()},[j,Ue,xt,_e,t]),Zs=oe;return n.jsxs(n.Fragment,{children:[n.jsxs(u.Modal,{open:s,closeHandler:a,hideCloseButton:!0,className:"agent-workspace",children:[n.jsxs(u.Modal.Header,{className:"agent-workspace__header",children:[n.jsxs("div",{className:"agent-workspace__header-title",children:[n.jsx("span",{className:"agent-workspace__header-avatar","aria-hidden":"true",children:n.jsx(u.Icon,{name:"ask-arbor",size:24})}),n.jsx(u.Modal.Title,{children:G?n.jsx("span",{className:"agent-workspace__header-name",children:Z}):n.jsx(u.EditableText,{className:"agent-workspace__header-name",text:Z,onEditSave:Ws},ct)}),n.jsx("span",{className:Y("agent-workspace__phase",`agent-workspace__phase--${te}`),children:Ca[te]}),G?n.jsx("span",{className:"agent-workspace__phase agent-workspace__phase--archived",children:"Archived"}):null,Re&&n.jsx("p",{className:"agent-workspace__error agent-workspace__name-error",role:"alert",children:Re})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(u.Button,{variant:Vt?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!Vt,onClick:()=>Us(g=>!g),children:"Checklist"}),n.jsx(u.Button,{variant:Kt?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Kt,onClick:()=>Ds(g=>!g),children:"Resources"}),n.jsx(u.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),n.jsxs(u.Modal.Body,{className:Y("agent-workspace__body",{"agent-workspace__body--no-checklist":Vt,"agent-workspace__body--no-resources":Kt}),children:[n.jsxs("section",{className:Y("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!p&&(G||ue==="timeline")}),"aria-label":"Agent",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(u.Heading,{level:4,children:"Agent"}),o&&!Ct&&!G&&te===$.running&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Pause",disabled:At,onClick:()=>void qs(),children:At?"Pausing…":"Pause agent"}),v&&!Ct&&!G&&te===$.paused&&Ps&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"iteration-ccw",iconLeftScreenReaderText:"Resume",disabled:Ht,onClick:()=>void Vs(),children:Ht?"Resuming…":"Resume agent"}),E&&!Ct&&!G&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>{et(null),se(null),Nt(!0)},children:"Archive agent"}),S&&!Ct&&G&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",onClick:()=>{c(null),se(null),tt(!0)},children:"Unarchive agent"}),j&&G&&n.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",onClick:()=>{de(null),se(null),fe(!0)},children:"Delete agent"})]}),kt&&n.jsx("p",{className:"agent-workspace__error agent-workspace__lifecycle-error",role:"alert",children:kt}),p&&!G&&n.jsxs(u.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(u.Tabs.Item,{active:ue==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>N("chat")},children:"Chat"}),n.jsx(u.Tabs.Item,{active:ue==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>N("timeline")},children:"Timeline"})]}),p&&!G&&ue==="chat"&&L&&n.jsx("div",{className:"agent-workspace__center-back",children:n.jsx(u.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:pn,children:"Back to main chat"})}),p&&(G||ue==="timeline")&&n.jsx(sr,{timeline:Pe,isLoading:ln,error:Pt,onOpenChatSession:G?void 0:zs}),!G&&n.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!p&&ue!=="chat",children:n.jsx(Ba,{connector:F,phase:te,chatHistory:ie,chatSessionKey:dt,readOnly:Ct,enableUpload:P,onTurn:gn,onAwaitingChange:Et})}),G&&!p&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Chat is not available for archived agents."})]}),!Vt&&n.jsx(Fa,{checklist:Zs,isLoading:Qe,error:Mt,phase:te,adminMode:j,context:Ut,contextLoaded:Ue,contextLoading:xt,contextError:on,onContextSelect:Xs},t),!Kt&&n.jsx(qa,{resources:sn,isLoading:an,error:Je,onOpenResource:Gs}),n.jsx(Ga,{resource:ht,html:rn,isLoading:Oe,error:mt,onClose:Fs})]})]}),n.jsx(us,{open:cn,isInProgress:te===$.running||te===$.paused&&!gs(oe??void 0),isArchiving:Bt,error:un,onCancel:()=>{Bt||(et(null),Nt(!1))},onConfirm:()=>{Ks()}}),n.jsx(hs,{open:dn,isUnarchiving:Gt,error:qt,onCancel:()=>{Gt||(c(null),tt(!1))},onConfirm:()=>{Ys()}}),n.jsx(ds,{open:ne,isDeleting:b,error:nt,onCancel:()=>{b||(de(null),fe(!1))},onConfirm:()=>{Js()}})]})},Dr="Unable to load agent definitions. Please try again.",Hr="Unable to start the agent.",Zn="Loading agents…",$r="Which agent?",Br="Select an agent",Fr="What do you want to call this agent?",Gr="Science Museum Trip, or Governor's Report",zr="Make this something you can easily recognise that relates to the task the agent is carrying out.",Qn="new-agent-invocation-name-hint",es=(e,t)=>{const s=t==null?void 0:t.trim();if(s)return e.find(a=>a.ref===s)},qr=(e,t)=>`${e.replace(/\/+$/,"")}/${encodeURIComponent(t)}`,Is=({open:e,onClose:t,onStart:s,agentDefinitions:a,definitionsState:i="idle",definitionsError:d=null,onRetryDefinitions:l,embedded:m=!1,preselectAgent:h})=>{const[p,_]=r.useState(void 0),[A,o]=r.useState(""),[v,E]=r.useState(!1),[S,I]=r.useState(null),P=[...a].sort((R,V)=>R.display_name.localeCompare(V.display_name)).map(R=>({value:R.ref,label:R.display_name}));r.useEffect(()=>{e&&(o(""),E(!1),I(null),_(es(a,h)))},[e,h]),r.useEffect(()=>{if(!e)return;const R=es(a,h);R&&_(V=>V??R)},[e,h,a]);const j=p!==void 0&&A.trim().length>0,y=r.useCallback(R=>{const V=a.find(ae=>ae.ref===R[0]);V&&_(V)},[a]),f=r.useCallback(async()=>{if(!(!p||!j||v)){E(!0),I(null);try{await s({definition:p,invocationName:A.trim()})}catch(R){I(R instanceof Error?R.message:Hr)}finally{E(!1)}}},[j,p,A,v,s]);if(i==="idle"&&a.length===0||!e)return null;let x;return i==="loading"?x=n.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[n.jsx(u.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:Zn}),n.jsx("p",{className:"new-agent__state-message",children:Zn})]}):i==="error"?x=n.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[n.jsx(u.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"new-agent__state-message",children:d??Dr}),l?n.jsx(u.Button,{variant:"secondary",size:"S",onClick:l,children:"Try again"}):null]}):x=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:R=>{R.preventDefault(),j&&!v&&f()},children:[n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:$r}),n.jsx(u.SelectDropdown,{id:"new-agent-type",placeholder:Br,options:P,selectedValues:p?[p.ref]:[],onSelectionChange:y,"aria-describedBy":p!=null&&p.description?"new-agent-type-description":void 0}),p!=null&&p.description?n.jsx("p",{className:"new-agent__field-hint",id:"new-agent-type-description",children:p.description}):null]}),n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:Fr}),n.jsx("p",{className:"new-agent__field-hint",id:Qn,children:zr}),n.jsx(u.TextInput,{id:"new-agent-invocation-name",value:A,placeholder:Gr,"aria-describedby":Qn,onChange:R=>o(R.target.value)})]}),S?n.jsx("p",{className:"new-agent__error",role:"alert",children:S}):null,n.jsx("div",{className:"new-agent__actions",children:n.jsx(u.Button,{type:"submit",variant:"primary",className:Y("new-agent__start-button",{"new-agent__start-button--starting":v}),disabled:!j||v,iconLeftName:v?"loader":"sparkles",iconLeftScreenReaderText:v?"Starting":void 0,children:v?"Starting…":"Start"})})]}),m?n.jsx("div",{className:Y("new-agent","new-agent--embedded"),children:n.jsx("div",{className:"new-agent__body",children:x})}):n.jsxs(u.Modal,{open:e,closeHandler:t,className:"new-agent",children:[n.jsx(u.Modal.Title,{children:"Start an agent"}),n.jsx(u.Modal.Body,{className:"new-agent__body",children:x})]})},An=e=>{window.location.assign(e)},Vr=({open:e,authToken:t,headers:s,agentDefinitionsUrl:a,agentsUrl:i,closeUrl:d,successUrl:l,viewAgentUrlPrefix:m,preselectAgent:h,onClose:p,onStart:_,embedded:A=!1})=>{const o=JSON.stringify(s??{}),v=r.useMemo(()=>new nn({token:t,headers:s,urls:{agentDefinitions:a,agents:i}}),[t,a,i,o]),[E,S]=r.useState([]),[I,P]=r.useState("loading"),[j,y]=r.useState(null),[f,x]=r.useState(0);r.useEffect(()=>{if(!e)return;let X=!1;return P("loading"),y(null),(async()=>{try{const B=await v.listAgentDefinitions();if(X)return;S(B.map(Rn)),P("idle")}catch(B){if(X)return;S([]),y(Es(B)),P("error")}})(),()=>{X=!0}},[v,e,f]);const R=r.useCallback(()=>{p==null||p(),d&&An(d)},[d,p]),V=r.useCallback(async X=>{const B=await v.createAgent(X.definition.ref,{invocationName:X.invocationName}),J={id:B.id};_==null||_(X,J);const ee=m==null?void 0:m.trim();if(ee){An(qr(ee,B.id));return}l&&An(l)},[v,_,l,m]),ae=r.useCallback(()=>{x(X=>X+1)},[]);return n.jsx(Is,{open:e,onClose:R,onStart:V,agentDefinitions:E,definitionsState:I,definitionsError:j,onRetryDefinitions:ae,embedded:A,preselectAgent:h})},Kr=e=>"agentDefinitionsUrl"in e,Os=e=>Kr(e)?n.jsx(Vr,{...e}):n.jsx(Is,{...e}),Yr=({open:e,onClose:t})=>{const s=r.useId(),a=r.useId();return n.jsxs(u.Modal,{open:e,closeHandler:t,className:"archive-agent-confirm",children:[n.jsx(u.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(u.Modal.Title,{id:s,children:Na})}),n.jsxs(u.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsx("div",{role:"alertdialog","aria-labelledby":s,"aria-describedby":a,children:n.jsx("p",{id:a,className:"archive-agent-confirm__lead",children:ka})}),n.jsx("div",{className:"archive-agent-confirm__actions",children:n.jsx(u.Button,{variant:"secondary",size:"S",onClick:t,children:"Close"})})]})]})},Jr=3,Wr=56,Xr=e=>e.archivedAt?"archived":e.status===k.paused?"paused":null,Zr=e=>{if(e==="archived")return ea;if(e==="paused")return lt[k.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(u.Icon,{name:a.name,size:16,color:a.color,className:Y({"agent-view__progress-icon--spinning":a.spin}),screenReaderText:s})}):n.jsx("span",{className:Y("agent-view__dot",{[`agent-view__dot--${e.dotModifier}`]:e.dotModifier}),children:n.jsx(u.Dot,{colour:e.dotColour,label:s})})},Ls=({agent:e,agentName:t,column:s,isExpanded:a,isLoading:i,checklist:d,error:l,canArchive:m,canUnarchive:h=!1,canDelete:p=!1,onToggle:_,onViewAgent:A,onArchive:o,onUnarchive:v,onDelete:E})=>{const{id:S,invocation_name:I}=e,P=`agent-card-${S}-header`,j=`agent-card-${S}-progress`,y=Xr(e),f=Zr(y);return n.jsx("li",{className:Y("agent-view__card",{"agent-view__card--expanded":a,"agent-view__card--paused":y==="paused","agent-view__card--archived":y==="archived","agent-view__card--view-only":!e.usable}),children:n.jsxs(u.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":j,"aria-label":I,id:P,onClick:()=>_(S),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(Qr,{column:s,overlayIcon:f}),n.jsx("span",{className:"agent-view__card-invocation-name",children:I}),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,e.usable?null:n.jsx("span",{className:"agent-view__card-state-pill",children:"View only"}),n.jsx(u.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&n.jsxs("div",{id:j,"aria-labelledby":P,className:"agent-view__card-progress",children:[i&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:it}),n.jsx("span",{children:it})]}),!i&&l&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:l}),!i&&!l&&d!==null&&n.jsx(Da,{checklist:d}),!i&&!l&&d===null&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:it}),n.jsx("span",{children:it})]}),n.jsxs("div",{className:"agent-view__card-actions",children:[m?n.jsx(u.Button,{variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>o==null?void 0:o(e),children:"Archive"}):h?n.jsx(u.Button,{variant:"secondary",size:"S",onClick:()=>v==null?void 0:v(e),children:"Unarchive"}):p?n.jsx(u.Button,{variant:"secondary-destructive",size:"S",onClick:()=>E==null?void 0:E(e),children:"Delete"}):n.jsx("span",{}),h&&p?n.jsx(u.Button,{variant:"secondary-destructive",size:"S",onClick:()=>E==null?void 0:E(e),children:"Delete"}):null,n.jsx(u.Button,{variant:"secondary",size:"S",onClick:()=>A==null?void 0:A(e),children:"View agent"})]})]})]})})},ei=()=>n.jsx("ul",{className:"agent-view__card-list","aria-hidden":"true",children:Array.from({length:Jr},(e,t)=>n.jsx("li",{className:"agent-view__card agent-view__card--skeleton",children:n.jsx(u.Skeleton,{className:"agent-view__card-skeleton",width:"100%",height:Wr})},t))}),ts=({column:e,agents:t,expandedAgentId:s,loadingAgentId:a,checklistByInvocationId:i,errorByAgentId:d,definitionNameByRef:l,onToggleAgent:m,onViewAgent:h,onArchiveAgent:p,canArchive:_,isLoading:A=!1})=>n.jsxs("section",{className:"agent-view__column","aria-label":e.title,children:[n.jsxs("div",{className:"agent-view__column-header",children:[n.jsx(u.Heading,{level:4,children:e.title}),n.jsx("span",{className:"agent-view__column-count",children:A?0:t.length})]}),A?n.jsx(ei,{}):n.jsx("ul",{className:"agent-view__card-list",children:t.map(o=>n.jsx(Ls,{agent:o,agentName:Zt(o,l),column:e,isExpanded:s===o.id,isLoading:a===o.id,checklist:i[o.invocation_id]??null,error:d[o.id]??null,canArchive:_&&!o.archivedAt&&o.usable,onToggle:m,onViewAgent:h,onArchive:p},o.id))})]}),Zt=(e,t)=>t.get(e.agent_definition_ref)??e.agent_definition_ref.replace(/_/g," "),ti=({jwt:e,headers:t,agentDefinitionsUrl:s,agentsUrl:a,agentUrl:i,agentChecklistUrl:d,agentResourcesUrl:l,agentTimelineUrl:m,agentChatUrl:h,agentConversationUrl:p,pauseAgentUrl:_,resumeAgentUrl:A,archiveAgentUrl:o,unarchiveAgentUrl:v,enableUpload:E,adminMode:S=!1,showHeader:I=!1,institutions:P,usePusherToRepoll:j=!1,pusherChannelPrefix:y=jn,pusherKey:f,pusherCluster:x,subscribeToPusher:R,selectedAgent:V,scope:ae=ls})=>{var qt;const X=r.useMemo(()=>({agentDefinitions:s,agents:a,agent:i,agentChecklist:d,...l?{agentResources:l}:{},...m?{agentTimeline:m}:{},agentChat:h,agentConversation:p,...o?{archiveAgent:o}:{},...v?{unarchiveAgent:v}:{}}),[s,a,i,d,l,m,h,p,o,v]),[B,J]=r.useState(null),ee=B?(qt=P==null?void 0:P.find(c=>c.applicationId===B.application_id))==null?void 0:qt.applicationUrl:void 0,pe=r.useMemo(()=>{const c={...t??{}};return ee?c[Be.arborApplicationUrl]=ee:delete c[Be.arborApplicationUrl],c},[t,ee]),{agents:M,agentDefinitions:le,loadState:re,loadError:ue,reload:N,refresh:L,fetchAgentChecklist:T,createAgent:F,archiveAgent:D,unarchiveAgent:q,deleteAgent:_e,removeAgent:Ge,replaceAgent:Lt}=js({jwt:e,headers:pe,urls:X,scope:ae}),[ze,qe]=r.useState(!1),[Se,je]=r.useState(null),[ot,K]=r.useState(null),[Z,Ve]=r.useState({}),[ct,xe]=r.useState({}),[Re,ut]=r.useState([]),[te,we]=r.useState([]),[ie,Q]=r.useState(null),[dt,Ke]=r.useState(!1),[sn,Te]=r.useState(null),[an,Ye]=r.useState(!1),[Je,Ie]=r.useState(null),[ht,gt]=r.useState(!1),[rn,ye]=r.useState(null),[Oe,Le]=r.useState(null),[mt,We]=r.useState(!1),[Pe,Me]=r.useState(null),[ln,pt]=r.useState(!1),Pt=r.useRef(!1);r.useEffect(()=>{J(c=>{if(!c)return null;const b=M.find(C=>C.id===c.id||C.invocation_id===c.invocation_id||C.invocation_id===c.id);return b||(re==="loading"?c:null)})},[M,re]),r.useEffect(()=>{if(!V||Pt.current||re==="loading")return;Pt.current=!0;const c=M.find(({id:b})=>b===V);if(c){J(c);return}pt(!0)},[V,M,re]);const Xe=r.useMemo(()=>{const c=new Set(M.map(C=>C.application_id)),b=new Map((P??[]).map(C=>[C.applicationId,C.name]));return[...c].sort((C,ne)=>(b.get(C)??C).localeCompare(b.get(ne)??ne)).map(C=>({value:C,label:b.get(C)??C}))},[M,P]),oe=r.useMemo(()=>new Map(le.map(c=>[c.ref,c.display_name])),[le]),Ze=r.useMemo(()=>[...new Set(M.map(b=>Zt(b,oe)))].sort((b,C)=>b.localeCompare(C)).map(b=>({value:b,label:b})),[M,oe]),Qe=r.useMemo(()=>M.filter(c=>!(Re.length>0&&!Re.includes(c.application_id)||te.length>0&&!te.includes(Zt(c,oe)))),[M,oe,te,Re]),_t=Xe.length>1,Mt=Ze.length>1,ft=_t||Mt;r.useEffect(()=>{const c=window.setInterval(()=>{L()},6e4);return()=>{window.clearInterval(c)}},[L]),r.useEffect(()=>{if(M.length===0)return;let c=!1;return(async()=>{const b=await Promise.allSettled(M.map(async C=>{const ne=await T(C.invocation_id);return{agentId:C.id,invocationId:C.invocation_id,checklist:ne.checklist}}));c||(Ve(C=>{const ne={...C};let fe=!1;for(const nt of b){if(nt.status!=="fulfilled")continue;const{invocationId:de,checklist:kt}=nt.value;JSON.stringify(C[de])!==JSON.stringify(kt)&&(ne[de]=kt,fe=!0)}return fe?ne:C}),xe(C=>{const ne={...C};let fe=!1;return b.forEach((nt,de)=>{nt.status==="rejected"&&ne[M[de].id]!==Xt&&(ne[M[de].id]=Xt,fe=!0)}),fe?ne:C}))})(),()=>{c=!0}},[M,T]);const Ut=r.useCallback(async c=>{if(!Z[c.invocation_id]){K(c.id),xe(b=>{const C={...b};return delete C[c.id],C});try{const b=await T(c.invocation_id);Ve(C=>({...C,[c.invocation_id]:b.checklist}))}catch{xe(b=>({...b,[c.id]:Xt}))}finally{K(b=>b===c.id?null:b)}}},[T,Z]),vt=r.useCallback(c=>{if(Se===c){je(null);return}const b=M.find(({id:C})=>C===c);b&&(je(c),Ut(b))},[M,Se,Ut]),Ue=r.useMemo(()=>Qe.filter(c=>!!c.archivedAt),[Qe]),De=r.useMemo(()=>Qe.filter(c=>!c.archivedAt),[Qe]),xt=r.useMemo(()=>{const c={};for(const b of De){const C=vn(b,Z[b.invocation_id]);(c[C]??(c[C]=[])).push(b)}return c},[De,Z]),wt=re==="loading"&&M.length===0,on=De.length>0&&De.some(c=>Z[c.invocation_id]===void 0&&ct[c.id]===void 0),yt=wt||on,At=r.useCallback(c=>{J(c)},[]),Dt=r.useCallback(c=>{Te(null),Q(c)},[]),Ht=r.useCallback(()=>{dt||(Te(null),Q(null))},[dt]),$t=r.useCallback(async()=>{if(ie){Ke(!0),Te(null),xe(c=>{const b={...c};return delete b[ie.id],b});try{await D(ie.invocation_id),J(c=>(c==null?void 0:c.id)===ie.id?null:c),je(ie.id),Ye(!0),Q(null)}catch{Te(Nn)}finally{Ke(!1)}}},[ie,D]),Bt=r.useCallback(c=>{ye(null),Ie(c)},[]),Ft=r.useCallback(()=>{ht||(ye(null),Ie(null))},[ht]),cn=r.useCallback(async()=>{if(Je){gt(!0),ye(null);try{await q(Je.invocation_id),Ie(null)}catch{ye(kn)}finally{gt(!1)}}},[Je,q]),Nt=ie?vn(ie,Z[ie.invocation_id])!==k.complete:!1,un=r.useCallback(async c=>{const b=await F(c);J(b),qe(!1)},[F]),et=r.useCallback(c=>{Me(null),Le(c)},[]),Gt=r.useCallback(()=>{mt||(Me(null),Le(null))},[mt]),zt=r.useCallback(async()=>{if(Oe){We(!0),Me(null);try{await _e(Oe.invocation_id),J(c=>(c==null?void 0:c.id)===Oe.id?null:c),Le(null)}catch(c){Me(Ss(c))}finally{We(!1)}}},[Oe,_e]),dn=r.useCallback(()=>{J(null)},[]),tt={expandedAgentId:Se,loadingAgentId:ot,checklistByInvocationId:Z,errorByAgentId:ct,definitionNameByRef:oe,onToggleAgent:vt,onViewAgent:At,onArchiveAgent:Dt,canArchive:!!o};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[I&&n.jsxs("div",{className:"agent-view__header",children:[n.jsx(u.Heading,{level:1,children:"Agents"}),n.jsx(u.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>qe(!0),children:"Start an agent"})]}),M.length>0&&ft&&n.jsxs("div",{className:"agent-view__filters",children:[_t&&n.jsxs("div",{className:"agent-view__filter",children:[n.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-institution-filter",children:"Institution"}),n.jsx(u.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:Xe,value:Re,onValueChange:ut,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Mt&&n.jsxs("div",{className:"agent-view__filter",children:[n.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-agent-filter",children:"Agent"}),n.jsx(u.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:Ze,value:te,onValueChange:we,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),re==="error"?n.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[n.jsx(u.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"agent-view__state-message",children:ue??is}),n.jsx(u.Button,{variant:"secondary",size:"S",onClick:N,children:"Try again"})]}):yt?n.jsx("div",{className:"agent-view__board","aria-busy":"true","aria-live":"polite",children:$n.map(c=>n.jsx(ts,{column:lt[c],agents:[],isLoading:!0,...tt},c))}):M.length===0?n.jsx(Ta,{}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"agent-view__board",children:$n.map(c=>n.jsx(ts,{column:lt[c],agents:xt[c]??[],...tt},c))}),Ue.length>0?n.jsxs("details",{className:"agent-view__archived",open:an,onToggle:c=>{Ye(c.currentTarget.open)},children:[n.jsxs("summary",{className:"agent-view__archived-summary",children:[n.jsx(u.Heading,{level:4,children:"Archived"}),n.jsx("span",{className:"agent-view__column-count",children:Ue.length})]}),n.jsx("ul",{className:"agent-view__card-list agent-view__archived-list",children:Ue.map(c=>n.jsx(Ls,{agent:c,agentName:Zt(c,oe),column:lt[vn(c,Z[c.invocation_id])],isExpanded:Se===c.id,isLoading:ot===c.id,checklist:Z[c.invocation_id]??null,error:ct[c.id]??null,canArchive:!1,canUnarchive:!!v&&c.usable,canDelete:S&&c.usable,onToggle:vt,onViewAgent:At,onUnarchive:Bt,onDelete:et},c.id))})]}):null]}),B&&n.jsx(Ts,{agent:B,invocationId:B.invocation_id,open:!0,jwt:e,headers:pe,agentUrl:i,agentChecklistUrl:d,agentResourcesUrl:l,agentTimelineUrl:m,agentChatUrl:h,agentConversationUrl:p,pauseAgentUrl:_,resumeAgentUrl:A,archiveAgentUrl:o,unarchiveAgentUrl:v,enableUpload:E,adminMode:S,initialChecklist:Z[B.invocation_id]??null,usePusherToRepoll:j,pusherChannelPrefix:y,pusherKey:f,pusherCluster:x,subscribeToPusher:R,onClose:dn,onAgentUpdated:Lt,onArchived:()=>{je(B.id),Ye(!0),L()},onUnarchived:()=>{L()},onDeleted:()=>{Ge(B.invocation_id)}},B.id||B.invocation_id),n.jsx(us,{open:!!ie,isInProgress:Nt,isArchiving:dt,error:sn,onCancel:Ht,onConfirm:()=>{$t()}}),n.jsx(hs,{open:!!Je,isUnarchiving:ht,error:rn,onCancel:Ft,onConfirm:()=>{cn()}}),n.jsx(ds,{open:!!Oe,isDeleting:mt,error:Pe,onCancel:Gt,onConfirm:()=>{zt()}}),n.jsx(Yr,{open:ln,onClose:()=>pt(!1)}),n.jsx(Os,{open:ze,onClose:()=>qe(!1),onStart:un,agentDefinitions:le})]})},ni=(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:ta,created_by:na,usable:!0,status:k["generating-a-response"],archivedAt:null,context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=ti;exports.AgentServiceClient=nn;exports.AgentServiceError=Fe;exports.AgentView=Ts;exports.DEFAULT_PUSHER_CHANNEL_PREFIX=jn;exports.HttpChatConnector=Cs;exports.MESSAGE_TYPE_REPOLL=Cn;exports.NewAgentModal=Os;exports.PUSHER_AGENT_MESSAGE_EVENT=_s;exports.REPOLL_TARGET=be;exports.buildAgentFromDefinition=ni;exports.buildAgentPusherChannel=fs;exports.createHttpChatConnectorFactory=In;exports.formatUserFileChatCardText=Ar;exports.mapApiAgent=Ce;exports.mapApiAgentDefinition=Rn;exports.mapApiAgentStatus=ws;exports.mapApiAgentTimelineResponse=ks;exports.mapApiChecklistEndpointResponse=tn;exports.mapApiChecklistItem=Tn;exports.mapApiChecklistResponse=wr;exports.mapApiChecklistStatus=ys;exports.mapApiConversationMessages=bs;exports.mapApiOpeningMessage=Ot;exports.mapApiResource=As;exports.mapApiResourcesEndpointResponse=Ns;exports.mapApiTripOption=_r;exports.parseConversationContentCaption=yr;exports.parseRepollMessages=vs;exports.useAgentService=js;exports.useAgentWorkspace=Rs;exports.useSubscribeToPusher=xs;
9
+ `):null}},Wn=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:rs,author:pe.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 Xn=0;const Tr=e=>(Xn+=1,`${e}-${Date.now()}-${Xn}`),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 Ss{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=bs(t.messages);return s.length===0?[this.opening]:s}async start(t){return{...await this.exchange(Ir(t)),phase:F.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 N;const i=[{role:pr.user,content:t}];let h="",l=null,m;const d=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:o=>{var y;const x=o.message;if((x==null?void 0:x.role)==="assistant"&&x.tool_calls&&x.tool_calls.length>0){const O=Te.thinkingPhrasesFromToolCalls(x.tool_calls);for(const P of O)P.phrase!==l&&(l=P.phrase,(y=a==null?void 0:a.onThinking)==null||y.call(a,P))}const j=x==null?void 0:x.content;j&&(h=o.is_final?j:h+j),o.is_final&&(m=o)}}),v=m??d,f={id:v.event_id||Tr("msg-agent"),author:pe.agent,text:h||v.message.content||"",...(N=v.follow_up_prompts)!=null&&N.length?{followUpPrompts:v.follow_up_prompts}:{}};try{const o=await this.client.getAgentChecklist(this.agentId),{checklist:x}=an(this.agentId,o);return x.length===0?{message:f}:(this.seededChecklist=x,{message:f,checklist:x})}catch{return{message:f,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const Ln=(e,t)=>s=>{var a,i;return new Ss(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)})},Es=e=>e instanceof Ve?e.message:e instanceof TypeError?"Network error while contacting the agent service.":e instanceof Error&&e.message?e.message:ls,js=e=>{if(e instanceof Ve){if(e.status===403)return ma;if(e.status===409)return pa;if(e.status===404)return _a}return ga},Or=e=>{const t={};for(const s of e){const a=Et(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),Qt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Rs=e=>{const{jwt:t,headers:s,urls:a,scope:i=os}=e,h=JSON.stringify(s??{}),l=Lr(a),m=r.useMemo(()=>({scope:i}),[i]),d=r.useMemo(()=>new rn({token:t,headers:s,urls:a}),[t,l]);r.useLayoutEffect(()=>{d.setHeaders(s)},[d,h]);const[v,f]=r.useState([]),[N,o]=r.useState([]),[x,j]=r.useState({}),[y,O]=r.useState("loading"),[P,I]=r.useState(null),[k,p]=r.useState(0),A=r.useRef(0),G=r.useCallback((_,R)=>{const E=_.map(Re),D=R.map(In),$=Or(_);f(W=>Qt(W,E)?W:E),o(W=>Qt(W,D)?W:D),j(W=>Qt(W,$)?W:$),O("idle"),I(null)},[]);r.useEffect(()=>{const _=++A.current;O("loading"),I(null),(async()=>{try{const[R,E]=await Promise.all([d.listAgents(m),d.listAgentDefinitions()]);if(_!==A.current)return;G(R,E)}catch(R){if(_!==A.current)return;f([]),o([]),j({}),O("error"),I(Es(R))}})()},[G,d,m,k]);const ae=r.useCallback(()=>{p(_=>_+1)},[]),ne=r.useCallback(async()=>{const _=++A.current;try{const[R,E]=await Promise.all([d.listAgents(m),d.listAgentDefinitions()]);if(_!==A.current)return;G(R,E)}catch{}},[G,d,m]),Z=r.useCallback(async _=>{const[R,E]=await Promise.all([d.getAgentChecklist(_),d.getAgent(_).catch(()=>null)]);return an(_,R,E??void 0)},[d]),M=r.useCallback(async _=>d.listAllAgentResources(_),[d]),H=r.useCallback(async({definition:_,invocationName:R})=>{const E=await d.createAgent(_.ref,{invocationName:R}),D=await d.getAgent(E.id),$=Re(D),W=Et(D);return f(_e=>[$,..._e]),W&&j(_e=>({..._e,[$.invocation_id]:W,[$.id]:W})),$},[d]),z=r.useCallback(async _=>{const R=await d.archiveAgent(_),E=Re(R);return f(D=>D.map($=>$.id===E.id||$.id===_||$.invocation_id===_?E:$)),E},[d]),ie=r.useCallback(async _=>{const R=await d.unarchiveAgent(_),E=Re(R);return f(D=>D.map($=>$.id===E.id||$.id===_||$.invocation_id===_?E:$)),E},[d]),oe=r.useCallback(_=>{f(R=>R.filter(E=>E.id!==_&&E.invocation_id!==_))},[]),L=r.useCallback(_=>{f(R=>{const E=R.map(D=>D.id===_.id||D.invocation_id===_.invocation_id?{...D,..._}:D);return Qt(R,E)?R:E})},[]),ce=r.useCallback(async _=>{await d.deleteAgent(_),oe(_)},[d,oe]),K=r.useMemo(()=>Ln(d,{resolveOpeningMessage:_=>x[_.invocation_id]??x[_.id]}),[d,x]);return{agents:v,agentDefinitions:N,loadState:y,loadError:P,reload:ae,refresh:ne,fetchAgentChecklist:Z,fetchAgentResources:M,createAgent:H,archiveAgent:z,unarchiveAgent:ie,deleteAgent:ce,removeAgent:oe,replaceAgent:L,chatConnector:K}},Pr=e=>JSON.stringify(e),Ts=e=>{const{agent:t,jwt:s,headers:a,urls:i,chatId:h}=e,l=JSON.stringify(a??{}),m=Pr(i),d=r.useMemo(()=>new rn({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,m]);r.useLayoutEffect(()=>{d.setHeaders(a)},[d,l]);const v=r.useCallback(async p=>Re(await d.getAgent(p)),[d]),f=r.useCallback(async p=>{const[A,G]=await Promise.all([d.getAgentChecklist(p),d.getAgent(p).catch(()=>null)]);return an(p,A,G??void 0)},[d]),N=r.useCallback(async p=>d.listAllAgentResources(p),[d]),o=r.useCallback(async p=>d.getAgentContext(p),[d]),x=r.useCallback(async(p,A)=>d.getAgentResourceHtml(p,A),[d]),j=r.useCallback(async p=>{const A=await d.getAgentTimeline(p);return Cs(A)},[d]),y=r.useCallback(async(p,A)=>{await d.updateAgent(p,{invocationName:A})},[d]),O=r.useCallback(async p=>Re(await d.archiveAgent(p)),[d]),P=r.useCallback(async p=>Re(await d.unarchiveAgent(p)),[d]),I=r.useCallback(async p=>{await d.deleteAgent(p)},[d]);return{connector:r.useMemo(()=>Ln(d,{chatId:h??t.invocation_id})(t),[d,t.invocation_id,h]),fetchAgent:v,fetchAgentChecklist:f,fetchAgentContext:o,fetchAgentResources:N,fetchAgentResourceHtml:x,fetchAgentTimeline:j,updateAgentInvocationName:y,archiveAgent:O,unarchiveAgent:P,deleteAgent:I}},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()},Zn=e=>{switch(e){case C.paused:return F.paused;case C.complete:return F.complete;default:return F.running}},yn=e=>e===C.paused,Qn=(e,t)=>{t([be(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}),Is=({agent:e,invocationId:t,open:s,onClose:a,jwt:i,headers:h,agentUrl:l,agentChecklistUrl:m,agentResourcesUrl:d,agentTimelineUrl:v,agentChatUrl:f,agentConversationUrl:N,pauseAgentUrl:o,resumeAgentUrl:x,archiveAgentUrl:j,unarchiveAgentUrl:y,chatId:O,enableUpload:P,adminMode:I=!1,initialBrief:k,initialPhase:p,initialChecklist:A,usePusherToRepoll:G=!1,pusherChannelPrefix:ae=Tn,pusherKey:ne="",pusherCluster:Z="",subscribeToPusher:M,onArchived:H,onUnarchived:z,onDeleted:ie,onAgentUpdated:oe})=>{const[L,ce]=r.useState(O??t),[K,_]=r.useState("chat"),[R,E]=r.useState(!1),{connector:D,fetchAgent:$,fetchAgentChecklist:W,fetchAgentContext:_e,fetchAgentResources:Ie,fetchAgentResourceHtml:jt,fetchAgentTimeline:Ke,updateAgentInvocationName:Rt,archiveAgent:Ye,unarchiveAgent:Oe,deleteAgent:Le}=Ts({agent:{...e,invocation_id:t},jwt:i,headers:h,chatId:L,urls:{agentUrl:l,agentChecklistUrl:m,agentResourcesUrl:d,agentTimelineUrl:v,agentChatUrl:f,agentConversationUrl:N,pauseAgentUrl:o,resumeAgentUrl:x,archiveAgentUrl:j,unarchiveAgentUrl:y}}),X=r.useRef(D),[Pe,re]=r.useState(e.invocation_name),[Tt,Me]=r.useState(0),[Ue,we]=r.useState(null),[he,ue]=r.useState(p??(k?F.running:Zn(e.status))),[ln,Y]=r.useState([]),[ot,De]=r.useState(0),[It,Ot]=r.useState([]),[Je,Lt]=r.useState(!1),[ct,ke]=r.useState(null),[ut,We]=r.useState(null),[Pt,dt]=r.useState(null),[Xe,fe]=r.useState(!1),[ht,He]=r.useState(null),[ye,Mt]=r.useState(null),[Ze,Ut]=r.useState(!1),[Dt,Qe]=r.useState(null),[$e,de]=r.useState(A??null),[Ht,Ne]=r.useState(!1),[$t,et]=r.useState(null),[on,gt]=r.useState(void 0),[tt,nt]=r.useState(!1),[Ae,mt]=r.useState(!1),[cn,pt]=r.useState(null),[Bt,_t]=r.useState(!1),[Ft,Gt]=r.useState(!1),[zt,qt]=r.useState(!1),[un,ft]=r.useState(!1),[dn,st]=r.useState(null),[Vt,Kt]=r.useState(!1),[hn,vt]=r.useState(!1),[Yt,Be]=r.useState(null),[u,b]=r.useState(!1),[S,se]=r.useState(!1),[Fe,ve]=r.useState(null),[Ce,ee]=r.useState(null),[Ms,xt]=r.useState(()=>yn(e.status)),[Us,Pn]=r.useState(e.archivedAt??null),q=!!Us,wt=!e.usable,[gn,kt]=r.useState(!1),[Jt,Ds]=r.useState(!1),[Wt,Hs]=r.useState(!1),Mn=r.useRef(gn),Un=r.useRef(e.invocation_name),at=r.useRef(e),ge=r.useRef(oe),Dn=r.useRef(0),Hn=r.useRef(0),rt=r.useRef(0),yt=r.useRef(0),Nt=r.useRef($e);Nt.current=$e,ge.current=oe,r.useEffect(()=>{Pn(e.archivedAt??null)},[e.archivedAt]),r.useEffect(()=>{X.current=D},[D]),r.useEffect(()=>{Un.current=e.invocation_name},[e.invocation_name]),r.useEffect(()=>{at.current=e},[e]),r.useEffect(()=>{Mn.current=gn},[gn]),r.useEffect(()=>{ce(O??t),_("chat"),E(!1),Y([]),De(g=>g+1),we(null)},[t,O]),r.useEffect(()=>(rt.current+=1,gt(void 0),nt(!1),mt(!1),pt(null),()=>{rt.current+=1}),[t]),r.useEffect(()=>{xt(yn(e.status))},[e.status,t]),r.useEffect(()=>{if(!s||k||q)return;const g=++yt.current;return(async()=>{var w;try{const T=await $(t);if(g!==yt.current)return;ue(Zn(T.status)),xt(yn(T.status)),at.current=T,(w=ge.current)==null||w.call(ge,T)}catch{}})(),()=>{yt.current+=1}},[s,t,k,q,$]),r.useEffect(()=>{re(e.invocation_name),Me(g=>g+1)},[e.invocation_name]),r.useEffect(()=>{q&&_("timeline")},[q]),r.useEffect(()=>{if(!s||k||q)return;const g=X.current.bootstrapConversation;if(!g){Qn(X.current.openingMessage(),Y);return}let w=!1;return kt(!0),(async()=>{try{const T=await g.call(X.current);if(w)return;Y(T.map(be))}catch{w||Qn(X.current.openingMessage(),Y)}finally{w||kt(!1)}})(),()=>{w=!0}},[s,k,q,t,L]);const Ge=r.useCallback(()=>{const g=++Dn.current;(async()=>{var w,T;try{const te=await W(t);if(g!==Dn.current)return;de(Q=>te.checklist.length===0&&Array.isArray(Q)&&Q.length>0||JSON.stringify(Q)===JSON.stringify(te.checklist)?Q:te.checklist),et(null),(T=(w=X.current).seedChecklist)==null||T.call(w,te.checklist)}catch{}})()},[W,t]),ze=r.useCallback(()=>{d&&(async()=>{try{const g=await Ie(t);Ot(g),ke(null)}catch{}})()},[d,Ie,t]),xe=r.useCallback(()=>{if(!v)return;const g=++Hn.current;(async()=>{try{const w=await Ke(t);if(g!==Hn.current)return;Mt(T=>JSON.stringify(T)===JSON.stringify(w)?T:w),Qe(null)}catch{}})()},[v,Ke,t]),At=r.useCallback(g=>{const w=X.current.bootstrapConversation;w&&(async()=>{try{const T=await w.call(X.current);if(Mn.current)return;const te=T.map(be);let Q=!1;Y(le=>Dr(le,te)?le:(Q=!0,te)),Q&&(g!=null&&g.refreshSidePanelsOnChange)&&(Ge(),xe())}catch{}})()},[Ge,xe]),$s=r.useCallback(g=>{switch(g){case je.checklist:Ge();return;case je.resources:ze();return;case je.chat:At();return;case je.timeline:xe();return;case je.all:default:Ge(),ze(),At(),xe()}},[Ge,At,ze,xe]),Bs=ws({enabled:!!(s&&G&&!M),key:ne,cluster:Z,isAdmin:I}),Fs=M??Bs,$n=cr({enabled:s&&G,channelPrefix:ae,agentId:e.id||t,subscribeToPusher:Fs,onRepoll:$s});r.useEffect(()=>{if(!s||k||q||$n)return;const g=window.setInterval(()=>{At({refreshSidePanelsOnChange:!0})},Mr);return()=>{window.clearInterval(g)}},[s,k,q,$n,t,L,At]);const Xt=r.useCallback(g=>{var w,T;if(g&&g.length>0){de(g),(T=(w=X.current).seedChecklist)==null||T.call(w,g);return}Ge()},[Ge]),mn=r.useCallback(g=>{Xt(g.checklist),g.phase&&ue(g.phase),ze(),xe()},[Xt,ze,xe]);r.useEffect(()=>{var g,w;!s||k||A&&A.length>0&&(de(T=>T&&T.length>0?T:A),Ne(!1),(w=(g=X.current).seedChecklist)==null||w.call(g,A))},[s,k,A]),r.useEffect(()=>{if(!s||k)return;let g=!1;return Ne(w=>{var T;return(((T=Nt.current)==null?void 0:T.length)??0)>0?!1:w||Nt.current===null||Nt.current.length===0}),et(null),(async()=>{var w,T,te;try{const Q=await W(t);if(g)return;de(le=>Q.checklist.length===0&&Array.isArray(le)&&le.length>0||JSON.stringify(le)===JSON.stringify(Q.checklist)?le:Q.checklist),Q.checklist.length>0&&((T=(w=X.current).seedChecklist)==null||T.call(w,Q.checklist))}catch{!g&&!((te=Nt.current)!=null&&te.length)&&et(en)}finally{g||Ne(!1)}})(),()=>{g=!0}},[s,t,k,W]),r.useEffect(()=>{if(!s||!d)return;let g=!1;return Lt(!0),ke(null),(async()=>{try{const w=await Ie(t);g||Ot(w)}catch{g||ke(ra)}finally{g||Lt(!1)}})(),()=>{g=!0}},[s,t,d,Ie]);const Gs=r.useCallback(()=>{We(null),dt(null),He(null),fe(!1)},[]),zs=r.useCallback(g=>{if(g.misRecordUrl){window.open(g.misRecordUrl,"_blank","noopener,noreferrer");return}We(g),dt(null),He(null),fe(!0),(async()=>{try{const w=await jt(t,g.id);dt(w)}catch{He(ia)}finally{fe(!1)}})()},[jt,t]);r.useEffect(()=>{if(!s||!v)return;let g=!1;return Ut(w=>w||ye===null),Qe(null),(async()=>{try{const w=await Ke(t);g||Mt(w)}catch{g||Qe(is)}finally{g||Ut(!1)}})(),()=>{g=!0}},[s,t,v,Ke]),r.useEffect(()=>{if(!s||!k)return;let g=!1;const w={id:`user-brief-${Date.now()}`,author:pe.user,text:Ur(k,Un.current)};return(async()=>{const T=await X.current.start(k);g||(Y([be(X.current.openingMessage()),be(w),be(T.message)]),Xt(T.checklist),ue(T.phase??F.running),ze(),xe())})(),()=>{g=!0}},[s,k,t,Xt,ze,xe]);const pn=O??t,Zt=ye==null?void 0:ye.chatSessions,Bn=Zt!=null&&Zt.length?Zt.reduce((g,w)=>Date.parse(w.timestamp)<Date.parse(g.timestamp)?w:g).sessionId:void 0,_n=r.useCallback(()=>{_("chat"),E(!1),L!==pn&&(ce(pn),Y([]),De(g=>g+1))},[L,pn]),qs=r.useCallback(g=>{if(g===Bn){_n();return}ce(g),E(!0),_("chat"),Y([]),De(w=>w+1)},[Bn,_n]),Vs=r.useCallback(async()=>{var g;ee(null),_t(!0);try{await X.current.pause(),yt.current+=1,ue(F.paused),xt(!0);const w={...at.current,status:C.paused};at.current=w,(g=ge.current)==null||g.call(ge,w)}catch{ee(la)}finally{_t(!1)}},[]),Ks=r.useCallback(async()=>{var w;ee(null),Gt(!0);let g=!1;try{await X.current.resume(),g=!0,yt.current+=1,ue(F.running),xt(!1);const T={...at.current,status:C["generating-a-response"]};at.current=T,(w=ge.current)==null||w.call(ge,T),kt(!0);const te={id:`wake-${Date.now()}`,author:pe.user,text:Gn};Y(le=>[...le,be(te)]);const Q=await X.current.sendMessage(Gn);Y(le=>[...le,be(Q.message)]),mn(Q)}catch{ee(g?wa:xa)}finally{Gt(!1),kt(!1)}},[mn]),Ys=r.useCallback(async()=>{ee(null),st(null),qt(!0);try{await Ye(t),ft(!1),H==null||H(),a()}catch{st(Cn),ee(Cn)}finally{qt(!1)}},[t,Ye,H,a]),Js=r.useCallback(async()=>{ee(null),Be(null),Kt(!0);try{await Oe(t),Pn(null),ue(F.paused),xt(!0),_("chat"),vt(!1),z==null||z()}catch{Be(bn),ee(bn)}finally{Kt(!1)}},[t,Oe,z]),Ws=r.useCallback(async()=>{ee(null),ve(null),b(!0);try{await Le(t),se(!1),ie==null||ie(),a()}catch(g){ve(js(g))}finally{b(!1)}},[t,Le,ie,a]),Xs=r.useCallback(g=>{const w=g.trim(),T=Pe;if(we(null),!w){Me(te=>te+1);return}w!==T&&(re(w),(async()=>{try{await Rt(t,w)}catch{re(T),Me(te=>te+1),we(ka)}})())},[Pe,t,Rt]),Zs=r.useCallback(()=>{if(!I||tt||Ae)return;const g=++rt.current;mt(!0),pt(null),(async()=>{try{const w=await _e(t);if(rt.current!==g)return;gt(w),nt(!0)}catch{rt.current===g&&pt(aa)}finally{rt.current===g&&mt(!1)}})()},[I,tt,Ae,_e,t]),Qs=$e;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:q?n.jsx("span",{className:"agent-workspace__header-name",children:Pe}):n.jsx(c.EditableText,{className:"agent-workspace__header-name",text:Pe,onEditSave:Xs},Tt)}),n.jsx("span",{className:V("agent-workspace__phase",`agent-workspace__phase--${he}`),children:Sa[he]}),q?n.jsx("span",{className:"agent-workspace__phase agent-workspace__phase--archived",children:"Archived"}):null,Ue&&n.jsx("p",{className:"agent-workspace__error agent-workspace__name-error",role:"alert",children:Ue})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(c.Button,{variant:Jt?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!Jt,onClick:()=>Ds(g=>!g),children:"Checklist"}),n.jsx(c.Button,{variant:Wt?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Wt,onClick:()=>Hs(g=>!g),children:"Resources"}),n.jsx(c.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),n.jsxs(c.Modal.Body,{className:V("agent-workspace__body",{"agent-workspace__body--no-checklist":Jt,"agent-workspace__body--no-resources":Wt}),children:[n.jsxs("section",{className:V("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!v&&(q||K==="timeline")}),"aria-label":"Agent",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(c.Heading,{level:4,children:"Agent"}),o&&!wt&&!q&&he===F.running&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Pause",disabled:Bt,onClick:()=>void Vs(),children:Bt?"Pausing…":"Pause agent"}),x&&!wt&&!q&&he===F.paused&&Ms&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"iteration-ccw",iconLeftScreenReaderText:"Resume",disabled:Ft,onClick:()=>void Ks(),children:Ft?"Resuming…":"Resume agent"}),j&&!wt&&!q&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>{st(null),ee(null),ft(!0)},children:"Archive agent"}),y&&!wt&&q&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary",size:"S",onClick:()=>{Be(null),ee(null),vt(!0)},children:"Unarchive agent"}),I&&q&&n.jsx(c.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",onClick:()=>{ve(null),ee(null),se(!0)},children:"Delete agent"})]}),Ce&&n.jsx("p",{className:"agent-workspace__error agent-workspace__lifecycle-error",role:"alert",children:Ce}),v&&!q&&n.jsxs(c.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(c.Tabs.Item,{active:K==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>_("chat")},children:"Chat"}),n.jsx(c.Tabs.Item,{active:K==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>_("timeline")},children:"Timeline"})]}),v&&!q&&K==="chat"&&R&&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:_n,children:"Back to main chat"})}),v&&(q||K==="timeline")&&n.jsx(ar,{timeline:ye,isLoading:Ze,error:Dt,onOpenChatSession:q?void 0:qs}),!q&&n.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!v&&K!=="chat",children:n.jsx(Fa,{connector:D,phase:he,chatHistory:ln,chatSessionKey:ot,readOnly:wt,enableUpload:P,onTurn:mn,onAwaitingChange:kt})}),q&&!v&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Chat is not available for archived agents."})]}),!Jt&&n.jsx(Ga,{checklist:Qs,isLoading:Ht,error:$t,phase:he,adminMode:I,context:on,contextLoaded:tt,contextLoading:Ae,contextError:cn,onContextSelect:Zs},t),!Wt&&n.jsx(Va,{resources:It,isLoading:Je,error:ct,onOpenResource:zs}),n.jsx(za,{resource:ut,html:Pt,isLoading:Xe,error:ht,onClose:Gs})]})]}),n.jsx(ds,{open:un,isInProgress:he===F.running||he===F.paused&&!ms($e??void 0),isArchiving:zt,error:dn,onCancel:()=>{zt||(st(null),ft(!1))},onConfirm:()=>{Ys()}}),n.jsx(gs,{open:hn,isUnarchiving:Vt,error:Yt,onCancel:()=>{Vt||(Be(null),vt(!1))},onConfirm:()=>{Js()}}),n.jsx(hs,{open:S,isDeleting:u,error:Fe,onCancel:()=>{u||(ve(null),se(!1))},onConfirm:()=>{Ws()}})]})},Hr=["Setting up the agent","Creating the agent's memory","Thinking about the checklist","Making sure I have all of the information I need","Scheduling any tasks","Check to see if I need to create any resources","Gathering everything for a strong start","Double-checking the setup","Wiring up the first steps","Looking over the brief one more time","Getting the workspace ready","Lining up what needs to happen next","Making sure nothing important is missing","Putting the finishing touches on setup","Almost ready to get going","Preparing to take it from here"],$r="Unable to load agent definitions. Please try again.",Br="Unable to start the agent.",es="Loading agents…",Fr="Which agent would you like to start?",Gr="Select an agent",zr="What do you want to call this agent?",qr="Science Museum Trip, or Governor's Report",Vr="Make this something you can easily recognise that relates to the task the agent is carrying out. You may want to add details like a data, location or a person's name.",ts="new-agent-invocation-name-hint",Kr=5e3,Yr=e=>`Start the ${e}`,Jr=e=>{const t=[...e];for(let s=t.length-1;s>0;s-=1){const a=Math.floor(Math.random()*(s+1)),i=t[s];t[s]=t[a],t[a]=i}return t},Nn=(e,t)=>{const s=t==null?void 0:t.trim();if(s)return e.find(a=>a.ref===s)??e.find(a=>a.display_name===s)},Wr=(e,t)=>`${e.replace(/\/+$/,"")}/${encodeURIComponent(t)}`,Os=({open:e,onClose:t,onStart:s,agentDefinitions:a,definitionsState:i="idle",definitionsError:h=null,onRetryDefinitions:l,embedded:m=!1,preselectAgent:d})=>{const[v,f]=r.useState("select"),[N,o]=r.useState(void 0),[x,j]=r.useState(""),[y,O]=r.useState(!1),[P,I]=r.useState(null),[k,p]=r.useState(null),A=r.useRef([]),G=r.useRef(0),ae=[...a].sort((_,R)=>_.display_name.localeCompare(R.display_name)).map(_=>({value:_.ref,label:_.display_name}));r.useEffect(()=>{e&&(f("select"),j(""),O(!1),I(null),p(null),o(Nn(a,d)))},[e,d]),r.useEffect(()=>{if(!e)return;const _=Nn(a,d);_&&o(R=>R??_)},[e,d,a]),r.useEffect(()=>{if(!y){p(null),A.current=[],G.current=0;return}const _=Jr(Hr);A.current=_,G.current=0,p(_[0]??null);const R=window.setInterval(()=>{const E=A.current;E.length!==0&&(G.current=(G.current+1)%E.length,p(E[G.current]??null))},Kr);return()=>{window.clearInterval(R)}},[y]);const ne=Nn(a,d),Z=ne!==void 0,M=N??ne,H=M!==void 0,z=M!==void 0&&x.trim().length>0,ie=r.useCallback(_=>{const R=a.find(E=>E.ref===_[0]);R&&o(R)},[a]),oe=r.useCallback(()=>{!H||y||(I(null),f("details"))},[H,y]),L=r.useCallback(()=>{y||(I(null),f("select"))},[y]),ce=r.useCallback(async()=>{const _=N??ne;if(!(!_||!z||y)){O(!0),I(null);try{await s({definition:_,invocationName:x.trim()})}catch(R){I(R instanceof Error?R.message:Br)}finally{O(!1)}}},[z,N,x,y,s,ne]);if(i==="idle"&&a.length===0||!e)return null;let K;return i==="loading"?K=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:es}),n.jsx("p",{className:"new-agent__state-message",children:es})]}):i==="error"?K=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:h??$r}),l?n.jsx(c.Button,{variant:"secondary",size:"S",onClick:l,children:"Try again"}):null]}):K=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:_=>{if(_.preventDefault(),v==="select"){oe();return}z&&!y&&ce()},children:[n.jsxs("div",{className:V("new-agent__steps",{"new-agent__steps--details":v==="details"}),children:[n.jsx("div",{className:V("new-agent__step","new-agent__step--select",{"new-agent__step--active":v==="select"}),"aria-hidden":v!=="select",children:n.jsxs("div",{className:"new-agent__type-field",children:[Z&&M?n.jsx("p",{className:"new-agent__preselected-title",children:Yr(M.display_name)}):n.jsxs(n.Fragment,{children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:Fr}),n.jsx(c.SelectDropdown,{id:"new-agent-type",placeholder:Gr,options:ae,selectedValues:M?[M.ref]:[],onSelectionChange:ie,"aria-describedby":M!=null&&M.description?"new-agent-type-description":void 0})]}),M!=null&&M.description?n.jsxs("div",{className:"new-agent__description",children:[n.jsx("p",{className:"new-agent__description-title",children:"This agent..."}),n.jsx("p",{className:"new-agent__field-hint",id:"new-agent-type-description",children:M.description})]}):null]})}),n.jsx("div",{className:V("new-agent__step","new-agent__step--details",{"new-agent__step--active":v==="details"}),"aria-hidden":v!=="details",children:n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:zr}),n.jsx("p",{className:"new-agent__field-hint",id:ts,children:Vr}),n.jsx(c.TextInput,{id:"new-agent-invocation-name",value:x,placeholder:qr,"aria-describedby":ts,onChange:_=>j(_.target.value),tabIndex:v==="details"?void 0:-1})]})})]}),P?n.jsx("p",{className:"new-agent__error",role:"alert",children:P}):null,n.jsxs("div",{className:V("new-agent__actions",{"new-agent__actions--split":v==="details"}),children:[v==="details"?n.jsx(c.Button,{type:"button",variant:"secondary",onClick:L,disabled:y,children:"Back"}):null,v==="select"?n.jsx(c.Button,{type:"submit",variant:"primary",disabled:!H,children:"Continue"}):n.jsx(c.Button,{type:"submit",variant:"primary",className:V("new-agent__start-button",{"new-agent__start-button--starting":y}),disabled:!z||y,iconLeftName:y?"loader":"sparkles",iconLeftScreenReaderText:y?"Starting":void 0,children:y?k??"Starting…":"Start"})]})]}),m?n.jsx("div",{className:V("new-agent","new-agent--embedded"),children:n.jsx("div",{className:"new-agent__body",children:K})}):n.jsxs(c.Modal,{open:e,closeHandler:t,className:"new-agent",children:[n.jsx(c.Modal.Header,{children:n.jsx(c.Modal.Title,{children:"Start an agent"})}),n.jsx(c.Modal.Body,{className:"new-agent__body",children:K})]})},An=e=>{window.location.assign(e)},Xr=({open:e,authToken:t,headers:s,agentDefinitionsUrl:a,agentsUrl:i,closeUrl:h,successUrl:l,viewAgentUrlPrefix:m,preselectAgent:d,onClose:v,onStart:f,embedded:N=!1})=>{const o=JSON.stringify(s??{}),x=r.useMemo(()=>new rn({token:t,headers:s,urls:{agentDefinitions:a,agents:i}}),[t,a,i,o]),[j,y]=r.useState([]),[O,P]=r.useState("loading"),[I,k]=r.useState(null),[p,A]=r.useState(0);r.useEffect(()=>{if(!e)return;let Z=!1;return P("loading"),k(null),(async()=>{try{const M=await x.listAgentDefinitions();if(Z)return;y(M.map(In)),P("idle")}catch(M){if(Z)return;y([]),k(Es(M)),P("error")}})(),()=>{Z=!0}},[x,e,p]);const G=r.useCallback(()=>{v==null||v(),h&&An(h)},[h,v]),ae=r.useCallback(async Z=>{const M=await x.createAgent(Z.definition.ref,{invocationName:Z.invocationName}),H={id:M.id};f==null||f(Z,H);const z=m==null?void 0:m.trim();if(z){An(Wr(z,M.id));return}l&&An(l)},[x,f,l,m]),ne=r.useCallback(()=>{A(Z=>Z+1)},[]);return n.jsx(Os,{open:e,onClose:G,onStart:ae,agentDefinitions:j,definitionsState:O,definitionsError:I,onRetryDefinitions:ne,embedded:N,preselectAgent:d})},Zr=e=>"agentDefinitionsUrl"in e,Ls=e=>Zr(e)?n.jsx(Xr,{...e}):n.jsx(Os,{...e}),Qr=({open:e,onClose:t})=>{const s=r.useId(),a=r.useId();return n.jsxs(c.Modal,{open:e,closeHandler:t,className:"archive-agent-confirm",children:[n.jsx(c.Modal.Header,{className:"archive-agent-confirm__header",children:n.jsx(c.Modal.Title,{id:s,children:Aa})}),n.jsxs(c.Modal.Body,{className:"archive-agent-confirm__body",children:[n.jsx("div",{role:"alertdialog","aria-labelledby":s,"aria-describedby":a,children:n.jsx("p",{id:a,className:"archive-agent-confirm__lead",children:Ca})}),n.jsx("div",{className:"archive-agent-confirm__actions",children:n.jsx(c.Button,{variant:"secondary",size:"S",onClick:t,children:"Close"})})]})]})},ei=3,ti=56,ni=e=>e.archivedAt?"archived":e.status===C.paused?"paused":null,si=e=>{if(e==="archived")return ta;if(e==="paused")return lt[C.paused].statusIcon},ai=({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:V({"agent-view__progress-icon--spinning":a.spin}),screenReaderText:s})}):n.jsx("span",{className:V("agent-view__dot",{[`agent-view__dot--${e.dotModifier}`]:e.dotModifier}),children:n.jsx(c.Dot,{colour:e.dotColour,label:s})})},Ps=({agent:e,agentName:t,column:s,isExpanded:a,isLoading:i,checklist:h,error:l,canArchive:m,canUnarchive:d=!1,canDelete:v=!1,onToggle:f,onViewAgent:N,onArchive:o,onUnarchive:x,onDelete:j})=>{const{id:y,invocation_name:O}=e,P=`agent-card-${y}-header`,I=`agent-card-${y}-progress`,k=ni(e),p=si(k);return n.jsx("li",{className:V("agent-view__card",{"agent-view__card--expanded":a,"agent-view__card--paused":k==="paused","agent-view__card--archived":k==="archived","agent-view__card--view-only":!e.usable}),children:n.jsxs(c.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":I,"aria-label":O,id:P,onClick:()=>f(y),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(ai,{column:s,overlayIcon:p}),n.jsx("span",{className:"agent-view__card-invocation-name",children:O}),n.jsx("span",{className:"agent-view__card-agent-name",children:t}),k==="paused"?n.jsx("span",{className:"agent-view__card-state-pill",children:"Paused"}):null,k==="archived"?n.jsx("span",{className:"agent-view__card-state-pill",children:"Archived"}):null,e.usable?null:n.jsx("span",{className:"agent-view__card-state-pill",children:"View only"}),n.jsx(c.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&n.jsxs("div",{id:I,"aria-labelledby":P,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:it}),n.jsx("span",{children:it})]}),!i&&l&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:l}),!i&&!l&&h!==null&&n.jsx(Ha,{checklist:h}),!i&&!l&&h===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:it}),n.jsx("span",{children:it})]})]}),n.jsxs("div",{className:V("agent-view__card-actions",{"agent-view__card-actions--standalone":!a}),children:[a&&m?n.jsx(c.Button,{variant:"secondary",size:"S",iconLeftName:"archive",iconLeftScreenReaderText:"Archive",onClick:()=>o==null?void 0:o(e),children:"Archive"}):a&&d?n.jsx(c.Button,{variant:"secondary",size:"S",onClick:()=>x==null?void 0:x(e),children:"Unarchive"}):a&&v?n.jsx(c.Button,{variant:"secondary-destructive",size:"S",onClick:()=>j==null?void 0:j(e),children:"Delete"}):n.jsx("span",{}),a&&d&&v?n.jsx(c.Button,{variant:"secondary-destructive",size:"S",onClick:()=>j==null?void 0:j(e),children:"Delete"}):null,n.jsx(c.Button,{variant:"secondary",size:"S",onClick:()=>N==null?void 0:N(e),children:"View agent"})]})]})})},ri=()=>n.jsx("ul",{className:"agent-view__card-list","aria-hidden":"true",children:Array.from({length:ei},(e,t)=>n.jsx("li",{className:"agent-view__card agent-view__card--skeleton",children:n.jsx(c.Skeleton,{className:"agent-view__card-skeleton",width:"100%",height:ti})},t))}),ns=({column:e,agents:t,expandedAgentId:s,loadingAgentId:a,checklistByInvocationId:i,errorByAgentId:h,definitionNameByRef:l,onToggleAgent:m,onViewAgent:d,onArchiveAgent:v,canArchive:f,isLoading:N=!1})=>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:N?0:t.length})]}),N?n.jsx(ri,{}):n.jsx("ul",{className:"agent-view__card-list",children:t.map(o=>n.jsx(Ps,{agent:o,agentName:tn(o,l),column:e,isExpanded:s===o.id,isLoading:a===o.id,checklist:i[o.invocation_id]??null,error:h[o.id]??null,canArchive:f&&!o.archivedAt&&o.usable,onToggle:m,onViewAgent:d,onArchive:v},o.id))})]}),tn=(e,t)=>t.get(e.agent_definition_ref)??e.agent_definition_ref.replace(/_/g," "),ii=({jwt:e,headers:t,agentDefinitionsUrl:s,agentsUrl:a,agentUrl:i,agentChecklistUrl:h,agentResourcesUrl:l,agentTimelineUrl:m,agentChatUrl:d,agentConversationUrl:v,pauseAgentUrl:f,resumeAgentUrl:N,archiveAgentUrl:o,unarchiveAgentUrl:x,enableUpload:j,adminMode:y=!1,showHeader:O=!1,institutions:P,usePusherToRepoll:I=!1,pusherChannelPrefix:k=Tn,pusherKey:p,pusherCluster:A,subscribeToPusher:G,selectedAgent:ae,scope:ne=os,preselectAgent:Z})=>{var Be;const M=r.useMemo(()=>({agentDefinitions:s,agents:a,agent:i,agentChecklist:h,...l?{agentResources:l}:{},...m?{agentTimeline:m}:{},agentChat:d,agentConversation:v,...o?{archiveAgent:o}:{},...x?{unarchiveAgent:x}:{}}),[s,a,i,h,l,m,d,v,o,x]),[H,z]=r.useState(null),ie=H?(Be=P==null?void 0:P.find(u=>u.applicationId===H.application_id))==null?void 0:Be.applicationUrl:void 0,oe=r.useMemo(()=>{const u={...t??{}};return ie?u[qe.arborApplicationUrl]=ie:delete u[qe.arborApplicationUrl],u},[t,ie]),{agents:L,agentDefinitions:ce,loadState:K,loadError:_,reload:R,refresh:E,fetchAgentChecklist:D,createAgent:$,archiveAgent:W,unarchiveAgent:_e,deleteAgent:Ie,removeAgent:jt,replaceAgent:Ke}=Rs({jwt:e,headers:oe,urls:M,scope:ne}),[Rt,Ye]=r.useState(!1),[Oe,Le]=r.useState(null),[X,Pe]=r.useState(null),[re,Tt]=r.useState({}),[Me,Ue]=r.useState({}),[we,he]=r.useState([]),[ue,ln]=r.useState([]),[Y,ot]=r.useState(null),[De,It]=r.useState(!1),[Ot,Je]=r.useState(null),[Lt,ct]=r.useState(!1),[ke,ut]=r.useState(null),[We,Pt]=r.useState(!1),[dt,Xe]=r.useState(null),[fe,ht]=r.useState(null),[He,ye]=r.useState(!1),[Mt,Ze]=r.useState(null),[Ut,Dt]=r.useState(!1),Qe=r.useRef(!1);r.useEffect(()=>{z(u=>{if(!u)return null;const b=L.find(S=>S.id===u.id||S.invocation_id===u.invocation_id||S.invocation_id===u.id);return b||(K==="loading"?u:null)})},[L,K]),r.useEffect(()=>{if(!ae||Qe.current||K==="loading")return;Qe.current=!0;const u=L.find(({id:b})=>b===ae);if(u){z(u);return}Dt(!0)},[ae,L,K]);const $e=r.useMemo(()=>{const u=new Set(L.map(S=>S.application_id)),b=new Map((P??[]).map(S=>[S.applicationId,S.name]));return[...u].sort((S,se)=>(b.get(S)??S).localeCompare(b.get(se)??se)).map(S=>({value:S,label:b.get(S)??S}))},[L,P]),de=r.useMemo(()=>new Map(ce.map(u=>[u.ref,u.display_name])),[ce]),Ht=r.useMemo(()=>[...new Set(L.map(b=>tn(b,de)))].sort((b,S)=>b.localeCompare(S)).map(b=>({value:b,label:b})),[L,de]),Ne=r.useMemo(()=>L.filter(u=>!(we.length>0&&!we.includes(u.application_id)||ue.length>0&&!ue.includes(tn(u,de)))),[L,de,ue,we]),$t=$e.length>1,et=Ht.length>1,on=$t||et;r.useEffect(()=>{const u=window.setInterval(()=>{E()},6e4);return()=>{window.clearInterval(u)}},[E]),r.useEffect(()=>{if(L.length===0)return;let u=!1;return(async()=>{const b=await Promise.allSettled(L.map(async S=>{const se=await D(S.invocation_id);return{agentId:S.id,invocationId:S.invocation_id,checklist:se.checklist}}));u||(Tt(S=>{const se={...S};let Fe=!1;for(const ve of b){if(ve.status!=="fulfilled")continue;const{invocationId:Ce,checklist:ee}=ve.value;JSON.stringify(S[Ce])!==JSON.stringify(ee)&&(se[Ce]=ee,Fe=!0)}return Fe?se:S}),Ue(S=>{const se={...S};let Fe=!1;return b.forEach((ve,Ce)=>{ve.status==="rejected"&&se[L[Ce].id]!==en&&(se[L[Ce].id]=en,Fe=!0)}),Fe?se:S}))})(),()=>{u=!0}},[L,D]);const gt=r.useCallback(async u=>{if(!re[u.invocation_id]){Pe(u.id),Ue(b=>{const S={...b};return delete S[u.id],S});try{const b=await D(u.invocation_id);Tt(S=>({...S,[u.invocation_id]:b.checklist}))}catch{Ue(b=>({...b,[u.id]:en}))}finally{Pe(b=>b===u.id?null:b)}}},[D,re]),tt=r.useCallback(u=>{if(Oe===u){Le(null);return}const b=L.find(({id:S})=>S===u);b&&(Le(u),gt(b))},[L,Oe,gt]),nt=r.useMemo(()=>Ne.filter(u=>!!u.archivedAt),[Ne]),Ae=r.useMemo(()=>Ne.filter(u=>!u.archivedAt),[Ne]),mt=r.useMemo(()=>{const u={};for(const b of Ae){const S=xn(b,re[b.invocation_id]);(u[S]??(u[S]=[])).push(b)}return u},[Ae,re]),cn=K==="loading"&&L.length===0,pt=Ae.length>0&&Ae.some(u=>re[u.invocation_id]===void 0&&Me[u.id]===void 0),Bt=cn||pt,_t=r.useCallback(u=>{z(u)},[]),Ft=r.useCallback(u=>{Je(null),ot(u)},[]),Gt=r.useCallback(()=>{De||(Je(null),ot(null))},[De]),zt=r.useCallback(async()=>{if(Y){It(!0),Je(null),Ue(u=>{const b={...u};return delete b[Y.id],b});try{await W(Y.invocation_id),z(u=>(u==null?void 0:u.id)===Y.id?null:u),Le(Y.id),ct(!0),ot(null)}catch{Je(Cn)}finally{It(!1)}}},[Y,W]),qt=r.useCallback(u=>{Xe(null),ut(u)},[]),un=r.useCallback(()=>{We||(Xe(null),ut(null))},[We]),ft=r.useCallback(async()=>{if(ke){Pt(!0),Xe(null);try{await _e(ke.invocation_id),ut(null)}catch{Xe(bn)}finally{Pt(!1)}}},[ke,_e]),dn=Y?xn(Y,re[Y.invocation_id])!==C.complete:!1,st=r.useCallback(async u=>{const b=await $(u);z(b),Ye(!1)},[$]),Vt=r.useCallback(u=>{Ze(null),ht(u)},[]),Kt=r.useCallback(()=>{He||(Ze(null),ht(null))},[He]),hn=r.useCallback(async()=>{if(fe){ye(!0),Ze(null);try{await Ie(fe.invocation_id),z(u=>(u==null?void 0:u.id)===fe.id?null:u),ht(null)}catch(u){Ze(js(u))}finally{ye(!1)}}},[fe,Ie]),vt=r.useCallback(()=>{z(null)},[]),Yt={expandedAgentId:Oe,loadingAgentId:X,checklistByInvocationId:re,errorByAgentId:Me,definitionNameByRef:de,onToggleAgent:tt,onViewAgent:_t,onArchiveAgent:Ft,canArchive:!!o};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[O&&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:()=>Ye(!0),children:"Start an agent"})]}),L.length>0&&on&&n.jsxs("div",{className:"agent-view__filters",children:[$t&&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:$e,value:we,onValueChange:he,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),et&&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:Ht,value:ue,onValueChange:ln,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),K==="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:_??ls}),n.jsx(c.Button,{variant:"secondary",size:"S",onClick:R,children:"Try again"})]}):Bt?n.jsx("div",{className:"agent-view__board","aria-busy":"true","aria-live":"polite",children:Fn.map(u=>n.jsx(ns,{column:lt[u],agents:[],isLoading:!0,...Yt},u))}):L.length===0?n.jsx(Ia,{}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"agent-view__board",children:Fn.map(u=>n.jsx(ns,{column:lt[u],agents:mt[u]??[],...Yt},u))}),nt.length>0?n.jsxs("details",{className:"agent-view__archived",open:Lt,onToggle:u=>{ct(u.currentTarget.open)},children:[n.jsxs("summary",{className:"agent-view__archived-summary",children:[n.jsx(c.Heading,{level:4,children:"Archived"}),n.jsx("span",{className:"agent-view__column-count",children:nt.length})]}),n.jsx("ul",{className:"agent-view__card-list agent-view__archived-list",children:nt.map(u=>n.jsx(Ps,{agent:u,agentName:tn(u,de),column:lt[xn(u,re[u.invocation_id])],isExpanded:Oe===u.id,isLoading:X===u.id,checklist:re[u.invocation_id]??null,error:Me[u.id]??null,canArchive:!1,canUnarchive:!!x&&u.usable,canDelete:y&&u.usable,onToggle:tt,onViewAgent:_t,onUnarchive:qt,onDelete:Vt},u.id))})]}):null]}),H&&n.jsx(Is,{agent:H,invocationId:H.invocation_id,open:!0,jwt:e,headers:oe,agentUrl:i,agentChecklistUrl:h,agentResourcesUrl:l,agentTimelineUrl:m,agentChatUrl:d,agentConversationUrl:v,pauseAgentUrl:f,resumeAgentUrl:N,archiveAgentUrl:o,unarchiveAgentUrl:x,enableUpload:j,adminMode:y,initialChecklist:re[H.invocation_id]??null,usePusherToRepoll:I,pusherChannelPrefix:k,pusherKey:p,pusherCluster:A,subscribeToPusher:G,onClose:vt,onAgentUpdated:Ke,onArchived:()=>{Le(H.id),ct(!0),E()},onUnarchived:()=>{E()},onDeleted:()=>{jt(H.invocation_id)}},H.id||H.invocation_id),n.jsx(ds,{open:!!Y,isInProgress:dn,isArchiving:De,error:Ot,onCancel:Gt,onConfirm:()=>{zt()}}),n.jsx(gs,{open:!!ke,isUnarchiving:We,error:dt,onCancel:un,onConfirm:()=>{ft()}}),n.jsx(hs,{open:!!fe,isDeleting:He,error:Mt,onCancel:Kt,onConfirm:()=>{hn()}}),n.jsx(Qr,{open:Ut,onClose:()=>Dt(!1)}),n.jsx(Ls,{open:Rt,onClose:()=>Ye(!1),onStart:st,agentDefinitions:ce,preselectAgent:Z})]})},li=(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,usable:!0,status:C["generating-a-response"],archivedAt:null,context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=ii;exports.AgentServiceClient=rn;exports.AgentServiceError=Ve;exports.AgentView=Is;exports.DEFAULT_PUSHER_CHANNEL_PREFIX=Tn;exports.HttpChatConnector=Ss;exports.MESSAGE_TYPE_REPOLL=En;exports.NewAgentModal=Ls;exports.PUSHER_AGENT_MESSAGE_EVENT=fs;exports.REPOLL_TARGET=je;exports.buildAgentFromDefinition=li;exports.buildAgentPusherChannel=vs;exports.createHttpChatConnectorFactory=Ln;exports.formatUserFileChatCardText=Nr;exports.mapApiAgent=Re;exports.mapApiAgentDefinition=In;exports.mapApiAgentStatus=ks;exports.mapApiAgentTimelineResponse=Cs;exports.mapApiChecklistEndpointResponse=an;exports.mapApiChecklistItem=On;exports.mapApiChecklistResponse=kr;exports.mapApiChecklistStatus=ys;exports.mapApiConversationMessages=bs;exports.mapApiOpeningMessage=Et;exports.mapApiResource=Ns;exports.mapApiResourcesEndpointResponse=As;exports.mapApiTripOption=fr;exports.parseConversationContentCaption=yr;exports.parseRepollMessages=xs;exports.useAgentService=Rs;exports.useAgentWorkspace=Ts;exports.useSubscribeToPusher=ws;
package/dist/index.d.ts CHANGED
@@ -64,7 +64,7 @@ export declare type AgentDefinition = {
64
64
  description: string;
65
65
  };
66
66
 
67
- 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, selectedAgent: selectedAgentId, scope, }: AgentMonitorKanbanProps) => JSX_2.Element;
67
+ 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, selectedAgent: selectedAgentId, scope, preselectAgent, }: AgentMonitorKanbanProps) => JSX_2.Element;
68
68
 
69
69
  export declare type AgentMonitorKanbanProps = {
70
70
  jwt?: string;
@@ -92,6 +92,7 @@ export declare type AgentMonitorKanbanProps = {
92
92
  subscribeToPusher?: SubscribeToPusher;
93
93
  selectedAgent?: string;
94
94
  scope?: AgentScope;
95
+ preselectAgent?: string;
95
96
  };
96
97
 
97
98
  export declare type AgentResource = {
@@ -637,7 +638,10 @@ export declare type NewAgentModalControlledProps = {
637
638
  /** When true, render inline (no design-system Modal portal). */
638
639
  embedded?: boolean;
639
640
  /**
640
- * Pre-select a definition by `ref` (API `name` today). Temporary until API `code`.
641
+ * Pre-select a definition by `ref` (API `name` today; dropdown value), then
642
+ * `display_name` if no `ref` match. Temporary until API `code`.
643
+ * When matched, the select step hides the dropdown and shows
644
+ * `Start the {display_name}` instead.
641
645
  */
642
646
  preselectAgent?: string;
643
647
  };
@@ -664,8 +668,10 @@ export declare type NewAgentModalStandaloneProps = {
664
668
  */
665
669
  viewAgentUrlPrefix?: string;
666
670
  /**
667
- * Pre-select a definition by `ref` (API `name` today). Temporary until API `code`.
668
- * All definitions remain available; the matching one is selected on open.
671
+ * Pre-select a definition by `ref` (API `name` today; dropdown value), then
672
+ * `display_name` if no `ref` match. Temporary until API `code`.
673
+ * When matched, the select step hides the dropdown and shows
674
+ * `Start the {display_name}` instead.
669
675
  */
670
676
  preselectAgent?: string;
671
677
  /** Called when the modal is closed, before navigating to `closeUrl`. */