@arbor-education/agent-view-frontend 0.4.5 → 0.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +3 -3
- package/dist/index.js +589 -580
- package/dist/style.css +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),o=require("react"),z=require("classnames"),d=require("@arbor-education/design-system.components"),le=require("@arbor-education/ask-arbor-chat-panel"),C={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},$={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},U={briefing:"briefing",running:"running",stopped:"stopped",complete:"complete"},X={agent:"agent",user:"user",system:"system"},re={MIS_RECORD:"MIS_RECORD",FILE:"FILE",WORKFLOW:"WORKFLOW",LINK:"LINK"},Xe={cancelled:"cancelled",archived:"archived"},$e={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},J={[$.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)"}},Ee={[C["generating-a-response"]]:{status:C["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:J["generating-a-response"].icon,color:J["generating-a-response"].color}},[C.hitl]:{status:C.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:J.hitl.icon,color:J.hitl.color}},[C.complete]:{status:C.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:J.complete.icon,color:J.complete.color}},[C.failed]:{status:C.failed,title:"Failed",dotColour:"salmon",statusIcon:{name:J.failed.icon,color:J.failed.color}}},Rt=[C["generating-a-response"],C.hitl],Ot=[C.complete,C.failed],Lt="m4",Mt="1",ot="msg-opening",be="Unable to load agent tasks. Please try again.",Pt="Unable to load the resources for this agent",it="Unable to load the timeline for this agent",Dt="Something went wrong. Please try again.",ct="Unable to load agents. Please try again.",oe="Loading tasks…",Qe="Loading agents…",Ut="Task",$t={[U.briefing]:"Briefing",[U.running]:"Working",[U.stopped]:"Stopped",[U.complete]:"Complete"},Ht=[C["generating-a-response"],C.hitl,C.complete,C.failed],Bt={[C["generating-a-response"]]:"Agents currently working on tasks for you.",[C.hitl]:"Agents that need your input before they can continue.",[C.complete]:"Agents that have finished their work.",[C.failed]:"Agents that failed or were stopped."},Ft=()=>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)"})]}),zt=({status:t})=>{const e=Ee[t];return e.statusIcon?n.jsx(d.Icon,{name:e.statusIcon.name,size:16,color:e.statusIcon.color,screenReaderText:e.title}):n.jsx(d.Dot,{colour:e.dotColour,label:e.title})},Gt=()=>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(d.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:Ht.map(t=>{const e=Ee[t];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(zt,{status:t})}),n.jsxs("span",{className:"agent-view__empty-column-text",children:[n.jsx("span",{className:"agent-view__empty-column-title",children:e.title}),n.jsx("span",{className:"agent-view__empty-column-description",children:Bt[t]})]})]},t)})}),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(Ft,{})})]}),qt=(t,e)=>({...t,...e.length>0?{children:e}:{}}),lt=t=>{const e=[],s=[];for(const a of t){const r=a.children?lt(a.children):{needsInput:[],tasks:[]};if(e.push(...r.needsInput),a.status===$.hitl){e.push({...a,children:void 0});continue}s.push(qt(a,r.tasks))}return{needsInput:e,tasks:s}},Kt=t=>t.map((e,s)=>({item:e,index:s})).sort((e,s)=>{const a=e.item.status===$.hitl,r=s.item.status===$.hitl;return a!==r?a?-1:1:e.index-s.index}).map(({item:e})=>e),He=2,Wt=t=>{if(!t)return{canScrollUp:!1,canScrollDown:!1};const e=t.scrollHeight-t.clientHeight;return e<=He?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:t.scrollTop>He,canScrollDown:t.scrollTop<e-He}},Jt=(t,e)=>{if(!t||!e)return null;const s=t.getBoundingClientRect(),a=e.getBoundingClientRect();return{top:a.top-s.top,left:a.left-s.left,width:a.width,height:a.height}},Ie=({children:t,className:e,contentClassName:s,scrollSelector:a,style:r,"aria-label":c})=>{const i=o.useRef(null),g=o.useRef(null),[l,p]=o.useState(!1),[_,u]=o.useState(!1),[f,j]=o.useState(null),v=()=>{var x;return a?((x=i.current)==null?void 0:x.querySelector(a))??null:g.current},E=()=>{const x=v(),k=Wt(x);if(p(m=>m===k.canScrollUp?m:k.canScrollUp),u(m=>m===k.canScrollDown?m:k.canScrollDown),a){const m=Jt(i.current,x);j(T=>(T==null?void 0:T.top)===(m==null?void 0:m.top)&&(T==null?void 0:T.left)===(m==null?void 0:m.left)&&(T==null?void 0:T.width)===(m==null?void 0:m.width)&&(T==null?void 0:T.height)===(m==null?void 0:m.height)?T:m)}else j(m=>m===null?m:null)};o.useLayoutEffect(()=>{E()}),o.useEffect(()=>{const x=i.current;if(!x)return;let k=null,m=null;const T=()=>{k==null||k.removeEventListener("scroll",E),m==null||m.disconnect(),m=null,k=null},P=L=>{if(L===k){E();return}if(T(),k=L,!k){E();return}k.addEventListener("scroll",E,{passive:!0}),m=new ResizeObserver(()=>E()),m.observe(k),k.firstElementChild instanceof HTMLElement&&m.observe(k.firstElementChild),E()};P(v());const N=new MutationObserver(()=>{P(v())});return N.observe(x,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",E),()=>{window.removeEventListener("resize",E),N.disconnect(),T()}},[a]);const A=x=>{const k=v();if(!k)return;const m=Math.max(k.clientHeight*.75,120);k.scrollBy({top:x==="up"?-m:m,behavior:"smooth"})},M=n.jsxs(n.Fragment,{children:[l&&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:()=>A("up"),children:n.jsx(d.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),_&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>A("down"),children:n.jsx(d.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return n.jsx("div",{ref:i,className:z("scrollable-region",e),style:r,"aria-label":c,children:a?n.jsxs(n.Fragment,{children:[t,f&&(l||_)&&n.jsx("div",{className:"scrollable-region__overlay",style:{top:f.top,left:f.left,width:f.width,height:f.height},children:M})]}):n.jsxs(n.Fragment,{children:[M,n.jsx("div",{ref:g,className:z("scrollable-region__viewport",s),children:t})]})})},Vt=48,Yt=({checklist:t})=>{const e=o.useRef(null),s=o.useRef(!1);return o.useLayoutEffect(()=>{const a=e.current;if(!a)return;const r=a.scrollHeight-a.scrollTop-a.clientHeight;(!s.current||r<=Vt)&&(a.scrollTop=a.scrollHeight,s.current=!0)},[t]),t.length===0?n.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):n.jsx(Ie,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:n.jsx("ul",{ref:e,className:"agent-view__progress-list","aria-label":"Agent tasks",children:Kt(t).map(a=>{const r=J[a.status];return n.jsxs("li",{className:z("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[n.jsx(d.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!==$.complete&&n.jsx("span",{className:"agent-view__progress-description",children:a.description})]})]},a.task)})})})},Xt=({prompts:t,classNamePrefix:e="agent-workspace",onSelect:s})=>t.length===0?null:n.jsx("div",{className:`${e}__chips`,children:t.map(a=>n.jsx("button",{type:"button",className:`${e}__chip`,onClick:()=>s(a),children:a},a))});class Qt{constructor(e,s){this.connector=e,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(e){var s,a;if(!this.canSend())return null;(s=this.onAwaitingChange)==null||s.call(this,!0);try{const r=await this.connector.sendMessage(e.userMessage,e.uploadFiles);return this.onTurn(r),{id:r.message.id,text:r.message.text,type:le.CHAT_RESPONSE_TYPE_AGENT,...r.message.followUpPrompts?{followUpPrompts:r.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:Dt,type:le.CHAT_RESPONSE_TYPE_ERROR}}finally{(a=this.onAwaitingChange)==null||a.call(this,!1)}}async loadHistory(e){return null}async listInteractions(){return null}async rateMessage(e){}async sendNotification(e){return!1}}const Zt=({connector:t,phase:e,chatHistory:s,chatSessionKey:a,startQuery:r,clarificationMessage:c,enableUpload:i=!1,onTurn:g,onAwaitingChange:l,onClarificationPrompt:p,onDismissClarification:_})=>{const u=o.useMemo(()=>new Qt(t,{canSend:()=>e===U.running,onTurn:g,onAwaitingChange:l}),[t,e,g,l]),f=e!==U.running,j=e===U.running;return n.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[c&&n.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[n.jsx("p",{className:"agent-workspace__clarification-text",children:c.text}),c.followUpPrompts&&n.jsx(Xt,{prompts:c.followUpPrompts,onSelect:p}),n.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:_,children:"Dismiss"})]}),n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(Ie,{scrollSelector:".chat-panel-message-list",children:n.jsx(le.ChatPanel,{connector:u,chatHistory:s,startQuery:r,lockConversation:f,enableUpload:i,speechEnabled:j,speechLanguage:"en-GB",speechSubmissionDelay:1e3,slashMenuItems:[],menuContent:[],introHeading:"Message your agent",introBody:"Ask questions, share trip details, or paste a link. The agent will update the checklist as it works.",placeholder:j?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)})}),e===U.stopped&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(d.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 on the left."})]}),e===U.complete&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(d.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),n.jsx("span",{children:"The agent has finished."})]})]})},dt=({item:t,depth:e,canRequestInput:s,onAttentionItemClick:a})=>{const r=J[t.status],c=t.status.replace(/_/g,"-"),i=t.status===$.hitl&&s&&a,g=n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(d.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:t.task}),t.status!==$.complete&&t.description&&n.jsx("span",{className:"agent-workspace__task-description",children:t.description})]})]});return n.jsxs("li",{className:z("agent-workspace__task",`agent-workspace__task--${c}`,{"agent-workspace__task--child":e>0}),children:[i?n.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${t.task}`,onClick:()=>a(t),children:g}):g,t.children&&t.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:t.children.map(l=>n.jsx(dt,{item:l,depth:e+1,canRequestInput:s,onAttentionItemClick:a},l.task))})]})},Ze=({items:t,ariaLabel:e,canRequestInput:s,onAttentionItemClick:a})=>n.jsx("ul",{className:"agent-workspace__task-list","aria-label":e,children:t.map(r=>n.jsx(dt,{item:r,depth:0,canRequestInput:s,onAttentionItemClick:a},r.task))}),en=({checklist:t,isLoading:e,error:s,phase:a,canRequestInput:r,onAttentionItemClick:c})=>{const i=o.useMemo(()=>t?lt(t):null,[t]);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(d.Heading,{level:4,children:"Checklist"})}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsxs(Ie,{children:[e&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:oe}),n.jsx("span",{children:oe})]}),!e&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!e&&!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(Ze,{items:i.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:r,onAttentionItemClick:c})]}),i.tasks.length>0&&n.jsxs("div",{className:z("agent-workspace__task-group",{"agent-workspace__task-group--following":i.needsInput.length>0}),children:[i.needsInput.length>0&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Other tasks"}),n.jsx(Ze,{items:i.tasks,ariaLabel:"Agent tasks",canRequestInput:r,onAttentionItemClick:c})]})]}),!e&&!s&&(!i||i.needsInput.length===0&&i.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:a===U.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})]})},tn={[re.MIS_RECORD]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[re.FILE]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[re.WORKFLOW]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[re.LINK]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},nn=({resources:t,isLoading:e=!1,error:s=null})=>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(d.Heading,{level:4,children:"Resources"}),n.jsx("span",{className:"agent-workspace__panel-count",children:t.length})]}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsxs(Ie,{children:[e&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(d.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…"})]}),!e&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!e&&!s&&t.length>0&&n.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:t.map(a=>{const r=tn[a.type];return n.jsx("li",{className:"agent-workspace__resource",children:n.jsxs("a",{className:"agent-workspace__resource-card",href:a.uri,target:"_blank",rel:"noreferrer",children:[n.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${a.type.toLowerCase()}`,children:n.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`})}),n.jsxs("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:a.name}),n.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${a.type.toLowerCase()}`,children:r.label})]}),a.description&&n.jsx("span",{className:"agent-workspace__resource-description",children:a.description})]}),n.jsx(d.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]})},`${a.type}-${a.uri}`)})}),!e&&!s&&t.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),Te=t=>{const e=Date.parse(t);return Number.isFinite(e)?e:0},sn=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),Be=t=>{const e=new Date(t);return Number.isFinite(e.getTime())?sn.format(e):t},Ae=t=>t.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,e=>e.split(/[_-]/).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")),we=(t,e)=>e<=1?0:t/(e-1)*100,gt=t=>Math.max(t,0)+2,an=t=>t+1,rn=(t,e)=>{if(e.length===0)return 50;const s=gt(e.length),a=we(1,s),r=we(e.length,s),c=e.map(_=>Te(_.timestamp)),i=Math.min(...c),g=Math.max(...c);if(g<=i)return a;const l=(Te(t.timestamp)-i)/(g-i),p=Math.min(1,Math.max(0,l));return a+p*(r-a)},on=8,cn=20,ln=(t,e=on,s=cn)=>{const a=new Map;if(t.length===0)return a;const r=[...t].sort((i,g)=>i.leftPercent-g.leftPercent||i.timestampMs-g.timestampMs||i.id.localeCompare(g.id)),c=[];for(const i of r){const g=c[c.length-1];g&&i.leftPercent-g[g.length-1].leftPercent<e?g.push(i):c.push([i])}for(const i of c){const g=[...i].sort((p,_)=>p.timestampMs-_.timestampMs||p.id.localeCompare(_.id)),l=(g.length-1)/2;g.forEach((p,_)=>{a.set(p.id,(_-l)*s)})}return a},Ce=(t,e=0)=>({left:`calc(${t/100} * (100% - var(--agent-timeline-node-size)) + (var(--agent-timeline-node-size) / 2) + ${e}px)`,transform:"translateX(-50%)"}),dn=t=>t.type!=="message-sent",gn=({timeline:t,isLoading:e,error:s,onOpenChatSession:a})=>{const r=((t==null?void 0:t.actionLog)??[]).filter(dn),c=(t==null?void 0:t.chatSessions)??[],i=!e&&!s&&r.length===0&&c.length===0,g=gt(r.length),l=r.map((u,f)=>({id:`action-${u.timestamp}-${f}`,leftPercent:we(an(f),g),timestampMs:Te(u.timestamp)})),p=c.map(u=>({id:u.sessionId,leftPercent:rn(u,r),timestampMs:Te(u.timestamp)})),_=ln([...l,...p]);return n.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[e&&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||it}),i&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!e&&!s&&!i&&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",style:Ce(we(0,g)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(d.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Start"})]}),r.map((u,f)=>{const j=`action-${u.timestamp}-${f}`,v=l[f].leftPercent,E=u.type==="checklist-updated",A=u.type==="status-transition",M=E?"checklist":A?"status":"note";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${M}`,style:Ce(v,_.get(j)??0),children:[n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${M}`,"aria-label":`${Ae(u.type)}: ${Ae(u.entry)}`,children:[E&&n.jsx(d.Icon,{name:"check-solid",size:16,color:"currentColor"}),A&&n.jsx(d.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]}),n.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[n.jsx("strong",{className:"agent-timeline__pill-type",children:Ae(u.type)}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Ae(u.entry)}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Be(u.timestamp)})]})]},j)}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:Ce(we(g-1,g)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(d.Icon,{name:"flag",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Finish"})]}),c.map((u,f)=>{const j=p[f].leftPercent;return n.jsxs("div",{className:"agent-timeline__chat-station",style:Ce(j,_.get(u.sessionId)??0),children:[n.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${Be(u.timestamp)}`,onClick:()=>a(u.sessionId),children:n.jsx(d.Icon,{name:"sparkles",size:16,color:"currentColor"})}),n.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[n.jsx("strong",{className:"agent-timeline__pill-type",children:"Chat session"}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Be(u.timestamp)})]})]},u.sessionId)})]})]})},un=["I'll get the details and come back to you","Skip this for now"],hn=t=>{var s;const e=(s=t.prompt)!=null&&s.trim()?t.prompt.trim():`I need a bit more from you on "${t.task}". ${t.description} What can you tell me?`;return{id:`clarification-${Date.now()}`,author:X.agent,text:e,followUpPrompts:t.clarificationPrompts??un}},ae=t=>({id:t.id,text:t.text,type:t.author===X.user?le.CHAT_RESPONSE_TYPE_USER:t.author===X.system?le.CHAT_RESPONSE_TYPE_INFO:le.CHAT_RESPONSE_TYPE_AGENT,...t.followUpPrompts?{followUpPrompts:t.followUpPrompts}:{}});class ie extends Error{constructor(e,s,a){super(a??`Agent service request failed (${e})`),this.name="AgentServiceError",this.status=e,this.detail=s}}const pn="/api/v1",B={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},F={GET:"GET",POST:"POST"},mn={error:"error"},_n={user:"user"},ce={acceptJson:"application/json",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},fn=/:invocationId\b/g,vn=t=>t.trim().replace(/^Bearer\s+/i,""),wn=t=>t.endsWith("/")?t.slice(0,-1):t;class Re{constructor(e){var a;this.baseUrl=wn(e.baseUrl??"");const s=(a=e.token)==null?void 0:a.trim();this.token=s?vn(s):void 0,this.customHeaders=e.headers,this.urls=e.urls??{},this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis)}setHeaders(e){this.customHeaders=e}async listAgentDefinitions(){return(await this.request(F.GET,this.resolveUrl("agentDefinitions",B.agentDefinitions))).agent_definitions??[]}getAgentDefinition(e){return this.request(F.GET,this.apiUrl(`${B.agentDefinitions}/${encodeURIComponent(e)}`))}listTripOptions(){return this.request(F.GET,this.apiUrl(B.tripOptions))}getDataset(){return this.request(F.GET,this.apiUrl(B.demoDataset))}setDataset(e){return this.request(F.POST,this.apiUrl(B.demoDataset),{dataset:e})}listAgents(e={}){const s=new URLSearchParams;e.status&&s.set("status",e.status),e.agentDefinitionRef&&s.set("agent_definition_ref",e.agentDefinitionRef);const a=s.toString()?`?${s.toString()}`:"";return this.request(F.GET,`${this.resolveUrl("agents",B.agents)}${a}`)}createAgent(e,s={}){var i,g;const a={agent_definition_ref:e},r=(i=s.invocationName)==null?void 0:i.trim(),c=(g=s.agentIntent)==null?void 0:g.trim();return r&&(a.invocation_name=r),c&&(a.agent_intent=c),this.request(F.POST,this.resolveUrl("agents",B.agents),a)}getAgent(e){return this.request(F.GET,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(e)}`,e))}getAgentChecklist(e){return this.request(F.GET,this.resolveUrl("agentChecklist",`${B.agents}/${encodeURIComponent(e)}/checklist`,e))}getAgentResources(e){return this.request(F.GET,this.resolveUrl("agentResources",`${B.agents}/${encodeURIComponent(e)}/resources`,e))}getAgentTimeline(e){return this.request(F.GET,this.resolveUrl("agentTimeline",`${B.agents}/${encodeURIComponent(e)}/agent-timeline`,e))}getAgentContext(e){return this.request(F.GET,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/context`))}cancelAgent(e){return this.request(F.POST,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/cancel`))}archiveAgent(e){return this.request(F.POST,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/archive`))}getConversation(e){return this.request(F.GET,this.resolveUrl("agentConversation",`${B.conversations}/${encodeURIComponent(e)}`,e))}async chat(e,s,a={}){const r=!!(a.uploadFiles&&a.uploadFiles.length>0),c=await this.fetchImpl(this.resolveUrl("agentChat",`${B.agents}/${encodeURIComponent(e)}/chat`,e),{method:F.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:ce.acceptEventStream,...r?{}:{"Content-Type":ce.contentTypeJson}},body:r?kn(s,a.uploadFiles??[]):JSON.stringify(s),signal:a.signal});if(!c.ok)throw await this.toError(c);if(!c.body)throw new ie(c.status,null,"Chat response contained no stream body");return this.consumeSse(c.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(e){return`${this.baseUrl}${pn}${e}`}resolveUrl(e,s,a){const r=this.urls[e];return r?a?r.replace(fn,encodeURIComponent(a)):r:this.apiUrl(s)}async request(e,s,a){const r=await this.fetchImpl(s,{method:e,headers:{...this.customHeaders,...this.authHeaders(),Accept:ce.acceptJson,...a===void 0?{}:{"Content-Type":ce.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 toError(e){let s=null;try{s=await e.json()}catch{}return new ie(e.status,s,`Agent service request failed (${e.status} ${e.statusText})`)}async consumeSse(e,s){const a=e.getReader(),r=new TextDecoder;let c="",i;const g=l=>{const{event:p,data:_}=xn(l);if(_===null)return;if(p===mn.error){const f=et(_);throw new ie(502,f,(f==null?void 0:f.message)??"Chat stream error")}const u=et(_);u&&(i=u,s==null||s(u))};for(;;){const{done:l,value:p}=await a.read();if(l)break;c+=r.decode(p,{stream:!0});const _=c.split(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),o=require("react"),z=require("classnames"),d=require("@arbor-education/design-system.components"),de=require("@arbor-education/ask-arbor-chat-panel"),C={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},$={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},U={briefing:"briefing",running:"running",stopped:"stopped",complete:"complete"},X={agent:"agent",user:"user",system:"system"},oe={MIS_RECORD:"MIS_RECORD",FILE:"FILE",WORKFLOW:"WORKFLOW",LINK:"LINK"},tt={cancelled:"cancelled",archived:"archived"},Fe={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},J={[$.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)"}},Te={[C["generating-a-response"]]:{status:C["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:J["generating-a-response"].icon,color:J["generating-a-response"].color}},[C.hitl]:{status:C.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:J.hitl.icon,color:J.hitl.color}},[C.complete]:{status:C.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:J.complete.icon,color:J.complete.color}},[C.failed]:{status:C.failed,title:"Failed",dotColour:"salmon",statusIcon:{name:J.failed.icon,color:J.failed.color}}},Mt=[C["generating-a-response"],C.hitl],Pt=[C.complete,C.failed],Dt="m4",Ut="1",dt="msg-opening",Ee="Unable to load agent tasks. Please try again.",$t="Unable to load the resources for this agent",gt="Unable to load the timeline for this agent",Ht="Something went wrong. Please try again.",ut="Unable to load agents. Please try again.",ie="Loading tasks…",nt="Loading agents…",Bt="Task",Ft={[U.briefing]:"Briefing",[U.running]:"Working",[U.stopped]:"Stopped",[U.complete]:"Complete"},zt=[C["generating-a-response"],C.hitl,C.complete,C.failed],Gt={[C["generating-a-response"]]:"Agents currently working on tasks for you.",[C.hitl]:"Agents that need your input before they can continue.",[C.complete]:"Agents that have finished their work.",[C.failed]:"Agents that failed or were stopped."},qt=()=>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)"})]}),Kt=({status:t})=>{const e=Te[t];return e.statusIcon?n.jsx(d.Icon,{name:e.statusIcon.name,size:16,color:e.statusIcon.color,screenReaderText:e.title}):n.jsx(d.Dot,{colour:e.dotColour,label:e.title})},Wt=()=>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(d.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:zt.map(t=>{const e=Te[t];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(Kt,{status:t})}),n.jsxs("span",{className:"agent-view__empty-column-text",children:[n.jsx("span",{className:"agent-view__empty-column-title",children:e.title}),n.jsx("span",{className:"agent-view__empty-column-description",children:Gt[t]})]})]},t)})}),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(qt,{})})]}),Jt=(t,e)=>({...t,...e.length>0?{children:e}:{}}),ht=t=>{const e=[],s=[];for(const a of t){const r=a.children?ht(a.children):{needsInput:[],tasks:[]};if(e.push(...r.needsInput),a.status===$.hitl){e.push({...a,children:void 0});continue}s.push(Jt(a,r.tasks))}return{needsInput:e,tasks:s}},Vt=t=>t.map((e,s)=>({item:e,index:s})).sort((e,s)=>{const a=e.item.status===$.hitl,r=s.item.status===$.hitl;return a!==r?a?-1:1:e.index-s.index}).map(({item:e})=>e),ze=2,Yt=t=>{if(!t)return{canScrollUp:!1,canScrollDown:!1};const e=t.scrollHeight-t.clientHeight;return e<=ze?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:t.scrollTop>ze,canScrollDown:t.scrollTop<e-ze}},Xt=(t,e)=>{if(!t||!e)return null;const s=t.getBoundingClientRect(),a=e.getBoundingClientRect();return{top:a.top-s.top,left:a.left-s.left,width:a.width,height:a.height}},Re=({children:t,className:e,contentClassName:s,scrollSelector:a,style:r,"aria-label":c})=>{const i=o.useRef(null),g=o.useRef(null),[l,p]=o.useState(!1),[f,u]=o.useState(!1),[v,j]=o.useState(null),w=()=>{var x;return a?((x=i.current)==null?void 0:x.querySelector(a))??null:g.current},E=()=>{const x=w(),y=Yt(x);if(p(m=>m===y.canScrollUp?m:y.canScrollUp),u(m=>m===y.canScrollDown?m:y.canScrollDown),a){const m=Xt(i.current,x);j(T=>(T==null?void 0:T.top)===(m==null?void 0:m.top)&&(T==null?void 0:T.left)===(m==null?void 0:m.left)&&(T==null?void 0:T.width)===(m==null?void 0:m.width)&&(T==null?void 0:T.height)===(m==null?void 0:m.height)?T:m)}else j(m=>m===null?m:null)};o.useLayoutEffect(()=>{E()}),o.useEffect(()=>{const x=i.current;if(!x)return;let y=null,m=null;const T=()=>{y==null||y.removeEventListener("scroll",E),m==null||m.disconnect(),m=null,y=null},P=M=>{if(M===y){E();return}if(T(),y=M,!y){E();return}y.addEventListener("scroll",E,{passive:!0}),m=new ResizeObserver(()=>E()),m.observe(y),y.firstElementChild instanceof HTMLElement&&m.observe(y.firstElementChild),E()};P(w());const N=new MutationObserver(()=>{P(w())});return N.observe(x,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",E),()=>{window.removeEventListener("resize",E),N.disconnect(),T()}},[a]);const A=x=>{const y=w();if(!y)return;const m=Math.max(y.clientHeight*.75,120);y.scrollBy({top:x==="up"?-m:m,behavior:"smooth"})},L=n.jsxs(n.Fragment,{children:[l&&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:()=>A("up"),children:n.jsx(d.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),f&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>A("down"),children:n.jsx(d.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return n.jsx("div",{ref:i,className:z("scrollable-region",e),style:r,"aria-label":c,children:a?n.jsxs(n.Fragment,{children:[t,v&&(l||f)&&n.jsx("div",{className:"scrollable-region__overlay",style:{top:v.top,left:v.left,width:v.width,height:v.height},children:L})]}):n.jsxs(n.Fragment,{children:[L,n.jsx("div",{ref:g,className:z("scrollable-region__viewport",s),children:t})]})})},Qt=48,Zt=({checklist:t})=>{const e=o.useRef(null),s=o.useRef(!1);return o.useLayoutEffect(()=>{const a=e.current;if(!a)return;const r=a.scrollHeight-a.scrollTop-a.clientHeight;(!s.current||r<=Qt)&&(a.scrollTop=a.scrollHeight,s.current=!0)},[t]),t.length===0?n.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):n.jsx(Re,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:n.jsx("ul",{ref:e,className:"agent-view__progress-list","aria-label":"Agent tasks",children:Vt(t).map(a=>{const r=J[a.status];return n.jsxs("li",{className:z("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[n.jsx(d.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!==$.complete&&n.jsx("span",{className:"agent-view__progress-description",children:a.description})]})]},a.task)})})})},en=({prompts:t,classNamePrefix:e="agent-workspace",onSelect:s})=>t.length===0?null:n.jsx("div",{className:`${e}__chips`,children:t.map(a=>n.jsx("button",{type:"button",className:`${e}__chip`,onClick:()=>s(a),children:a},a))});class tn{constructor(e,s){this.connector=e,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(e){var s,a;if(!this.canSend())return null;(s=this.onAwaitingChange)==null||s.call(this,!0);try{const r=await this.connector.sendMessage(e.userMessage,e.uploadFiles);return this.onTurn(r),{id:r.message.id,text:r.message.text,type:de.CHAT_RESPONSE_TYPE_AGENT,...r.message.followUpPrompts?{followUpPrompts:r.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:Ht,type:de.CHAT_RESPONSE_TYPE_ERROR}}finally{(a=this.onAwaitingChange)==null||a.call(this,!1)}}async loadHistory(e){return null}async listInteractions(){return null}async rateMessage(e){}async sendNotification(e){return!1}}const nn=({connector:t,phase:e,chatHistory:s,chatSessionKey:a,startQuery:r,clarificationMessage:c,enableUpload:i=!1,onTurn:g,onAwaitingChange:l,onClarificationPrompt:p,onDismissClarification:f})=>{const u=o.useMemo(()=>new tn(t,{canSend:()=>e===U.running,onTurn:g,onAwaitingChange:l}),[t,e,g,l]),v=e!==U.running,j=e===U.running;return n.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[c&&n.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[n.jsx("p",{className:"agent-workspace__clarification-text",children:c.text}),c.followUpPrompts&&n.jsx(en,{prompts:c.followUpPrompts,onSelect:p}),n.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:f,children:"Dismiss"})]}),n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(Re,{scrollSelector:".chat-panel-message-list",children:n.jsx(de.ChatPanel,{connector:u,chatHistory:s,startQuery:r,lockConversation:v,enableUpload:i,speechEnabled:j,speechLanguage:"en-GB",speechSubmissionDelay:1e3,slashMenuItems:[],menuContent:[],introHeading:"Message your agent",introBody:"Ask questions, share trip details, or paste a link. The agent will update the checklist as it works.",placeholder:j?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)})}),e===U.stopped&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(d.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 on the left."})]}),e===U.complete&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(d.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),n.jsx("span",{children:"The agent has finished."})]})]})},pt=({item:t,depth:e,canRequestInput:s,onAttentionItemClick:a})=>{const r=J[t.status],c=t.status.replace(/_/g,"-"),i=t.status===$.hitl&&s&&a,g=n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(d.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:t.task}),t.status!==$.complete&&t.description&&n.jsx("span",{className:"agent-workspace__task-description",children:t.description})]})]});return n.jsxs("li",{className:z("agent-workspace__task",`agent-workspace__task--${c}`,{"agent-workspace__task--child":e>0}),children:[i?n.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${t.task}`,onClick:()=>a(t),children:g}):g,t.children&&t.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:t.children.map(l=>n.jsx(pt,{item:l,depth:e+1,canRequestInput:s,onAttentionItemClick:a},l.task))})]})},st=({items:t,ariaLabel:e,canRequestInput:s,onAttentionItemClick:a})=>n.jsx("ul",{className:"agent-workspace__task-list","aria-label":e,children:t.map(r=>n.jsx(pt,{item:r,depth:0,canRequestInput:s,onAttentionItemClick:a},r.task))}),sn=({checklist:t,isLoading:e,error:s,phase:a,canRequestInput:r,onAttentionItemClick:c})=>{const i=o.useMemo(()=>t?ht(t):null,[t]);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(d.Heading,{level:4,children:"Checklist"})}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsxs(Re,{children:[e&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:ie}),n.jsx("span",{children:ie})]}),!e&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!e&&!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(st,{items:i.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:r,onAttentionItemClick:c})]}),i.tasks.length>0&&n.jsxs("div",{className:z("agent-workspace__task-group",{"agent-workspace__task-group--following":i.needsInput.length>0}),children:[i.needsInput.length>0&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Other tasks"}),n.jsx(st,{items:i.tasks,ariaLabel:"Agent tasks",canRequestInput:r,onAttentionItemClick:c})]})]}),!e&&!s&&(!i||i.needsInput.length===0&&i.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:a===U.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})]})},an={[oe.MIS_RECORD]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[oe.FILE]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[oe.WORKFLOW]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[oe.LINK]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},rn=({resources:t,isLoading:e=!1,error:s=null})=>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(d.Heading,{level:4,children:"Resources"}),n.jsx("span",{className:"agent-workspace__panel-count",children:t.length})]}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsxs(Re,{children:[e&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(d.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…"})]}),!e&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!e&&!s&&t.length>0&&n.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:t.map(a=>{const r=an[a.type];return n.jsx("li",{className:"agent-workspace__resource",children:n.jsxs("a",{className:"agent-workspace__resource-card",href:a.uri,target:"_blank",rel:"noreferrer",children:[n.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${a.type.toLowerCase()}`,children:n.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`})}),n.jsxs("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:a.name}),n.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${a.type.toLowerCase()}`,children:r.label})]}),a.description&&n.jsx("span",{className:"agent-workspace__resource-description",children:a.description})]}),n.jsx(d.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]})},`${a.type}-${a.uri}`)})}),!e&&!s&&t.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),Ie=t=>{const e=Date.parse(t);return Number.isFinite(e)?e:0},on=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),Ge=t=>{const e=new Date(t);return Number.isFinite(e.getTime())?on.format(e):t},Ce=t=>t.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,e=>e.split(/[_-]/).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")),xe=(t,e)=>e<=1?0:t/(e-1)*100,mt=t=>Math.max(t,0)+2,cn=t=>t+1,ln=(t,e)=>{if(e.length===0)return 50;const s=mt(e.length),a=xe(1,s),r=xe(e.length,s),c=e.map(f=>Ie(f.timestamp)),i=Math.min(...c),g=Math.max(...c);if(g<=i)return a;const l=(Ie(t.timestamp)-i)/(g-i),p=Math.min(1,Math.max(0,l));return a+p*(r-a)},dn=8,gn=20,un=(t,e=dn,s=gn)=>{const a=new Map;if(t.length===0)return a;const r=[...t].sort((i,g)=>i.leftPercent-g.leftPercent||i.timestampMs-g.timestampMs||i.id.localeCompare(g.id)),c=[];for(const i of r){const g=c[c.length-1];g&&i.leftPercent-g[g.length-1].leftPercent<e?g.push(i):c.push([i])}for(const i of c){const g=[...i].sort((p,f)=>p.timestampMs-f.timestampMs||p.id.localeCompare(f.id)),l=(g.length-1)/2;g.forEach((p,f)=>{a.set(p.id,(f-l)*s)})}return a},be=(t,e=0)=>({left:`calc(${t/100} * (100% - var(--agent-timeline-node-size)) + (var(--agent-timeline-node-size) / 2) + ${e}px)`,transform:"translateX(-50%)"}),hn=t=>t.type!=="message-sent",pn=({timeline:t,isLoading:e,error:s,onOpenChatSession:a})=>{const r=((t==null?void 0:t.actionLog)??[]).filter(hn),c=(t==null?void 0:t.chatSessions)??[],i=!e&&!s&&r.length===0&&c.length===0,g=mt(r.length),l=r.map((u,v)=>({id:`action-${u.timestamp}-${v}`,leftPercent:xe(cn(v),g),timestampMs:Ie(u.timestamp)})),p=c.map(u=>({id:u.sessionId,leftPercent:ln(u,r),timestampMs:Ie(u.timestamp)})),f=un([...l,...p]);return n.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[e&&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||gt}),i&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!e&&!s&&!i&&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",style:be(xe(0,g)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(d.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Start"})]}),r.map((u,v)=>{const j=`action-${u.timestamp}-${v}`,w=l[v].leftPercent,E=u.type==="checklist-updated",A=u.type==="status-transition",L=E?"checklist":A?"status":"note";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${L}`,style:be(w,f.get(j)??0),children:[n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${L}`,"aria-label":`${Ce(u.type)}: ${Ce(u.entry)}`,children:[E&&n.jsx(d.Icon,{name:"check-solid",size:16,color:"currentColor"}),A&&n.jsx(d.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]}),n.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[n.jsx("strong",{className:"agent-timeline__pill-type",children:Ce(u.type)}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Ce(u.entry)}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Ge(u.timestamp)})]})]},j)}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:be(xe(g-1,g)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(d.Icon,{name:"flag",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Finish"})]}),c.map((u,v)=>{const j=p[v].leftPercent;return n.jsxs("div",{className:"agent-timeline__chat-station",style:be(j,f.get(u.sessionId)??0),children:[n.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${Ge(u.timestamp)}`,onClick:()=>a(u.sessionId),children:n.jsx(d.Icon,{name:"sparkles",size:16,color:"currentColor"})}),n.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[n.jsx("strong",{className:"agent-timeline__pill-type",children:"Chat session"}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Ge(u.timestamp)})]})]},u.sessionId)})]})]})},mn=["I'll get the details and come back to you","Skip this for now"],_n=t=>{var s;const e=(s=t.prompt)!=null&&s.trim()?t.prompt.trim():`I need a bit more from you on "${t.task}". ${t.description} What can you tell me?`;return{id:`clarification-${Date.now()}`,author:X.agent,text:e,followUpPrompts:t.clarificationPrompts??mn}},re=t=>({id:t.id,text:t.text,type:t.author===X.user?de.CHAT_RESPONSE_TYPE_USER:t.author===X.system?de.CHAT_RESPONSE_TYPE_INFO:de.CHAT_RESPONSE_TYPE_AGENT,...t.followUpPrompts?{followUpPrompts:t.followUpPrompts}:{}});class ce extends Error{constructor(e,s,a){super(a??`Agent service request failed (${e})`),this.name="AgentServiceError",this.status=e,this.detail=s}}const fn="/api/v1",B={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},F={GET:"GET",POST:"POST"},vn={error:"error"},wn={user:"user"},le={acceptJson:"application/json",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},xn=/:invocationId\b/g,yn=t=>t.trim().replace(/^Bearer\s+/i,""),kn=t=>t.endsWith("/")?t.slice(0,-1):t;class Oe{constructor(e){var a;this.baseUrl=kn(e.baseUrl??"");const s=(a=e.token)==null?void 0:a.trim();this.token=s?yn(s):void 0,this.customHeaders=e.headers,this.urls=e.urls??{},this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis)}setHeaders(e){this.customHeaders=e}async listAgentDefinitions(){return(await this.request(F.GET,this.resolveUrl("agentDefinitions",B.agentDefinitions))).agent_definitions??[]}getAgentDefinition(e){return this.request(F.GET,this.apiUrl(`${B.agentDefinitions}/${encodeURIComponent(e)}`))}listTripOptions(){return this.request(F.GET,this.apiUrl(B.tripOptions))}getDataset(){return this.request(F.GET,this.apiUrl(B.demoDataset))}setDataset(e){return this.request(F.POST,this.apiUrl(B.demoDataset),{dataset:e})}listAgents(e={}){const s=new URLSearchParams;e.status&&s.set("status",e.status),e.agentDefinitionRef&&s.set("agent_definition_ref",e.agentDefinitionRef);const a=s.toString()?`?${s.toString()}`:"";return this.request(F.GET,`${this.resolveUrl("agents",B.agents)}${a}`)}createAgent(e,s={}){var i,g;const a={agent_definition_ref:e},r=(i=s.invocationName)==null?void 0:i.trim(),c=(g=s.agentIntent)==null?void 0:g.trim();return r&&(a.invocation_name=r),c&&(a.agent_intent=c),this.request(F.POST,this.resolveUrl("agents",B.agents),a)}getAgent(e){return this.request(F.GET,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(e)}`,e))}getAgentChecklist(e){return this.request(F.GET,this.resolveUrl("agentChecklist",`${B.agents}/${encodeURIComponent(e)}/checklist`,e))}getAgentResources(e){return this.request(F.GET,this.resolveUrl("agentResources",`${B.agents}/${encodeURIComponent(e)}/resources`,e))}getAgentTimeline(e){return this.request(F.GET,this.resolveUrl("agentTimeline",`${B.agents}/${encodeURIComponent(e)}/agent-timeline`,e))}getAgentContext(e){return this.request(F.GET,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/context`))}cancelAgent(e){return this.request(F.POST,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/cancel`))}archiveAgent(e){return this.request(F.POST,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/archive`))}getConversation(e){return this.request(F.GET,this.resolveUrl("agentConversation",`${B.conversations}/${encodeURIComponent(e)}`,e))}async chat(e,s,a={}){const r=!!(a.uploadFiles&&a.uploadFiles.length>0),c=await this.fetchImpl(this.resolveUrl("agentChat",`${B.agents}/${encodeURIComponent(e)}/chat`,e),{method:F.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:le.acceptEventStream,...r?{}:{"Content-Type":le.contentTypeJson}},body:r?Sn(s,a.uploadFiles??[]):JSON.stringify(s),signal:a.signal});if(!c.ok)throw await this.toError(c);if(!c.body)throw new ce(c.status,null,"Chat response contained no stream body");return this.consumeSse(c.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(e){return`${this.baseUrl}${fn}${e}`}resolveUrl(e,s,a){const r=this.urls[e];return r?a?r.replace(xn,encodeURIComponent(a)):r:this.apiUrl(s)}async request(e,s,a){const r=await this.fetchImpl(s,{method:e,headers:{...this.customHeaders,...this.authHeaders(),Accept:le.acceptJson,...a===void 0?{}:{"Content-Type":le.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 toError(e){let s=null;try{s=await e.json()}catch{}return new ce(e.status,s,`Agent service request failed (${e.status} ${e.statusText})`)}async consumeSse(e,s){const a=e.getReader(),r=new TextDecoder;let c="",i;const g=l=>{const{event:p,data:f}=Nn(l);if(f===null)return;if(p===vn.error){const v=at(f);throw new ce(502,v,(v==null?void 0:v.message)??"Chat stream error")}const u=at(f);u&&(i=u,s==null||s(u))};for(;;){const{done:l,value:p}=await a.read();if(l)break;c+=r.decode(p,{stream:!0});const f=c.split(`
|
|
2
2
|
|
|
3
|
-
`);c=
|
|
3
|
+
`);c=f.pop()??"";for(const u of f)g(u)}if(c.trim()&&g(c),!i)throw new ce(502,null,"Chat stream ended without any events");return i}}const Nn=t=>{let e=null;const s=[];for(const a of t.split(`
|
|
4
4
|
`)){const r=a.trimEnd();r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&s.push(r.slice(5).trim())}return{event:e,data:s.length>0?s.join(`
|
|
5
|
-
`):null}},et=t=>{try{return JSON.parse(t)}catch{return}};function kn(t,e){const s=new FormData;s.append("body",JSON.stringify(t));for(const a of e)s.append("files",a,a.name);return s}const ut=t=>{switch(t){case Xe.cancelled:return C.failed;case Xe.archived:return C.complete;case C.hitl:case C.complete:case C.failed:case C["generating-a-response"]:return t;default:return C["generating-a-response"]}},ht=t=>{switch(t){case $e.requires_attention:return $.hitl;case $e.in_progress:case $e.available:return $["generating-a-response"];case $.failed:case $.complete:case $.hitl:case $["generating-a-response"]:return t;default:return $["generating-a-response"]}},qe=t=>({ref:t.name,display_name:t.display_name,agent_intent:t.agent_intent??"",description:t.description}),yn=t=>({id:t.id,name:t.name,...t.has_run_before?{hasRunBefore:t.has_run_before}:{}}),Nn=new Set(Object.values(re)),Sn=t=>t&&Nn.has(t)?t:re.LINK,pt=t=>({uri:t.uri??"",type:Sn(t.type),name:t.name??"",description:t.description??""}),Ke=t=>(Array.isArray(t)?t:t.resources??[]).map(pt),mt=t=>({actionLog:(t.action_log??[]).map(e=>({timestamp:e.timestamp,type:e.type,entry:e.entry,origin:e.origin})),chatSessions:(t.chat_sessions??[]).map(e=>({sessionId:e.session_id,timestamp:e.timestamp}))}),ze=t=>{var s;const e=t.invocation_id??t.id;return{id:t.id,invocation_id:e,agent_definition_ref:t.agent_definition_ref,...t.agent_intent?{agent_intent:t.agent_intent}:{},invocation_name:((s=t.invocation_name)==null?void 0:s.trim())||t.agent_definition_ref,application_id:t.application_id,...t.application_name?{application_name:t.application_name}:{},created_by:t.created_by,status:ut(t.status),context_ref:t.context_ref??null,checklist_ref:t.checklist_ref??null}},We=t=>{var e;return{task:t.task??t.name??t.label??Ut,status:ht(t.status),description:t.description??"",...t.prompt?{prompt:t.prompt}:{},...(e=t.follow_up_prompts)!=null&&e.length?{clarificationPrompts:t.follow_up_prompts}:{}}},jn=t=>Array.isArray(t)?t:t.checklist_items??t.checklist??t.items??[],Je=(t,e,s)=>{var c;const a=!Array.isArray(e)&&(e.opening_message||(c=e.opening_follow_up_prompts)!=null&&c.length)?e:s,r=a?xe(a):void 0;return{invocation_id:t,checklist:jn(e).map(We),...r?{openingMessage:r}:{}}},_t=(t,e)=>{const s=xe(e);return{invocation_id:e.invocation_id??t,checklist:(e.checklist_items??[]).map(We),...s?{openingMessage:s}:{}}},xe=t=>{var s,a;const e=(s=t.opening_message)==null?void 0:s.trim();if(e)return{id:ot,author:X.agent,text:e,...(a=t.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:t.opening_follow_up_prompts}:{}}},ft=t=>t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.length>0&&e.message_type!=="tool_request").map(e=>({id:e.message_id,author:e.role==="user"?X.user:X.agent,text:e.content})),An={id:ot,author:X.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 tt=0;const Cn=t=>(tt+=1,`${t}-${Date.now()}-${tt}`),bn=t=>{const e=t.destination?` to ${t.destination}`:"";return`Let's get started on ${t.tripName.trim()||t.destination.trim()||"this task"}${e}. What will you do first?`};class vt{constructor(e,s,a={}){this.seededChecklist=[],this.client=e,this.agentId=s,this.chatId=a.chatId??s,this.opening=a.openingMessage??An,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const e=await this.client.getConversation(this.chatId),s=ft(e.messages);return s.length===0?[this.opening]:s}async start(e){return{...await this.exchange(bn(e)),phase:U.running}}sendMessage(e,s){return this.exchange(e,s)}async stop(){}seedChecklist(e){this.seededChecklist=e}async exchange(e,s){var i;const a=[{role:_n.user,content:e}],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}]:[]),c={id:r.event_id||Cn("msg-agent"),author:X.agent,text:r.message.content,...(i=r.follow_up_prompts)!=null&&i.length?{followUpPrompts:r.follow_up_prompts}:{}};try{const g=await this.client.getAgent(this.agentId),{checklist:l}=_t(this.agentId,g);return this.seededChecklist=l,{message:c,checklist:l}}catch{return{message:c,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const Ve=(t,e)=>s=>{var a,r;return new vt(t,s.invocation_id,{model:e==null?void 0:e.model,chatId:((a=e==null?void 0:e.resolveChatId)==null?void 0:a.call(e,s))??(e==null?void 0:e.chatId)??s.invocation_id,openingMessage:((r=e==null?void 0:e.resolveOpeningMessage)==null?void 0:r.call(e,s))??(e==null?void 0:e.openingMessage)})},wt=t=>t instanceof ie?t.message:t instanceof TypeError?"Network error while contacting the agent service.":t instanceof Error&&t.message?t.message:ct,En=t=>{const e={};for(const s of t){const a=xe(s);if(!a)continue;const r=s.invocation_id??s.id;e[r]=a,e[s.id]=a}return e},Tn=t=>JSON.stringify(t),Fe=(t,e)=>JSON.stringify(t)===JSON.stringify(e),xt=t=>{const{jwt:e,headers:s,urls:a}=t,r=JSON.stringify(s??{}),c=Tn(a),i=o.useMemo(()=>new Re({token:e,headers:s,urls:a}),[e,c]);o.useLayoutEffect(()=>{i.setHeaders(s)},[i,r]);const[g,l]=o.useState([]),[p,_]=o.useState([]),[u,f]=o.useState({}),[j,v]=o.useState("loading"),[E,A]=o.useState(null),[M,x]=o.useState(0),k=o.useCallback((I,b)=>{const D=I.map(ze),G=b.map(qe),K=En(I);l(R=>Fe(R,D)?R:D),_(R=>Fe(R,G)?R:G),f(R=>Fe(R,K)?R:K),v("idle"),A(null)},[]);o.useEffect(()=>{let I=!1;return v("loading"),A(null),(async()=>{try{const[b,D]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);if(I)return;k(b,D)}catch(b){if(I)return;l([]),_([]),f({}),v("error"),A(wt(b))}})(),()=>{I=!0}},[k,i,M]);const m=o.useCallback(()=>{x(I=>I+1)},[]),T=o.useCallback(async()=>{try{const[I,b]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);k(I,b)}catch{}},[k,i]),P=o.useCallback(async I=>{const[b,D]=await Promise.all([i.getAgentChecklist(I),i.getAgent(I).catch(()=>null)]);return Je(I,b,D??void 0)},[i]),N=o.useCallback(async I=>{const b=await i.getAgentResources(I);return Ke(b)},[i]),L=o.useCallback(async({definition:I,invocationName:b})=>{const D=await i.createAgent(I.ref,{invocationName:b}),G=await i.getAgent(D.id),K=ze(G),R=xe(G);return l(q=>[K,...q]),R&&f(q=>({...q,[K.invocation_id]:R,[K.id]:R})),K},[i]),V=o.useMemo(()=>Ve(i,{resolveOpeningMessage:I=>u[I.invocation_id]??u[I.id]}),[i,u]);return{agents:g,agentDefinitions:p,loadState:j,loadError:E,reload:m,refresh:T,fetchAgentChecklist:P,fetchAgentResources:N,createAgent:L,chatConnector:V}},In=t=>JSON.stringify(t),kt=t=>{const{agent:e,jwt:s,headers:a,urls:r,chatId:c}=t,i=JSON.stringify(a??{}),g=In(r),l=o.useMemo(()=>new Re({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}}),[s,g]);o.useLayoutEffect(()=>{l.setHeaders(a)},[l,i]);const p=o.useCallback(async j=>{const[v,E]=await Promise.all([l.getAgentChecklist(j),l.getAgent(j).catch(()=>null)]);return Je(j,v,E??void 0)},[l]),_=o.useCallback(async j=>{const v=await l.getAgentResources(j);return Ke(v)},[l]),u=o.useCallback(async j=>{const v=await l.getAgentTimeline(j);return mt(v)},[l]);return{connector:o.useMemo(()=>Ve(l,{chatId:c??e.invocation_id})(e),[l,e.invocation_id,c]),fetchAgentChecklist:p,fetchAgentResources:_,fetchAgentTimeline:u}},Rn=3e4,On=(t,e)=>{const s=t.hasRunBefore?e||"This trip":t.tripName.trim()||"A new trip",a=t.destination?` to ${t.destination}`:"",r=t.hasRunBefore?" It has run before.":"";return`${s}${a}.${r}`.trim()},Ln=t=>{switch(t){case C.failed:return U.stopped;case C.complete:return U.complete;default:return U.running}},nt=(t,e)=>{e([ae(t)])},Mn=(t,e)=>t.length===e.length&&t.every((s,a)=>{const r=e[a];return r!==void 0&&s.id===r.id&&s.text===r.text}),yt=({agent:t,invocationId:e,open:s,onClose:a,jwt:r,headers:c,agentUrl:i,agentChecklistUrl:g,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:_,agentConversationUrl:u,chatId:f,enableUpload:j,initialBrief:v,initialPhase:E,initialChecklist:A})=>{const[M,x]=o.useState(f??e),[k,m]=o.useState("chat"),[T,P]=o.useState(!1),{connector:N,fetchAgentChecklist:L,fetchAgentResources:V,fetchAgentTimeline:I}=kt({agent:{...t,invocation_id:e},jwt:r,headers:c,chatId:M,urls:{agentUrl:i,agentChecklistUrl:g,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:_,agentConversationUrl:u}}),b=o.useRef(N),[D,G]=o.useState(E??(v?U.running:Ln(t.status))),[K,R]=o.useState([]),[q,Z]=o.useState(0),[Oe,de]=o.useState(),[ne,ge]=o.useState(null),[se,Le]=o.useState([]),[ke,Q]=o.useState(!1),[ye,ue]=o.useState(null),[Ne,Se]=o.useState(null),[Me,he]=o.useState(!1),[Pe,pe]=o.useState(null),[De,me]=o.useState(A??null),[Ue,_e]=o.useState(!1),[je,h]=o.useState(null),[S,y]=o.useState(!1),[H,ee]=o.useState(!1),[Y,te]=o.useState(!1),fe=o.useRef(S);o.useEffect(()=>{b.current=N},[N]),o.useEffect(()=>{fe.current=S},[S]),o.useEffect(()=>{x(f??e),m("chat"),P(!1),R([]),Z(w=>w+1)},[e,f]),o.useEffect(()=>{if(!s||v)return;const w=b.current.bootstrapConversation;if(!w){nt(b.current.openingMessage(),R);return}let O=!1;return y(!0),(async()=>{try{const W=await w.call(b.current);if(O)return;R(W.map(ae))}catch{O||nt(b.current.openingMessage(),R)}finally{O||y(!1)}})(),()=>{O=!0}},[s,v,e,M]),o.useEffect(()=>{if(!s||v)return;const w=window.setInterval(()=>{const O=b.current.bootstrapConversation;O&&(async()=>{try{const W=await O.call(b.current);if(fe.current)return;const ve=W.map(ae);R(Ye=>Mn(Ye,ve)?Ye:ve)}catch{}})()},Rn);return()=>{window.clearInterval(w)}},[s,v,e,M]);const jt=o.useCallback(w=>{w.checklist&&me(w.checklist),w.phase&&G(w.phase)},[]);o.useEffect(()=>{var w,O;!s||v||A&&A.length>0&&((O=(w=b.current).seedChecklist)==null||O.call(w,A))},[s,v,A]),o.useEffect(()=>{if(!s||v)return;let w=!1;return _e(!(A!=null&&A.length)),h(null),(async()=>{var O,W;try{const ve=await L(e);if(w)return;A!=null&&A.length||(me(ve.checklist),(W=(O=b.current).seedChecklist)==null||W.call(O,ve.checklist))}catch{!w&&!(A!=null&&A.length)&&h(be)}finally{w||_e(!1)}})(),()=>{w=!0}},[s,e,v,A,L]),o.useEffect(()=>{if(!s||!l)return;let w=!1;return Q(!0),ue(null),(async()=>{try{const O=await V(e);w||Le(O)}catch{w||ue(Pt)}finally{w||Q(!1)}})(),()=>{w=!0}},[s,e,l,V]),o.useEffect(()=>{if(!s||!p)return;let w=!1;return he(!0),pe(null),(async()=>{try{const O=await I(e);w||Se(O)}catch{w||pe(it)}finally{w||he(!1)}})(),()=>{w=!0}},[s,e,p,I]),o.useEffect(()=>{if(!s||!v)return;let w=!1;const O={id:`user-brief-${Date.now()}`,author:X.user,text:On(v,t.invocation_name)};return(async()=>{const W=await b.current.start(v);w||(R([ae(b.current.openingMessage()),ae(O),ae(W.message)]),W.checklist&&me(W.checklist),G(W.phase??U.running))})(),()=>{w=!0}},[s,v,t.invocation_name,e]);const At=o.useCallback(w=>{ge(hn(w))},[]),Ct=o.useCallback(w=>{x(w),P(!0),m("chat"),R([]),Z(O=>O+1)},[]),bt=o.useCallback(()=>{m("chat"),P(!1),x(f??e),R([]),Z(w=>w+1)},[e,f]),Et=o.useCallback(w=>{ge(null),de(w),Z(O=>O+1)},[]),Tt=o.useCallback(async()=>{await b.current.stop(),G(U.stopped)},[]),It=De;return n.jsxs(d.Modal,{open:s,closeHandler:a,hideCloseButton:!0,className:"agent-workspace",children:[n.jsxs(d.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(d.Icon,{name:"ask-arbor",size:24})}),n.jsx(d.Modal.Title,{children:t.invocation_name}),n.jsx("span",{className:z("agent-workspace__phase",`agent-workspace__phase--${D}`),children:$t[D]})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(d.Button,{variant:H?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!H,onClick:()=>ee(w=>!w),children:"Checklist"}),n.jsx(d.Button,{variant:Y?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Y,onClick:()=>te(w=>!w),children:"Resources"}),n.jsx(d.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),n.jsxs(d.Modal.Body,{className:z("agent-workspace__body",{"agent-workspace__body--no-checklist":H,"agent-workspace__body--no-resources":Y}),children:[" ",n.jsxs("section",{className:z("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!p&&k==="timeline"}),"aria-label":"Agent",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(d.Heading,{level:4,children:"Agent"}),D===U.running&&n.jsx(d.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Stop",onClick:()=>void Tt(),children:"Stop agent"})]}),p&&n.jsxs(d.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(d.Tabs.Item,{active:k==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>m("chat")},children:"Chat"}),n.jsx(d.Tabs.Item,{active:k==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>m("timeline")},children:"Timeline"})]}),p&&k==="chat"&&T&&n.jsx("div",{className:"agent-workspace__center-back",children:n.jsx(d.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:bt,children:"Back to main chat"})}),p&&k==="timeline"&&n.jsx(gn,{timeline:Ne,isLoading:Me,error:Pe,onOpenChatSession:Ct}),n.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!p&&k!=="chat",children:n.jsx(Zt,{connector:N,phase:D,chatHistory:K,chatSessionKey:q,startQuery:Oe,clarificationMessage:ne,enableUpload:j,onTurn:jt,onAwaitingChange:y,onClarificationPrompt:Et,onDismissClarification:()=>ge(null)})})]}),!H&&n.jsx(en,{checklist:It,isLoading:Ue,error:je,phase:D,canRequestInput:D===U.running&&!S,onAttentionItemClick:At}),!Y&&n.jsx(nn,{resources:se,isLoading:ke,error:ye})]})]})},Pn="Unable to load agent definitions. Please try again.",Dn="Unable to start the agent.",st="Loading agents…",Nt=({open:t,onClose:e,onStart:s,agentDefinitions:a,definitionsState:r="idle",definitionsError:c=null,onRetryDefinitions:i,embedded:g=!1})=>{const l=a[0],[p,_]=o.useState(l),[u,f]=o.useState(""),[j,v]=o.useState(!1),[E,A]=o.useState(null),M=[...a].sort((N,L)=>N.agent_intent.localeCompare(L.agent_intent)).map(N=>({value:N.ref,label:N.agent_intent}));o.useEffect(()=>{t&&(_(l),f(""),v(!1),A(null))},[t,l]);const x=p!==void 0&&u.trim().length>0,k=o.useCallback(N=>{const L=a.find(V=>V.ref===N[0]);L&&_(L)},[a]),m=o.useCallback(async()=>{if(!(!p||!x||j)){v(!0),A(null);try{await s({definition:p,invocationName:u.trim()})}catch(N){A(N instanceof Error?N.message:Dn)}finally{v(!1)}}},[x,p,u,j,s]);if(r==="idle"&&a.length===0||!t)return null;const T=n.jsxs("div",{className:"new-agent__header-title",children:[n.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:n.jsx(d.Icon,{name:"ask-arbor",size:24})}),g?n.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):n.jsx(d.Modal.Title,{children:"Start an agent"})]});let P;return r==="loading"?P=n.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:st}),n.jsx("p",{className:"new-agent__state-message",children:st})]}):r==="error"?P=n.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[n.jsx(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"new-agent__state-message",children:c??Pn}),i?n.jsx(d.Button,{variant:"secondary",size:"S",onClick:i,children:"Try again"}):null]}):p?P=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:N=>{N.preventDefault(),x&&!j&&m()},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(d.SelectDropdown,{id:"new-agent-type",placeholder:"Choose an intent",options:M,selectedValues:[p.ref],onSelectionChange:k}),n.jsx("p",{className:"new-agent__type-description",children:p.description})]}),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(d.TextInput,{id:"new-agent-invocation-name",value:u,placeholder:"What would you like to call your agent?",onChange:N=>f(N.target.value)})]}),E?n.jsx("p",{className:"new-agent__error",role:"alert",children:E}):null,n.jsx("div",{className:"new-agent__actions",children:n.jsx(d.Button,{type:"submit",variant:"primary",disabled:!x||j,iconLeftName:j?"loader":"sparkles",iconLeftScreenReaderText:j?"Starting":void 0,children:j?"Starting…":"Start"})})]}):P=null,g?n.jsxs("div",{className:z("new-agent","new-agent--embedded"),children:[n.jsx("div",{className:"new-agent__header",children:T}),n.jsx("div",{className:"new-agent__body",children:P})]}):n.jsxs(d.Modal,{open:t,closeHandler:e,className:"new-agent",children:[n.jsx(d.Modal.Header,{className:"new-agent__header",children:T}),n.jsx(d.Modal.Body,{className:"new-agent__body",children:P})]})},at=t=>{window.location.assign(t)},Un=({open:t,authToken:e,headers:s,agentDefinitionsUrl:a,agentsUrl:r,closeUrl:c,successUrl:i,onClose:g,onStart:l,embedded:p=!1})=>{const _=JSON.stringify(s??{}),u=o.useMemo(()=>new Re({token:e,headers:s,urls:{agentDefinitions:a,agents:r}}),[e,a,r,_]),[f,j]=o.useState([]),[v,E]=o.useState("loading"),[A,M]=o.useState(null),[x,k]=o.useState(0);o.useEffect(()=>{if(!t)return;let N=!1;return E("loading"),M(null),(async()=>{try{const L=await u.listAgentDefinitions();if(N)return;j(L.map(qe)),E("idle")}catch(L){if(N)return;j([]),M(wt(L)),E("error")}})(),()=>{N=!0}},[u,t,x]);const m=o.useCallback(()=>{g==null||g(),c&&at(c)},[c,g]),T=o.useCallback(async N=>{await u.createAgent(N.definition.ref,{invocationName:N.invocationName}),l==null||l(N),i&&at(i)},[u,l,i]),P=o.useCallback(()=>{k(N=>N+1)},[]);return n.jsx(Nt,{open:t,onClose:m,onStart:T,agentDefinitions:f,definitionsState:v,definitionsError:A,onRetryDefinitions:P,embedded:p})},$n=t=>"agentDefinitionsUrl"in t,St=t=>$n(t)?n.jsx(Un,{...t}):n.jsx(Nt,{...t}),Hn=t=>t!==void 0&&t.some(e=>e.status===$.hitl),Bn=(t,e)=>Hn(e)?C.hitl:t.status,Fn=({column:t,label:e})=>t.statusIcon?n.jsx("span",{className:"agent-view__status-indicator",children:n.jsx(d.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,className:z({"agent-view__progress-icon--spinning":t.statusIcon.spin}),screenReaderText:e})}):n.jsx("span",{className:z("agent-view__dot",{[`agent-view__dot--${t.dotModifier}`]:t.dotModifier}),children:n.jsx(d.Dot,{colour:t.dotColour,label:e})}),zn=({agent:t,agentName:e,column:s,isExpanded:a,isLoading:r,checklist:c,error:i,onToggle:g,onViewAgent:l})=>{const{id:p,invocation_name:_}=t,u=`agent-card-${p}-header`,f=`agent-card-${p}-progress`;return n.jsx("li",{className:z("agent-view__card",{"agent-view__card--expanded":a}),children:n.jsxs(d.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":f,"aria-label":_,id:u,onClick:()=>g(p),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(Fn,{column:s}),n.jsx("span",{className:"agent-view__card-invocation-name",children:_}),n.jsx("span",{className:"agent-view__card-agent-name",children:e}),n.jsx(d.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&n.jsxs("div",{id:f,"aria-labelledby":u,className:"agent-view__card-progress",children:[r&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:oe}),n.jsx("span",{children:oe})]}),!r&&i&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:i}),!r&&!i&&c!==null&&n.jsx(Yt,{checklist:c}),!r&&!i&&c===null&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:oe}),n.jsx("span",{children:oe})]}),n.jsx("div",{className:"agent-view__card-actions",children:n.jsx(d.Button,{variant:"secondary",size:"S",onClick:()=>l==null?void 0:l(t),children:"View agent"})})]})]})})},rt=({column:t,agents:e,expandedAgentId:s,loadingAgentId:a,checklistByInvocationId:r,errorByAgentId:c,definitionNameByRef:i,onToggleAgent:g,onViewAgent:l,isSplit:p=!1})=>n.jsxs("section",{className:z("agent-view__column",{"agent-view__column--split":p}),"aria-label":t.title,children:[n.jsxs("div",{className:"agent-view__column-header",children:[n.jsx(d.Heading,{level:4,children:t.title}),n.jsx("span",{className:"agent-view__column-count",children:e.length})]}),n.jsx("ul",{className:"agent-view__card-list",children:e.map(_=>n.jsx(zn,{agent:_,agentName:Ge(_,i),column:t,isExpanded:s===_.id,isLoading:a===_.id,checklist:r[_.invocation_id]??null,error:c[_.id]??null,onToggle:g,onViewAgent:l},_.id))})]}),Ge=(t,e)=>e.get(t.agent_definition_ref)??t.agent_definition_ref.replace(/_/g," "),Gn=({jwt:t,headers:e,agentDefinitionsUrl:s,agentsUrl:a,agentUrl:r,agentChecklistUrl:c,agentResourcesUrl:i,agentTimelineUrl:g,agentChatUrl:l,agentConversationUrl:p,enableUpload:_,showHeader:u=!1,institutions:f})=>{var je;const j=o.useMemo(()=>({agentDefinitions:s,agents:a,agent:r,agentChecklist:c,...i?{agentResources:i}:{},...g?{agentTimeline:g}:{},agentChat:l,agentConversation:p}),[s,a,r,c,i,g,l,p]),[v,E]=o.useState(null),A=v?(je=f==null?void 0:f.find(h=>h.applicationId===v.application_id))==null?void 0:je.applicationUrl:void 0,M=o.useMemo(()=>{const h={...e??{}};return A?h[ce.arborApplicationUrl]=A:delete h[ce.arborApplicationUrl],h},[e,A]),{agents:x,agentDefinitions:k,loadState:m,loadError:T,reload:P,refresh:N,fetchAgentChecklist:L,createAgent:V}=xt({jwt:t,headers:M,urls:j}),[I,b]=o.useState(!1),[D,G]=o.useState(null),[K,R]=o.useState(null),[q,Z]=o.useState({}),[Oe,de]=o.useState({}),[ne,ge]=o.useState([]),[se,Le]=o.useState([]),ke=o.useMemo(()=>{const h=new Set(x.map(y=>y.application_id)),S=new Map((f??[]).map(y=>[y.applicationId,y.name]));return[...h].sort((y,H)=>(S.get(y)??y).localeCompare(S.get(H)??H)).map(y=>({value:y,label:S.get(y)??y}))},[x,f]),Q=o.useMemo(()=>new Map(k.map(h=>[h.ref,h.display_name])),[k]),ye=o.useMemo(()=>[...new Set(x.map(S=>Ge(S,Q)))].sort((S,y)=>S.localeCompare(y)).map(S=>({value:S,label:S})),[x,Q]),ue=o.useMemo(()=>x.filter(h=>!(ne.length>0&&!ne.includes(h.application_id)||se.length>0&&!se.includes(Ge(h,Q)))),[x,Q,se,ne]),Ne=ke.length>1,Se=ye.length>1,Me=Ne||Se;o.useEffect(()=>{const h=window.setInterval(()=>{N()},6e4);return()=>{window.clearInterval(h)}},[N]),o.useEffect(()=>{if(x.length===0)return;let h=!1;return(async()=>{const S=await Promise.allSettled(x.map(async y=>{const H=await L(y.invocation_id);return{agentId:y.id,invocationId:y.invocation_id,checklist:H.checklist}}));h||(Z(y=>{const H={...y};let ee=!1;for(const Y of S){if(Y.status!=="fulfilled")continue;const{invocationId:te,checklist:fe}=Y.value;JSON.stringify(y[te])!==JSON.stringify(fe)&&(H[te]=fe,ee=!0)}return ee?H:y}),de(y=>{const H={...y};let ee=!1;return S.forEach((Y,te)=>{Y.status==="rejected"&&H[x[te].id]!==be&&(H[x[te].id]=be,ee=!0)}),ee?H:y}))})(),()=>{h=!0}},[x,L]);const he=o.useCallback(async h=>{if(!q[h.invocation_id]){R(h.id),de(S=>{const y={...S};return delete y[h.id],y});try{const S=await L(h.invocation_id);Z(y=>({...y,[h.invocation_id]:S.checklist}))}catch{de(S=>({...S,[h.id]:be}))}finally{R(S=>S===h.id?null:S)}}},[L,q]),Pe=o.useCallback(h=>{if(D===h){G(null);return}const S=x.find(({id:y})=>y===h);S&&(G(h),he(S))},[x,D,he]),pe=o.useMemo(()=>{const h={};for(const S of ue){const y=Bn(S,q[S.invocation_id]);(h[y]??(h[y]=[])).push(S)}return h},[ue,q]),De=o.useCallback(h=>{E(h)},[]),me=o.useCallback(async h=>{const S=await V(h);E(S),b(!1)},[V]),Ue=o.useCallback(()=>{E(null)},[]),_e={expandedAgentId:D,loadingAgentId:K,checklistByInvocationId:q,errorByAgentId:Oe,definitionNameByRef:Q,onToggleAgent:Pe,onViewAgent:De};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[u&&n.jsxs("div",{className:"agent-view__header",children:[n.jsx(d.Heading,{level:1,children:"Agents"}),n.jsx(d.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>b(!0),children:"Start an agent"})]}),x.length>0&&Me&&n.jsxs("div",{className:"agent-view__filters",children:[Ne&&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(d.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:ke,value:ne,onValueChange:ge,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Se&&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(d.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:ye,value:se,onValueChange:Le,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(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"agent-view__state-message",children:T??ct}),n.jsx(d.Button,{variant:"secondary",size:"S",onClick:P,children:"Try again"})]}):m==="loading"&&x.length===0?n.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:Qe}),n.jsx("p",{className:"agent-view__state-message",children:Qe})]}):x.length===0?n.jsx(Gt,{}):n.jsxs("div",{className:"agent-view__board",children:[Rt.map(h=>n.jsx(rt,{column:Ee[h],agents:pe[h]??[],..._e},h)),n.jsx("div",{className:"agent-view__split-column",children:Ot.map(h=>n.jsx(rt,{column:Ee[h],agents:pe[h]??[],isSplit:!0,..._e},h))})]}),v&&n.jsx(yt,{agent:v,invocationId:v.invocation_id,open:!0,jwt:t,headers:M,agentUrl:r,agentChecklistUrl:c,agentResourcesUrl:i,agentTimelineUrl:g,agentChatUrl:l,agentConversationUrl:p,enableUpload:_,initialChecklist:q[v.invocation_id]??null,onClose:Ue},v.id),n.jsx(St,{open:I,onClose:()=>b(!1),onStart:me,agentDefinitions:k})]})},qn=(t,e)=>{const s=Date.now(),a=e.trim()||t.agent_intent;return{id:`agent-${s}`,invocation_id:`inv-${s}`,agent_definition_ref:t.ref,agent_intent:t.agent_intent,invocation_name:a,application_id:Lt,created_by:Mt,status:C["generating-a-response"],context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=Gn;exports.AgentServiceClient=Re;exports.AgentServiceError=ie;exports.AgentView=yt;exports.HttpChatConnector=vt;exports.NewAgentModal=St;exports.buildAgentFromDefinition=qn;exports.createHttpChatConnectorFactory=Ve;exports.mapApiAgent=ze;exports.mapApiAgentDefinition=qe;exports.mapApiAgentStatus=ut;exports.mapApiAgentTimelineResponse=mt;exports.mapApiChecklistEndpointResponse=Je;exports.mapApiChecklistItem=We;exports.mapApiChecklistResponse=_t;exports.mapApiChecklistStatus=ht;exports.mapApiConversationMessages=ft;exports.mapApiOpeningMessage=xe;exports.mapApiResource=pt;exports.mapApiResourcesEndpointResponse=Ke;exports.mapApiTripOption=yn;exports.useAgentService=xt;exports.useAgentWorkspace=kt;
|
|
5
|
+
`):null}},at=t=>{try{return JSON.parse(t)}catch{return}};function Sn(t,e){const s=new FormData;s.append("body",JSON.stringify(t));for(const a of e)s.append("files",a,a.name);return s}const _t=t=>{switch(t){case tt.cancelled:return C.failed;case tt.archived:return C.complete;case C.hitl:case C.complete:case C.failed:case C["generating-a-response"]:return t;default:return C["generating-a-response"]}},ft=t=>{switch(t){case Fe.requires_attention:return $.hitl;case Fe.in_progress:case Fe.available:return $["generating-a-response"];case $.failed:case $.complete:case $.hitl:case $["generating-a-response"]:return t;default:return $["generating-a-response"]}},Je=t=>({ref:t.name,display_name:t.display_name,agent_intent:t.agent_intent??"",description:t.description}),jn=t=>({id:t.id,name:t.name,...t.has_run_before?{hasRunBefore:t.has_run_before}:{}}),An=new Set(Object.values(oe)),Cn=t=>t&&An.has(t)?t:oe.LINK,vt=t=>({uri:t.uri??"",type:Cn(t.type),name:t.name??"",description:t.description??""}),Ve=t=>(Array.isArray(t)?t:t.resources??[]).map(vt),wt=t=>({actionLog:(t.action_log??[]).map(e=>({timestamp:e.timestamp,type:e.type,entry:e.entry,origin:e.origin})),chatSessions:(t.chat_sessions??[]).map(e=>({sessionId:e.session_id,timestamp:e.timestamp}))}),Ke=t=>{var s;const e=t.invocation_id??t.id;return{id:t.id,invocation_id:e,agent_definition_ref:t.agent_definition_ref,...t.agent_intent?{agent_intent:t.agent_intent}:{},invocation_name:((s=t.invocation_name)==null?void 0:s.trim())||t.agent_definition_ref,application_id:t.application_id,...t.application_name?{application_name:t.application_name}:{},created_by:t.created_by,status:_t(t.status),context_ref:t.context_ref??null,checklist_ref:t.checklist_ref??null}},Ye=t=>{var e;return{task:t.task??t.name??t.label??Bt,status:ft(t.status),description:t.description??"",...t.prompt?{prompt:t.prompt}:{},...(e=t.follow_up_prompts)!=null&&e.length?{clarificationPrompts:t.follow_up_prompts}:{}}},bn=t=>Array.isArray(t)?t:t.checklist_items??t.checklist??t.items??[],Xe=(t,e,s)=>{var c;const a=!Array.isArray(e)&&(e.opening_message||(c=e.opening_follow_up_prompts)!=null&&c.length)?e:s,r=a?ye(a):void 0;return{invocation_id:t,checklist:bn(e).map(Ye),...r?{openingMessage:r}:{}}},xt=(t,e)=>{const s=ye(e);return{invocation_id:e.invocation_id??t,checklist:(e.checklist_items??[]).map(Ye),...s?{openingMessage:s}:{}}},ye=t=>{var s,a;const e=(s=t.opening_message)==null?void 0:s.trim();if(e)return{id:dt,author:X.agent,text:e,...(a=t.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:t.opening_follow_up_prompts}:{}}},yt=t=>t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.length>0&&e.message_type!=="tool_request").map(e=>({id:e.message_id,author:e.role==="user"?X.user:X.agent,text:e.content})),En={id:dt,author:X.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 rt=0;const Tn=t=>(rt+=1,`${t}-${Date.now()}-${rt}`),In=t=>{const e=t.destination?` to ${t.destination}`:"";return`Let's get started on ${t.tripName.trim()||t.destination.trim()||"this task"}${e}. What will you do first?`};class kt{constructor(e,s,a={}){this.seededChecklist=[],this.client=e,this.agentId=s,this.chatId=a.chatId??s,this.opening=a.openingMessage??En,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const e=await this.client.getConversation(this.chatId),s=yt(e.messages);return s.length===0?[this.opening]:s}async start(e){return{...await this.exchange(In(e)),phase:U.running}}sendMessage(e,s){return this.exchange(e,s)}async stop(){}seedChecklist(e){this.seededChecklist=e}async exchange(e,s){var i;const a=[{role:wn.user,content:e}],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}]:[]),c={id:r.event_id||Tn("msg-agent"),author:X.agent,text:r.message.content,...(i=r.follow_up_prompts)!=null&&i.length?{followUpPrompts:r.follow_up_prompts}:{}};try{const g=await this.client.getAgent(this.agentId),{checklist:l}=xt(this.agentId,g);return this.seededChecklist=l,{message:c,checklist:l}}catch{return{message:c,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const Qe=(t,e)=>s=>{var a,r;return new kt(t,s.invocation_id,{model:e==null?void 0:e.model,chatId:((a=e==null?void 0:e.resolveChatId)==null?void 0:a.call(e,s))??(e==null?void 0:e.chatId)??s.invocation_id,openingMessage:((r=e==null?void 0:e.resolveOpeningMessage)==null?void 0:r.call(e,s))??(e==null?void 0:e.openingMessage)})},Nt=t=>t instanceof ce?t.message:t instanceof TypeError?"Network error while contacting the agent service.":t instanceof Error&&t.message?t.message:ut,Rn=t=>{const e={};for(const s of t){const a=ye(s);if(!a)continue;const r=s.invocation_id??s.id;e[r]=a,e[s.id]=a}return e},On=t=>JSON.stringify(t),qe=(t,e)=>JSON.stringify(t)===JSON.stringify(e),St=t=>{const{jwt:e,headers:s,urls:a}=t,r=JSON.stringify(s??{}),c=On(a),i=o.useMemo(()=>new Oe({token:e,headers:s,urls:a}),[e,c]);o.useLayoutEffect(()=>{i.setHeaders(s)},[i,r]);const[g,l]=o.useState([]),[p,f]=o.useState([]),[u,v]=o.useState({}),[j,w]=o.useState("loading"),[E,A]=o.useState(null),[L,x]=o.useState(0),y=o.useCallback((I,b)=>{const D=I.map(Ke),G=b.map(Je),K=Rn(I);l(O=>qe(O,D)?O:D),f(O=>qe(O,G)?O:G),v(O=>qe(O,K)?O:K),w("idle"),A(null)},[]);o.useEffect(()=>{let I=!1;return w("loading"),A(null),(async()=>{try{const[b,D]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);if(I)return;y(b,D)}catch(b){if(I)return;l([]),f([]),v({}),w("error"),A(Nt(b))}})(),()=>{I=!0}},[y,i,L]);const m=o.useCallback(()=>{x(I=>I+1)},[]),T=o.useCallback(async()=>{try{const[I,b]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);y(I,b)}catch{}},[y,i]),P=o.useCallback(async I=>{const[b,D]=await Promise.all([i.getAgentChecklist(I),i.getAgent(I).catch(()=>null)]);return Xe(I,b,D??void 0)},[i]),N=o.useCallback(async I=>{const b=await i.getAgentResources(I);return Ve(b)},[i]),M=o.useCallback(async({definition:I,invocationName:b})=>{const D=await i.createAgent(I.ref,{invocationName:b}),G=await i.getAgent(D.id),K=Ke(G),O=ye(G);return l(q=>[K,...q]),O&&v(q=>({...q,[K.invocation_id]:O,[K.id]:O})),K},[i]),V=o.useMemo(()=>Qe(i,{resolveOpeningMessage:I=>u[I.invocation_id]??u[I.id]}),[i,u]);return{agents:g,agentDefinitions:p,loadState:j,loadError:E,reload:m,refresh:T,fetchAgentChecklist:P,fetchAgentResources:N,createAgent:M,chatConnector:V}},Ln=t=>JSON.stringify(t),jt=t=>{const{agent:e,jwt:s,headers:a,urls:r,chatId:c}=t,i=JSON.stringify(a??{}),g=Ln(r),l=o.useMemo(()=>new Oe({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}}),[s,g]);o.useLayoutEffect(()=>{l.setHeaders(a)},[l,i]);const p=o.useCallback(async j=>{const[w,E]=await Promise.all([l.getAgentChecklist(j),l.getAgent(j).catch(()=>null)]);return Xe(j,w,E??void 0)},[l]),f=o.useCallback(async j=>{const w=await l.getAgentResources(j);return Ve(w)},[l]),u=o.useCallback(async j=>{const w=await l.getAgentTimeline(j);return wt(w)},[l]);return{connector:o.useMemo(()=>Qe(l,{chatId:c??e.invocation_id})(e),[l,e.invocation_id,c]),fetchAgentChecklist:p,fetchAgentResources:f,fetchAgentTimeline:u}},Mn=3e4,Pn=(t,e)=>{const s=t.hasRunBefore?e||"This trip":t.tripName.trim()||"A new trip",a=t.destination?` to ${t.destination}`:"",r=t.hasRunBefore?" It has run before.":"";return`${s}${a}.${r}`.trim()},Dn=t=>{switch(t){case C.failed:return U.stopped;case C.complete:return U.complete;default:return U.running}},ot=(t,e)=>{e([re(t)])},Un=(t,e)=>t.length===e.length&&t.every((s,a)=>{const r=e[a];return r!==void 0&&s.id===r.id&&s.text===r.text}),At=({agent:t,invocationId:e,open:s,onClose:a,jwt:r,headers:c,agentUrl:i,agentChecklistUrl:g,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:f,agentConversationUrl:u,chatId:v,enableUpload:j,initialBrief:w,initialPhase:E,initialChecklist:A})=>{const[L,x]=o.useState(v??e),[y,m]=o.useState("chat"),[T,P]=o.useState(!1),{connector:N,fetchAgentChecklist:M,fetchAgentResources:V,fetchAgentTimeline:I}=jt({agent:{...t,invocation_id:e},jwt:r,headers:c,chatId:L,urls:{agentUrl:i,agentChecklistUrl:g,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:f,agentConversationUrl:u}}),b=o.useRef(N),[D,G]=o.useState(E??(w?U.running:Dn(t.status))),[K,O]=o.useState([]),[q,Z]=o.useState(0),[Le,ge]=o.useState(),[se,ue]=o.useState(null),[ae,Me]=o.useState([]),[ke,Q]=o.useState(!1),[Ne,he]=o.useState(null),[ee,Se]=o.useState(null),[Pe,pe]=o.useState(!1),[De,me]=o.useState(null),[Ue,_e]=o.useState(A??null),[$e,fe]=o.useState(!1),[je,h]=o.useState(null),[S,k]=o.useState(!1),[H,te]=o.useState(!1),[Y,ne]=o.useState(!1),ve=o.useRef(S);o.useEffect(()=>{b.current=N},[N]),o.useEffect(()=>{ve.current=S},[S]),o.useEffect(()=>{x(v??e),m("chat"),P(!1),O([]),Z(_=>_+1)},[e,v]),o.useEffect(()=>{if(!s||w)return;const _=b.current.bootstrapConversation;if(!_){ot(b.current.openingMessage(),O);return}let R=!1;return k(!0),(async()=>{try{const W=await _.call(b.current);if(R)return;O(W.map(re))}catch{R||ot(b.current.openingMessage(),O)}finally{R||k(!1)}})(),()=>{R=!0}},[s,w,e,L]),o.useEffect(()=>{if(!s||w)return;const _=window.setInterval(()=>{const R=b.current.bootstrapConversation;R&&(async()=>{try{const W=await R.call(b.current);if(ve.current)return;const we=W.map(re);O(et=>Un(et,we)?et:we)}catch{}})()},Mn);return()=>{window.clearInterval(_)}},[s,w,e,L]);const Et=o.useCallback(_=>{_.checklist&&_e(_.checklist),_.phase&&G(_.phase)},[]);o.useEffect(()=>{var _,R;!s||w||A&&A.length>0&&((R=(_=b.current).seedChecklist)==null||R.call(_,A))},[s,w,A]),o.useEffect(()=>{if(!s||w)return;let _=!1;return fe(!(A!=null&&A.length)),h(null),(async()=>{var R,W;try{const we=await M(e);if(_)return;A!=null&&A.length||(_e(we.checklist),(W=(R=b.current).seedChecklist)==null||W.call(R,we.checklist))}catch{!_&&!(A!=null&&A.length)&&h(Ee)}finally{_||fe(!1)}})(),()=>{_=!0}},[s,e,w,A,M]),o.useEffect(()=>{if(!s||!l)return;let _=!1;return Q(!0),he(null),(async()=>{try{const R=await V(e);_||Me(R)}catch{_||he($t)}finally{_||Q(!1)}})(),()=>{_=!0}},[s,e,l,V]),o.useEffect(()=>{if(!s||!p)return;let _=!1;return pe(!0),me(null),(async()=>{try{const R=await I(e);_||Se(R)}catch{_||me(gt)}finally{_||pe(!1)}})(),()=>{_=!0}},[s,e,p,I]),o.useEffect(()=>{if(!s||!w)return;let _=!1;const R={id:`user-brief-${Date.now()}`,author:X.user,text:Pn(w,t.invocation_name)};return(async()=>{const W=await b.current.start(w);_||(O([re(b.current.openingMessage()),re(R),re(W.message)]),W.checklist&&_e(W.checklist),G(W.phase??U.running))})(),()=>{_=!0}},[s,w,t.invocation_name,e]);const Tt=o.useCallback(_=>{ue(_n(_))},[]),He=v??e,Ae=ee==null?void 0:ee.chatSessions,Ze=Ae!=null&&Ae.length?Ae.reduce((_,R)=>Date.parse(R.timestamp)<Date.parse(_.timestamp)?R:_).sessionId:void 0,Be=o.useCallback(()=>{m("chat"),P(!1),L!==He&&(x(He),O([]),Z(_=>_+1))},[L,He]),It=o.useCallback(_=>{if(_===Ze){Be();return}x(_),P(!0),m("chat"),O([]),Z(R=>R+1)},[Ze,Be]),Rt=o.useCallback(_=>{ue(null),ge(_),Z(R=>R+1)},[]),Ot=o.useCallback(async()=>{await b.current.stop(),G(U.stopped)},[]),Lt=Ue;return n.jsxs(d.Modal,{open:s,closeHandler:a,hideCloseButton:!0,className:"agent-workspace",children:[n.jsxs(d.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(d.Icon,{name:"ask-arbor",size:24})}),n.jsx(d.Modal.Title,{children:t.invocation_name}),n.jsx("span",{className:z("agent-workspace__phase",`agent-workspace__phase--${D}`),children:Ft[D]})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(d.Button,{variant:H?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!H,onClick:()=>te(_=>!_),children:"Checklist"}),n.jsx(d.Button,{variant:Y?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Y,onClick:()=>ne(_=>!_),children:"Resources"}),n.jsx(d.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),n.jsxs(d.Modal.Body,{className:z("agent-workspace__body",{"agent-workspace__body--no-checklist":H,"agent-workspace__body--no-resources":Y}),children:[" ",n.jsxs("section",{className:z("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!p&&y==="timeline"}),"aria-label":"Agent",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(d.Heading,{level:4,children:"Agent"}),D===U.running&&n.jsx(d.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Stop",onClick:()=>void Ot(),children:"Stop agent"})]}),p&&n.jsxs(d.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(d.Tabs.Item,{active:y==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>m("chat")},children:"Chat"}),n.jsx(d.Tabs.Item,{active:y==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>m("timeline")},children:"Timeline"})]}),p&&y==="chat"&&T&&n.jsx("div",{className:"agent-workspace__center-back",children:n.jsx(d.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:Be,children:"Back to main chat"})}),p&&y==="timeline"&&n.jsx(pn,{timeline:ee,isLoading:Pe,error:De,onOpenChatSession:It}),n.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!p&&y!=="chat",children:n.jsx(nn,{connector:N,phase:D,chatHistory:K,chatSessionKey:q,startQuery:Le,clarificationMessage:se,enableUpload:j,onTurn:Et,onAwaitingChange:k,onClarificationPrompt:Rt,onDismissClarification:()=>ue(null)})})]}),!H&&n.jsx(sn,{checklist:Lt,isLoading:$e,error:je,phase:D,canRequestInput:D===U.running&&!S,onAttentionItemClick:Tt}),!Y&&n.jsx(rn,{resources:ae,isLoading:ke,error:Ne})]})]})},$n="Unable to load agent definitions. Please try again.",Hn="Unable to start the agent.",it="Loading agents…",Ct=({open:t,onClose:e,onStart:s,agentDefinitions:a,definitionsState:r="idle",definitionsError:c=null,onRetryDefinitions:i,embedded:g=!1})=>{const l=a[0],[p,f]=o.useState(l),[u,v]=o.useState(""),[j,w]=o.useState(!1),[E,A]=o.useState(null),L=[...a].sort((N,M)=>N.display_name.localeCompare(M.display_name)).map(N=>({value:N.ref,label:N.display_name}));o.useEffect(()=>{t&&(f(l),v(""),w(!1),A(null))},[t,l]);const x=p!==void 0&&u.trim().length>0,y=o.useCallback(N=>{const M=a.find(V=>V.ref===N[0]);M&&f(M)},[a]),m=o.useCallback(async()=>{if(!(!p||!x||j)){w(!0),A(null);try{await s({definition:p,invocationName:u.trim()})}catch(N){A(N instanceof Error?N.message:Hn)}finally{w(!1)}}},[x,p,u,j,s]);if(r==="idle"&&a.length===0||!t)return null;const T=n.jsxs("div",{className:"new-agent__header-title",children:[n.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:n.jsx(d.Icon,{name:"ask-arbor",size:24})}),g?n.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):n.jsx(d.Modal.Title,{children:"Start an agent"})]});let P;return r==="loading"?P=n.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:it}),n.jsx("p",{className:"new-agent__state-message",children:it})]}):r==="error"?P=n.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[n.jsx(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"new-agent__state-message",children:c??$n}),i?n.jsx(d.Button,{variant:"secondary",size:"S",onClick:i,children:"Try again"}):null]}):p?P=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:N=>{N.preventDefault(),x&&!j&&m()},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(d.SelectDropdown,{id:"new-agent-type",placeholder:"Choose an agent",options:L,selectedValues:[p.ref],onSelectionChange:y}),n.jsx("p",{className:"new-agent__type-description",children:p.description})]}),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(d.TextInput,{id:"new-agent-invocation-name",value:u,placeholder:"What would you like to call your agent?",onChange:N=>v(N.target.value)})]}),E?n.jsx("p",{className:"new-agent__error",role:"alert",children:E}):null,n.jsx("div",{className:"new-agent__actions",children:n.jsx(d.Button,{type:"submit",variant:"primary",disabled:!x||j,iconLeftName:j?"loader":"sparkles",iconLeftScreenReaderText:j?"Starting":void 0,children:j?"Starting…":"Start"})})]}):P=null,g?n.jsxs("div",{className:z("new-agent","new-agent--embedded"),children:[n.jsx("div",{className:"new-agent__header",children:T}),n.jsx("div",{className:"new-agent__body",children:P})]}):n.jsxs(d.Modal,{open:t,closeHandler:e,className:"new-agent",children:[n.jsx(d.Modal.Header,{className:"new-agent__header",children:T}),n.jsx(d.Modal.Body,{className:"new-agent__body",children:P})]})},ct=t=>{window.location.assign(t)},Bn=({open:t,authToken:e,headers:s,agentDefinitionsUrl:a,agentsUrl:r,closeUrl:c,successUrl:i,onClose:g,onStart:l,embedded:p=!1})=>{const f=JSON.stringify(s??{}),u=o.useMemo(()=>new Oe({token:e,headers:s,urls:{agentDefinitions:a,agents:r}}),[e,a,r,f]),[v,j]=o.useState([]),[w,E]=o.useState("loading"),[A,L]=o.useState(null),[x,y]=o.useState(0);o.useEffect(()=>{if(!t)return;let N=!1;return E("loading"),L(null),(async()=>{try{const M=await u.listAgentDefinitions();if(N)return;j(M.map(Je)),E("idle")}catch(M){if(N)return;j([]),L(Nt(M)),E("error")}})(),()=>{N=!0}},[u,t,x]);const m=o.useCallback(()=>{g==null||g(),c&&ct(c)},[c,g]),T=o.useCallback(async N=>{await u.createAgent(N.definition.ref,{invocationName:N.invocationName}),l==null||l(N),i&&ct(i)},[u,l,i]),P=o.useCallback(()=>{y(N=>N+1)},[]);return n.jsx(Ct,{open:t,onClose:m,onStart:T,agentDefinitions:v,definitionsState:w,definitionsError:A,onRetryDefinitions:P,embedded:p})},Fn=t=>"agentDefinitionsUrl"in t,bt=t=>Fn(t)?n.jsx(Bn,{...t}):n.jsx(Ct,{...t}),zn=t=>t!==void 0&&t.some(e=>e.status===$.hitl),Gn=(t,e)=>zn(e)?C.hitl:t.status,qn=({column:t,label:e})=>t.statusIcon?n.jsx("span",{className:"agent-view__status-indicator",children:n.jsx(d.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,className:z({"agent-view__progress-icon--spinning":t.statusIcon.spin}),screenReaderText:e})}):n.jsx("span",{className:z("agent-view__dot",{[`agent-view__dot--${t.dotModifier}`]:t.dotModifier}),children:n.jsx(d.Dot,{colour:t.dotColour,label:e})}),Kn=({agent:t,agentName:e,column:s,isExpanded:a,isLoading:r,checklist:c,error:i,onToggle:g,onViewAgent:l})=>{const{id:p,invocation_name:f}=t,u=`agent-card-${p}-header`,v=`agent-card-${p}-progress`;return n.jsx("li",{className:z("agent-view__card",{"agent-view__card--expanded":a}),children:n.jsxs(d.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":v,"aria-label":f,id:u,onClick:()=>g(p),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(qn,{column:s}),n.jsx("span",{className:"agent-view__card-invocation-name",children:f}),n.jsx("span",{className:"agent-view__card-agent-name",children:e}),n.jsx(d.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&n.jsxs("div",{id:v,"aria-labelledby":u,className:"agent-view__card-progress",children:[r&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:ie}),n.jsx("span",{children:ie})]}),!r&&i&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:i}),!r&&!i&&c!==null&&n.jsx(Zt,{checklist:c}),!r&&!i&&c===null&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:ie}),n.jsx("span",{children:ie})]}),n.jsx("div",{className:"agent-view__card-actions",children:n.jsx(d.Button,{variant:"secondary",size:"S",onClick:()=>l==null?void 0:l(t),children:"View agent"})})]})]})})},lt=({column:t,agents:e,expandedAgentId:s,loadingAgentId:a,checklistByInvocationId:r,errorByAgentId:c,definitionNameByRef:i,onToggleAgent:g,onViewAgent:l,isSplit:p=!1})=>n.jsxs("section",{className:z("agent-view__column",{"agent-view__column--split":p}),"aria-label":t.title,children:[n.jsxs("div",{className:"agent-view__column-header",children:[n.jsx(d.Heading,{level:4,children:t.title}),n.jsx("span",{className:"agent-view__column-count",children:e.length})]}),n.jsx("ul",{className:"agent-view__card-list",children:e.map(f=>n.jsx(Kn,{agent:f,agentName:We(f,i),column:t,isExpanded:s===f.id,isLoading:a===f.id,checklist:r[f.invocation_id]??null,error:c[f.id]??null,onToggle:g,onViewAgent:l},f.id))})]}),We=(t,e)=>e.get(t.agent_definition_ref)??t.agent_definition_ref.replace(/_/g," "),Wn=({jwt:t,headers:e,agentDefinitionsUrl:s,agentsUrl:a,agentUrl:r,agentChecklistUrl:c,agentResourcesUrl:i,agentTimelineUrl:g,agentChatUrl:l,agentConversationUrl:p,enableUpload:f,showHeader:u=!1,institutions:v})=>{var je;const j=o.useMemo(()=>({agentDefinitions:s,agents:a,agent:r,agentChecklist:c,...i?{agentResources:i}:{},...g?{agentTimeline:g}:{},agentChat:l,agentConversation:p}),[s,a,r,c,i,g,l,p]),[w,E]=o.useState(null),A=w?(je=v==null?void 0:v.find(h=>h.applicationId===w.application_id))==null?void 0:je.applicationUrl:void 0,L=o.useMemo(()=>{const h={...e??{}};return A?h[le.arborApplicationUrl]=A:delete h[le.arborApplicationUrl],h},[e,A]),{agents:x,agentDefinitions:y,loadState:m,loadError:T,reload:P,refresh:N,fetchAgentChecklist:M,createAgent:V}=St({jwt:t,headers:L,urls:j}),[I,b]=o.useState(!1),[D,G]=o.useState(null),[K,O]=o.useState(null),[q,Z]=o.useState({}),[Le,ge]=o.useState({}),[se,ue]=o.useState([]),[ae,Me]=o.useState([]),ke=o.useMemo(()=>{const h=new Set(x.map(k=>k.application_id)),S=new Map((v??[]).map(k=>[k.applicationId,k.name]));return[...h].sort((k,H)=>(S.get(k)??k).localeCompare(S.get(H)??H)).map(k=>({value:k,label:S.get(k)??k}))},[x,v]),Q=o.useMemo(()=>new Map(y.map(h=>[h.ref,h.display_name])),[y]),Ne=o.useMemo(()=>[...new Set(x.map(S=>We(S,Q)))].sort((S,k)=>S.localeCompare(k)).map(S=>({value:S,label:S})),[x,Q]),he=o.useMemo(()=>x.filter(h=>!(se.length>0&&!se.includes(h.application_id)||ae.length>0&&!ae.includes(We(h,Q)))),[x,Q,ae,se]),ee=ke.length>1,Se=Ne.length>1,Pe=ee||Se;o.useEffect(()=>{const h=window.setInterval(()=>{N()},6e4);return()=>{window.clearInterval(h)}},[N]),o.useEffect(()=>{if(x.length===0)return;let h=!1;return(async()=>{const S=await Promise.allSettled(x.map(async k=>{const H=await M(k.invocation_id);return{agentId:k.id,invocationId:k.invocation_id,checklist:H.checklist}}));h||(Z(k=>{const H={...k};let te=!1;for(const Y of S){if(Y.status!=="fulfilled")continue;const{invocationId:ne,checklist:ve}=Y.value;JSON.stringify(k[ne])!==JSON.stringify(ve)&&(H[ne]=ve,te=!0)}return te?H:k}),ge(k=>{const H={...k};let te=!1;return S.forEach((Y,ne)=>{Y.status==="rejected"&&H[x[ne].id]!==Ee&&(H[x[ne].id]=Ee,te=!0)}),te?H:k}))})(),()=>{h=!0}},[x,M]);const pe=o.useCallback(async h=>{if(!q[h.invocation_id]){O(h.id),ge(S=>{const k={...S};return delete k[h.id],k});try{const S=await M(h.invocation_id);Z(k=>({...k,[h.invocation_id]:S.checklist}))}catch{ge(S=>({...S,[h.id]:Ee}))}finally{O(S=>S===h.id?null:S)}}},[M,q]),De=o.useCallback(h=>{if(D===h){G(null);return}const S=x.find(({id:k})=>k===h);S&&(G(h),pe(S))},[x,D,pe]),me=o.useMemo(()=>{const h={};for(const S of he){const k=Gn(S,q[S.invocation_id]);(h[k]??(h[k]=[])).push(S)}return h},[he,q]),Ue=o.useCallback(h=>{E(h)},[]),_e=o.useCallback(async h=>{const S=await V(h);E(S),b(!1)},[V]),$e=o.useCallback(()=>{E(null)},[]),fe={expandedAgentId:D,loadingAgentId:K,checklistByInvocationId:q,errorByAgentId:Le,definitionNameByRef:Q,onToggleAgent:De,onViewAgent:Ue};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[u&&n.jsxs("div",{className:"agent-view__header",children:[n.jsx(d.Heading,{level:1,children:"Agents"}),n.jsx(d.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>b(!0),children:"Start an agent"})]}),x.length>0&&Pe&&n.jsxs("div",{className:"agent-view__filters",children:[ee&&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(d.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:ke,value:se,onValueChange:ue,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Se&&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(d.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:Ne,value:ae,onValueChange:Me,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(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"agent-view__state-message",children:T??ut}),n.jsx(d.Button,{variant:"secondary",size:"S",onClick:P,children:"Try again"})]}):m==="loading"&&x.length===0?n.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:nt}),n.jsx("p",{className:"agent-view__state-message",children:nt})]}):x.length===0?n.jsx(Wt,{}):n.jsxs("div",{className:"agent-view__board",children:[Mt.map(h=>n.jsx(lt,{column:Te[h],agents:me[h]??[],...fe},h)),n.jsx("div",{className:"agent-view__split-column",children:Pt.map(h=>n.jsx(lt,{column:Te[h],agents:me[h]??[],isSplit:!0,...fe},h))})]}),w&&n.jsx(At,{agent:w,invocationId:w.invocation_id,open:!0,jwt:t,headers:L,agentUrl:r,agentChecklistUrl:c,agentResourcesUrl:i,agentTimelineUrl:g,agentChatUrl:l,agentConversationUrl:p,enableUpload:f,initialChecklist:q[w.invocation_id]??null,onClose:$e},w.id),n.jsx(bt,{open:I,onClose:()=>b(!1),onStart:_e,agentDefinitions:y})]})},Jn=(t,e)=>{const s=Date.now(),a=e.trim()||t.agent_intent;return{id:`agent-${s}`,invocation_id:`inv-${s}`,agent_definition_ref:t.ref,agent_intent:t.agent_intent,invocation_name:a,application_id:Dt,created_by:Ut,status:C["generating-a-response"],context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=Wn;exports.AgentServiceClient=Oe;exports.AgentServiceError=ce;exports.AgentView=At;exports.HttpChatConnector=kt;exports.NewAgentModal=bt;exports.buildAgentFromDefinition=Jn;exports.createHttpChatConnectorFactory=Qe;exports.mapApiAgent=Ke;exports.mapApiAgentDefinition=Je;exports.mapApiAgentStatus=_t;exports.mapApiAgentTimelineResponse=wt;exports.mapApiChecklistEndpointResponse=Xe;exports.mapApiChecklistItem=Ye;exports.mapApiChecklistResponse=xt;exports.mapApiChecklistStatus=ft;exports.mapApiConversationMessages=yt;exports.mapApiOpeningMessage=ye;exports.mapApiResource=vt;exports.mapApiResourcesEndpointResponse=Ve;exports.mapApiTripOption=jn;exports.useAgentService=St;exports.useAgentWorkspace=jt;
|