@arbor-education/agent-view-frontend 0.5.2 → 0.6.0

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