@arbor-education/agent-view-frontend 0.4.6 → 0.4.8
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 +4 -4
- package/dist/index.d.ts +40 -12
- package/dist/index.js +1621 -1458
- package/dist/style.css +1 -1
- package/package.json +2 -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"),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(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),o=require("react"),J=require("classnames"),d=require("@arbor-education/design-system.components"),me=require("@arbor-education/ask-arbor-chat-panel"),A={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},B={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},H={briefing:"briefing",running:"running",stopped:"stopped",complete:"complete"},Z={agent:"agent",user:"user",system:"system"},re={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",link:"link"},gt={cancelled:"cancelled",archived:"archived"},Xe={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},V={[B.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[B.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[B.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[B["generating-a-response"]]:{label:"Generating a response",icon:"sparkles",color:"var(--color-brand-600)"}},He={[A["generating-a-response"]]:{status:A["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:V["generating-a-response"].icon,color:V["generating-a-response"].color}},[A.hitl]:{status:A.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:V.hitl.icon,color:V.hitl.color}},[A.complete]:{status:A.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:V.complete.icon,color:V.complete.color}},[A.failed]:{status:A.failed,title:"Failed",dotColour:"salmon",statusIcon:{name:V.failed.icon,color:V.failed.color}}},Zt=[A["generating-a-response"],A.hitl],es=[A.complete,A.failed],ts="m4",ss="1",yt="msg-opening",$e="Unable to load agent tasks. Please try again.",ns="Unable to load the resources for this agent",as="Unable to load this document. Please try again.",St="Unable to load the timeline for this agent",rs="Something went wrong. Please try again.",Nt="Unable to load agents. Please try again.",he="Loading tasks…",ht="Loading agents…",os="Task",is={[H.briefing]:"Briefing",[H.running]:"Working",[H.stopped]:"Stopped",[H.complete]:"Complete"},ls=[A["generating-a-response"],A.hitl,A.complete,A.failed],cs={[A["generating-a-response"]]:"Agents currently working on tasks for you.",[A.hitl]:"Agents that need your input before they can continue.",[A.complete]:"Agents that have finished their work.",[A.failed]:"Agents that failed or were stopped."},ds=()=>s.jsxs("svg",{className:"agent-view__empty-illustration",viewBox:"0 0 360 240",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Preview of the agents board layout",children:[s.jsx("rect",{x:"0",y:"0",width:"360",height:"240",rx:"12",fill:"var(--color-grey-100)"}),s.jsx("rect",{x:"16",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"130",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"244",y:"16",width:"100",height:"100",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"244",y:"124",width:"100",height:"100",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"28",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("rect",{x:"28",y:"96",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("rect",{x:"142",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-semantic-warning-050)"}),s.jsx("circle",{cx:"40",cy:"70",r:"4",fill:"var(--color-brand-600)"}),s.jsx("circle",{cx:"40",cy:"114",r:"4",fill:"var(--color-brand-600)"}),s.jsx("circle",{cx:"154",cy:"70",r:"4",fill:"var(--color-semantic-warning-600)"}),s.jsx("circle",{cx:"256",cy:"52",r:"4",fill:"var(--color-grey-400)"}),s.jsx("circle",{cx:"256",cy:"160",r:"4",fill:"var(--color-semantic-destructive-500)"})]}),us=({status:t})=>{const e=He[t];return e.statusIcon?s.jsx(d.Icon,{name:e.statusIcon.name,size:16,color:e.statusIcon.color,screenReaderText:e.title}):s.jsx(d.Dot,{colour:e.dotColour,label:e.title})},gs=()=>s.jsxs("section",{className:"agent-view__empty","aria-label":"About the agents board",children:[s.jsxs("div",{className:"agent-view__empty-content",children:[s.jsx(d.Heading,{level:4,children:"Your agents board"}),s.jsx("p",{className:"agent-view__empty-lead",children:"When you start an agent, it appears here so you can track progress at a glance. Agents move between columns as their status changes."}),s.jsx("ul",{className:"agent-view__empty-columns",children:ls.map(t=>{const e=He[t];return s.jsxs("li",{className:"agent-view__empty-column",children:[s.jsx("span",{className:"agent-view__empty-column-indicator",children:s.jsx(us,{status:t})}),s.jsxs("span",{className:"agent-view__empty-column-text",children:[s.jsx("span",{className:"agent-view__empty-column-title",children:e.title}),s.jsx("span",{className:"agent-view__empty-column-description",children:cs[t]})]})]},t)})}),s.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",s.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),s.jsx("div",{className:"agent-view__empty-visual",children:s.jsx(ds,{})})]}),hs=(t,e)=>({...t,...e.length>0?{children:e}:{}}),jt=t=>{const e=[],n=[];for(const a of t){const r=a.children?jt(a.children):{needsInput:[],tasks:[]};if(e.push(...r.needsInput),a.status===B.hitl){e.push({...a,children:void 0});continue}n.push(hs(a,r.tasks))}return{needsInput:e,tasks:n}},ps=t=>t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{const a=e.item.status===B.hitl,r=n.item.status===B.hitl;return a!==r?a?-1:1:e.index-n.index}).map(({item:e})=>e),Qe=2,ms=t=>{if(!t)return{canScrollUp:!1,canScrollDown:!1};const e=t.scrollHeight-t.clientHeight;return e<=Qe?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:t.scrollTop>Qe,canScrollDown:t.scrollTop<e-Qe}},_s=(t,e)=>{if(!t||!e)return null;const n=t.getBoundingClientRect(),a=e.getBoundingClientRect();return{top:a.top-n.top,left:a.left-n.left,width:a.width,height:a.height}},ze=({children:t,className:e,contentClassName:n,scrollSelector:a,style:r,"aria-label":l})=>{const i=o.useRef(null),u=o.useRef(null),[c,v]=o.useState(!1),[f,h]=o.useState(!1),[p,O]=o.useState(null),w=()=>{var y;return a?((y=i.current)==null?void 0:y.querySelector(a))??null:u.current},j=()=>{const y=w(),k=ms(y);if(v(_=>_===k.canScrollUp?_:k.canScrollUp),h(_=>_===k.canScrollDown?_:k.canScrollDown),a){const _=_s(i.current,y);O(C=>(C==null?void 0:C.top)===(_==null?void 0:_.top)&&(C==null?void 0:C.left)===(_==null?void 0:_.left)&&(C==null?void 0:C.width)===(_==null?void 0:_.width)&&(C==null?void 0:C.height)===(_==null?void 0:_.height)?C:_)}else O(_=>_===null?_:null)};o.useLayoutEffect(()=>{j()}),o.useEffect(()=>{const y=i.current;if(!y)return;let k=null,_=null;const C=()=>{k==null||k.removeEventListener("scroll",j),_==null||_.disconnect(),_=null,k=null},R=M=>{if(M===k){j();return}if(C(),k=M,!k){j();return}k.addEventListener("scroll",j,{passive:!0}),_=new ResizeObserver(()=>j()),_.observe(k),k.firstElementChild instanceof HTMLElement&&_.observe(k.firstElementChild),j()};R(w());const T=new MutationObserver(()=>{R(w())});return T.observe(y,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",j),()=>{window.removeEventListener("resize",j),T.disconnect(),C()}},[a]);const N=y=>{const k=w();if(!k)return;const _=Math.max(k.clientHeight*.75,120);k.scrollBy({top:y==="up"?-_:_,behavior:"smooth"})},P=s.jsxs(s.Fragment,{children:[c&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--top","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--top","aria-label":"Scroll up",onClick:()=>N("up"),children:s.jsx(d.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),f&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>N("down"),children:s.jsx(d.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return s.jsx("div",{ref:i,className:J("scrollable-region",e),style:r,"aria-label":l,children:a?s.jsxs(s.Fragment,{children:[t,p&&(c||f)&&s.jsx("div",{className:"scrollable-region__overlay",style:{top:p.top,left:p.left,width:p.width,height:p.height},children:P})]}):s.jsxs(s.Fragment,{children:[P,s.jsx("div",{ref:u,className:J("scrollable-region__viewport",n),children:t})]})})},fs=48,vs=({checklist:t})=>{const e=o.useRef(null),n=o.useRef(!1);return o.useLayoutEffect(()=>{const a=e.current;if(!a)return;const r=a.scrollHeight-a.scrollTop-a.clientHeight;(!n.current||r<=fs)&&(a.scrollTop=a.scrollHeight,n.current=!0)},[t]),t.length===0?s.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):s.jsx(ze,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:s.jsx("ul",{ref:e,className:"agent-view__progress-list","aria-label":"Agent tasks",children:ps(t).map(a=>{const r=V[a.status];return s.jsxs("li",{className:J("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[s.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`}),s.jsxs("div",{className:"agent-view__progress-item-content",children:[s.jsx("span",{className:"agent-view__progress-label",children:a.task}),a.status!==B.complete&&s.jsx("span",{className:"agent-view__progress-description",children:a.description})]})]},a.task)})})})},ws=({prompts:t,classNamePrefix:e="agent-workspace",onSelect:n})=>t.length===0?null:s.jsx("div",{className:`${e}__chips`,children:t.map(a=>s.jsx("button",{type:"button",className:`${e}__chip`,onClick:()=>n(a),children:a},a))});class xs{constructor(e,n){this.connector=e,this.canSend=n.canSend,this.onTurn=n.onTurn,this.onAwaitingChange=n.onAwaitingChange}get canRate(){return!1}get canLoadHistory(){return!1}get canListInteractions(){return!1}get canSendNotification(){return!1}get ratingPopupUrls(){return{}}async sendMessage(e){var n,a;if(!this.canSend())return null;(n=this.onAwaitingChange)==null||n.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:me.CHAT_RESPONSE_TYPE_AGENT,...r.message.followUpPrompts?{followUpPrompts:r.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:rs,type:me.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 ks=({connector:t,phase:e,chatHistory:n,chatSessionKey:a,startQuery:r,clarificationMessage:l,enableUpload:i=!1,onTurn:u,onAwaitingChange:c,onClarificationPrompt:v,onDismissClarification:f})=>{const h=o.useMemo(()=>new xs(t,{canSend:()=>e===H.running,onTurn:u,onAwaitingChange:c}),[t,e,u,c]),p=e!==H.running,O=e===H.running;return s.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[l&&s.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[s.jsx("p",{className:"agent-workspace__clarification-text",children:l.text}),l.followUpPrompts&&s.jsx(ws,{prompts:l.followUpPrompts,onSelect:v}),s.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:f,children:"Dismiss"})]}),s.jsx("div",{className:"agent-workspace__ask-arbor",children:s.jsx(ze,{scrollSelector:".chat-panel-message-list",children:s.jsx(me.ChatPanel,{connector:h,chatHistory:n,startQuery:r,lockConversation:p,enableUpload:i,speechEnabled:O,speechLanguage:"en-GB",speechSubmissionDelay:1e3,slashMenuItems:[],menuContent:[],introHeading:"Message your agent",introBody:"Ask questions, share trip details, or paste a link. The agent will update the checklist as it works.",placeholder:O?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)})}),e===H.stopped&&s.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[s.jsx(d.Icon,{name:"circle-alert",size:16,color:"var(--color-semantic-warning-600)"}),s.jsx("span",{children:"You stopped the agent. Its progress is saved in the checklist on the left."})]}),e===H.complete&&s.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[s.jsx(d.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),s.jsx("span",{children:"The agent has finished."})]})]})},bt=({item:t,depth:e,canRequestInput:n,onAttentionItemClick:a})=>{const r=V[t.status],l=t.status.replace(/_/g,"-"),i=t.status===B.hitl&&n&&a,u=s.jsxs("div",{className:"agent-workspace__task-row",children:[s.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`}),s.jsxs("div",{className:"agent-workspace__task-content",children:[s.jsx("span",{className:"agent-workspace__task-label",children:t.task}),t.status!==B.complete&&t.description&&s.jsx("span",{className:"agent-workspace__task-description",children:t.description})]})]});return s.jsxs("li",{className:J("agent-workspace__task",`agent-workspace__task--${l}`,{"agent-workspace__task--child":e>0}),children:[i?s.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${t.task}`,onClick:()=>a(t),children:u}):u,t.children&&t.children.length>0&&s.jsx("ul",{className:"agent-workspace__task-children",children:t.children.map(c=>s.jsx(bt,{item:c,depth:e+1,canRequestInput:n,onAttentionItemClick:a},c.task))})]})},pt=({items:t,ariaLabel:e,canRequestInput:n,onAttentionItemClick:a})=>s.jsx("ul",{className:"agent-workspace__task-list","aria-label":e,children:t.map(r=>s.jsx(bt,{item:r,depth:0,canRequestInput:n,onAttentionItemClick:a},r.task))}),ys=({checklist:t,isLoading:e,error:n,phase:a,canRequestInput:r,onAttentionItemClick:l})=>{const i=o.useMemo(()=>t?jt(t):null,[t]);return s.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--checklist","aria-label":"Checklist",children:[s.jsx("div",{className:"agent-workspace__panel-header",children:s.jsx(d.Heading,{level:4,children:"Checklist"})}),s.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:s.jsxs(ze,{children:[e&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:he}),s.jsx("span",{children:he})]}),!e&&n&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:n}),!e&&!n&&i&&s.jsxs(s.Fragment,{children:[i.needsInput.length>0&&s.jsxs("div",{className:"agent-workspace__task-group",children:[s.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),s.jsx(pt,{items:i.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:r,onAttentionItemClick:l})]}),i.tasks.length>0&&s.jsxs("div",{className:J("agent-workspace__task-group",{"agent-workspace__task-group--following":i.needsInput.length>0}),children:[i.needsInput.length>0&&s.jsx("p",{className:"agent-workspace__task-group-label",children:"Other tasks"}),s.jsx(pt,{items:i.tasks,ariaLabel:"Agent tasks",canRequestInput:r,onAttentionItemClick:l})]})]}),!e&&!n&&(!i||i.needsInput.length===0&&i.tasks.length===0)&&s.jsx("p",{className:"agent-workspace__empty",children:a===H.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})]})},Ss=({resource:t,html:e,isLoading:n,error:a,onClose:r})=>{o.useEffect(()=>{if(!t)return;const i=d.SlideoverUtils.removeSlideover;return d.SlideoverUtils.removeSlideover=()=>{i(),r()},()=>{d.SlideoverUtils.removeSlideover=i}},[t,r]),o.useEffect(()=>{if(!t)return;const i=u=>{u.key==="Escape"&&d.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[t]);const l=o.useMemo(()=>t?[{centerHeaderText:!1,children:s.jsxs("div",{className:"resource-preview-slideover__body",children:[n&&s.jsxs("div",{className:"resource-preview-slideover__status",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading document"}),s.jsx("span",{children:"Loading document…"})]}),!n&&a&&s.jsx("p",{className:"resource-preview-slideover__error",role:"alert",children:a}),!n&&!a&&e!==null&&s.jsx("iframe",{className:"resource-preview-slideover__frame",title:t.title,sandbox:"",srcDoc:e})]})}]:[],[t,e,n,a]);return s.jsx("div",{className:"resource-preview-slideover",children:s.jsx(d.SlideoverManager,{slideovers:l})})},Ns={[re.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[re.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[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)"}},js=({resources:t,isLoading:e=!1,error:n=null,onOpenResource:a})=>s.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--documents","aria-label":"Resources",children:[s.jsxs("div",{className:"agent-workspace__panel-header",children:[s.jsx(d.Heading,{level:4,children:"Resources"}),s.jsx("span",{className:"agent-workspace__panel-count",children:t.length})]}),s.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:s.jsxs(ze,{children:[e&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading resources"}),s.jsx("span",{children:"Loading resources…"})]}),!e&&n&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:n}),!e&&!n&&t.length>0&&s.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:t.map(r=>{const l=Ns[r.type],i=r.misRecordUrl;return s.jsx("li",{className:"agent-workspace__resource",children:i?s.jsx("a",{className:"agent-workspace__resource-card",href:i,target:"_blank",rel:"noreferrer",onClick:u=>{u.preventDefault(),a(r)},children:s.jsx(mt,{resource:r,config:l,external:!0})}):s.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>a(r),children:s.jsx(mt,{resource:r,config:l})})},r.id)})}),!e&&!n&&t.length===0&&s.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),mt=({resource:t,config:e,external:n=!1})=>s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${t.type}`,children:s.jsx(d.Icon,{name:e.icon,size:16,color:e.color,screenReaderText:`${e.label}:`})}),s.jsx("span",{className:"agent-workspace__resource-content",children:s.jsxs("span",{className:"agent-workspace__resource-top",children:[s.jsx("span",{className:"agent-workspace__resource-name",children:t.title}),s.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${t.type}`,children:e.label})]})}),n&&s.jsx(d.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]}),Be=t=>{const e=Date.parse(t);return Number.isFinite(e)?e:0},bs=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),Ze=t=>{const e=new Date(t);return Number.isFinite(e.getTime())?bs.format(e):t},Ue=t=>t.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,e=>e.split(/[_-]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" ")),Ne=(t,e)=>e<=1?0:t/(e-1)*100,At=t=>Math.max(t,0)+2,As=t=>t+1,Cs=(t,e)=>{if(e.length===0)return 50;const n=At(e.length),a=Ne(1,n),r=Ne(e.length,n),l=e.map(f=>Be(f.timestamp)),i=Math.min(...l),u=Math.max(...l);if(u<=i)return a;const c=(Be(t.timestamp)-i)/(u-i),v=Math.min(1,Math.max(0,c));return a+v*(r-a)},Es=8,Ts=20,Rs=(t,e=Es,n=Ts)=>{const a=new Map;if(t.length===0)return a;const r=[...t].sort((i,u)=>i.leftPercent-u.leftPercent||i.timestampMs-u.timestampMs||i.id.localeCompare(u.id)),l=[];for(const i of r){const u=l[l.length-1];u&&i.leftPercent-u[u.length-1].leftPercent<e?u.push(i):l.push([i])}for(const i of l){const u=[...i].sort((v,f)=>v.timestampMs-f.timestampMs||v.id.localeCompare(f.id)),c=(u.length-1)/2;u.forEach((v,f)=>{a.set(v.id,(f-c)*n)})}return a},De=(t,e=0)=>({left:`calc(${t/100} * (100% - var(--agent-timeline-node-size)) + (var(--agent-timeline-node-size) / 2) + ${e}px)`,transform:"translateX(-50%)"}),Is=t=>t.type!=="message-sent",Os=({timeline:t,isLoading:e,error:n,onOpenChatSession:a})=>{const r=((t==null?void 0:t.actionLog)??[]).filter(Is),l=(t==null?void 0:t.chatSessions)??[],i=!e&&!n&&r.length===0&&l.length===0,u=At(r.length),c=r.map((h,p)=>({id:`action-${h.timestamp}-${p}`,leftPercent:Ne(As(p),u),timestampMs:Be(h.timestamp)})),v=l.map(h=>({id:h.sessionId,leftPercent:Cs(h,r),timestampMs:Be(h.timestamp)})),f=Rs([...c,...v]);return s.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[e&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),n&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:n||St}),i&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!e&&!n&&!i&&s.jsxs("div",{className:"agent-timeline",children:[s.jsx("div",{className:"agent-timeline__track","aria-hidden":"true"}),s.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:De(Ne(0,u)),children:[s.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:s.jsx(d.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})}),s.jsx("span",{className:"agent-timeline__terminus-label",children:"Start"})]}),r.map((h,p)=>{const O=`action-${h.timestamp}-${p}`,w=c[p].leftPercent,j=h.type==="checklist-updated",N=h.type==="status-transition",P=j?"checklist":N?"status":"note";return s.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${P}`,style:De(w,f.get(O)??0),children:[s.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${P}`,"aria-label":`${Ue(h.type)}: ${Ue(h.entry)}`,children:[j&&s.jsx(d.Icon,{name:"check-solid",size:16,color:"currentColor"}),N&&s.jsx(d.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]}),s.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[s.jsx("strong",{className:"agent-timeline__pill-type",children:Ue(h.type)}),s.jsx("span",{className:"agent-timeline__pill-entry",children:Ue(h.entry)}),s.jsx("span",{className:"agent-timeline__pill-entry",children:Ze(h.timestamp)})]})]},O)}),s.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:De(Ne(u-1,u)),children:[s.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:s.jsx(d.Icon,{name:"flag",size:16,color:"currentColor"})}),s.jsx("span",{className:"agent-timeline__terminus-label",children:"Finish"})]}),l.map((h,p)=>{const O=v[p].leftPercent;return s.jsxs("div",{className:"agent-timeline__chat-station",style:De(O,f.get(h.sessionId)??0),children:[s.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${Ze(h.timestamp)}`,onClick:()=>a(h.sessionId),children:s.jsx(d.Icon,{name:"sparkles",size:16,color:"currentColor"})}),s.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[s.jsx("strong",{className:"agent-timeline__pill-type",children:"Chat session"}),s.jsx("span",{className:"agent-timeline__pill-entry",children:Ze(h.timestamp)})]})]},h.sessionId)})]})]})},Ps=["I'll get the details and come back to you","Skip this for now"],Ls=t=>{var n;const e=(n=t.prompt)!=null&&n.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:Z.agent,text:e,followUpPrompts:t.clarificationPrompts??Ps}},ge=t=>({id:t.id,text:t.text,type:t.author===Z.user?me.CHAT_RESPONSE_TYPE_USER:t.author===Z.system?me.CHAT_RESPONSE_TYPE_INFO:me.CHAT_RESPONSE_TYPE_AGENT,...t.followUpPrompts?{followUpPrompts:t.followUpPrompts}:{}});class pe extends Error{constructor(e,n,a){super(a??`Agent service request failed (${e})`),this.name="AgentServiceError",this.status=e,this.detail=n}}const Ms="/api/v1",$={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},F={GET:"GET",POST:"POST"},Us={error:"error"},Ds={user:"user"},oe={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},$s=100,Ct=t=>{switch(t){case gt.cancelled:return A.failed;case gt.archived:return A.complete;case A.hitl:case A.complete:case A.failed:case A["generating-a-response"]:return t;default:return A["generating-a-response"]}},Et=t=>{switch(t){case Xe.requires_attention:return B.hitl;case Xe.in_progress:case Xe.available:return B["generating-a-response"];case B.failed:case B.complete:case B.hitl:case B["generating-a-response"]:return t;default:return B["generating-a-response"]}},nt=t=>({ref:t.name,display_name:t.display_name,agent_intent:t.agent_intent??"",description:t.description}),Hs=t=>({id:t.id,name:t.name,...t.has_run_before?{hasRunBefore:t.has_run_before}:{}}),Bs=new Set(Object.values(re)),zs=t=>Bs.has(t)?t:re.document_html,Tt=t=>({id:t.id,type:zs(t.type),title:t.title,createdDatetime:t.created_datetime,lastUpdatedDatetime:t.last_updated_datetime,misRecordUrl:t.mis_record_url}),Rt=t=>({resources:t.resources.map(Tt),pageNumber:t.page_number,pageSize:t.page_size,totalRecords:t.total_records}),It=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}))}),tt=t=>{var n;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:((n=t.invocation_name)==null?void 0:n.trim())||t.agent_definition_ref,application_id:t.application_id,...t.application_name?{application_name:t.application_name}:{},created_by:t.created_by,status:Ct(t.status),context_ref:t.context_ref??null,checklist_ref:t.checklist_ref??null}},at=t=>{var e;return{task:t.task??t.name??t.label??os,status:Et(t.status),description:t.description??"",...t.prompt?{prompt:t.prompt}:{},...(e=t.follow_up_prompts)!=null&&e.length?{clarificationPrompts:t.follow_up_prompts}:{}}},Fs=t=>Array.isArray(t)?t:t.checklist_items??t.checklist??t.items??[],rt=(t,e,n)=>{var l;const a=!Array.isArray(e)&&(e.opening_message||(l=e.opening_follow_up_prompts)!=null&&l.length)?e:n,r=a?je(a):void 0;return{invocation_id:t,checklist:Fs(e).map(at),...r?{openingMessage:r}:{}}},Ot=(t,e)=>{const n=je(e);return{invocation_id:e.invocation_id??t,checklist:(e.checklist_items??[]).map(at),...n?{openingMessage:n}:{}}},je=t=>{var n,a;const e=(n=t.opening_message)==null?void 0:n.trim();if(e)return{id:yt,author:Z.agent,text:e,...(a=t.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:t.opening_follow_up_prompts}:{}}},Pt=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"?Z.user:Z.agent,text:e.content})),qs=/:invocationId\b/g,Gs=/:resourceId\b/g,Js=t=>t.trim().replace(/^Bearer\s+/i,""),Ks=t=>t.endsWith("/")?t.slice(0,-1):t;class Fe{constructor(e){var a;this.baseUrl=Ks(e.baseUrl??"");const n=(a=e.token)==null?void 0:a.trim();this.token=n?Js(n):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",$.agentDefinitions))).agent_definitions??[]}getAgentDefinition(e){return this.request(F.GET,this.apiUrl(`${$.agentDefinitions}/${encodeURIComponent(e)}`))}listTripOptions(){return this.request(F.GET,this.apiUrl($.tripOptions))}getDataset(){return this.request(F.GET,this.apiUrl($.demoDataset))}setDataset(e){return this.request(F.POST,this.apiUrl($.demoDataset),{dataset:e})}listAgents(e={}){const n=new URLSearchParams;e.status&&n.set("status",e.status),e.agentDefinitionRef&&n.set("agent_definition_ref",e.agentDefinitionRef);const a=n.toString()?`?${n.toString()}`:"";return this.request(F.GET,`${this.resolveUrl("agents",$.agents)}${a}`)}createAgent(e,n={}){var i,u;const a={agent_definition_ref:e},r=(i=n.invocationName)==null?void 0:i.trim(),l=(u=n.agentIntent)==null?void 0:u.trim();return r&&(a.invocation_name=r),l&&(a.agent_intent=l),this.request(F.POST,this.resolveUrl("agents",$.agents),a)}getAgent(e){return this.request(F.GET,this.resolveUrl("agent",`${$.agents}/${encodeURIComponent(e)}`,e))}getAgentChecklist(e){return this.request(F.GET,this.resolveUrl("agentChecklist",`${$.agents}/${encodeURIComponent(e)}/checklist`,e))}getAgentResources(e,n={}){const a=new URLSearchParams;n.pageNumber!==void 0&&a.set("page_number",String(n.pageNumber)),n.pageSize!==void 0&&a.set("page_size",String(n.pageSize)),n.type&&a.set("type",n.type);const r=a.toString(),l=this.resolveUrl("agentResources",`${$.agents}/${encodeURIComponent(e)}/resources`,e);return this.request(F.GET,r?`${l}?${r}`:l)}async listAllAgentResources(e){const n=$s;let a=1;const r=[];let l=Number.POSITIVE_INFINITY;for(;r.length<l;){const i=Rt(await this.getAgentResources(e,{pageNumber:a,pageSize:n}));if(l=i.totalRecords,i.resources.length===0||(r.push(...i.resources),r.length>=l))break;a+=1}return r}getAgentResourceHtml(e,n){return this.requestText(F.GET,this.resolveResourceHtmlUrl(e,n))}getAgentTimeline(e){return this.request(F.GET,this.resolveUrl("agentTimeline",`${$.agents}/${encodeURIComponent(e)}/agent-timeline`,e))}getAgentContext(e){return this.request(F.GET,this.apiUrl(`${$.agents}/${encodeURIComponent(e)}/context`))}cancelAgent(e){return this.request(F.POST,this.apiUrl(`${$.agents}/${encodeURIComponent(e)}/cancel`))}archiveAgent(e){return this.request(F.POST,this.apiUrl(`${$.agents}/${encodeURIComponent(e)}/archive`))}getConversation(e){return this.request(F.GET,this.resolveUrl("agentConversation",`${$.conversations}/${encodeURIComponent(e)}`,e))}async chat(e,n,a={}){const r=!!(a.uploadFiles&&a.uploadFiles.length>0),l=await this.fetchImpl(this.resolveUrl("agentChat",`${$.agents}/${encodeURIComponent(e)}/chat`,e),{method:F.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:oe.acceptEventStream,...r?{}:{"Content-Type":oe.contentTypeJson}},body:r?Vs(n,a.uploadFiles??[]):JSON.stringify(n),signal:a.signal});if(!l.ok)throw await this.toError(l);if(!l.body)throw new pe(l.status,null,"Chat response contained no stream body");return this.consumeSse(l.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(e){return`${this.baseUrl}${Ms}${e}`}resolveUrl(e,n,a,r){const l=this.urls[e];if(!l)return this.apiUrl(n);let i=l;return a&&(i=i.replace(qs,encodeURIComponent(a))),r&&(i=i.replace(Gs,encodeURIComponent(r))),i}resolveResourceHtmlUrl(e,n){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${$.agents}/${encodeURIComponent(e)}/resources/${encodeURIComponent(n)}`,e,n):this.urls.agentResources?`${this.resolveUrl("agentResources",`${$.agents}/${encodeURIComponent(e)}/resources`,e).replace(/\/$/,"")}/${encodeURIComponent(n)}`:this.apiUrl(`${$.agents}/${encodeURIComponent(e)}/resources/${encodeURIComponent(n)}`)}async request(e,n,a){const r=await this.fetchImpl(n,{method:e,headers:{...this.customHeaders,...this.authHeaders(),Accept:oe.acceptJson,...a===void 0?{}:{"Content-Type":oe.contentTypeJson}},...a===void 0?{}:{body:JSON.stringify(a)}});if(!r.ok)throw await this.toError(r);if(r.status!==204)return await r.json()}async requestText(e,n){const a=await this.fetchImpl(n,{method:e,headers:{...this.customHeaders,...this.authHeaders(),Accept:oe.acceptHtml}});if(!a.ok)throw await this.toError(a);return a.text()}async toError(e){let n=null;try{n=await e.json()}catch{}return new pe(e.status,n,`Agent service request failed (${e.status} ${e.statusText})`)}async consumeSse(e,n){const a=e.getReader(),r=new TextDecoder;let l="",i;const u=c=>{const{event:v,data:f}=Ws(c);if(f===null)return;if(v===Us.error){const p=_t(f);throw new pe(502,p,(p==null?void 0:p.message)??"Chat stream error")}const h=_t(f);h&&(i=h,n==null||n(h))};for(;;){const{done:c,value:v}=await a.read();if(c)break;l+=r.decode(v,{stream:!0});const f=l.split(`
|
|
2
2
|
|
|
3
|
-
`);
|
|
4
|
-
`)){const r=a.trimEnd();r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&
|
|
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;
|
|
3
|
+
`);l=f.pop()??"";for(const h of f)u(h)}if(l.trim()&&u(l),!i)throw new pe(502,null,"Chat stream ended without any events");return i}}const Ws=t=>{let e=null;const n=[];for(const a of t.split(`
|
|
4
|
+
`)){const r=a.trimEnd();r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&n.push(r.slice(5).trim())}return{event:e,data:n.length>0?n.join(`
|
|
5
|
+
`):null}},_t=t=>{try{return JSON.parse(t)}catch{return}};function Vs(t,e){const n=new FormData;n.append("body",JSON.stringify(t));for(const a of e)n.append("files",a,a.name);return n}const Ys={id:yt,author:Z.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 ft=0;const Xs=t=>(ft+=1,`${t}-${Date.now()}-${ft}`),Qs=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 Lt{constructor(e,n,a={}){this.seededChecklist=[],this.client=e,this.agentId=n,this.chatId=a.chatId??n,this.opening=a.openingMessage??Ys,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const e=await this.client.getConversation(this.chatId),n=Pt(e.messages);return n.length===0?[this.opening]:n}async start(e){return{...await this.exchange(Qs(e)),phase:H.running}}sendMessage(e,n){return this.exchange(e,n)}async stop(){}seedChecklist(e){this.seededChecklist=e}async exchange(e,n){var i;const a=[{role:Ds.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"}},...n&&n.length>0?[{uploadFiles:n}]:[]),l={id:r.event_id||Xs("msg-agent"),author:Z.agent,text:r.message.content,...(i=r.follow_up_prompts)!=null&&i.length?{followUpPrompts:r.follow_up_prompts}:{}};try{const u=await this.client.getAgent(this.agentId),{checklist:c}=Ot(this.agentId,u);return this.seededChecklist=c,{message:l,checklist:c}}catch{return{message:l,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const ot=(t,e)=>n=>{var a,r;return new Lt(t,n.invocation_id,{model:e==null?void 0:e.model,chatId:((a=e==null?void 0:e.resolveChatId)==null?void 0:a.call(e,n))??(e==null?void 0:e.chatId)??n.invocation_id,openingMessage:((r=e==null?void 0:e.resolveOpeningMessage)==null?void 0:r.call(e,n))??(e==null?void 0:e.openingMessage)})},Mt=t=>t instanceof pe?t.message:t instanceof TypeError?"Network error while contacting the agent service.":t instanceof Error&&t.message?t.message:Nt,Zs=t=>{const e={};for(const n of t){const a=je(n);if(!a)continue;const r=n.invocation_id??n.id;e[r]=a,e[n.id]=a}return e},en=t=>JSON.stringify(t),et=(t,e)=>JSON.stringify(t)===JSON.stringify(e),Ut=t=>{const{jwt:e,headers:n,urls:a}=t,r=JSON.stringify(n??{}),l=en(a),i=o.useMemo(()=>new Fe({token:e,headers:n,urls:a}),[e,l]);o.useLayoutEffect(()=>{i.setHeaders(n)},[i,r]);const[u,c]=o.useState([]),[v,f]=o.useState([]),[h,p]=o.useState({}),[O,w]=o.useState("loading"),[j,N]=o.useState(null),[P,y]=o.useState(0),k=o.useCallback((I,U)=>{const E=I.map(tt),q=U.map(nt),K=Zs(I);c(z=>et(z,E)?z:E),f(z=>et(z,q)?z:q),p(z=>et(z,K)?z:K),w("idle"),N(null)},[]);o.useEffect(()=>{let I=!1;return w("loading"),N(null),(async()=>{try{const[U,E]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);if(I)return;k(U,E)}catch(U){if(I)return;c([]),f([]),p({}),w("error"),N(Mt(U))}})(),()=>{I=!0}},[k,i,P]);const _=o.useCallback(()=>{y(I=>I+1)},[]),C=o.useCallback(async()=>{try{const[I,U]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);k(I,U)}catch{}},[k,i]),R=o.useCallback(async I=>{const[U,E]=await Promise.all([i.getAgentChecklist(I),i.getAgent(I).catch(()=>null)]);return rt(I,U,E??void 0)},[i]),T=o.useCallback(async I=>i.listAllAgentResources(I),[i]),M=o.useCallback(async({definition:I,invocationName:U})=>{const E=await i.createAgent(I.ref,{invocationName:U}),q=await i.getAgent(E.id),K=tt(q),z=je(q);return c(D=>[K,...D]),z&&p(D=>({...D,[K.invocation_id]:z,[K.id]:z})),K},[i]),Y=o.useMemo(()=>ot(i,{resolveOpeningMessage:I=>h[I.invocation_id]??h[I.id]}),[i,h]);return{agents:u,agentDefinitions:v,loadState:O,loadError:j,reload:_,refresh:C,fetchAgentChecklist:R,fetchAgentResources:T,createAgent:M,chatConnector:Y}},tn=t=>JSON.stringify(t),Dt=t=>{const{agent:e,jwt:n,headers:a,urls:r,chatId:l}=t,i=JSON.stringify(a??{}),u=tn(r),c=o.useMemo(()=>new Fe({token:n,headers:a,urls:{agent:r.agentUrl,agentChecklist:r.agentChecklistUrl,...r.agentResourcesUrl?{agentResources:r.agentResourcesUrl}:{},...r.agentTimelineUrl?{agentTimeline:r.agentTimelineUrl}:{},agentChat:r.agentChatUrl,agentConversation:r.agentConversationUrl}}),[n,u]);o.useLayoutEffect(()=>{c.setHeaders(a)},[c,i]);const v=o.useCallback(async w=>{const[j,N]=await Promise.all([c.getAgentChecklist(w),c.getAgent(w).catch(()=>null)]);return rt(w,j,N??void 0)},[c]),f=o.useCallback(async w=>c.listAllAgentResources(w),[c]),h=o.useCallback(async(w,j)=>c.getAgentResourceHtml(w,j),[c]),p=o.useCallback(async w=>{const j=await c.getAgentTimeline(w);return It(j)},[c]);return{connector:o.useMemo(()=>ot(c,{chatId:l??e.invocation_id})(e),[c,e.invocation_id,l]),fetchAgentChecklist:v,fetchAgentResources:f,fetchAgentResourceHtml:h,fetchAgentTimeline:p}},sn=3e4,nn=(t,e)=>{const n=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`${n}${a}.${r}`.trim()},an=t=>{switch(t){case A.failed:return H.stopped;case A.complete:return H.complete;default:return H.running}},vt=(t,e)=>{e([ge(t)])},rn=(t,e)=>t.length===e.length&&t.every((n,a)=>{const r=e[a];return r!==void 0&&n.id===r.id&&n.text===r.text}),$t=({agent:t,invocationId:e,open:n,onClose:a,jwt:r,headers:l,agentUrl:i,agentChecklistUrl:u,agentResourcesUrl:c,agentTimelineUrl:v,agentChatUrl:f,agentConversationUrl:h,chatId:p,enableUpload:O,initialBrief:w,initialPhase:j,initialChecklist:N})=>{const[P,y]=o.useState(p??e),[k,_]=o.useState("chat"),[C,R]=o.useState(!1),{connector:T,fetchAgentChecklist:M,fetchAgentResources:Y,fetchAgentResourceHtml:I,fetchAgentTimeline:U}=Dt({agent:{...t,invocation_id:e},jwt:r,headers:l,chatId:P,urls:{agentUrl:i,agentChecklistUrl:u,agentResourcesUrl:c,agentTimelineUrl:v,agentChatUrl:f,agentConversationUrl:h}}),E=o.useRef(T),[q,K]=o.useState(j??(w?H.running:an(t.status))),[z,D]=o.useState([]),[be,ie]=o.useState(0),[_e,le]=o.useState(),[qe,ee]=o.useState(null),[Ge,fe]=o.useState([]),[ne,ve]=o.useState(!1),[Ae,ce]=o.useState(null),[Ce,Ee]=o.useState(null),[Te,we]=o.useState(null),[Re,xe]=o.useState(!1),[Je,ke]=o.useState(null),[te,ye]=o.useState(null),[m,b]=o.useState(!1),[S,G]=o.useState(null),[X,Q]=o.useState(N??null),[ae,Se]=o.useState(!1),[zt,Ke]=o.useState(null),[Ie,We]=o.useState(!1),[Oe,Ft]=o.useState(!1),[Pe,qt]=o.useState(!1),it=o.useRef(Ie),lt=o.useRef(0),ct=o.useRef(0);o.useEffect(()=>{E.current=T},[T]),o.useEffect(()=>{it.current=Ie},[Ie]),o.useEffect(()=>{y(p??e),_("chat"),R(!1),D([]),ie(g=>g+1)},[e,p]),o.useEffect(()=>{if(!n||w)return;const g=E.current.bootstrapConversation;if(!g){vt(E.current.openingMessage(),D);return}let x=!1;return We(!0),(async()=>{try{const L=await g.call(E.current);if(x)return;D(L.map(ge))}catch{x||vt(E.current.openingMessage(),D)}finally{x||We(!1)}})(),()=>{x=!0}},[n,w,e,P]);const de=o.useCallback(()=>{const g=++lt.current;(async()=>{var x,L;try{const W=await M(e);if(g!==lt.current)return;Q(se=>JSON.stringify(se)===JSON.stringify(W.checklist)?se:W.checklist),Ke(null),(L=(x=E.current).seedChecklist)==null||L.call(x,W.checklist)}catch{}})()},[M,e]),Le=o.useCallback(()=>{c&&(async()=>{try{const g=await Y(e);fe(g),ce(null)}catch{}})()},[c,Y,e]),ue=o.useCallback(()=>{if(!v)return;const g=++ct.current;(async()=>{try{const x=await U(e);if(g!==ct.current)return;ye(L=>JSON.stringify(L)===JSON.stringify(x)?L:x),G(null)}catch{}})()},[v,U,e]);o.useEffect(()=>{if(!n||w)return;const g=window.setInterval(()=>{const x=E.current.bootstrapConversation;x&&(async()=>{try{const L=await x.call(E.current);if(it.current)return;const W=L.map(ge);let se=!1;D(ut=>rn(ut,W)?ut:(se=!0,W)),se&&(de(),ue())}catch{}})()},sn);return()=>{window.clearInterval(g)}},[n,w,e,P,de,ue]);const Gt=o.useCallback(g=>{var x,L;g.checklist?(Q(g.checklist),(L=(x=E.current).seedChecklist)==null||L.call(x,g.checklist)):de(),g.phase&&K(g.phase),Le(),ue()},[de,Le,ue]);o.useEffect(()=>{var g,x;!n||w||N&&N.length>0&&((x=(g=E.current).seedChecklist)==null||x.call(g,N))},[n,w,N]),o.useEffect(()=>{if(!n||w)return;let g=!1;return Se(x=>N!=null&&N.length?!1:x||X===null||X.length===0),Ke(null),(async()=>{var x,L;try{const W=await M(e);if(g)return;N!=null&&N.length||(Q(W.checklist),(L=(x=E.current).seedChecklist)==null||L.call(x,W.checklist))}catch{!g&&!(N!=null&&N.length)&&Ke($e)}finally{g||Se(!1)}})(),()=>{g=!0}},[n,e,w,N,M]),o.useEffect(()=>{if(!n||!c)return;let g=!1;return ve(!0),ce(null),(async()=>{try{const x=await Y(e);g||fe(x)}catch{g||ce(ns)}finally{g||ve(!1)}})(),()=>{g=!0}},[n,e,c,Y]);const Jt=o.useCallback(()=>{Ee(null),we(null),ke(null),xe(!1)},[]),Kt=o.useCallback(g=>{if(g.misRecordUrl){window.open(g.misRecordUrl,"_blank","noopener,noreferrer");return}Ee(g),we(null),ke(null),xe(!0),(async()=>{try{const x=await I(e,g.id);we(x)}catch{ke(as)}finally{xe(!1)}})()},[I,e]);o.useEffect(()=>{if(!n||!v)return;let g=!1;return b(x=>x||te===null),G(null),(async()=>{try{const x=await U(e);g||ye(x)}catch{g||G(St)}finally{g||b(!1)}})(),()=>{g=!0}},[n,e,v,U]),o.useEffect(()=>{if(!n||!w)return;let g=!1;const x={id:`user-brief-${Date.now()}`,author:Z.user,text:nn(w,t.invocation_name)};return(async()=>{var W,se;const L=await E.current.start(w);g||(D([ge(E.current.openingMessage()),ge(x),ge(L.message)]),L.checklist?(Q(L.checklist),(se=(W=E.current).seedChecklist)==null||se.call(W,L.checklist)):de(),K(L.phase??H.running),Le(),ue())})(),()=>{g=!0}},[n,w,t.invocation_name,e,de,Le,ue]);const Wt=o.useCallback(g=>{ee(Ls(g))},[]),Ve=p??e,Me=te==null?void 0:te.chatSessions,dt=Me!=null&&Me.length?Me.reduce((g,x)=>Date.parse(x.timestamp)<Date.parse(g.timestamp)?x:g).sessionId:void 0,Ye=o.useCallback(()=>{_("chat"),R(!1),P!==Ve&&(y(Ve),D([]),ie(g=>g+1))},[P,Ve]),Vt=o.useCallback(g=>{if(g===dt){Ye();return}y(g),R(!0),_("chat"),D([]),ie(x=>x+1)},[dt,Ye]),Yt=o.useCallback(g=>{ee(null),le(g),ie(x=>x+1)},[]),Xt=o.useCallback(async()=>{await E.current.stop(),K(H.stopped)},[]),Qt=X;return s.jsxs(d.Modal,{open:n,closeHandler:a,hideCloseButton:!0,className:"agent-workspace",children:[s.jsxs(d.Modal.Header,{className:"agent-workspace__header",children:[s.jsxs("div",{className:"agent-workspace__header-title",children:[s.jsx("span",{className:"agent-workspace__header-avatar","aria-hidden":"true",children:s.jsx(d.Icon,{name:"ask-arbor",size:24})}),s.jsx(d.Modal.Title,{children:t.invocation_name}),s.jsx("span",{className:J("agent-workspace__phase",`agent-workspace__phase--${q}`),children:is[q]})]}),s.jsxs("div",{className:"agent-workspace__header-actions",children:[s.jsx(d.Button,{variant:Oe?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!Oe,onClick:()=>Ft(g=>!g),children:"Checklist"}),s.jsx(d.Button,{variant:Pe?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Pe,onClick:()=>qt(g=>!g),children:"Resources"}),s.jsx(d.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),s.jsxs(d.Modal.Body,{className:J("agent-workspace__body",{"agent-workspace__body--no-checklist":Oe,"agent-workspace__body--no-resources":Pe}),children:[" ",s.jsxs("section",{className:J("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!v&&k==="timeline"}),"aria-label":"Agent",children:[s.jsxs("div",{className:"agent-workspace__panel-header",children:[s.jsx(d.Heading,{level:4,children:"Agent"}),q===H.running&&s.jsx(d.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Stop",onClick:()=>void Xt(),children:"Stop agent"})]}),v&&s.jsxs(d.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[s.jsx(d.Tabs.Item,{active:k==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>_("chat")},children:"Chat"}),s.jsx(d.Tabs.Item,{active:k==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>_("timeline")},children:"Timeline"})]}),v&&k==="chat"&&C&&s.jsx("div",{className:"agent-workspace__center-back",children:s.jsx(d.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:Ye,children:"Back to main chat"})}),v&&k==="timeline"&&s.jsx(Os,{timeline:te,isLoading:m,error:S,onOpenChatSession:Vt}),s.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!v&&k!=="chat",children:s.jsx(ks,{connector:T,phase:q,chatHistory:z,chatSessionKey:be,startQuery:_e,clarificationMessage:qe,enableUpload:O,onTurn:Gt,onAwaitingChange:We,onClarificationPrompt:Yt,onDismissClarification:()=>ee(null)})})]}),!Oe&&s.jsx(ys,{checklist:Qt,isLoading:ae,error:zt,phase:q,canRequestInput:q===H.running&&!Ie,onAttentionItemClick:Wt}),!Pe&&s.jsx(js,{resources:Ge,isLoading:ne,error:Ae,onOpenResource:Kt}),s.jsx(Ss,{resource:Ce,html:Te,isLoading:Re,error:Je,onClose:Jt})]})]})},on="Unable to load agent definitions. Please try again.",ln="Unable to start the agent.",wt="Loading agents…",Ht=({open:t,onClose:e,onStart:n,agentDefinitions:a,definitionsState:r="idle",definitionsError:l=null,onRetryDefinitions:i,embedded:u=!1})=>{const[c,v]=o.useState(void 0),[f,h]=o.useState(""),[p,O]=o.useState(!1),[w,j]=o.useState(null),N=[...a].sort((R,T)=>R.display_name.localeCompare(T.display_name)).map(R=>({value:R.ref,label:R.display_name}));o.useEffect(()=>{t&&(v(void 0),h(""),O(!1),j(null))},[t]);const P=c!==void 0&&f.trim().length>0,y=o.useCallback(R=>{const T=a.find(M=>M.ref===R[0]);T&&v(T)},[a]),k=o.useCallback(async()=>{if(!(!c||!P||p)){O(!0),j(null);try{await n({definition:c,invocationName:f.trim()})}catch(R){j(R instanceof Error?R.message:ln)}finally{O(!1)}}},[P,c,f,p,n]);if(r==="idle"&&a.length===0||!t)return null;const _=s.jsxs("div",{className:"new-agent__header-title",children:[s.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:s.jsx(d.Icon,{name:"ask-arbor",size:24})}),u?s.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):s.jsx(d.Modal.Title,{children:"Start an agent"})]});let C;return r==="loading"?C=s.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[s.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:wt}),s.jsx("p",{className:"new-agent__state-message",children:wt})]}):r==="error"?C=s.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[s.jsx(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),s.jsx("p",{className:"new-agent__state-message",children:l??on}),i?s.jsx(d.Button,{variant:"secondary",size:"S",onClick:i,children:"Try again"}):null]}):C=s.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:R=>{R.preventDefault(),P&&!p&&k()},children:[s.jsxs("div",{className:"new-agent__type-field",children:[s.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:"What would you like your agent to do?"}),s.jsx(d.SelectDropdown,{id:"new-agent-type",placeholder:"Which agent would you like to start?",options:N,selectedValues:c?[c.ref]:[],onSelectionChange:y})]}),s.jsxs("div",{className:"new-agent__type-field",children:[s.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:"Name"}),s.jsx(d.TextInput,{id:"new-agent-invocation-name",value:f,placeholder:"What would you like to call your agent?",onChange:R=>h(R.target.value)})]}),w?s.jsx("p",{className:"new-agent__error",role:"alert",children:w}):null,s.jsx("div",{className:"new-agent__actions",children:s.jsx(d.Button,{type:"submit",variant:"primary",className:J("new-agent__start-button",{"new-agent__start-button--starting":p}),disabled:!P||p,iconLeftName:p?"loader":"sparkles",iconLeftScreenReaderText:p?"Starting":void 0,children:p?"Starting…":"Start"})})]}),u?s.jsxs("div",{className:J("new-agent","new-agent--embedded"),children:[s.jsx("div",{className:"new-agent__header",children:_}),s.jsx("div",{className:"new-agent__body",children:C})]}):s.jsxs(d.Modal,{open:t,closeHandler:e,className:"new-agent",children:[s.jsx(d.Modal.Header,{className:"new-agent__header",children:_}),s.jsx(d.Modal.Body,{className:"new-agent__body",children:C})]})},xt=t=>{window.location.assign(t)},cn=({open:t,authToken:e,headers:n,agentDefinitionsUrl:a,agentsUrl:r,closeUrl:l,successUrl:i,onClose:u,onStart:c,embedded:v=!1})=>{const f=JSON.stringify(n??{}),h=o.useMemo(()=>new Fe({token:e,headers:n,urls:{agentDefinitions:a,agents:r}}),[e,a,r,f]),[p,O]=o.useState([]),[w,j]=o.useState("loading"),[N,P]=o.useState(null),[y,k]=o.useState(0);o.useEffect(()=>{if(!t)return;let T=!1;return j("loading"),P(null),(async()=>{try{const M=await h.listAgentDefinitions();if(T)return;O(M.map(nt)),j("idle")}catch(M){if(T)return;O([]),P(Mt(M)),j("error")}})(),()=>{T=!0}},[h,t,y]);const _=o.useCallback(()=>{u==null||u(),l&&xt(l)},[l,u]),C=o.useCallback(async T=>{await h.createAgent(T.definition.ref,{invocationName:T.invocationName}),c==null||c(T),i&&xt(i)},[h,c,i]),R=o.useCallback(()=>{k(T=>T+1)},[]);return s.jsx(Ht,{open:t,onClose:_,onStart:C,agentDefinitions:p,definitionsState:w,definitionsError:N,onRetryDefinitions:R,embedded:v})},dn=t=>"agentDefinitionsUrl"in t,Bt=t=>dn(t)?s.jsx(cn,{...t}):s.jsx(Ht,{...t}),un=t=>t!==void 0&&t.some(e=>e.status===B.hitl),gn=(t,e)=>un(e)?A.hitl:t.status,hn=({column:t,label:e})=>t.statusIcon?s.jsx("span",{className:"agent-view__status-indicator",children:s.jsx(d.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,className:J({"agent-view__progress-icon--spinning":t.statusIcon.spin}),screenReaderText:e})}):s.jsx("span",{className:J("agent-view__dot",{[`agent-view__dot--${t.dotModifier}`]:t.dotModifier}),children:s.jsx(d.Dot,{colour:t.dotColour,label:e})}),pn=({agent:t,agentName:e,column:n,isExpanded:a,isLoading:r,checklist:l,error:i,onToggle:u,onViewAgent:c})=>{const{id:v,invocation_name:f}=t,h=`agent-card-${v}-header`,p=`agent-card-${v}-progress`;return s.jsx("li",{className:J("agent-view__card",{"agent-view__card--expanded":a}),children:s.jsxs(d.Card,{spacing:"dense",children:[s.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":p,"aria-label":f,id:h,onClick:()=>u(v),children:s.jsxs("div",{className:"agent-view__card-content",children:[s.jsx(hn,{column:n}),s.jsx("span",{className:"agent-view__card-invocation-name",children:f}),s.jsx("span",{className:"agent-view__card-agent-name",children:e}),s.jsx(d.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&s.jsxs("div",{id:p,"aria-labelledby":h,className:"agent-view__card-progress",children:[r&&s.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:he}),s.jsx("span",{children:he})]}),!r&&i&&s.jsx("p",{className:"agent-view__progress-error",role:"alert",children:i}),!r&&!i&&l!==null&&s.jsx(vs,{checklist:l}),!r&&!i&&l===null&&s.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:he}),s.jsx("span",{children:he})]}),s.jsx("div",{className:"agent-view__card-actions",children:s.jsx(d.Button,{variant:"secondary",size:"S",onClick:()=>c==null?void 0:c(t),children:"View agent"})})]})]})})},kt=({column:t,agents:e,expandedAgentId:n,loadingAgentId:a,checklistByInvocationId:r,errorByAgentId:l,definitionNameByRef:i,onToggleAgent:u,onViewAgent:c,isSplit:v=!1})=>s.jsxs("section",{className:J("agent-view__column",{"agent-view__column--split":v}),"aria-label":t.title,children:[s.jsxs("div",{className:"agent-view__column-header",children:[s.jsx(d.Heading,{level:4,children:t.title}),s.jsx("span",{className:"agent-view__column-count",children:e.length})]}),s.jsx("ul",{className:"agent-view__card-list",children:e.map(f=>s.jsx(pn,{agent:f,agentName:st(f,i),column:t,isExpanded:n===f.id,isLoading:a===f.id,checklist:r[f.invocation_id]??null,error:l[f.id]??null,onToggle:u,onViewAgent:c},f.id))})]}),st=(t,e)=>e.get(t.agent_definition_ref)??t.agent_definition_ref.replace(/_/g," "),mn=({jwt:t,headers:e,agentDefinitionsUrl:n,agentsUrl:a,agentUrl:r,agentChecklistUrl:l,agentResourcesUrl:i,agentTimelineUrl:u,agentChatUrl:c,agentConversationUrl:v,enableUpload:f,showHeader:h=!1,institutions:p})=>{var ye;const O=o.useMemo(()=>({agentDefinitions:n,agents:a,agent:r,agentChecklist:l,...i?{agentResources:i}:{},...u?{agentTimeline:u}:{},agentChat:c,agentConversation:v}),[n,a,r,l,i,u,c,v]),[w,j]=o.useState(null),N=w?(ye=p==null?void 0:p.find(m=>m.applicationId===w.application_id))==null?void 0:ye.applicationUrl:void 0,P=o.useMemo(()=>{const m={...e??{}};return N?m[oe.arborApplicationUrl]=N:delete m[oe.arborApplicationUrl],m},[e,N]),{agents:y,agentDefinitions:k,loadState:_,loadError:C,reload:R,refresh:T,fetchAgentChecklist:M,createAgent:Y}=Ut({jwt:t,headers:P,urls:O}),[I,U]=o.useState(!1),[E,q]=o.useState(null),[K,z]=o.useState(null),[D,be]=o.useState({}),[ie,_e]=o.useState({}),[le,qe]=o.useState([]),[ee,Ge]=o.useState([]),fe=o.useMemo(()=>{const m=new Set(y.map(S=>S.application_id)),b=new Map((p??[]).map(S=>[S.applicationId,S.name]));return[...m].sort((S,G)=>(b.get(S)??S).localeCompare(b.get(G)??G)).map(S=>({value:S,label:b.get(S)??S}))},[y,p]),ne=o.useMemo(()=>new Map(k.map(m=>[m.ref,m.display_name])),[k]),ve=o.useMemo(()=>[...new Set(y.map(b=>st(b,ne)))].sort((b,S)=>b.localeCompare(S)).map(b=>({value:b,label:b})),[y,ne]),Ae=o.useMemo(()=>y.filter(m=>!(le.length>0&&!le.includes(m.application_id)||ee.length>0&&!ee.includes(st(m,ne)))),[y,ne,ee,le]),ce=fe.length>1,Ce=ve.length>1,Ee=ce||Ce;o.useEffect(()=>{const m=window.setInterval(()=>{T()},6e4);return()=>{window.clearInterval(m)}},[T]),o.useEffect(()=>{if(y.length===0)return;let m=!1;return(async()=>{const b=await Promise.allSettled(y.map(async S=>{const G=await M(S.invocation_id);return{agentId:S.id,invocationId:S.invocation_id,checklist:G.checklist}}));m||(be(S=>{const G={...S};let X=!1;for(const Q of b){if(Q.status!=="fulfilled")continue;const{invocationId:ae,checklist:Se}=Q.value;JSON.stringify(S[ae])!==JSON.stringify(Se)&&(G[ae]=Se,X=!0)}return X?G:S}),_e(S=>{const G={...S};let X=!1;return b.forEach((Q,ae)=>{Q.status==="rejected"&&G[y[ae].id]!==$e&&(G[y[ae].id]=$e,X=!0)}),X?G:S}))})(),()=>{m=!0}},[y,M]);const Te=o.useCallback(async m=>{if(!D[m.invocation_id]){z(m.id),_e(b=>{const S={...b};return delete S[m.id],S});try{const b=await M(m.invocation_id);be(S=>({...S,[m.invocation_id]:b.checklist}))}catch{_e(b=>({...b,[m.id]:$e}))}finally{z(b=>b===m.id?null:b)}}},[M,D]),we=o.useCallback(m=>{if(E===m){q(null);return}const b=y.find(({id:S})=>S===m);b&&(q(m),Te(b))},[y,E,Te]),Re=o.useMemo(()=>{const m={};for(const b of Ae){const S=gn(b,D[b.invocation_id]);(m[S]??(m[S]=[])).push(b)}return m},[Ae,D]),xe=o.useCallback(m=>{j(m)},[]),Je=o.useCallback(async m=>{const b=await Y(m);j(b),U(!1)},[Y]),ke=o.useCallback(()=>{j(null)},[]),te={expandedAgentId:E,loadingAgentId:K,checklistByInvocationId:D,errorByAgentId:ie,definitionNameByRef:ne,onToggleAgent:we,onViewAgent:xe};return s.jsxs("div",{className:"agent-view-frontend agent-view",children:[h&&s.jsxs("div",{className:"agent-view__header",children:[s.jsx(d.Heading,{level:1,children:"Agents"}),s.jsx(d.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>U(!0),children:"Start an agent"})]}),y.length>0&&Ee&&s.jsxs("div",{className:"agent-view__filters",children:[ce&&s.jsxs("div",{className:"agent-view__filter",children:[s.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-institution-filter",children:"Institution"}),s.jsx(d.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:fe,value:le,onValueChange:qe,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Ce&&s.jsxs("div",{className:"agent-view__filter",children:[s.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-agent-filter",children:"Agent"}),s.jsx(d.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:ve,value:ee,onValueChange:Ge,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),_==="error"?s.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[s.jsx(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),s.jsx("p",{className:"agent-view__state-message",children:C??Nt}),s.jsx(d.Button,{variant:"secondary",size:"S",onClick:R,children:"Try again"})]}):_==="loading"&&y.length===0?s.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[s.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:ht}),s.jsx("p",{className:"agent-view__state-message",children:ht})]}):y.length===0?s.jsx(gs,{}):s.jsxs("div",{className:"agent-view__board",children:[Zt.map(m=>s.jsx(kt,{column:He[m],agents:Re[m]??[],...te},m)),s.jsx("div",{className:"agent-view__split-column",children:es.map(m=>s.jsx(kt,{column:He[m],agents:Re[m]??[],isSplit:!0,...te},m))})]}),w&&s.jsx($t,{agent:w,invocationId:w.invocation_id,open:!0,jwt:t,headers:P,agentUrl:r,agentChecklistUrl:l,agentResourcesUrl:i,agentTimelineUrl:u,agentChatUrl:c,agentConversationUrl:v,enableUpload:f,initialChecklist:D[w.invocation_id]??null,onClose:ke},w.id),s.jsx(Bt,{open:I,onClose:()=>U(!1),onStart:Je,agentDefinitions:k})]})},_n=(t,e)=>{const n=Date.now(),a=e.trim()||t.agent_intent;return{id:`agent-${n}`,invocation_id:`inv-${n}`,agent_definition_ref:t.ref,agent_intent:t.agent_intent,invocation_name:a,application_id:ts,created_by:ss,status:A["generating-a-response"],context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=mn;exports.AgentServiceClient=Fe;exports.AgentServiceError=pe;exports.AgentView=$t;exports.HttpChatConnector=Lt;exports.NewAgentModal=Bt;exports.buildAgentFromDefinition=_n;exports.createHttpChatConnectorFactory=ot;exports.mapApiAgent=tt;exports.mapApiAgentDefinition=nt;exports.mapApiAgentStatus=Ct;exports.mapApiAgentTimelineResponse=It;exports.mapApiChecklistEndpointResponse=rt;exports.mapApiChecklistItem=at;exports.mapApiChecklistResponse=Ot;exports.mapApiChecklistStatus=Et;exports.mapApiConversationMessages=Pt;exports.mapApiOpeningMessage=je;exports.mapApiResource=Tt;exports.mapApiResourcesEndpointResponse=Rt;exports.mapApiTripOption=Hs;exports.useAgentService=Ut;exports.useAgentWorkspace=Dt;
|
package/dist/index.d.ts
CHANGED
|
@@ -84,13 +84,22 @@ export declare type AgentMonitorKanbanProps = {
|
|
|
84
84
|
};
|
|
85
85
|
|
|
86
86
|
export declare type AgentResource = {
|
|
87
|
-
|
|
87
|
+
id: string;
|
|
88
88
|
type: AgentResourceType;
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
title: string;
|
|
90
|
+
createdDatetime: string;
|
|
91
|
+
lastUpdatedDatetime: string;
|
|
92
|
+
misRecordUrl?: string | null;
|
|
91
93
|
};
|
|
92
94
|
|
|
93
|
-
export declare type
|
|
95
|
+
export declare type AgentResourcesPage = {
|
|
96
|
+
resources: AgentResource[];
|
|
97
|
+
pageNumber: number;
|
|
98
|
+
pageSize: number;
|
|
99
|
+
totalRecords: number;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export declare type AgentResourceType = 'document_html' | 'mis_record' | 'workflow' | 'file' | 'link';
|
|
94
103
|
|
|
95
104
|
export declare class AgentServiceClient {
|
|
96
105
|
private readonly baseUrl;
|
|
@@ -116,7 +125,9 @@ export declare class AgentServiceClient {
|
|
|
116
125
|
}): Promise<ApiCreateAgentResponse>;
|
|
117
126
|
getAgent(agentId: string): Promise<ApiAgentInvocationDetail>;
|
|
118
127
|
getAgentChecklist(agentId: string): Promise<ApiChecklistEndpointResponse>;
|
|
119
|
-
getAgentResources(agentId: string): Promise<ApiResourcesEndpointResponse>;
|
|
128
|
+
getAgentResources(agentId: string, params?: ApiListResourcesParams): Promise<ApiResourcesEndpointResponse>;
|
|
129
|
+
listAllAgentResources(agentId: string): Promise<AgentResource[]>;
|
|
130
|
+
getAgentResourceHtml(agentId: string, resourceId: string): Promise<string>;
|
|
120
131
|
getAgentTimeline(agentId: string): Promise<ApiAgentTimelineResponse>;
|
|
121
132
|
getAgentContext(agentId: string): Promise<unknown>;
|
|
122
133
|
cancelAgent(agentId: string): Promise<ApiAgentInvocation>;
|
|
@@ -126,7 +137,9 @@ export declare class AgentServiceClient {
|
|
|
126
137
|
private authHeaders;
|
|
127
138
|
private apiUrl;
|
|
128
139
|
private resolveUrl;
|
|
140
|
+
private resolveResourceHtmlUrl;
|
|
129
141
|
private request;
|
|
142
|
+
private requestText;
|
|
130
143
|
private toError;
|
|
131
144
|
private consumeSse;
|
|
132
145
|
}
|
|
@@ -159,6 +172,7 @@ export declare type AgentServiceUrlOverrides = {
|
|
|
159
172
|
agent?: string;
|
|
160
173
|
agentChecklist?: string;
|
|
161
174
|
agentResources?: string;
|
|
175
|
+
agentResourceHtml?: string;
|
|
162
176
|
agentTimeline?: string;
|
|
163
177
|
agentChat?: string;
|
|
164
178
|
agentConversation?: string;
|
|
@@ -259,12 +273,16 @@ export declare type ApiAgentInvocationDetail = ApiAgentInvocation & {
|
|
|
259
273
|
export declare type ApiAgentInvocationStatus = 'active' | 'cancelled' | 'archived';
|
|
260
274
|
|
|
261
275
|
export declare type ApiAgentResource = {
|
|
262
|
-
|
|
263
|
-
type
|
|
264
|
-
|
|
265
|
-
|
|
276
|
+
id: string;
|
|
277
|
+
type: ApiAgentResourceType | string;
|
|
278
|
+
title: string;
|
|
279
|
+
mis_record_url?: string | null;
|
|
280
|
+
created_datetime: string;
|
|
281
|
+
last_updated_datetime: string;
|
|
266
282
|
};
|
|
267
283
|
|
|
284
|
+
export declare type ApiAgentResourceType = 'document_html' | 'mis_record' | 'workflow' | 'file' | 'link';
|
|
285
|
+
|
|
268
286
|
export declare type ApiAgentTimelineActionLogEntry = {
|
|
269
287
|
timestamp: string;
|
|
270
288
|
type: string;
|
|
@@ -379,8 +397,17 @@ export declare type ApiCreateAgentResponse = {
|
|
|
379
397
|
|
|
380
398
|
export declare type ApiDemoDataset = 'full' | 'sparse' | 'empty';
|
|
381
399
|
|
|
382
|
-
export declare type
|
|
383
|
-
|
|
400
|
+
export declare type ApiListResourcesParams = {
|
|
401
|
+
pageNumber?: number;
|
|
402
|
+
pageSize?: number;
|
|
403
|
+
type?: ApiAgentResourceType;
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
export declare type ApiResourcesEndpointResponse = {
|
|
407
|
+
resources: ApiAgentResource[];
|
|
408
|
+
page_number: number;
|
|
409
|
+
page_size: number;
|
|
410
|
+
total_records: number;
|
|
384
411
|
};
|
|
385
412
|
|
|
386
413
|
export declare type ApiTripOption = {
|
|
@@ -495,7 +522,7 @@ export declare const mapApiOpeningMessage: (record: Pick<ApiAgentInvocation, "op
|
|
|
495
522
|
|
|
496
523
|
export declare const mapApiResource: (record: ApiAgentResource) => AgentResource;
|
|
497
524
|
|
|
498
|
-
export declare const mapApiResourcesEndpointResponse: (payload: ApiResourcesEndpointResponse) =>
|
|
525
|
+
export declare const mapApiResourcesEndpointResponse: (payload: ApiResourcesEndpointResponse) => AgentResourcesPage;
|
|
499
526
|
|
|
500
527
|
export declare const mapApiTripOption: (record: ApiTripOption) => {
|
|
501
528
|
hasRunBefore?: true | undefined;
|
|
@@ -579,6 +606,7 @@ export declare type UseAgentWorkspaceResult = {
|
|
|
579
606
|
connector: ChatConnector;
|
|
580
607
|
fetchAgentChecklist: (invocationId: string) => Promise<AgentChecklistResponse>;
|
|
581
608
|
fetchAgentResources: (invocationId: string) => Promise<AgentResource[]>;
|
|
609
|
+
fetchAgentResourceHtml: (invocationId: string, resourceId: string) => Promise<string>;
|
|
582
610
|
fetchAgentTimeline: (invocationId: string) => Promise<AgentTimeline>;
|
|
583
611
|
};
|
|
584
612
|
|