@arbor-education/agent-view-frontend 0.4.2 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -0
- package/dist/index.cjs +4 -4
- package/dist/index.d.ts +28 -2
- package/dist/index.js +1216 -1154
- package/dist/style.css +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -151,6 +151,43 @@ const api = 'https://ai-agent-service.qa.arbor.engineering/api/v1';
|
|
|
151
151
|
Parameterised routes substitute the `:invocationId` placeholder. See the
|
|
152
152
|
[AI service SDK](#ai-service-sdk) section for the underlying client.
|
|
153
153
|
|
|
154
|
+
### Standalone `NewAgentModal`
|
|
155
|
+
|
|
156
|
+
`NewAgentModal` normally renders as a child of `AgentMonitorKanban` (the board
|
|
157
|
+
supplies `agentDefinitions` and an `onStart` handler). It can also be mounted on
|
|
158
|
+
its own — e.g. as a server-rendered `new-agent-modal` widget — by passing
|
|
159
|
+
endpoint URLs instead. In this mode the modal loads its own definitions, creates
|
|
160
|
+
the agent, and navigates the page on close/success.
|
|
161
|
+
|
|
162
|
+
```tsx
|
|
163
|
+
import { NewAgentModal } from 'agent-view-frontend';
|
|
164
|
+
|
|
165
|
+
const api = 'https://ai-agent-service.qa.arbor.engineering/api/v1';
|
|
166
|
+
|
|
167
|
+
<NewAgentModal
|
|
168
|
+
open
|
|
169
|
+
authToken={jwt}
|
|
170
|
+
headers={{ 'X-Arbor-Application': 'agent-view' }}
|
|
171
|
+
agentDefinitionsUrl={`${api}/agent-definitions`}
|
|
172
|
+
agentsUrl={`${api}/agents`}
|
|
173
|
+
closeUrl="/dashboard"
|
|
174
|
+
successUrl="/agents"
|
|
175
|
+
/>;
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
| Prop | Attribute | Required | Purpose |
|
|
179
|
+
|---|---|---|---|
|
|
180
|
+
| `agentDefinitionsUrl` | `agent-definitions-url` | yes | Full URL to GET the agent definitions list. |
|
|
181
|
+
| `agentsUrl` | `agents-url` | yes | Full URL to POST a new agent. |
|
|
182
|
+
| `authToken` | `auth-token` | no | Bearer token attached to every request. |
|
|
183
|
+
| `headers` | `headers` | no | Extra headers merged into every request. |
|
|
184
|
+
| `open` | `open` | no | Whether the modal is open. |
|
|
185
|
+
| `closeUrl` | `close-url` | no | Page navigated to when the modal is closed. |
|
|
186
|
+
| `successUrl` | `success-url` | no | Page navigated to after a successful start. |
|
|
187
|
+
|
|
188
|
+
Navigation uses `window.location.assign`. `closeUrl`/`successUrl` are optional —
|
|
189
|
+
omit them (and pass `onClose`/`onStart`) to keep the modal fully controlled.
|
|
190
|
+
|
|
154
191
|
---
|
|
155
192
|
|
|
156
193
|
## NPM usage
|
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"),i=require("react"),F=require("classnames"),g=require("@arbor-education/design-system.components"),oe=require("@arbor-education/ask-arbor-chat-panel"),y={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},E={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},T={briefing:"briefing",running:"running",stopped:"stopped",complete:"complete"},K={agent:"agent",user:"user",system:"system"},se={MIS_RECORD:"MIS_RECORD",FILE:"FILE",WORKFLOW:"WORKFLOW",LINK:"LINK"},We={cancelled:"cancelled",archived:"archived"},Le={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},B={[E.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[E.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[E.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[E["generating-a-response"]]:{label:"Generating a response",icon:"sparkles",color:"var(--color-brand-600)"}},Ee={[y["generating-a-response"]]:{status:y["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:B["generating-a-response"].icon,color:B["generating-a-response"].color}},[y.hitl]:{status:y.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:B.hitl.icon,color:B.hitl.color}},[y.complete]:{status:y.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:B.complete.icon,color:B.complete.color}},[y.failed]:{status:y.failed,title:"Failed",dotColour:"salmon",statusIcon:{name:B.failed.icon,color:B.failed.color}}},At=[y["generating-a-response"],y.hitl],Nt=[y.complete,y.failed],jt="m4",St="1",et="msg-opening",Te="Unable to load agent tasks. Please try again.",Ct="Unable to load the resources for this agent",tt="Unable to load the timeline for this agent",bt="Something went wrong. Please try again.",nt="Unable to load agents. Please try again.",ae="Loading tasks…",Je="Loading agents…",Tt="Task",Et={[T.briefing]:"Briefing",[T.running]:"Working",[T.stopped]:"Stopped",[T.complete]:"Complete"},It=[y["generating-a-response"],y.hitl,y.complete,y.failed],Rt={[y["generating-a-response"]]:"Agents currently working on tasks for you.",[y.hitl]:"Agents that need your input before they can continue.",[y.complete]:"Agents that have finished their work.",[y.failed]:"Agents that failed or were stopped."},Ot=()=>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)"})]}),Pt=({status:t})=>{const e=Ee[t];return e.statusIcon?n.jsx(g.Icon,{name:e.statusIcon.name,size:16,color:e.statusIcon.color,screenReaderText:e.title}):n.jsx(g.Dot,{colour:e.dotColour,label:e.title})},Mt=()=>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(g.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:It.map(t=>{const e=Ee[t];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(Pt,{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:Rt[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(Ot,{})})]}),Lt=(t,e)=>({...t,...e.length>0?{children:e}:{}}),st=t=>{const e=[],s=[];for(const a of t){const r=a.children?st(a.children):{needsInput:[],tasks:[]};if(e.push(...r.needsInput),a.status===E.hitl){e.push({...a,children:void 0});continue}s.push(Lt(a,r.tasks))}return{needsInput:e,tasks:s}},Ut=t=>t.map((e,s)=>({item:e,index:s})).sort((e,s)=>{const a=e.item.status===E.hitl,r=s.item.status===E.hitl;return a!==r?a?-1:1:e.index-s.index}).map(({item:e})=>e),$t=({checklist:t})=>t.length===0?n.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):n.jsx("ul",{className:"agent-view__progress-list","aria-label":"Agent tasks",children:Ut(t).map(e=>{const s=B[e.status];return n.jsxs("li",{className:F("agent-view__progress-item",`agent-view__progress-item--${e.status.replace(/_/g,"-")}`),children:[n.jsx(g.Icon,{name:s.icon,size:16,color:s.color,screenReaderText:`${s.label}:`}),n.jsxs("div",{className:"agent-view__progress-item-content",children:[n.jsx("span",{className:"agent-view__progress-label",children:e.task}),e.status!==E.complete&&n.jsx("span",{className:"agent-view__progress-description",children:e.description})]})]},e.task)})}),Dt=({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 Ht{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:oe.CHAT_RESPONSE_TYPE_AGENT,...r.message.followUpPrompts?{followUpPrompts:r.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:bt,type:oe.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 Bt=({connector:t,phase:e,chatHistory:s,chatSessionKey:a,startQuery:r,clarificationMessage:c,enableUpload:o=!1,onTurn:l,onAwaitingChange:d,onClarificationPrompt:_,onDismissClarification:h})=>{const p=i.useMemo(()=>new Ht(t,{canSend:()=>e===T.running,onTurn:l,onAwaitingChange:d}),[t,e,l,d]),x=e!==T.running,k=e===T.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(Dt,{prompts:c.followUpPrompts,onSelect:_}),n.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:h,children:"Dismiss"})]}),n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(oe.ChatPanel,{connector:p,chatHistory:s,startQuery:r,lockConversation:x,enableUpload:o,speechEnabled:k,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:k?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)}),e===T.stopped&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(g.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===T.complete&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(g.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),n.jsx("span",{children:"The agent has finished."})]})]})},at=({item:t,depth:e,canRequestInput:s,onAttentionItemClick:a})=>{const r=B[t.status],c=t.status.replace(/_/g,"-"),o=t.status===E.hitl&&s&&a,l=n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(g.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!==E.complete&&t.description&&n.jsx("span",{className:"agent-workspace__task-description",children:t.description})]})]});return n.jsxs("li",{className:F("agent-workspace__task",`agent-workspace__task--${c}`,{"agent-workspace__task--child":e>0}),children:[o?n.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${t.task}`,onClick:()=>a(t),children:l}):l,t.children&&t.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:t.children.map(d=>n.jsx(at,{item:d,depth:e+1,canRequestInput:s,onAttentionItemClick:a},d.task))})]})},Ve=({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(at,{item:r,depth:0,canRequestInput:s,onAttentionItemClick:a},r.task))}),Ft=({checklist:t,isLoading:e,error:s,phase:a,canRequestInput:r,onStop:c,onAttentionItemClick:o})=>{const l=i.useMemo(()=>t?st(t):null,[t]);return n.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--checklist","aria-label":"Checklist",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(g.Heading,{level:4,children:"Checklist"}),a===T.running&&n.jsx(g.Button,{variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Stop",onClick:c,children:"Stop agent"})]}),n.jsxs("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:[e&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(g.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:ae}),n.jsx("span",{children:ae})]}),!e&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!e&&!s&&l&&n.jsxs(n.Fragment,{children:[l.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(Ve,{items:l.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:r,onAttentionItemClick:o})]}),l.tasks.length>0&&n.jsxs("div",{className:F("agent-workspace__task-group",{"agent-workspace__task-group--following":l.needsInput.length>0}),children:[l.needsInput.length>0&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Other tasks"}),n.jsx(Ve,{items:l.tasks,ariaLabel:"Agent tasks",canRequestInput:r,onAttentionItemClick:o})]})]}),!e&&!s&&(!l||l.needsInput.length===0&&l.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:a===T.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})]})},Gt={[se.MIS_RECORD]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[se.FILE]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[se.WORKFLOW]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[se.LINK]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},zt=({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(g.Heading,{level:4,children:"Resources"}),n.jsx("span",{className:"agent-workspace__panel-count",children:t.length})]}),n.jsxs("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:[e&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(g.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=Gt[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(g.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(g.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},qt=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),Ue=t=>{const e=new Date(t);return Number.isFinite(e.getTime())?qt.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(" ")),he=(t,e)=>e<=1?0:t/(e-1)*100,rt=t=>Math.max(t,0)+2,Kt=t=>t+1,Wt=(t,e)=>{if(e.length===0)return 50;const s=rt(e.length),a=he(1,s),r=he(e.length,s),c=e.map(h=>Ie(h.timestamp)),o=Math.min(...c),l=Math.max(...c);if(l<=o)return a;const d=(Ie(t.timestamp)-o)/(l-o),_=Math.min(1,Math.max(0,d));return a+_*(r-a)},Jt=8,Vt=20,Yt=(t,e=Jt,s=Vt)=>{const a=new Map;if(t.length===0)return a;const r=[...t].sort((o,l)=>o.leftPercent-l.leftPercent||o.timestampMs-l.timestampMs||o.id.localeCompare(l.id)),c=[];for(const o of r){const l=c[c.length-1];l&&o.leftPercent-l[l.length-1].leftPercent<e?l.push(o):c.push([o])}for(const o of c){const l=[...o].sort((_,h)=>_.timestampMs-h.timestampMs||_.id.localeCompare(h.id)),d=(l.length-1)/2;l.forEach((_,h)=>{a.set(_.id,(h-d)*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%)"}),Xt=t=>t.type!=="message-sent",Qt=({timeline:t,isLoading:e,error:s,onOpenChatSession:a})=>{const r=((t==null?void 0:t.actionLog)??[]).filter(Xt),c=(t==null?void 0:t.chatSessions)??[],o=!e&&!s&&r.length===0&&c.length===0,l=rt(r.length),d=r.map((p,x)=>({id:`action-${p.timestamp}-${x}`,leftPercent:he(Kt(x),l),timestampMs:Ie(p.timestamp)})),_=c.map(p=>({id:p.sessionId,leftPercent:Wt(p,r),timestampMs:Ie(p.timestamp)})),h=Yt([...d,..._]);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||tt}),o&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!e&&!s&&!o&&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(he(0,l)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(g.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Start"})]}),r.map((p,x)=>{const k=`action-${p.timestamp}-${x}`,j=d[x].leftPercent,N=p.type==="checklist-updated",U=p.type==="status-transition",S=N?"checklist":U?"status":"note";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${S}`,style:be(j,h.get(k)??0),children:[n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${S}`,"aria-label":`${Ce(p.type)}: ${Ce(p.entry)}`,children:[N&&n.jsx(g.Icon,{name:"check-solid",size:16,color:"currentColor"}),U&&n.jsx(g.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(p.type)}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Ce(p.entry)}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Ue(p.timestamp)})]})]},k)}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:be(he(l-1,l)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(g.Icon,{name:"flag",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Finish"})]}),c.map((p,x)=>{const k=_[x].leftPercent;return n.jsxs("div",{className:"agent-timeline__chat-station",style:be(k,h.get(p.sessionId)??0),children:[n.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${Ue(p.timestamp)}`,onClick:()=>a(p.sessionId),children:n.jsx(g.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:Ue(p.timestamp)})]})]},p.sessionId)})]})]})},Zt=["I'll get the details and come back to you","Skip this for now"],en=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:K.agent,text:e,followUpPrompts:t.clarificationPrompts??Zt}},pe=t=>({id:t.id,text:t.text,type:t.author===K.user?oe.CHAT_RESPONSE_TYPE_USER:t.author===K.system?oe.CHAT_RESPONSE_TYPE_INFO:oe.CHAT_RESPONSE_TYPE_AGENT,...t.followUpPrompts?{followUpPrompts:t.followUpPrompts}:{}});class re extends Error{constructor(e,s,a){super(a??`Agent service request failed (${e})`),this.name="AgentServiceError",this.status=e,this.detail=s}}const tn="/api/v1",M={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},L={GET:"GET",POST:"POST"},nn={error:"error"},sn={user:"user"},ie={acceptJson:"application/json",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},an=/:invocationId\b/g,rn=t=>t.trim().replace(/^Bearer\s+/i,""),on=t=>t.endsWith("/")?t.slice(0,-1):t;class Be{constructor(e){var a;this.baseUrl=on(e.baseUrl??"");const s=(a=e.token)==null?void 0:a.trim();this.token=s?rn(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(L.GET,this.resolveUrl("agentDefinitions",M.agentDefinitions))).agent_definitions??[]}getAgentDefinition(e){return this.request(L.GET,this.apiUrl(`${M.agentDefinitions}/${encodeURIComponent(e)}`))}listTripOptions(){return this.request(L.GET,this.apiUrl(M.tripOptions))}getDataset(){return this.request(L.GET,this.apiUrl(M.demoDataset))}setDataset(e){return this.request(L.POST,this.apiUrl(M.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(L.GET,`${this.resolveUrl("agents",M.agents)}${a}`)}createAgent(e,s={}){var o,l;const a={agent_definition_ref:e},r=(o=s.invocationName)==null?void 0:o.trim(),c=(l=s.agentIntent)==null?void 0:l.trim();return r&&(a.invocation_name=r),c&&(a.agent_intent=c),this.request(L.POST,this.resolveUrl("agents",M.agents),a)}getAgent(e){return this.request(L.GET,this.resolveUrl("agent",`${M.agents}/${encodeURIComponent(e)}`,e))}getAgentChecklist(e){return this.request(L.GET,this.resolveUrl("agentChecklist",`${M.agents}/${encodeURIComponent(e)}/checklist`,e))}getAgentResources(e){return this.request(L.GET,this.resolveUrl("agentResources",`${M.agents}/${encodeURIComponent(e)}/resources`,e))}getAgentTimeline(e){return this.request(L.GET,this.resolveUrl("agentTimeline",`${M.agents}/${encodeURIComponent(e)}/agent-timeline`,e))}getAgentContext(e){return this.request(L.GET,this.apiUrl(`${M.agents}/${encodeURIComponent(e)}/context`))}cancelAgent(e){return this.request(L.POST,this.apiUrl(`${M.agents}/${encodeURIComponent(e)}/cancel`))}archiveAgent(e){return this.request(L.POST,this.apiUrl(`${M.agents}/${encodeURIComponent(e)}/archive`))}getConversation(e){return this.request(L.GET,this.resolveUrl("agentConversation",`${M.conversations}/${encodeURIComponent(e)}`,e))}async chat(e,s,a={}){const r=!!(a.uploadFiles&&a.uploadFiles.length>0),c=await this.fetchImpl(this.resolveUrl("agentChat",`${M.agents}/${encodeURIComponent(e)}/chat`,e),{method:L.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:ie.acceptEventStream,...r?{}:{"Content-Type":ie.contentTypeJson}},body:r?ln(s,a.uploadFiles??[]):JSON.stringify(s),signal:a.signal});if(!c.ok)throw await this.toError(c);if(!c.body)throw new re(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}${tn}${e}`}resolveUrl(e,s,a){const r=this.urls[e];return r?a?r.replace(an,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:ie.acceptJson,...a===void 0?{}:{"Content-Type":ie.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 re(e.status,s,`Agent service request failed (${e.status} ${e.statusText})`)}async consumeSse(e,s){const a=e.getReader(),r=new TextDecoder;let c="",o;const l=d=>{const{event:_,data:h}=cn(d);if(h===null)return;if(_===nn.error){const x=Ye(h);throw new re(502,x,(x==null?void 0:x.message)??"Chat stream error")}const p=Ye(h);p&&(o=p,s==null||s(p))};for(;;){const{done:d,value:_}=await a.read();if(d)break;c+=r.decode(_,{stream:!0});const h=c.split(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),r=require("react"),G=require("classnames"),g=require("@arbor-education/design-system.components"),oe=require("@arbor-education/ask-arbor-chat-panel"),j={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},O={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},E={briefing:"briefing",running:"running",stopped:"stopped",complete:"complete"},X={agent:"agent",user:"user",system:"system"},se={MIS_RECORD:"MIS_RECORD",FILE:"FILE",WORKFLOW:"WORKFLOW",LINK:"LINK"},Je={cancelled:"cancelled",archived:"archived"},De={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},W={[O.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[O.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[O.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[O["generating-a-response"]]:{label:"Generating a response",icon:"sparkles",color:"var(--color-brand-600)"}},Ee={[j["generating-a-response"]]:{status:j["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:W["generating-a-response"].icon,color:W["generating-a-response"].color}},[j.hitl]:{status:j.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:W.hitl.icon,color:W.hitl.color}},[j.complete]:{status:j.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:W.complete.icon,color:W.complete.color}},[j.failed]:{status:j.failed,title:"Failed",dotColour:"salmon",statusIcon:{name:W.failed.icon,color:W.failed.color}}},Ct=[j["generating-a-response"],j.hitl],bt=[j.complete,j.failed],Tt="m4",Et="1",st="msg-opening",Te="Unable to load agent tasks. Please try again.",It="Unable to load the resources for this agent",at="Unable to load the timeline for this agent",Rt="Something went wrong. Please try again.",it="Unable to load agents. Please try again.",ae="Loading tasks…",Ve="Loading agents…",Ot="Task",Pt={[E.briefing]:"Briefing",[E.running]:"Working",[E.stopped]:"Stopped",[E.complete]:"Complete"},Mt=[j["generating-a-response"],j.hitl,j.complete,j.failed],Lt={[j["generating-a-response"]]:"Agents currently working on tasks for you.",[j.hitl]:"Agents that need your input before they can continue.",[j.complete]:"Agents that have finished their work.",[j.failed]:"Agents that failed or were stopped."},Dt=()=>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)"})]}),$t=({status:e})=>{const t=Ee[e];return t.statusIcon?n.jsx(g.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,screenReaderText:t.title}):n.jsx(g.Dot,{colour:t.dotColour,label:t.title})},Ut=()=>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(g.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:Mt.map(e=>{const t=Ee[e];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx($t,{status:e})}),n.jsxs("span",{className:"agent-view__empty-column-text",children:[n.jsx("span",{className:"agent-view__empty-column-title",children:t.title}),n.jsx("span",{className:"agent-view__empty-column-description",children:Lt[e]})]})]},e)})}),n.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",n.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),n.jsx("div",{className:"agent-view__empty-visual",children:n.jsx(Dt,{})})]}),Bt=(e,t)=>({...e,...t.length>0?{children:t}:{}}),rt=e=>{const t=[],s=[];for(const a of e){const i=a.children?rt(a.children):{needsInput:[],tasks:[]};if(t.push(...i.needsInput),a.status===O.hitl){t.push({...a,children:void 0});continue}s.push(Bt(a,i.tasks))}return{needsInput:t,tasks:s}},Ht=e=>e.map((t,s)=>({item:t,index:s})).sort((t,s)=>{const a=t.item.status===O.hitl,i=s.item.status===O.hitl;return a!==i?a?-1:1:t.index-s.index}).map(({item:t})=>t),Ft=({checklist:e})=>e.length===0?n.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):n.jsx("ul",{className:"agent-view__progress-list","aria-label":"Agent tasks",children:Ht(e).map(t=>{const s=W[t.status];return n.jsxs("li",{className:G("agent-view__progress-item",`agent-view__progress-item--${t.status.replace(/_/g,"-")}`),children:[n.jsx(g.Icon,{name:s.icon,size:16,color:s.color,screenReaderText:`${s.label}:`}),n.jsxs("div",{className:"agent-view__progress-item-content",children:[n.jsx("span",{className:"agent-view__progress-label",children:t.task}),t.status!==O.complete&&n.jsx("span",{className:"agent-view__progress-description",children:t.description})]})]},t.task)})}),zt=({prompts:e,classNamePrefix:t="agent-workspace",onSelect:s})=>e.length===0?null:n.jsx("div",{className:`${t}__chips`,children:e.map(a=>n.jsx("button",{type:"button",className:`${t}__chip`,onClick:()=>s(a),children:a},a))});class Gt{constructor(t,s){this.connector=t,this.canSend=s.canSend,this.onTurn=s.onTurn,this.onAwaitingChange=s.onAwaitingChange}get canRate(){return!1}get canLoadHistory(){return!1}get canListInteractions(){return!1}get canSendNotification(){return!1}get ratingPopupUrls(){return{}}async sendMessage(t){var s,a;if(!this.canSend())return null;(s=this.onAwaitingChange)==null||s.call(this,!0);try{const i=await this.connector.sendMessage(t.userMessage,t.uploadFiles);return this.onTurn(i),{id:i.message.id,text:i.message.text,type:oe.CHAT_RESPONSE_TYPE_AGENT,...i.message.followUpPrompts?{followUpPrompts:i.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:Rt,type:oe.CHAT_RESPONSE_TYPE_ERROR}}finally{(a=this.onAwaitingChange)==null||a.call(this,!1)}}async loadHistory(t){return null}async listInteractions(){return null}async rateMessage(t){}async sendNotification(t){return!1}}const qt=({connector:e,phase:t,chatHistory:s,chatSessionKey:a,startQuery:i,clarificationMessage:l,enableUpload:o=!1,onTurn:c,onAwaitingChange:d,onClarificationPrompt:f,onDismissClarification:h})=>{const u=r.useMemo(()=>new Gt(e,{canSend:()=>t===E.running,onTurn:c,onAwaitingChange:d}),[e,t,c,d]),w=t!==E.running,m=t===E.running;return n.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[l&&n.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[n.jsx("p",{className:"agent-workspace__clarification-text",children:l.text}),l.followUpPrompts&&n.jsx(zt,{prompts:l.followUpPrompts,onSelect:f}),n.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:h,children:"Dismiss"})]}),n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(oe.ChatPanel,{connector:u,chatHistory:s,startQuery:i,lockConversation:w,enableUpload:o,speechEnabled:m,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:m?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)}),t===E.stopped&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(g.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."})]}),t===E.complete&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(g.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),n.jsx("span",{children:"The agent has finished."})]})]})},ot=({item:e,depth:t,canRequestInput:s,onAttentionItemClick:a})=>{const i=W[e.status],l=e.status.replace(/_/g,"-"),o=e.status===O.hitl&&s&&a,c=n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(g.Icon,{name:i.icon,size:16,color:i.color,screenReaderText:`${i.label}:`}),n.jsxs("div",{className:"agent-workspace__task-content",children:[n.jsx("span",{className:"agent-workspace__task-label",children:e.task}),e.status!==O.complete&&e.description&&n.jsx("span",{className:"agent-workspace__task-description",children:e.description})]})]});return n.jsxs("li",{className:G("agent-workspace__task",`agent-workspace__task--${l}`,{"agent-workspace__task--child":t>0}),children:[o?n.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${e.task}`,onClick:()=>a(e),children:c}):c,e.children&&e.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:e.children.map(d=>n.jsx(ot,{item:d,depth:t+1,canRequestInput:s,onAttentionItemClick:a},d.task))})]})},Ye=({items:e,ariaLabel:t,canRequestInput:s,onAttentionItemClick:a})=>n.jsx("ul",{className:"agent-workspace__task-list","aria-label":t,children:e.map(i=>n.jsx(ot,{item:i,depth:0,canRequestInput:s,onAttentionItemClick:a},i.task))}),Kt=({checklist:e,isLoading:t,error:s,phase:a,canRequestInput:i,onStop:l,onAttentionItemClick:o})=>{const c=r.useMemo(()=>e?rt(e):null,[e]);return n.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--checklist","aria-label":"Checklist",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(g.Heading,{level:4,children:"Checklist"}),a===E.running&&n.jsx(g.Button,{variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Stop",onClick:l,children:"Stop agent"})]}),n.jsxs("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:[t&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(g.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:ae}),n.jsx("span",{children:ae})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!t&&!s&&c&&n.jsxs(n.Fragment,{children:[c.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(Ye,{items:c.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:i,onAttentionItemClick:o})]}),c.tasks.length>0&&n.jsxs("div",{className:G("agent-workspace__task-group",{"agent-workspace__task-group--following":c.needsInput.length>0}),children:[c.needsInput.length>0&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Other tasks"}),n.jsx(Ye,{items:c.tasks,ariaLabel:"Agent tasks",canRequestInput:i,onAttentionItemClick:o})]})]}),!t&&!s&&(!c||c.needsInput.length===0&&c.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:a===E.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})]})},Wt={[se.MIS_RECORD]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[se.FILE]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[se.WORKFLOW]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[se.LINK]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},Jt=({resources:e,isLoading:t=!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(g.Heading,{level:4,children:"Resources"}),n.jsx("span",{className:"agent-workspace__panel-count",children:e.length})]}),n.jsxs("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:[t&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(g.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading resources"}),n.jsx("span",{children:"Loading resources…"})]}),!t&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!t&&!s&&e.length>0&&n.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:e.map(a=>{const i=Wt[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(g.Icon,{name:i.icon,size:16,color:i.color,screenReaderText:`${i.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:i.label})]}),a.description&&n.jsx("span",{className:"agent-workspace__resource-description",children:a.description})]}),n.jsx(g.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}`)})}),!t&&!s&&e.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})]}),Ie=e=>{const t=Date.parse(e);return Number.isFinite(t)?t:0},Vt=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),$e=e=>{const t=new Date(e);return Number.isFinite(t.getTime())?Vt.format(t):e},Ce=e=>e.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,t=>t.split(/[_-]/).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")),he=(e,t)=>t<=1?0:e/(t-1)*100,ct=e=>Math.max(e,0)+2,Yt=e=>e+1,Xt=(e,t)=>{if(t.length===0)return 50;const s=ct(t.length),a=he(1,s),i=he(t.length,s),l=t.map(h=>Ie(h.timestamp)),o=Math.min(...l),c=Math.max(...l);if(c<=o)return a;const d=(Ie(e.timestamp)-o)/(c-o),f=Math.min(1,Math.max(0,d));return a+f*(i-a)},Qt=8,Zt=20,en=(e,t=Qt,s=Zt)=>{const a=new Map;if(e.length===0)return a;const i=[...e].sort((o,c)=>o.leftPercent-c.leftPercent||o.timestampMs-c.timestampMs||o.id.localeCompare(c.id)),l=[];for(const o of i){const c=l[l.length-1];c&&o.leftPercent-c[c.length-1].leftPercent<t?c.push(o):l.push([o])}for(const o of l){const c=[...o].sort((f,h)=>f.timestampMs-h.timestampMs||f.id.localeCompare(h.id)),d=(c.length-1)/2;c.forEach((f,h)=>{a.set(f.id,(h-d)*s)})}return a},be=(e,t=0)=>({left:`calc(${e/100} * (100% - var(--agent-timeline-node-size)) + (var(--agent-timeline-node-size) / 2) + ${t}px)`,transform:"translateX(-50%)"}),tn=e=>e.type!=="message-sent",nn=({timeline:e,isLoading:t,error:s,onOpenChatSession:a})=>{const i=((e==null?void 0:e.actionLog)??[]).filter(tn),l=(e==null?void 0:e.chatSessions)??[],o=!t&&!s&&i.length===0&&l.length===0,c=ct(i.length),d=i.map((u,w)=>({id:`action-${u.timestamp}-${w}`,leftPercent:he(Yt(w),c),timestampMs:Ie(u.timestamp)})),f=l.map(u=>({id:u.sessionId,leftPercent:Xt(u,i),timestampMs:Ie(u.timestamp)})),h=en([...d,...f]);return n.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[t&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),s&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:s||at}),o&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!t&&!s&&!o&&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(he(0,c)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(g.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Start"})]}),i.map((u,w)=>{const m=`action-${u.timestamp}-${w}`,S=d[w].leftPercent,y=u.type==="checklist-updated",T=u.type==="status-transition",D=y?"checklist":T?"status":"note";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${D}`,style:be(S,h.get(m)??0),children:[n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${D}`,"aria-label":`${Ce(u.type)}: ${Ce(u.entry)}`,children:[y&&n.jsx(g.Icon,{name:"check-solid",size:16,color:"currentColor"}),T&&n.jsx(g.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:$e(u.timestamp)})]})]},m)}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:be(he(c-1,c)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(g.Icon,{name:"flag",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Finish"})]}),l.map((u,w)=>{const m=f[w].leftPercent;return n.jsxs("div",{className:"agent-timeline__chat-station",style:be(m,h.get(u.sessionId)??0),children:[n.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${$e(u.timestamp)}`,onClick:()=>a(u.sessionId),children:n.jsx(g.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:$e(u.timestamp)})]})]},u.sessionId)})]})]})},sn=["I'll get the details and come back to you","Skip this for now"],an=e=>{var s;const t=(s=e.prompt)!=null&&s.trim()?e.prompt.trim():`I need a bit more from you on "${e.task}". ${e.description} What can you tell me?`;return{id:`clarification-${Date.now()}`,author:X.agent,text:t,followUpPrompts:e.clarificationPrompts??sn}},pe=e=>({id:e.id,text:e.text,type:e.author===X.user?oe.CHAT_RESPONSE_TYPE_USER:e.author===X.system?oe.CHAT_RESPONSE_TYPE_INFO:oe.CHAT_RESPONSE_TYPE_AGENT,...e.followUpPrompts?{followUpPrompts:e.followUpPrompts}:{}});class ie extends Error{constructor(t,s,a){super(a??`Agent service request failed (${t})`),this.name="AgentServiceError",this.status=t,this.detail=s}}const rn="/api/v1",U={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},B={GET:"GET",POST:"POST"},on={error:"error"},cn={user:"user"},re={acceptJson:"application/json",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},ln=/:invocationId\b/g,dn=e=>e.trim().replace(/^Bearer\s+/i,""),gn=e=>e.endsWith("/")?e.slice(0,-1):e;class Re{constructor(t){var a;this.baseUrl=gn(t.baseUrl??"");const s=(a=t.token)==null?void 0:a.trim();this.token=s?dn(s):void 0,this.customHeaders=t.headers,this.urls=t.urls??{},this.fetchImpl=t.fetch??globalThis.fetch.bind(globalThis)}setHeaders(t){this.customHeaders=t}async listAgentDefinitions(){return(await this.request(B.GET,this.resolveUrl("agentDefinitions",U.agentDefinitions))).agent_definitions??[]}getAgentDefinition(t){return this.request(B.GET,this.apiUrl(`${U.agentDefinitions}/${encodeURIComponent(t)}`))}listTripOptions(){return this.request(B.GET,this.apiUrl(U.tripOptions))}getDataset(){return this.request(B.GET,this.apiUrl(U.demoDataset))}setDataset(t){return this.request(B.POST,this.apiUrl(U.demoDataset),{dataset:t})}listAgents(t={}){const s=new URLSearchParams;t.status&&s.set("status",t.status),t.agentDefinitionRef&&s.set("agent_definition_ref",t.agentDefinitionRef);const a=s.toString()?`?${s.toString()}`:"";return this.request(B.GET,`${this.resolveUrl("agents",U.agents)}${a}`)}createAgent(t,s={}){var o,c;const a={agent_definition_ref:t},i=(o=s.invocationName)==null?void 0:o.trim(),l=(c=s.agentIntent)==null?void 0:c.trim();return i&&(a.invocation_name=i),l&&(a.agent_intent=l),this.request(B.POST,this.resolveUrl("agents",U.agents),a)}getAgent(t){return this.request(B.GET,this.resolveUrl("agent",`${U.agents}/${encodeURIComponent(t)}`,t))}getAgentChecklist(t){return this.request(B.GET,this.resolveUrl("agentChecklist",`${U.agents}/${encodeURIComponent(t)}/checklist`,t))}getAgentResources(t){return this.request(B.GET,this.resolveUrl("agentResources",`${U.agents}/${encodeURIComponent(t)}/resources`,t))}getAgentTimeline(t){return this.request(B.GET,this.resolveUrl("agentTimeline",`${U.agents}/${encodeURIComponent(t)}/agent-timeline`,t))}getAgentContext(t){return this.request(B.GET,this.apiUrl(`${U.agents}/${encodeURIComponent(t)}/context`))}cancelAgent(t){return this.request(B.POST,this.apiUrl(`${U.agents}/${encodeURIComponent(t)}/cancel`))}archiveAgent(t){return this.request(B.POST,this.apiUrl(`${U.agents}/${encodeURIComponent(t)}/archive`))}getConversation(t){return this.request(B.GET,this.resolveUrl("agentConversation",`${U.conversations}/${encodeURIComponent(t)}`,t))}async chat(t,s,a={}){const i=!!(a.uploadFiles&&a.uploadFiles.length>0),l=await this.fetchImpl(this.resolveUrl("agentChat",`${U.agents}/${encodeURIComponent(t)}/chat`,t),{method:B.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:re.acceptEventStream,...i?{}:{"Content-Type":re.contentTypeJson}},body:i?pn(s,a.uploadFiles??[]):JSON.stringify(s),signal:a.signal});if(!l.ok)throw await this.toError(l);if(!l.body)throw new ie(l.status,null,"Chat response contained no stream body");return this.consumeSse(l.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(t){return`${this.baseUrl}${rn}${t}`}resolveUrl(t,s,a){const i=this.urls[t];return i?a?i.replace(ln,encodeURIComponent(a)):i:this.apiUrl(s)}async request(t,s,a){const i=await this.fetchImpl(s,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:re.acceptJson,...a===void 0?{}:{"Content-Type":re.contentTypeJson}},...a===void 0?{}:{body:JSON.stringify(a)}});if(!i.ok)throw await this.toError(i);if(i.status!==204)return await i.json()}async toError(t){let s=null;try{s=await t.json()}catch{}return new ie(t.status,s,`Agent service request failed (${t.status} ${t.statusText})`)}async consumeSse(t,s){const a=t.getReader(),i=new TextDecoder;let l="",o;const c=d=>{const{event:f,data:h}=un(d);if(h===null)return;if(f===on.error){const w=Xe(h);throw new ie(502,w,(w==null?void 0:w.message)??"Chat stream error")}const u=Xe(h);u&&(o=u,s==null||s(u))};for(;;){const{done:d,value:f}=await a.read();if(d)break;l+=i.decode(f,{stream:!0});const h=l.split(`
|
|
2
2
|
|
|
3
|
-
`);
|
|
4
|
-
`)){const
|
|
5
|
-
`):null}},Ye=t=>{try{return JSON.parse(t)}catch{return}};function ln(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 it=t=>{switch(t){case We.cancelled:return y.failed;case We.archived:return y.complete;case y.hitl:case y.complete:case y.failed:case y["generating-a-response"]:return t;default:return y["generating-a-response"]}},ot=t=>{switch(t){case Le.requires_attention:return E.hitl;case Le.in_progress:case Le.available:return E["generating-a-response"];case E.failed:case E.complete:case E.hitl:case E["generating-a-response"]:return t;default:return E["generating-a-response"]}},ct=t=>({ref:t.name,display_name:t.display_name,agent_intent:t.agent_intent??t.display_name,description:t.description}),dn=t=>({id:t.id,name:t.name,...t.has_run_before?{hasRunBefore:t.has_run_before}:{}}),gn=new Set(Object.values(se)),un=t=>t&&gn.has(t)?t:se.LINK,lt=t=>({uri:t.uri??"",type:un(t.type),name:t.name??"",description:t.description??""}),Fe=t=>(Array.isArray(t)?t:t.resources??[]).map(lt),dt=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}))}),De=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:it(t.status),context_ref:t.context_ref??null,checklist_ref:t.checklist_ref??null}},Ge=t=>{var e;return{task:t.task??t.name??t.label??Tt,status:ot(t.status),description:t.description??"",...t.prompt?{prompt:t.prompt}:{},...(e=t.follow_up_prompts)!=null&&e.length?{clarificationPrompts:t.follow_up_prompts}:{}}},pn=t=>Array.isArray(t)?t:t.checklist_items??t.checklist??t.items??[],ze=(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?me(a):void 0;return{invocation_id:t,checklist:pn(e).map(Ge),...r?{openingMessage:r}:{}}},gt=(t,e)=>{const s=me(e);return{invocation_id:e.invocation_id??t,checklist:(e.checklist_items??[]).map(Ge),...s?{openingMessage:s}:{}}},me=t=>{var s,a;const e=(s=t.opening_message)==null?void 0:s.trim();if(e)return{id:et,author:K.agent,text:e,...(a=t.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:t.opening_follow_up_prompts}:{}}},ut=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"?K.user:K.agent,text:e.content})),hn={id:et,author:K.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 Xe=0;const mn=t=>(Xe+=1,`${t}-${Date.now()}-${Xe}`),_n=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 pt{constructor(e,s,a={}){this.seededChecklist=[],this.client=e,this.agentId=s,this.chatId=a.chatId??s,this.opening=a.openingMessage??hn,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const e=await this.client.getConversation(this.chatId),s=ut(e.messages);return s.length===0?[this.opening]:s}async start(e){return{...await this.exchange(_n(e)),phase:T.running}}sendMessage(e,s){return this.exchange(e,s)}async stop(){}seedChecklist(e){this.seededChecklist=e}async exchange(e,s){var o;const a=[{role:sn.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||mn("msg-agent"),author:K.agent,text:r.message.content,...(o=r.follow_up_prompts)!=null&&o.length?{followUpPrompts:r.follow_up_prompts}:{}};try{const l=await this.client.getAgent(this.agentId),{checklist:d}=gt(this.agentId,l);return this.seededChecklist=d,{message:c,checklist:d}}catch{return{message:c,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const qe=(t,e)=>s=>{var a,r;return new pt(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)})},fn=t=>t instanceof re?t.message:t instanceof TypeError?"Network error while contacting the agent service.":t instanceof Error&&t.message?t.message:nt,vn=t=>{const e={};for(const s of t){const a=me(s);if(!a)continue;const r=s.invocation_id??s.id;e[r]=a,e[s.id]=a}return e},xn=t=>JSON.stringify(t),$e=(t,e)=>JSON.stringify(t)===JSON.stringify(e),ht=t=>{const{jwt:e,headers:s,urls:a}=t,r=JSON.stringify(s??{}),c=xn(a),o=i.useMemo(()=>new Be({token:e,headers:s,urls:a}),[e,c]);i.useLayoutEffect(()=>{o.setHeaders(s)},[o,r]);const[l,d]=i.useState([]),[_,h]=i.useState([]),[p,x]=i.useState({}),[k,j]=i.useState("loading"),[N,U]=i.useState(null),[S,A]=i.useState(0),O=i.useCallback((w,C)=>{const P=w.map(De),H=C.map(ct),I=vn(w);d(R=>$e(R,P)?R:P),h(R=>$e(R,H)?R:H),x(R=>$e(R,I)?R:I),j("idle"),U(null)},[]);i.useEffect(()=>{let w=!1;return j("loading"),U(null),(async()=>{try{const[C,P]=await Promise.all([o.listAgents(),o.listAgentDefinitions()]);if(w)return;O(C,P)}catch(C){if(w)return;d([]),h([]),x({}),j("error"),U(fn(C))}})(),()=>{w=!0}},[O,o,S]);const ee=i.useCallback(()=>{A(w=>w+1)},[]),V=i.useCallback(async()=>{try{const[w,C]=await Promise.all([o.listAgents(),o.listAgentDefinitions()]);O(w,C)}catch{}},[O,o]),W=i.useCallback(async w=>{const[C,P]=await Promise.all([o.getAgentChecklist(w),o.getAgent(w).catch(()=>null)]);return ze(w,C,P??void 0)},[o]),Y=i.useCallback(async w=>{const C=await o.getAgentResources(w);return Fe(C)},[o]),G=i.useCallback(async({definition:w,invocationName:C})=>{const P=await o.createAgent(w.ref,{invocationName:C}),H=await o.getAgent(P.id),I=De(H),R=me(H);return d($=>[I,...$]),R&&x($=>({...$,[I.invocation_id]:R,[I.id]:R})),I},[o]),X=i.useMemo(()=>qe(o,{resolveOpeningMessage:w=>p[w.invocation_id]??p[w.id]}),[o,p]);return{agents:l,agentDefinitions:_,loadState:k,loadError:N,reload:ee,refresh:V,fetchAgentChecklist:W,fetchAgentResources:Y,createAgent:G,chatConnector:X}},wn=t=>JSON.stringify(t),mt=t=>{const{agent:e,jwt:s,headers:a,urls:r,chatId:c}=t,o=JSON.stringify(a??{}),l=wn(r),d=i.useMemo(()=>new Be({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,l]);i.useLayoutEffect(()=>{d.setHeaders(a)},[d,o]);const _=i.useCallback(async k=>{const[j,N]=await Promise.all([d.getAgentChecklist(k),d.getAgent(k).catch(()=>null)]);return ze(k,j,N??void 0)},[d]),h=i.useCallback(async k=>{const j=await d.getAgentResources(k);return Fe(j)},[d]),p=i.useCallback(async k=>{const j=await d.getAgentTimeline(k);return dt(j)},[d]);return{connector:i.useMemo(()=>qe(d,{chatId:c??e.invocation_id})(e),[d,e.invocation_id,c]),fetchAgentChecklist:_,fetchAgentResources:h,fetchAgentTimeline:p}},kn=(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()},yn=t=>{switch(t){case y.failed:return T.stopped;case y.complete:return T.complete;default:return T.running}},Qe=(t,e)=>{e([pe(t)])},_t=({agent:t,open:e,onClose:s,jwt:a,headers:r,agentUrl:c,agentChecklistUrl:o,agentResourcesUrl:l,agentTimelineUrl:d,agentChatUrl:_,agentConversationUrl:h,chatId:p,enableUpload:x,initialBrief:k,initialPhase:j,initialChecklist:N})=>{const[U,S]=i.useState(p??t.invocation_id),[A,O]=i.useState("chat"),[ee,V]=i.useState(!1),{connector:W,fetchAgentChecklist:Y,fetchAgentResources:G,fetchAgentTimeline:X}=mt({agent:t,jwt:a,headers:r,chatId:U,urls:{agentUrl:c,agentChecklistUrl:o,agentResourcesUrl:l,agentTimelineUrl:d,agentChatUrl:_,agentConversationUrl:h}}),w=i.useRef(W),[C,P]=i.useState(j??(k?T.running:yn(t.status))),[H,I]=i.useState([]),[R,$]=i.useState(0),[_e,Re]=i.useState(),[ce,J]=i.useState(null),[Oe,te]=i.useState([]),[Pe,le]=i.useState(!1),[Q,de]=i.useState(null),[fe,ve]=i.useState(null),[xe,we]=i.useState(!1),[ke,ye]=i.useState(null),[Ae,ge]=i.useState(N??null),[Me,Ne]=i.useState(!1),[je,ue]=i.useState(null),[u,v]=i.useState(!1),[f,D]=i.useState(!1),[z,ne]=i.useState(!1);i.useEffect(()=>{w.current=W},[W]),i.useEffect(()=>{S(p??t.invocation_id),O("chat"),V(!1),I([]),$(m=>m+1)},[t.invocation_id,p]),i.useEffect(()=>{if(!e||k)return;const m=w.current.bootstrapConversation;if(!m){Qe(w.current.openingMessage(),I);return}let b=!1;return v(!0),(async()=>{try{const q=await m.call(w.current);if(b)return;I(q.map(pe))}catch{b||Qe(w.current.openingMessage(),I)}finally{b||v(!1)}})(),()=>{b=!0}},[e,k,t.invocation_id,U]);const Z=i.useCallback(m=>{m.checklist&&ge(m.checklist),m.phase&&P(m.phase)},[]);i.useEffect(()=>{var m,b;!e||k||N&&N.length>0&&((b=(m=w.current).seedChecklist)==null||b.call(m,N))},[e,k,N]),i.useEffect(()=>{if(!e||k)return;let m=!1;return Ne(!(N!=null&&N.length)),ue(null),(async()=>{var b,q;try{const Ke=await Y(t.invocation_id);if(m)return;N!=null&&N.length||(ge(Ke.checklist),(q=(b=w.current).seedChecklist)==null||q.call(b,Ke.checklist))}catch{!m&&!(N!=null&&N.length)&&ue(Te)}finally{m||Ne(!1)}})(),()=>{m=!0}},[e,t.invocation_id,k,N,Y]),i.useEffect(()=>{if(!e||!l)return;let m=!1;return le(!0),de(null),(async()=>{try{const b=await G(t.invocation_id);m||te(b)}catch{m||de(Ct)}finally{m||le(!1)}})(),()=>{m=!0}},[e,t.invocation_id,l,G]),i.useEffect(()=>{if(!e||!d)return;let m=!1;return we(!0),ye(null),(async()=>{try{const b=await X(t.invocation_id);m||ve(b)}catch{m||ye(tt)}finally{m||we(!1)}})(),()=>{m=!0}},[e,t.invocation_id,d,X]),i.useEffect(()=>{if(!e||!k)return;let m=!1;const b={id:`user-brief-${Date.now()}`,author:K.user,text:kn(k,t.invocation_name)};return(async()=>{const q=await w.current.start(k);m||(I([pe(w.current.openingMessage()),pe(b),pe(q.message)]),q.checklist&&ge(q.checklist),P(q.phase??T.running))})(),()=>{m=!0}},[e,k,t.invocation_name,t.invocation_id]);const Se=i.useCallback(m=>{J(en(m))},[]),vt=i.useCallback(m=>{S(m),V(!0),O("chat"),I([]),$(b=>b+1)},[]),xt=i.useCallback(()=>{O("timeline"),V(!1),S(p??t.invocation_id),I([]),$(m=>m+1)},[t.invocation_id,p]),wt=i.useCallback(m=>{J(null),Re(m),$(b=>b+1)},[]),kt=i.useCallback(async()=>{await w.current.stop(),P(T.stopped)},[]),yt=Ae;return n.jsxs(g.Modal,{open:e,closeHandler:s,hideCloseButton:!0,className:"agent-workspace",children:[n.jsxs(g.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(g.Icon,{name:"ask-arbor",size:24})}),n.jsx(g.Modal.Title,{children:t.invocation_name}),n.jsx("span",{className:F("agent-workspace__phase",`agent-workspace__phase--${C}`),children:Et[C]})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(g.Button,{variant:"tertiary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!z,onClick:()=>ne(m=>!m),children:"Checklist"}),n.jsx(g.Button,{variant:"tertiary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!f,onClick:()=>D(m=>!m),children:"Resources"}),n.jsx(g.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:s,children:"Close"})]})]}),n.jsxs(g.Modal.Body,{className:F("agent-workspace__body",{"agent-workspace__body--no-left":z,"agent-workspace__body--no-right":f}),children:[!z&&n.jsx(Ft,{checklist:yt,isLoading:Me,error:je,phase:C,canRequestInput:C===T.running&&!u,onStop:()=>void kt(),onAttentionItemClick:Se}),n.jsxs("section",{className:F("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!d&&A==="timeline"}),"aria-label":"Agent conversation",children:[d&&n.jsxs(g.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(g.Tabs.Item,{active:A==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>O("chat")},children:"Chat"}),n.jsx(g.Tabs.Item,{active:A==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>O("timeline")},children:"Timeline"})]}),d&&A==="chat"&&ee&&n.jsx("div",{className:"agent-workspace__center-back",children:n.jsx(g.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to timeline",onClick:xt,children:"Back to timeline"})}),!d||A==="chat"?n.jsx(Bt,{connector:W,phase:C,chatHistory:H,chatSessionKey:R,startQuery:_e,clarificationMessage:ce,enableUpload:x,onTurn:Z,onAwaitingChange:v,onClarificationPrompt:wt,onDismissClarification:()=>J(null)}):n.jsx(Qt,{timeline:fe,isLoading:xe,error:ke,onOpenChatSession:vt})]}),!f&&n.jsx(zt,{resources:Oe,isLoading:Pe,error:Q})]})]})},ft=({open:t,onClose:e,onStart:s,agentDefinitions:a})=>{const r=a[0],[c,o]=i.useState(r),[l,d]=i.useState(""),[_,h]=i.useState(!1),[p,x]=i.useState(null),k=[...a].sort((S,A)=>S.agent_intent.localeCompare(A.agent_intent)).map(S=>({value:S.ref,label:S.agent_intent}));i.useEffect(()=>{t&&(o(r),d(""),h(!1),x(null))},[t,r]);const j=c!==void 0&&l.trim().length>0,N=i.useCallback(S=>{const A=a.find(O=>O.ref===S[0]);A&&o(A)},[a]),U=i.useCallback(async()=>{if(!(!c||!j||_)){h(!0),x(null);try{await s({definition:c,invocationName:l.trim()})}catch(S){x(S instanceof Error?S.message:"Unable to start the agent.")}finally{h(!1)}}},[j,c,l,_,s]);return!c||a.length===0?null:n.jsxs(g.Modal,{open:t,closeHandler:e,className:"new-agent",children:[n.jsx(g.Modal.Header,{className:"new-agent__header",children:n.jsxs("div",{className:"new-agent__header-title",children:[n.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:n.jsx(g.Icon,{name:"ask-arbor",size:24})}),n.jsx(g.Modal.Title,{children:"Start an agent"})]})}),n.jsx(g.Modal.Body,{className:"new-agent__body",children:n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:S=>{S.preventDefault(),j&&!_&&U()},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(g.SelectDropdown,{id:"new-agent-type",placeholder:"Choose an intent",options:k,selectedValues:[c.ref],onSelectionChange:N}),n.jsx("p",{className:"new-agent__type-description",children:c.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(g.TextInput,{id:"new-agent-invocation-name",value:l,placeholder:"e.g. Test with memory3",onChange:S=>d(S.target.value)})]}),p?n.jsx("p",{className:"new-agent__error",role:"alert",children:p}):null,n.jsx("div",{className:"new-agent__actions",children:n.jsx(g.Button,{type:"submit",variant:"primary",disabled:!j||_,iconLeftName:_?"loader":"sparkles",iconLeftScreenReaderText:_?"Starting":void 0,children:_?"Starting…":"Start"})})]})})]})},An=t=>t!==void 0&&t.some(e=>e.status===E.hitl),Nn=(t,e)=>An(e)?y.hitl:t.status,jn=({column:t,label:e})=>t.statusIcon?n.jsx("span",{className:"agent-view__status-indicator",children:n.jsx(g.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,className:F({"agent-view__progress-icon--spinning":t.statusIcon.spin}),screenReaderText:e})}):n.jsx("span",{className:F("agent-view__dot",{[`agent-view__dot--${t.dotModifier}`]:t.dotModifier}),children:n.jsx(g.Dot,{colour:t.dotColour,label:e})}),Sn=({agent:t,agentName:e,column:s,isExpanded:a,isLoading:r,checklist:c,error:o,onToggle:l,onViewAgent:d})=>{const{id:_,invocation_name:h}=t,p=`agent-card-${_}-header`,x=`agent-card-${_}-progress`;return n.jsx("li",{className:F("agent-view__card",{"agent-view__card--expanded":a}),children:n.jsxs(g.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":x,"aria-label":h,id:p,onClick:()=>l(_),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(jn,{column:s}),n.jsx("span",{className:"agent-view__card-invocation-name",children:h}),n.jsx("span",{className:"agent-view__card-agent-name",children:e}),n.jsx(g.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&n.jsxs("div",{id:x,"aria-labelledby":p,className:"agent-view__card-progress",children:[r&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(g.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:ae}),n.jsx("span",{children:ae})]}),!r&&o&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:o}),!r&&!o&&c!==null&&n.jsx($t,{checklist:c}),!r&&!o&&c===null&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(g.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:ae}),n.jsx("span",{children:ae})]}),n.jsx("div",{className:"agent-view__card-actions",children:n.jsx(g.Button,{variant:"secondary",size:"S",onClick:()=>d==null?void 0:d(t),children:"View agent"})})]})]})})},Ze=({column:t,agents:e,expandedAgentId:s,loadingAgentId:a,checklistByInvocationId:r,errorByAgentId:c,definitionNameByRef:o,onToggleAgent:l,onViewAgent:d,isSplit:_=!1})=>n.jsxs("section",{className:F("agent-view__column",{"agent-view__column--split":_}),"aria-label":t.title,children:[n.jsxs("div",{className:"agent-view__column-header",children:[n.jsx(g.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(h=>n.jsx(Sn,{agent:h,agentName:He(h,o),column:t,isExpanded:s===h.id,isLoading:a===h.id,checklist:r[h.invocation_id]??null,error:c[h.id]??null,onToggle:l,onViewAgent:d},h.id))})]}),He=(t,e)=>e.get(t.agent_definition_ref)??t.agent_definition_ref.replace(/_/g," "),Cn=({jwt:t,headers:e,agentDefinitionsUrl:s,agentsUrl:a,agentUrl:r,agentChecklistUrl:c,agentResourcesUrl:o,agentTimelineUrl:l,agentChatUrl:d,agentConversationUrl:_,enableUpload:h,showHeader:p=!1,institutions:x})=>{var ue;const k=i.useMemo(()=>({agentDefinitions:s,agents:a,agent:r,agentChecklist:c,...o?{agentResources:o}:{},...l?{agentTimeline:l}:{},agentChat:d,agentConversation:_}),[s,a,r,c,o,l,d,_]),[j,N]=i.useState(null),U=j?(ue=x==null?void 0:x.find(u=>u.applicationId===j.application_id))==null?void 0:ue.applicationUrl:void 0,S=i.useMemo(()=>{const u={...e??{}};return U?u[ie.arborApplicationUrl]=U:delete u[ie.arborApplicationUrl],u},[e,U]),{agents:A,agentDefinitions:O,loadState:ee,loadError:V,reload:W,refresh:Y,fetchAgentChecklist:G,createAgent:X}=ht({jwt:t,headers:S,urls:k}),[w,C]=i.useState(!1),[P,H]=i.useState(null),[I,R]=i.useState(null),[$,_e]=i.useState({}),[Re,ce]=i.useState({}),[J,Oe]=i.useState([]),[te,Pe]=i.useState([]),le=i.useMemo(()=>{const u=new Set(A.map(f=>f.application_id)),v=new Map((x??[]).map(f=>[f.applicationId,f.name]));return[...u].sort((f,D)=>(v.get(f)??f).localeCompare(v.get(D)??D)).map(f=>({value:f,label:v.get(f)??f}))},[A,x]),Q=i.useMemo(()=>new Map(O.map(u=>[u.ref,u.display_name])),[O]),de=i.useMemo(()=>[...new Set(A.map(v=>He(v,Q)))].sort((v,f)=>v.localeCompare(f)).map(v=>({value:v,label:v})),[A,Q]),fe=i.useMemo(()=>A.filter(u=>!(J.length>0&&!J.includes(u.application_id)||te.length>0&&!te.includes(He(u,Q)))),[A,Q,te,J]),ve=le.length>1,xe=de.length>1,we=ve||xe;i.useEffect(()=>{const u=window.setInterval(()=>{Y()},6e4);return()=>{window.clearInterval(u)}},[Y]),i.useEffect(()=>{if(A.length===0)return;let u=!1;return(async()=>{const v=await Promise.allSettled(A.map(async f=>{const D=await G(f.invocation_id);return{agentId:f.id,invocationId:f.invocation_id,checklist:D.checklist}}));u||(_e(f=>{const D={...f};let z=!1;for(const ne of v){if(ne.status!=="fulfilled")continue;const{invocationId:Z,checklist:Se}=ne.value;JSON.stringify(f[Z])!==JSON.stringify(Se)&&(D[Z]=Se,z=!0)}return z?D:f}),ce(f=>{const D={...f};let z=!1;return v.forEach((ne,Z)=>{ne.status==="rejected"&&D[A[Z].id]!==Te&&(D[A[Z].id]=Te,z=!0)}),z?D:f}))})(),()=>{u=!0}},[A,G]);const ke=i.useCallback(async u=>{if(!$[u.invocation_id]){R(u.id),ce(v=>{const f={...v};return delete f[u.id],f});try{const v=await G(u.invocation_id);_e(f=>({...f,[u.invocation_id]:v.checklist}))}catch{ce(v=>({...v,[u.id]:Te}))}finally{R(v=>v===u.id?null:v)}}},[G,$]),ye=i.useCallback(u=>{if(P===u){H(null);return}const v=A.find(({id:f})=>f===u);v&&(H(u),ke(v))},[A,P,ke]),Ae=i.useMemo(()=>{const u={};for(const v of fe){const f=Nn(v,$[v.invocation_id]);(u[f]??(u[f]=[])).push(v)}return u},[fe,$]),ge=i.useCallback(u=>{N(u)},[]),Me=i.useCallback(async u=>{const v=await X(u);N(v),C(!1)},[X]),Ne=i.useCallback(()=>{N(null)},[]),je={expandedAgentId:P,loadingAgentId:I,checklistByInvocationId:$,errorByAgentId:Re,definitionNameByRef:Q,onToggleAgent:ye,onViewAgent:ge};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[p&&n.jsxs("div",{className:"agent-view__header",children:[n.jsx(g.Heading,{level:1,children:"Agents"}),n.jsx(g.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>C(!0),children:"Start an agent"})]}),A.length>0&&we&&n.jsxs("div",{className:"agent-view__filters",children:[ve&&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(g.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:le,value:J,onValueChange:Oe,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),xe&&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(g.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:de,value:te,onValueChange:Pe,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),ee==="error"?n.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[n.jsx(g.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"agent-view__state-message",children:V??nt}),n.jsx(g.Button,{variant:"secondary",size:"S",onClick:W,children:"Try again"})]}):ee==="loading"&&A.length===0?n.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[n.jsx(g.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:Je}),n.jsx("p",{className:"agent-view__state-message",children:Je})]}):A.length===0?n.jsx(Mt,{}):n.jsxs("div",{className:"agent-view__board",children:[At.map(u=>n.jsx(Ze,{column:Ee[u],agents:Ae[u]??[],...je},u)),n.jsx("div",{className:"agent-view__split-column",children:Nt.map(u=>n.jsx(Ze,{column:Ee[u],agents:Ae[u]??[],isSplit:!0,...je},u))})]}),j&&n.jsx(_t,{agent:j,open:!0,jwt:t,headers:S,agentUrl:r,agentChecklistUrl:c,agentResourcesUrl:o,agentTimelineUrl:l,agentChatUrl:d,agentConversationUrl:_,enableUpload:h,initialChecklist:$[j.invocation_id]??null,onClose:Ne},j.id),n.jsx(ft,{open:w,onClose:()=>C(!1),onStart:Me,agentDefinitions:O})]})},bn=(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:jt,created_by:St,status:y["generating-a-response"],context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=Cn;exports.AgentServiceClient=Be;exports.AgentServiceError=re;exports.AgentView=_t;exports.HttpChatConnector=pt;exports.NewAgentModal=ft;exports.buildAgentFromDefinition=bn;exports.createHttpChatConnectorFactory=qe;exports.mapApiAgent=De;exports.mapApiAgentDefinition=ct;exports.mapApiAgentStatus=it;exports.mapApiAgentTimelineResponse=dt;exports.mapApiChecklistEndpointResponse=ze;exports.mapApiChecklistItem=Ge;exports.mapApiChecklistResponse=gt;exports.mapApiChecklistStatus=ot;exports.mapApiConversationMessages=ut;exports.mapApiOpeningMessage=me;exports.mapApiResource=lt;exports.mapApiResourcesEndpointResponse=Fe;exports.mapApiTripOption=dn;exports.useAgentService=ht;exports.useAgentWorkspace=mt;
|
|
3
|
+
`);l=h.pop()??"";for(const u of h)c(u)}if(l.trim()&&c(l),!o)throw new ie(502,null,"Chat stream ended without any events");return o}}const un=e=>{let t=null;const s=[];for(const a of e.split(`
|
|
4
|
+
`)){const i=a.trimEnd();i.startsWith("event:")?t=i.slice(6).trim():i.startsWith("data:")&&s.push(i.slice(5).trim())}return{event:t,data:s.length>0?s.join(`
|
|
5
|
+
`):null}},Xe=e=>{try{return JSON.parse(e)}catch{return}};function pn(e,t){const s=new FormData;s.append("body",JSON.stringify(e));for(const a of t)s.append("files",a,a.name);return s}const lt=e=>{switch(e){case Je.cancelled:return j.failed;case Je.archived:return j.complete;case j.hitl:case j.complete:case j.failed:case j["generating-a-response"]:return e;default:return j["generating-a-response"]}},dt=e=>{switch(e){case De.requires_attention:return O.hitl;case De.in_progress:case De.available:return O["generating-a-response"];case O.failed:case O.complete:case O.hitl:case O["generating-a-response"]:return e;default:return O["generating-a-response"]}},Fe=e=>({ref:e.name,display_name:e.display_name,agent_intent:e.agent_intent??e.display_name,description:e.description}),hn=e=>({id:e.id,name:e.name,...e.has_run_before?{hasRunBefore:e.has_run_before}:{}}),mn=new Set(Object.values(se)),_n=e=>e&&mn.has(e)?e:se.LINK,gt=e=>({uri:e.uri??"",type:_n(e.type),name:e.name??"",description:e.description??""}),ze=e=>(Array.isArray(e)?e:e.resources??[]).map(gt),ut=e=>({actionLog:(e.action_log??[]).map(t=>({timestamp:t.timestamp,type:t.type,entry:t.entry,origin:t.origin})),chatSessions:(e.chat_sessions??[]).map(t=>({sessionId:t.session_id,timestamp:t.timestamp}))}),Be=e=>{var s;const t=e.invocation_id??e.id;return{id:e.id,invocation_id:t,agent_definition_ref:e.agent_definition_ref,...e.agent_intent?{agent_intent:e.agent_intent}:{},invocation_name:((s=e.invocation_name)==null?void 0:s.trim())||e.agent_definition_ref,application_id:e.application_id,...e.application_name?{application_name:e.application_name}:{},created_by:e.created_by,status:lt(e.status),context_ref:e.context_ref??null,checklist_ref:e.checklist_ref??null}},Ge=e=>{var t;return{task:e.task??e.name??e.label??Ot,status:dt(e.status),description:e.description??"",...e.prompt?{prompt:e.prompt}:{},...(t=e.follow_up_prompts)!=null&&t.length?{clarificationPrompts:e.follow_up_prompts}:{}}},fn=e=>Array.isArray(e)?e:e.checklist_items??e.checklist??e.items??[],qe=(e,t,s)=>{var l;const a=!Array.isArray(t)&&(t.opening_message||(l=t.opening_follow_up_prompts)!=null&&l.length)?t:s,i=a?me(a):void 0;return{invocation_id:e,checklist:fn(t).map(Ge),...i?{openingMessage:i}:{}}},pt=(e,t)=>{const s=me(t);return{invocation_id:t.invocation_id??e,checklist:(t.checklist_items??[]).map(Ge),...s?{openingMessage:s}:{}}},me=e=>{var s,a;const t=(s=e.opening_message)==null?void 0:s.trim();if(t)return{id:st,author:X.agent,text:t,...(a=e.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:e.opening_follow_up_prompts}:{}}},ht=e=>e.filter(t=>(t.role==="user"||t.role==="assistant")&&typeof t.content=="string"&&t.content.length>0&&t.message_type!=="tool_request").map(t=>({id:t.message_id,author:t.role==="user"?X.user:X.agent,text:t.content})),vn={id:st,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 Qe=0;const wn=e=>(Qe+=1,`${e}-${Date.now()}-${Qe}`),xn=e=>{const t=e.destination?` to ${e.destination}`:"";return`Let's get started on ${e.tripName.trim()||e.destination.trim()||"this task"}${t}. What will you do first?`};class mt{constructor(t,s,a={}){this.seededChecklist=[],this.client=t,this.agentId=s,this.chatId=a.chatId??s,this.opening=a.openingMessage??vn,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const t=await this.client.getConversation(this.chatId),s=ht(t.messages);return s.length===0?[this.opening]:s}async start(t){return{...await this.exchange(xn(t)),phase:E.running}}sendMessage(t,s){return this.exchange(t,s)}async stop(){}seedChecklist(t){this.seededChecklist=t}async exchange(t,s){var o;const a=[{role:cn.user,content:t}],i=await this.client.chat(this.agentId,{messages:a,chat_id:this.chatId,...this.model?{model:this.model}:{},moderation_enabled:!0,meta:{feature_id:"agent_view",source:"agent_view_frontend"}},...s&&s.length>0?[{uploadFiles:s}]:[]),l={id:i.event_id||wn("msg-agent"),author:X.agent,text:i.message.content,...(o=i.follow_up_prompts)!=null&&o.length?{followUpPrompts:i.follow_up_prompts}:{}};try{const c=await this.client.getAgent(this.agentId),{checklist:d}=pt(this.agentId,c);return this.seededChecklist=d,{message:l,checklist:d}}catch{return{message:l,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const Ke=(e,t)=>s=>{var a,i;return new mt(e,s.invocation_id,{model:t==null?void 0:t.model,chatId:((a=t==null?void 0:t.resolveChatId)==null?void 0:a.call(t,s))??(t==null?void 0:t.chatId)??s.invocation_id,openingMessage:((i=t==null?void 0:t.resolveOpeningMessage)==null?void 0:i.call(t,s))??(t==null?void 0:t.openingMessage)})},_t=e=>e instanceof ie?e.message:e instanceof TypeError?"Network error while contacting the agent service.":e instanceof Error&&e.message?e.message:it,kn=e=>{const t={};for(const s of e){const a=me(s);if(!a)continue;const i=s.invocation_id??s.id;t[i]=a,t[s.id]=a}return t},yn=e=>JSON.stringify(e),Ue=(e,t)=>JSON.stringify(e)===JSON.stringify(t),ft=e=>{const{jwt:t,headers:s,urls:a}=e,i=JSON.stringify(s??{}),l=yn(a),o=r.useMemo(()=>new Re({token:t,headers:s,urls:a}),[t,l]);r.useLayoutEffect(()=>{o.setHeaders(s)},[o,i]);const[c,d]=r.useState([]),[f,h]=r.useState([]),[u,w]=r.useState({}),[m,S]=r.useState("loading"),[y,T]=r.useState(null),[D,N]=r.useState(0),I=r.useCallback((k,C)=>{const $=k.map(Be),K=C.map(Fe),M=kn(k);d(L=>Ue(L,$)?L:$),h(L=>Ue(L,K)?L:K),w(L=>Ue(L,M)?L:M),S("idle"),T(null)},[]);r.useEffect(()=>{let k=!1;return S("loading"),T(null),(async()=>{try{const[C,$]=await Promise.all([o.listAgents(),o.listAgentDefinitions()]);if(k)return;I(C,$)}catch(C){if(k)return;d([]),h([]),w({}),S("error"),T(_t(C))}})(),()=>{k=!0}},[I,o,D]);const q=r.useCallback(()=>{N(k=>k+1)},[]),z=r.useCallback(async()=>{try{const[k,C]=await Promise.all([o.listAgents(),o.listAgentDefinitions()]);I(k,C)}catch{}},[I,o]),P=r.useCallback(async k=>{const[C,$]=await Promise.all([o.getAgentChecklist(k),o.getAgent(k).catch(()=>null)]);return qe(k,C,$??void 0)},[o]),A=r.useCallback(async k=>{const C=await o.getAgentResources(k);return ze(C)},[o]),R=r.useCallback(async({definition:k,invocationName:C})=>{const $=await o.createAgent(k.ref,{invocationName:C}),K=await o.getAgent($.id),M=Be(K),L=me(K);return d(H=>[M,...H]),L&&w(H=>({...H,[M.invocation_id]:L,[M.id]:L})),M},[o]),J=r.useMemo(()=>Ke(o,{resolveOpeningMessage:k=>u[k.invocation_id]??u[k.id]}),[o,u]);return{agents:c,agentDefinitions:f,loadState:m,loadError:y,reload:q,refresh:z,fetchAgentChecklist:P,fetchAgentResources:A,createAgent:R,chatConnector:J}},Nn=e=>JSON.stringify(e),vt=e=>{const{agent:t,jwt:s,headers:a,urls:i,chatId:l}=e,o=JSON.stringify(a??{}),c=Nn(i),d=r.useMemo(()=>new Re({token:s,headers:a,urls:{agent:i.agentUrl,agentChecklist:i.agentChecklistUrl,...i.agentResourcesUrl?{agentResources:i.agentResourcesUrl}:{},...i.agentTimelineUrl?{agentTimeline:i.agentTimelineUrl}:{},agentChat:i.agentChatUrl,agentConversation:i.agentConversationUrl}}),[s,c]);r.useLayoutEffect(()=>{d.setHeaders(a)},[d,o]);const f=r.useCallback(async m=>{const[S,y]=await Promise.all([d.getAgentChecklist(m),d.getAgent(m).catch(()=>null)]);return qe(m,S,y??void 0)},[d]),h=r.useCallback(async m=>{const S=await d.getAgentResources(m);return ze(S)},[d]),u=r.useCallback(async m=>{const S=await d.getAgentTimeline(m);return ut(S)},[d]);return{connector:r.useMemo(()=>Ke(d,{chatId:l??t.invocation_id})(t),[d,t.invocation_id,l]),fetchAgentChecklist:f,fetchAgentResources:h,fetchAgentTimeline:u}},An=(e,t)=>{const s=e.hasRunBefore?t||"This trip":e.tripName.trim()||"A new trip",a=e.destination?` to ${e.destination}`:"",i=e.hasRunBefore?" It has run before.":"";return`${s}${a}.${i}`.trim()},jn=e=>{switch(e){case j.failed:return E.stopped;case j.complete:return E.complete;default:return E.running}},Ze=(e,t)=>{t([pe(e)])},wt=({agent:e,open:t,onClose:s,jwt:a,headers:i,agentUrl:l,agentChecklistUrl:o,agentResourcesUrl:c,agentTimelineUrl:d,agentChatUrl:f,agentConversationUrl:h,chatId:u,enableUpload:w,initialBrief:m,initialPhase:S,initialChecklist:y})=>{const[T,D]=r.useState(u??e.invocation_id),[N,I]=r.useState("chat"),[q,z]=r.useState(!1),{connector:P,fetchAgentChecklist:A,fetchAgentResources:R,fetchAgentTimeline:J}=vt({agent:e,jwt:a,headers:i,chatId:T,urls:{agentUrl:l,agentChecklistUrl:o,agentResourcesUrl:c,agentTimelineUrl:d,agentChatUrl:f,agentConversationUrl:h}}),k=r.useRef(P),[C,$]=r.useState(S??(m?E.running:jn(e.status))),[K,M]=r.useState([]),[L,H]=r.useState(0),[_e,Oe]=r.useState(),[ce,Q]=r.useState(null),[Pe,te]=r.useState([]),[Me,le]=r.useState(!1),[Z,de]=r.useState(null),[fe,ve]=r.useState(null),[we,xe]=r.useState(!1),[ke,ye]=r.useState(null),[Ne,ge]=r.useState(y??null),[Le,Ae]=r.useState(!1),[je,ue]=r.useState(null),[p,x]=r.useState(!1),[v,F]=r.useState(!1),[V,ne]=r.useState(!1);r.useEffect(()=>{k.current=P},[P]),r.useEffect(()=>{D(u??e.invocation_id),I("chat"),z(!1),M([]),H(_=>_+1)},[e.invocation_id,u]),r.useEffect(()=>{if(!t||m)return;const _=k.current.bootstrapConversation;if(!_){Ze(k.current.openingMessage(),M);return}let b=!1;return x(!0),(async()=>{try{const Y=await _.call(k.current);if(b)return;M(Y.map(pe))}catch{b||Ze(k.current.openingMessage(),M)}finally{b||x(!1)}})(),()=>{b=!0}},[t,m,e.invocation_id,T]);const ee=r.useCallback(_=>{_.checklist&&ge(_.checklist),_.phase&&$(_.phase)},[]);r.useEffect(()=>{var _,b;!t||m||y&&y.length>0&&((b=(_=k.current).seedChecklist)==null||b.call(_,y))},[t,m,y]),r.useEffect(()=>{if(!t||m)return;let _=!1;return Ae(!(y!=null&&y.length)),ue(null),(async()=>{var b,Y;try{const We=await A(e.invocation_id);if(_)return;y!=null&&y.length||(ge(We.checklist),(Y=(b=k.current).seedChecklist)==null||Y.call(b,We.checklist))}catch{!_&&!(y!=null&&y.length)&&ue(Te)}finally{_||Ae(!1)}})(),()=>{_=!0}},[t,e.invocation_id,m,y,A]),r.useEffect(()=>{if(!t||!c)return;let _=!1;return le(!0),de(null),(async()=>{try{const b=await R(e.invocation_id);_||te(b)}catch{_||de(It)}finally{_||le(!1)}})(),()=>{_=!0}},[t,e.invocation_id,c,R]),r.useEffect(()=>{if(!t||!d)return;let _=!1;return xe(!0),ye(null),(async()=>{try{const b=await J(e.invocation_id);_||ve(b)}catch{_||ye(at)}finally{_||xe(!1)}})(),()=>{_=!0}},[t,e.invocation_id,d,J]),r.useEffect(()=>{if(!t||!m)return;let _=!1;const b={id:`user-brief-${Date.now()}`,author:X.user,text:An(m,e.invocation_name)};return(async()=>{const Y=await k.current.start(m);_||(M([pe(k.current.openingMessage()),pe(b),pe(Y.message)]),Y.checklist&&ge(Y.checklist),$(Y.phase??E.running))})(),()=>{_=!0}},[t,m,e.invocation_name,e.invocation_id]);const Se=r.useCallback(_=>{Q(an(_))},[]),yt=r.useCallback(_=>{D(_),z(!0),I("chat"),M([]),H(b=>b+1)},[]),Nt=r.useCallback(()=>{I("timeline"),z(!1),D(u??e.invocation_id),M([]),H(_=>_+1)},[e.invocation_id,u]),At=r.useCallback(_=>{Q(null),Oe(_),H(b=>b+1)},[]),jt=r.useCallback(async()=>{await k.current.stop(),$(E.stopped)},[]),St=Ne;return n.jsxs(g.Modal,{open:t,closeHandler:s,hideCloseButton:!0,className:"agent-workspace",children:[n.jsxs(g.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(g.Icon,{name:"ask-arbor",size:24})}),n.jsx(g.Modal.Title,{children:e.invocation_name}),n.jsx("span",{className:G("agent-workspace__phase",`agent-workspace__phase--${C}`),children:Pt[C]})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(g.Button,{variant:"tertiary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!V,onClick:()=>ne(_=>!_),children:"Checklist"}),n.jsx(g.Button,{variant:"tertiary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!v,onClick:()=>F(_=>!_),children:"Resources"}),n.jsx(g.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:s,children:"Close"})]})]}),n.jsxs(g.Modal.Body,{className:G("agent-workspace__body",{"agent-workspace__body--no-left":V,"agent-workspace__body--no-right":v}),children:[!V&&n.jsx(Kt,{checklist:St,isLoading:Le,error:je,phase:C,canRequestInput:C===E.running&&!p,onStop:()=>void jt(),onAttentionItemClick:Se}),n.jsxs("section",{className:G("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!d&&N==="timeline"}),"aria-label":"Agent conversation",children:[d&&n.jsxs(g.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(g.Tabs.Item,{active:N==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>I("chat")},children:"Chat"}),n.jsx(g.Tabs.Item,{active:N==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>I("timeline")},children:"Timeline"})]}),d&&N==="chat"&&q&&n.jsx("div",{className:"agent-workspace__center-back",children:n.jsx(g.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to timeline",onClick:Nt,children:"Back to timeline"})}),!d||N==="chat"?n.jsx(qt,{connector:P,phase:C,chatHistory:K,chatSessionKey:L,startQuery:_e,clarificationMessage:ce,enableUpload:w,onTurn:ee,onAwaitingChange:x,onClarificationPrompt:At,onDismissClarification:()=>Q(null)}):n.jsx(nn,{timeline:fe,isLoading:we,error:ke,onOpenChatSession:yt})]}),!v&&n.jsx(Jt,{resources:Pe,isLoading:Me,error:Z})]})]})},Sn="Unable to load agent definitions. Please try again.",Cn="Unable to start the agent.",et="Loading agents…",xt=({open:e,onClose:t,onStart:s,agentDefinitions:a,definitionsState:i="idle",definitionsError:l=null,onRetryDefinitions:o,embedded:c=!1})=>{const d=a[0],[f,h]=r.useState(d),[u,w]=r.useState(""),[m,S]=r.useState(!1),[y,T]=r.useState(null),D=[...a].sort((A,R)=>A.agent_intent.localeCompare(R.agent_intent)).map(A=>({value:A.ref,label:A.agent_intent}));r.useEffect(()=>{e&&(h(d),w(""),S(!1),T(null))},[e,d]);const N=f!==void 0&&u.trim().length>0,I=r.useCallback(A=>{const R=a.find(J=>J.ref===A[0]);R&&h(R)},[a]),q=r.useCallback(async()=>{if(!(!f||!N||m)){S(!0),T(null);try{await s({definition:f,invocationName:u.trim()})}catch(A){T(A instanceof Error?A.message:Cn)}finally{S(!1)}}},[N,f,u,m,s]);if(i==="idle"&&a.length===0||!e)return null;const z=n.jsxs("div",{className:"new-agent__header-title",children:[n.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:n.jsx(g.Icon,{name:"ask-arbor",size:24})}),c?n.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):n.jsx(g.Modal.Title,{children:"Start an agent"})]});let P;return i==="loading"?P=n.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[n.jsx(g.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:et}),n.jsx("p",{className:"new-agent__state-message",children:et})]}):i==="error"?P=n.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[n.jsx(g.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"new-agent__state-message",children:l??Sn}),o?n.jsx(g.Button,{variant:"secondary",size:"S",onClick:o,children:"Try again"}):null]}):f?P=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:A=>{A.preventDefault(),N&&!m&&q()},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(g.SelectDropdown,{id:"new-agent-type",placeholder:"Choose an intent",options:D,selectedValues:[f.ref],onSelectionChange:I}),n.jsx("p",{className:"new-agent__type-description",children:f.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(g.TextInput,{id:"new-agent-invocation-name",value:u,placeholder:"e.g. Test with memory3",onChange:A=>w(A.target.value)})]}),y?n.jsx("p",{className:"new-agent__error",role:"alert",children:y}):null,n.jsx("div",{className:"new-agent__actions",children:n.jsx(g.Button,{type:"submit",variant:"primary",disabled:!N||m,iconLeftName:m?"loader":"sparkles",iconLeftScreenReaderText:m?"Starting":void 0,children:m?"Starting…":"Start"})})]}):P=null,c?n.jsxs("div",{className:G("new-agent","new-agent--embedded"),children:[n.jsx("div",{className:"new-agent__header",children:z}),n.jsx("div",{className:"new-agent__body",children:P})]}):n.jsxs(g.Modal,{open:e,closeHandler:t,className:"new-agent",children:[n.jsx(g.Modal.Header,{className:"new-agent__header",children:z}),n.jsx(g.Modal.Body,{className:"new-agent__body",children:P})]})},tt=e=>{window.location.assign(e)},bn=({open:e,authToken:t,headers:s,agentDefinitionsUrl:a,agentsUrl:i,closeUrl:l,successUrl:o,onClose:c,onStart:d,embedded:f=!1})=>{const h=JSON.stringify(s??{}),u=r.useMemo(()=>new Re({token:t,headers:s,urls:{agentDefinitions:a,agents:i}}),[t,a,i,h]),[w,m]=r.useState([]),[S,y]=r.useState("loading"),[T,D]=r.useState(null),[N,I]=r.useState(0);r.useEffect(()=>{if(!e)return;let A=!1;return y("loading"),D(null),(async()=>{try{const R=await u.listAgentDefinitions();if(A)return;m(R.map(Fe)),y("idle")}catch(R){if(A)return;m([]),D(_t(R)),y("error")}})(),()=>{A=!0}},[u,e,N]);const q=r.useCallback(()=>{c==null||c(),l&&tt(l)},[l,c]),z=r.useCallback(async A=>{await u.createAgent(A.definition.ref,{invocationName:A.invocationName}),d==null||d(A),o&&tt(o)},[u,d,o]),P=r.useCallback(()=>{I(A=>A+1)},[]);return n.jsx(xt,{open:e,onClose:q,onStart:z,agentDefinitions:w,definitionsState:S,definitionsError:T,onRetryDefinitions:P,embedded:f})},Tn=e=>"agentDefinitionsUrl"in e,kt=e=>Tn(e)?n.jsx(bn,{...e}):n.jsx(xt,{...e}),En=e=>e!==void 0&&e.some(t=>t.status===O.hitl),In=(e,t)=>En(t)?j.hitl:e.status,Rn=({column:e,label:t})=>e.statusIcon?n.jsx("span",{className:"agent-view__status-indicator",children:n.jsx(g.Icon,{name:e.statusIcon.name,size:16,color:e.statusIcon.color,className:G({"agent-view__progress-icon--spinning":e.statusIcon.spin}),screenReaderText:t})}):n.jsx("span",{className:G("agent-view__dot",{[`agent-view__dot--${e.dotModifier}`]:e.dotModifier}),children:n.jsx(g.Dot,{colour:e.dotColour,label:t})}),On=({agent:e,agentName:t,column:s,isExpanded:a,isLoading:i,checklist:l,error:o,onToggle:c,onViewAgent:d})=>{const{id:f,invocation_name:h}=e,u=`agent-card-${f}-header`,w=`agent-card-${f}-progress`;return n.jsx("li",{className:G("agent-view__card",{"agent-view__card--expanded":a}),children:n.jsxs(g.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":w,"aria-label":h,id:u,onClick:()=>c(f),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(Rn,{column:s}),n.jsx("span",{className:"agent-view__card-invocation-name",children:h}),n.jsx("span",{className:"agent-view__card-agent-name",children:t}),n.jsx(g.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&n.jsxs("div",{id:w,"aria-labelledby":u,className:"agent-view__card-progress",children:[i&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(g.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:ae}),n.jsx("span",{children:ae})]}),!i&&o&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:o}),!i&&!o&&l!==null&&n.jsx(Ft,{checklist:l}),!i&&!o&&l===null&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(g.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:ae}),n.jsx("span",{children:ae})]}),n.jsx("div",{className:"agent-view__card-actions",children:n.jsx(g.Button,{variant:"secondary",size:"S",onClick:()=>d==null?void 0:d(e),children:"View agent"})})]})]})})},nt=({column:e,agents:t,expandedAgentId:s,loadingAgentId:a,checklistByInvocationId:i,errorByAgentId:l,definitionNameByRef:o,onToggleAgent:c,onViewAgent:d,isSplit:f=!1})=>n.jsxs("section",{className:G("agent-view__column",{"agent-view__column--split":f}),"aria-label":e.title,children:[n.jsxs("div",{className:"agent-view__column-header",children:[n.jsx(g.Heading,{level:4,children:e.title}),n.jsx("span",{className:"agent-view__column-count",children:t.length})]}),n.jsx("ul",{className:"agent-view__card-list",children:t.map(h=>n.jsx(On,{agent:h,agentName:He(h,o),column:e,isExpanded:s===h.id,isLoading:a===h.id,checklist:i[h.invocation_id]??null,error:l[h.id]??null,onToggle:c,onViewAgent:d},h.id))})]}),He=(e,t)=>t.get(e.agent_definition_ref)??e.agent_definition_ref.replace(/_/g," "),Pn=({jwt:e,headers:t,agentDefinitionsUrl:s,agentsUrl:a,agentUrl:i,agentChecklistUrl:l,agentResourcesUrl:o,agentTimelineUrl:c,agentChatUrl:d,agentConversationUrl:f,enableUpload:h,showHeader:u=!1,institutions:w})=>{var ue;const m=r.useMemo(()=>({agentDefinitions:s,agents:a,agent:i,agentChecklist:l,...o?{agentResources:o}:{},...c?{agentTimeline:c}:{},agentChat:d,agentConversation:f}),[s,a,i,l,o,c,d,f]),[S,y]=r.useState(null),T=S?(ue=w==null?void 0:w.find(p=>p.applicationId===S.application_id))==null?void 0:ue.applicationUrl:void 0,D=r.useMemo(()=>{const p={...t??{}};return T?p[re.arborApplicationUrl]=T:delete p[re.arborApplicationUrl],p},[t,T]),{agents:N,agentDefinitions:I,loadState:q,loadError:z,reload:P,refresh:A,fetchAgentChecklist:R,createAgent:J}=ft({jwt:e,headers:D,urls:m}),[k,C]=r.useState(!1),[$,K]=r.useState(null),[M,L]=r.useState(null),[H,_e]=r.useState({}),[Oe,ce]=r.useState({}),[Q,Pe]=r.useState([]),[te,Me]=r.useState([]),le=r.useMemo(()=>{const p=new Set(N.map(v=>v.application_id)),x=new Map((w??[]).map(v=>[v.applicationId,v.name]));return[...p].sort((v,F)=>(x.get(v)??v).localeCompare(x.get(F)??F)).map(v=>({value:v,label:x.get(v)??v}))},[N,w]),Z=r.useMemo(()=>new Map(I.map(p=>[p.ref,p.display_name])),[I]),de=r.useMemo(()=>[...new Set(N.map(x=>He(x,Z)))].sort((x,v)=>x.localeCompare(v)).map(x=>({value:x,label:x})),[N,Z]),fe=r.useMemo(()=>N.filter(p=>!(Q.length>0&&!Q.includes(p.application_id)||te.length>0&&!te.includes(He(p,Z)))),[N,Z,te,Q]),ve=le.length>1,we=de.length>1,xe=ve||we;r.useEffect(()=>{const p=window.setInterval(()=>{A()},6e4);return()=>{window.clearInterval(p)}},[A]),r.useEffect(()=>{if(N.length===0)return;let p=!1;return(async()=>{const x=await Promise.allSettled(N.map(async v=>{const F=await R(v.invocation_id);return{agentId:v.id,invocationId:v.invocation_id,checklist:F.checklist}}));p||(_e(v=>{const F={...v};let V=!1;for(const ne of x){if(ne.status!=="fulfilled")continue;const{invocationId:ee,checklist:Se}=ne.value;JSON.stringify(v[ee])!==JSON.stringify(Se)&&(F[ee]=Se,V=!0)}return V?F:v}),ce(v=>{const F={...v};let V=!1;return x.forEach((ne,ee)=>{ne.status==="rejected"&&F[N[ee].id]!==Te&&(F[N[ee].id]=Te,V=!0)}),V?F:v}))})(),()=>{p=!0}},[N,R]);const ke=r.useCallback(async p=>{if(!H[p.invocation_id]){L(p.id),ce(x=>{const v={...x};return delete v[p.id],v});try{const x=await R(p.invocation_id);_e(v=>({...v,[p.invocation_id]:x.checklist}))}catch{ce(x=>({...x,[p.id]:Te}))}finally{L(x=>x===p.id?null:x)}}},[R,H]),ye=r.useCallback(p=>{if($===p){K(null);return}const x=N.find(({id:v})=>v===p);x&&(K(p),ke(x))},[N,$,ke]),Ne=r.useMemo(()=>{const p={};for(const x of fe){const v=In(x,H[x.invocation_id]);(p[v]??(p[v]=[])).push(x)}return p},[fe,H]),ge=r.useCallback(p=>{y(p)},[]),Le=r.useCallback(async p=>{const x=await J(p);y(x),C(!1)},[J]),Ae=r.useCallback(()=>{y(null)},[]),je={expandedAgentId:$,loadingAgentId:M,checklistByInvocationId:H,errorByAgentId:Oe,definitionNameByRef:Z,onToggleAgent:ye,onViewAgent:ge};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[u&&n.jsxs("div",{className:"agent-view__header",children:[n.jsx(g.Heading,{level:1,children:"Agents"}),n.jsx(g.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>C(!0),children:"Start an agent"})]}),N.length>0&&xe&&n.jsxs("div",{className:"agent-view__filters",children:[ve&&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(g.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:le,value:Q,onValueChange:Pe,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),we&&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(g.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:de,value:te,onValueChange:Me,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),q==="error"?n.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[n.jsx(g.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"agent-view__state-message",children:z??it}),n.jsx(g.Button,{variant:"secondary",size:"S",onClick:P,children:"Try again"})]}):q==="loading"&&N.length===0?n.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[n.jsx(g.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:Ve}),n.jsx("p",{className:"agent-view__state-message",children:Ve})]}):N.length===0?n.jsx(Ut,{}):n.jsxs("div",{className:"agent-view__board",children:[Ct.map(p=>n.jsx(nt,{column:Ee[p],agents:Ne[p]??[],...je},p)),n.jsx("div",{className:"agent-view__split-column",children:bt.map(p=>n.jsx(nt,{column:Ee[p],agents:Ne[p]??[],isSplit:!0,...je},p))})]}),S&&n.jsx(wt,{agent:S,open:!0,jwt:e,headers:D,agentUrl:i,agentChecklistUrl:l,agentResourcesUrl:o,agentTimelineUrl:c,agentChatUrl:d,agentConversationUrl:f,enableUpload:h,initialChecklist:H[S.invocation_id]??null,onClose:Ae},S.id),n.jsx(kt,{open:k,onClose:()=>C(!1),onStart:Le,agentDefinitions:I})]})},Mn=(e,t)=>{const s=Date.now(),a=t.trim()||e.agent_intent;return{id:`agent-${s}`,invocation_id:`inv-${s}`,agent_definition_ref:e.ref,agent_intent:e.agent_intent,invocation_name:a,application_id:Tt,created_by:Et,status:j["generating-a-response"],context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=Pn;exports.AgentServiceClient=Re;exports.AgentServiceError=ie;exports.AgentView=wt;exports.HttpChatConnector=mt;exports.NewAgentModal=kt;exports.buildAgentFromDefinition=Mn;exports.createHttpChatConnectorFactory=Ke;exports.mapApiAgent=Be;exports.mapApiAgentDefinition=Fe;exports.mapApiAgentStatus=lt;exports.mapApiAgentTimelineResponse=ut;exports.mapApiChecklistEndpointResponse=qe;exports.mapApiChecklistItem=Ge;exports.mapApiChecklistResponse=pt;exports.mapApiChecklistStatus=dt;exports.mapApiConversationMessages=ht;exports.mapApiOpeningMessage=me;exports.mapApiResource=gt;exports.mapApiResourcesEndpointResponse=ze;exports.mapApiTripOption=hn;exports.useAgentService=ft;exports.useAgentWorkspace=vt;
|
package/dist/index.d.ts
CHANGED
|
@@ -506,13 +506,39 @@ export declare const mapApiTripOption: (record: ApiTripOption) => {
|
|
|
506
506
|
name: string;
|
|
507
507
|
};
|
|
508
508
|
|
|
509
|
-
export declare const NewAgentModal: (
|
|
509
|
+
export declare const NewAgentModal: (props: NewAgentModalProps) => JSX_2.Element;
|
|
510
510
|
|
|
511
|
-
export declare type
|
|
511
|
+
export declare type NewAgentModalControlledProps = {
|
|
512
512
|
open: boolean;
|
|
513
513
|
onClose: () => void;
|
|
514
514
|
onStart: (payload: NewAgentStartPayload) => void | Promise<void>;
|
|
515
515
|
agentDefinitions: AgentDefinition[];
|
|
516
|
+
/** When true, render inline (no design-system Modal portal). */
|
|
517
|
+
embedded?: boolean;
|
|
518
|
+
};
|
|
519
|
+
|
|
520
|
+
export declare type NewAgentModalProps = NewAgentModalControlledProps | NewAgentModalStandaloneProps;
|
|
521
|
+
|
|
522
|
+
export declare type NewAgentModalStandaloneProps = {
|
|
523
|
+
open: boolean;
|
|
524
|
+
/** Bearer token attached to every AI Service SDK request. */
|
|
525
|
+
authToken?: string;
|
|
526
|
+
/** Extra headers merged into every AI Service SDK request. */
|
|
527
|
+
headers?: Record<string, string>;
|
|
528
|
+
/** Full URL to GET the list of agent definitions. */
|
|
529
|
+
agentDefinitionsUrl: string;
|
|
530
|
+
/** Full URL to POST a new agent (the agents collection). */
|
|
531
|
+
agentsUrl: string;
|
|
532
|
+
/** Navigated to when the modal is closed without starting. */
|
|
533
|
+
closeUrl?: string;
|
|
534
|
+
/** Navigated to after a successful start. */
|
|
535
|
+
successUrl?: string;
|
|
536
|
+
/** Called when the modal is closed, before navigating to `closeUrl`. */
|
|
537
|
+
onClose?: () => void;
|
|
538
|
+
/** Called after a successful start, before navigating to `successUrl`. */
|
|
539
|
+
onStart?: (payload: NewAgentStartPayload) => void;
|
|
540
|
+
/** When true, render inline (no design-system Modal portal). For hosts like MIS `ui:window`. */
|
|
541
|
+
embedded?: boolean;
|
|
516
542
|
};
|
|
517
543
|
|
|
518
544
|
export declare type NewAgentStartPayload = {
|