@arbor-education/agent-view-frontend 0.4.3 → 0.4.5
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 +30 -0
- package/dist/index.cjs +4 -4
- package/dist/index.d.ts +2 -5
- package/dist/index.js +1498 -1286
- package/dist/style.css +1 -1
- package/package.json +13 -4
package/README.md
CHANGED
|
@@ -136,6 +136,7 @@ const api = 'https://ai-agent-service.qa.arbor.engineering/api/v1';
|
|
|
136
136
|
// Or mount the workspace alone:
|
|
137
137
|
<AgentView
|
|
138
138
|
agent={agent}
|
|
139
|
+
invocationId={agent.invocation_id}
|
|
139
140
|
open
|
|
140
141
|
onClose={onClose}
|
|
141
142
|
jwt={jwt}
|
|
@@ -175,6 +176,14 @@ const api = 'https://ai-agent-service.qa.arbor.engineering/api/v1';
|
|
|
175
176
|
/>;
|
|
176
177
|
```
|
|
177
178
|
|
|
179
|
+
When hosting inside an MIS `ui:window` (or any shell that already provides a
|
|
180
|
+
dialog), pass `embedded` so the content renders inline instead of opening a
|
|
181
|
+
second design-system Modal (which portals to `document.body`):
|
|
182
|
+
|
|
183
|
+
```tsx
|
|
184
|
+
<NewAgentModal open embedded {...standaloneProps} />
|
|
185
|
+
```
|
|
186
|
+
|
|
178
187
|
| Prop | Attribute | Required | Purpose |
|
|
179
188
|
|---|---|---|---|
|
|
180
189
|
| `agentDefinitionsUrl` | `agent-definitions-url` | yes | Full URL to GET the agent definitions list. |
|
|
@@ -182,6 +191,7 @@ const api = 'https://ai-agent-service.qa.arbor.engineering/api/v1';
|
|
|
182
191
|
| `authToken` | `auth-token` | no | Bearer token attached to every request. |
|
|
183
192
|
| `headers` | `headers` | no | Extra headers merged into every request. |
|
|
184
193
|
| `open` | `open` | no | Whether the modal is open. |
|
|
194
|
+
| `embedded` | — | no | Render inline without the design-system Modal portal. |
|
|
185
195
|
| `closeUrl` | `close-url` | no | Page navigated to when the modal is closed. |
|
|
186
196
|
| `successUrl` | `success-url` | no | Page navigated to after a successful start. |
|
|
187
197
|
|
|
@@ -190,6 +200,26 @@ omit them (and pass `onClose`/`onStart`) to keep the modal fully controlled.
|
|
|
190
200
|
|
|
191
201
|
---
|
|
192
202
|
|
|
203
|
+
## Publishing an alpha version
|
|
204
|
+
|
|
205
|
+
Ensure you are logged in to npm (`npm whoami`) and are a member of the `@arbor-education` npm organisation, then run:
|
|
206
|
+
|
|
207
|
+
```bash
|
|
208
|
+
npm run publish:alpha
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
This bumps the prerelease version (`0.4.x-alpha.0`, `0.4.x-alpha.1`, …) and publishes under the `alpha` dist-tag. Must be run with `npm run`, not `yarn` — yarn intercepts the publish step and will prompt for yarn credentials instead.
|
|
212
|
+
|
|
213
|
+
The version bump modifies `package.json` — do not commit this change. Revert it before raising or merging your PR.
|
|
214
|
+
|
|
215
|
+
To install the published alpha in another project:
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
yarn add @arbor-education/agent-view-frontend@alpha
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
---
|
|
222
|
+
|
|
193
223
|
## NPM usage
|
|
194
224
|
|
|
195
225
|
Install the package and its peer dependencies:
|
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"),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(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),o=require("react"),z=require("classnames"),d=require("@arbor-education/design-system.components"),le=require("@arbor-education/ask-arbor-chat-panel"),C={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},$={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},U={briefing:"briefing",running:"running",stopped:"stopped",complete:"complete"},X={agent:"agent",user:"user",system:"system"},re={MIS_RECORD:"MIS_RECORD",FILE:"FILE",WORKFLOW:"WORKFLOW",LINK:"LINK"},Xe={cancelled:"cancelled",archived:"archived"},$e={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},J={[$.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[$.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[$.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[$["generating-a-response"]]:{label:"Generating a response",icon:"sparkles",color:"var(--color-brand-600)"}},Ee={[C["generating-a-response"]]:{status:C["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:J["generating-a-response"].icon,color:J["generating-a-response"].color}},[C.hitl]:{status:C.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:J.hitl.icon,color:J.hitl.color}},[C.complete]:{status:C.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:J.complete.icon,color:J.complete.color}},[C.failed]:{status:C.failed,title:"Failed",dotColour:"salmon",statusIcon:{name:J.failed.icon,color:J.failed.color}}},Rt=[C["generating-a-response"],C.hitl],Ot=[C.complete,C.failed],Lt="m4",Mt="1",ot="msg-opening",be="Unable to load agent tasks. Please try again.",Pt="Unable to load the resources for this agent",it="Unable to load the timeline for this agent",Dt="Something went wrong. Please try again.",ct="Unable to load agents. Please try again.",oe="Loading tasks…",Qe="Loading agents…",Ut="Task",$t={[U.briefing]:"Briefing",[U.running]:"Working",[U.stopped]:"Stopped",[U.complete]:"Complete"},Ht=[C["generating-a-response"],C.hitl,C.complete,C.failed],Bt={[C["generating-a-response"]]:"Agents currently working on tasks for you.",[C.hitl]:"Agents that need your input before they can continue.",[C.complete]:"Agents that have finished their work.",[C.failed]:"Agents that failed or were stopped."},Ft=()=>n.jsxs("svg",{className:"agent-view__empty-illustration",viewBox:"0 0 360 240",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Preview of the agents board layout",children:[n.jsx("rect",{x:"0",y:"0",width:"360",height:"240",rx:"12",fill:"var(--color-grey-100)"}),n.jsx("rect",{x:"16",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"130",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"244",y:"16",width:"100",height:"100",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"244",y:"124",width:"100",height:"100",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),n.jsx("rect",{x:"28",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),n.jsx("rect",{x:"28",y:"96",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),n.jsx("rect",{x:"142",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-semantic-warning-050)"}),n.jsx("circle",{cx:"40",cy:"70",r:"4",fill:"var(--color-brand-600)"}),n.jsx("circle",{cx:"40",cy:"114",r:"4",fill:"var(--color-brand-600)"}),n.jsx("circle",{cx:"154",cy:"70",r:"4",fill:"var(--color-semantic-warning-600)"}),n.jsx("circle",{cx:"256",cy:"52",r:"4",fill:"var(--color-grey-400)"}),n.jsx("circle",{cx:"256",cy:"160",r:"4",fill:"var(--color-semantic-destructive-500)"})]}),zt=({status:t})=>{const e=Ee[t];return e.statusIcon?n.jsx(d.Icon,{name:e.statusIcon.name,size:16,color:e.statusIcon.color,screenReaderText:e.title}):n.jsx(d.Dot,{colour:e.dotColour,label:e.title})},Gt=()=>n.jsxs("section",{className:"agent-view__empty","aria-label":"About the agents board",children:[n.jsxs("div",{className:"agent-view__empty-content",children:[n.jsx(d.Heading,{level:4,children:"Your agents board"}),n.jsx("p",{className:"agent-view__empty-lead",children:"When you start an agent, it appears here so you can track progress at a glance. Agents move between columns as their status changes."}),n.jsx("ul",{className:"agent-view__empty-columns",children:Ht.map(t=>{const e=Ee[t];return n.jsxs("li",{className:"agent-view__empty-column",children:[n.jsx("span",{className:"agent-view__empty-column-indicator",children:n.jsx(zt,{status:t})}),n.jsxs("span",{className:"agent-view__empty-column-text",children:[n.jsx("span",{className:"agent-view__empty-column-title",children:e.title}),n.jsx("span",{className:"agent-view__empty-column-description",children:Bt[t]})]})]},t)})}),n.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",n.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),n.jsx("div",{className:"agent-view__empty-visual",children:n.jsx(Ft,{})})]}),qt=(t,e)=>({...t,...e.length>0?{children:e}:{}}),lt=t=>{const e=[],s=[];for(const a of t){const r=a.children?lt(a.children):{needsInput:[],tasks:[]};if(e.push(...r.needsInput),a.status===$.hitl){e.push({...a,children:void 0});continue}s.push(qt(a,r.tasks))}return{needsInput:e,tasks:s}},Kt=t=>t.map((e,s)=>({item:e,index:s})).sort((e,s)=>{const a=e.item.status===$.hitl,r=s.item.status===$.hitl;return a!==r?a?-1:1:e.index-s.index}).map(({item:e})=>e),He=2,Wt=t=>{if(!t)return{canScrollUp:!1,canScrollDown:!1};const e=t.scrollHeight-t.clientHeight;return e<=He?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:t.scrollTop>He,canScrollDown:t.scrollTop<e-He}},Jt=(t,e)=>{if(!t||!e)return null;const s=t.getBoundingClientRect(),a=e.getBoundingClientRect();return{top:a.top-s.top,left:a.left-s.left,width:a.width,height:a.height}},Ie=({children:t,className:e,contentClassName:s,scrollSelector:a,style:r,"aria-label":c})=>{const i=o.useRef(null),g=o.useRef(null),[l,p]=o.useState(!1),[_,u]=o.useState(!1),[f,j]=o.useState(null),v=()=>{var x;return a?((x=i.current)==null?void 0:x.querySelector(a))??null:g.current},E=()=>{const x=v(),k=Wt(x);if(p(m=>m===k.canScrollUp?m:k.canScrollUp),u(m=>m===k.canScrollDown?m:k.canScrollDown),a){const m=Jt(i.current,x);j(T=>(T==null?void 0:T.top)===(m==null?void 0:m.top)&&(T==null?void 0:T.left)===(m==null?void 0:m.left)&&(T==null?void 0:T.width)===(m==null?void 0:m.width)&&(T==null?void 0:T.height)===(m==null?void 0:m.height)?T:m)}else j(m=>m===null?m:null)};o.useLayoutEffect(()=>{E()}),o.useEffect(()=>{const x=i.current;if(!x)return;let k=null,m=null;const T=()=>{k==null||k.removeEventListener("scroll",E),m==null||m.disconnect(),m=null,k=null},P=L=>{if(L===k){E();return}if(T(),k=L,!k){E();return}k.addEventListener("scroll",E,{passive:!0}),m=new ResizeObserver(()=>E()),m.observe(k),k.firstElementChild instanceof HTMLElement&&m.observe(k.firstElementChild),E()};P(v());const N=new MutationObserver(()=>{P(v())});return N.observe(x,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",E),()=>{window.removeEventListener("resize",E),N.disconnect(),T()}},[a]);const A=x=>{const k=v();if(!k)return;const m=Math.max(k.clientHeight*.75,120);k.scrollBy({top:x==="up"?-m:m,behavior:"smooth"})},M=n.jsxs(n.Fragment,{children:[l&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--top","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--top","aria-label":"Scroll up",onClick:()=>A("up"),children:n.jsx(d.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),_&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),n.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>A("down"),children:n.jsx(d.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return n.jsx("div",{ref:i,className:z("scrollable-region",e),style:r,"aria-label":c,children:a?n.jsxs(n.Fragment,{children:[t,f&&(l||_)&&n.jsx("div",{className:"scrollable-region__overlay",style:{top:f.top,left:f.left,width:f.width,height:f.height},children:M})]}):n.jsxs(n.Fragment,{children:[M,n.jsx("div",{ref:g,className:z("scrollable-region__viewport",s),children:t})]})})},Vt=48,Yt=({checklist:t})=>{const e=o.useRef(null),s=o.useRef(!1);return o.useLayoutEffect(()=>{const a=e.current;if(!a)return;const r=a.scrollHeight-a.scrollTop-a.clientHeight;(!s.current||r<=Vt)&&(a.scrollTop=a.scrollHeight,s.current=!0)},[t]),t.length===0?n.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):n.jsx(Ie,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:n.jsx("ul",{ref:e,className:"agent-view__progress-list","aria-label":"Agent tasks",children:Kt(t).map(a=>{const r=J[a.status];return n.jsxs("li",{className:z("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[n.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`}),n.jsxs("div",{className:"agent-view__progress-item-content",children:[n.jsx("span",{className:"agent-view__progress-label",children:a.task}),a.status!==$.complete&&n.jsx("span",{className:"agent-view__progress-description",children:a.description})]})]},a.task)})})})},Xt=({prompts:t,classNamePrefix:e="agent-workspace",onSelect:s})=>t.length===0?null:n.jsx("div",{className:`${e}__chips`,children:t.map(a=>n.jsx("button",{type:"button",className:`${e}__chip`,onClick:()=>s(a),children:a},a))});class Qt{constructor(e,s){this.connector=e,this.canSend=s.canSend,this.onTurn=s.onTurn,this.onAwaitingChange=s.onAwaitingChange}get canRate(){return!1}get canLoadHistory(){return!1}get canListInteractions(){return!1}get canSendNotification(){return!1}get ratingPopupUrls(){return{}}async sendMessage(e){var s,a;if(!this.canSend())return null;(s=this.onAwaitingChange)==null||s.call(this,!0);try{const r=await this.connector.sendMessage(e.userMessage,e.uploadFiles);return this.onTurn(r),{id:r.message.id,text:r.message.text,type:le.CHAT_RESPONSE_TYPE_AGENT,...r.message.followUpPrompts?{followUpPrompts:r.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:Dt,type:le.CHAT_RESPONSE_TYPE_ERROR}}finally{(a=this.onAwaitingChange)==null||a.call(this,!1)}}async loadHistory(e){return null}async listInteractions(){return null}async rateMessage(e){}async sendNotification(e){return!1}}const Zt=({connector:t,phase:e,chatHistory:s,chatSessionKey:a,startQuery:r,clarificationMessage:c,enableUpload:i=!1,onTurn:g,onAwaitingChange:l,onClarificationPrompt:p,onDismissClarification:_})=>{const u=o.useMemo(()=>new Qt(t,{canSend:()=>e===U.running,onTurn:g,onAwaitingChange:l}),[t,e,g,l]),f=e!==U.running,j=e===U.running;return n.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[c&&n.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[n.jsx("p",{className:"agent-workspace__clarification-text",children:c.text}),c.followUpPrompts&&n.jsx(Xt,{prompts:c.followUpPrompts,onSelect:p}),n.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:_,children:"Dismiss"})]}),n.jsx("div",{className:"agent-workspace__ask-arbor",children:n.jsx(Ie,{scrollSelector:".chat-panel-message-list",children:n.jsx(le.ChatPanel,{connector:u,chatHistory:s,startQuery:r,lockConversation:f,enableUpload:i,speechEnabled:j,speechLanguage:"en-GB",speechSubmissionDelay:1e3,slashMenuItems:[],menuContent:[],introHeading:"Message your agent",introBody:"Ask questions, share trip details, or paste a link. The agent will update the checklist as it works.",placeholder:j?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)})}),e===U.stopped&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(d.Icon,{name:"circle-alert",size:16,color:"var(--color-semantic-warning-600)"}),n.jsx("span",{children:"You stopped the agent. Its progress is saved in the checklist on the left."})]}),e===U.complete&&n.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[n.jsx(d.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),n.jsx("span",{children:"The agent has finished."})]})]})},dt=({item:t,depth:e,canRequestInput:s,onAttentionItemClick:a})=>{const r=J[t.status],c=t.status.replace(/_/g,"-"),i=t.status===$.hitl&&s&&a,g=n.jsxs("div",{className:"agent-workspace__task-row",children:[n.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`}),n.jsxs("div",{className:"agent-workspace__task-content",children:[n.jsx("span",{className:"agent-workspace__task-label",children:t.task}),t.status!==$.complete&&t.description&&n.jsx("span",{className:"agent-workspace__task-description",children:t.description})]})]});return n.jsxs("li",{className:z("agent-workspace__task",`agent-workspace__task--${c}`,{"agent-workspace__task--child":e>0}),children:[i?n.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${t.task}`,onClick:()=>a(t),children:g}):g,t.children&&t.children.length>0&&n.jsx("ul",{className:"agent-workspace__task-children",children:t.children.map(l=>n.jsx(dt,{item:l,depth:e+1,canRequestInput:s,onAttentionItemClick:a},l.task))})]})},Ze=({items:t,ariaLabel:e,canRequestInput:s,onAttentionItemClick:a})=>n.jsx("ul",{className:"agent-workspace__task-list","aria-label":e,children:t.map(r=>n.jsx(dt,{item:r,depth:0,canRequestInput:s,onAttentionItemClick:a},r.task))}),en=({checklist:t,isLoading:e,error:s,phase:a,canRequestInput:r,onAttentionItemClick:c})=>{const i=o.useMemo(()=>t?lt(t):null,[t]);return n.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--checklist","aria-label":"Checklist",children:[n.jsx("div",{className:"agent-workspace__panel-header",children:n.jsx(d.Heading,{level:4,children:"Checklist"})}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsxs(Ie,{children:[e&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:oe}),n.jsx("span",{children:oe})]}),!e&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!e&&!s&&i&&n.jsxs(n.Fragment,{children:[i.needsInput.length>0&&n.jsxs("div",{className:"agent-workspace__task-group",children:[n.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),n.jsx(Ze,{items:i.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:r,onAttentionItemClick:c})]}),i.tasks.length>0&&n.jsxs("div",{className:z("agent-workspace__task-group",{"agent-workspace__task-group--following":i.needsInput.length>0}),children:[i.needsInput.length>0&&n.jsx("p",{className:"agent-workspace__task-group-label",children:"Other tasks"}),n.jsx(Ze,{items:i.tasks,ariaLabel:"Agent tasks",canRequestInput:r,onAttentionItemClick:c})]})]}),!e&&!s&&(!i||i.needsInput.length===0&&i.tasks.length===0)&&n.jsx("p",{className:"agent-workspace__empty",children:a===U.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})]})},tn={[re.MIS_RECORD]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[re.FILE]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[re.WORKFLOW]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[re.LINK]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},nn=({resources:t,isLoading:e=!1,error:s=null})=>n.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--documents","aria-label":"Resources",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(d.Heading,{level:4,children:"Resources"}),n.jsx("span",{className:"agent-workspace__panel-count",children:t.length})]}),n.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:n.jsxs(Ie,{children:[e&&n.jsxs("div",{className:"agent-workspace__loading",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading resources"}),n.jsx("span",{children:"Loading resources…"})]}),!e&&s&&n.jsx("p",{className:"agent-workspace__error",role:"alert",children:s}),!e&&!s&&t.length>0&&n.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:t.map(a=>{const r=tn[a.type];return n.jsx("li",{className:"agent-workspace__resource",children:n.jsxs("a",{className:"agent-workspace__resource-card",href:a.uri,target:"_blank",rel:"noreferrer",children:[n.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${a.type.toLowerCase()}`,children:n.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`})}),n.jsxs("span",{className:"agent-workspace__resource-content",children:[n.jsxs("span",{className:"agent-workspace__resource-top",children:[n.jsx("span",{className:"agent-workspace__resource-name",children:a.name}),n.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${a.type.toLowerCase()}`,children:r.label})]}),a.description&&n.jsx("span",{className:"agent-workspace__resource-description",children:a.description})]}),n.jsx(d.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]})},`${a.type}-${a.uri}`)})}),!e&&!s&&t.length===0&&n.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),Te=t=>{const e=Date.parse(t);return Number.isFinite(e)?e:0},sn=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),Be=t=>{const e=new Date(t);return Number.isFinite(e.getTime())?sn.format(e):t},Ae=t=>t.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,e=>e.split(/[_-]/).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")),we=(t,e)=>e<=1?0:t/(e-1)*100,gt=t=>Math.max(t,0)+2,an=t=>t+1,rn=(t,e)=>{if(e.length===0)return 50;const s=gt(e.length),a=we(1,s),r=we(e.length,s),c=e.map(_=>Te(_.timestamp)),i=Math.min(...c),g=Math.max(...c);if(g<=i)return a;const l=(Te(t.timestamp)-i)/(g-i),p=Math.min(1,Math.max(0,l));return a+p*(r-a)},on=8,cn=20,ln=(t,e=on,s=cn)=>{const a=new Map;if(t.length===0)return a;const r=[...t].sort((i,g)=>i.leftPercent-g.leftPercent||i.timestampMs-g.timestampMs||i.id.localeCompare(g.id)),c=[];for(const i of r){const g=c[c.length-1];g&&i.leftPercent-g[g.length-1].leftPercent<e?g.push(i):c.push([i])}for(const i of c){const g=[...i].sort((p,_)=>p.timestampMs-_.timestampMs||p.id.localeCompare(_.id)),l=(g.length-1)/2;g.forEach((p,_)=>{a.set(p.id,(_-l)*s)})}return a},Ce=(t,e=0)=>({left:`calc(${t/100} * (100% - var(--agent-timeline-node-size)) + (var(--agent-timeline-node-size) / 2) + ${e}px)`,transform:"translateX(-50%)"}),dn=t=>t.type!=="message-sent",gn=({timeline:t,isLoading:e,error:s,onOpenChatSession:a})=>{const r=((t==null?void 0:t.actionLog)??[]).filter(dn),c=(t==null?void 0:t.chatSessions)??[],i=!e&&!s&&r.length===0&&c.length===0,g=gt(r.length),l=r.map((u,f)=>({id:`action-${u.timestamp}-${f}`,leftPercent:we(an(f),g),timestampMs:Te(u.timestamp)})),p=c.map(u=>({id:u.sessionId,leftPercent:rn(u,r),timestampMs:Te(u.timestamp)})),_=ln([...l,...p]);return n.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[e&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),s&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:s||it}),i&&n.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!e&&!s&&!i&&n.jsxs("div",{className:"agent-timeline",children:[n.jsx("div",{className:"agent-timeline__track","aria-hidden":"true"}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:Ce(we(0,g)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(d.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Start"})]}),r.map((u,f)=>{const j=`action-${u.timestamp}-${f}`,v=l[f].leftPercent,E=u.type==="checklist-updated",A=u.type==="status-transition",M=E?"checklist":A?"status":"note";return n.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${M}`,style:Ce(v,_.get(j)??0),children:[n.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${M}`,"aria-label":`${Ae(u.type)}: ${Ae(u.entry)}`,children:[E&&n.jsx(d.Icon,{name:"check-solid",size:16,color:"currentColor"}),A&&n.jsx(d.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]}),n.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[n.jsx("strong",{className:"agent-timeline__pill-type",children:Ae(u.type)}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Ae(u.entry)}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Be(u.timestamp)})]})]},j)}),n.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:Ce(we(g-1,g)),children:[n.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:n.jsx(d.Icon,{name:"flag",size:16,color:"currentColor"})}),n.jsx("span",{className:"agent-timeline__terminus-label",children:"Finish"})]}),c.map((u,f)=>{const j=p[f].leftPercent;return n.jsxs("div",{className:"agent-timeline__chat-station",style:Ce(j,_.get(u.sessionId)??0),children:[n.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${Be(u.timestamp)}`,onClick:()=>a(u.sessionId),children:n.jsx(d.Icon,{name:"sparkles",size:16,color:"currentColor"})}),n.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[n.jsx("strong",{className:"agent-timeline__pill-type",children:"Chat session"}),n.jsx("span",{className:"agent-timeline__pill-entry",children:Be(u.timestamp)})]})]},u.sessionId)})]})]})},un=["I'll get the details and come back to you","Skip this for now"],hn=t=>{var s;const e=(s=t.prompt)!=null&&s.trim()?t.prompt.trim():`I need a bit more from you on "${t.task}". ${t.description} What can you tell me?`;return{id:`clarification-${Date.now()}`,author:X.agent,text:e,followUpPrompts:t.clarificationPrompts??un}},ae=t=>({id:t.id,text:t.text,type:t.author===X.user?le.CHAT_RESPONSE_TYPE_USER:t.author===X.system?le.CHAT_RESPONSE_TYPE_INFO:le.CHAT_RESPONSE_TYPE_AGENT,...t.followUpPrompts?{followUpPrompts:t.followUpPrompts}:{}});class ie extends Error{constructor(e,s,a){super(a??`Agent service request failed (${e})`),this.name="AgentServiceError",this.status=e,this.detail=s}}const pn="/api/v1",B={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},F={GET:"GET",POST:"POST"},mn={error:"error"},_n={user:"user"},ce={acceptJson:"application/json",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},fn=/:invocationId\b/g,vn=t=>t.trim().replace(/^Bearer\s+/i,""),wn=t=>t.endsWith("/")?t.slice(0,-1):t;class Re{constructor(e){var a;this.baseUrl=wn(e.baseUrl??"");const s=(a=e.token)==null?void 0:a.trim();this.token=s?vn(s):void 0,this.customHeaders=e.headers,this.urls=e.urls??{},this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis)}setHeaders(e){this.customHeaders=e}async listAgentDefinitions(){return(await this.request(F.GET,this.resolveUrl("agentDefinitions",B.agentDefinitions))).agent_definitions??[]}getAgentDefinition(e){return this.request(F.GET,this.apiUrl(`${B.agentDefinitions}/${encodeURIComponent(e)}`))}listTripOptions(){return this.request(F.GET,this.apiUrl(B.tripOptions))}getDataset(){return this.request(F.GET,this.apiUrl(B.demoDataset))}setDataset(e){return this.request(F.POST,this.apiUrl(B.demoDataset),{dataset:e})}listAgents(e={}){const s=new URLSearchParams;e.status&&s.set("status",e.status),e.agentDefinitionRef&&s.set("agent_definition_ref",e.agentDefinitionRef);const a=s.toString()?`?${s.toString()}`:"";return this.request(F.GET,`${this.resolveUrl("agents",B.agents)}${a}`)}createAgent(e,s={}){var i,g;const a={agent_definition_ref:e},r=(i=s.invocationName)==null?void 0:i.trim(),c=(g=s.agentIntent)==null?void 0:g.trim();return r&&(a.invocation_name=r),c&&(a.agent_intent=c),this.request(F.POST,this.resolveUrl("agents",B.agents),a)}getAgent(e){return this.request(F.GET,this.resolveUrl("agent",`${B.agents}/${encodeURIComponent(e)}`,e))}getAgentChecklist(e){return this.request(F.GET,this.resolveUrl("agentChecklist",`${B.agents}/${encodeURIComponent(e)}/checklist`,e))}getAgentResources(e){return this.request(F.GET,this.resolveUrl("agentResources",`${B.agents}/${encodeURIComponent(e)}/resources`,e))}getAgentTimeline(e){return this.request(F.GET,this.resolveUrl("agentTimeline",`${B.agents}/${encodeURIComponent(e)}/agent-timeline`,e))}getAgentContext(e){return this.request(F.GET,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/context`))}cancelAgent(e){return this.request(F.POST,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/cancel`))}archiveAgent(e){return this.request(F.POST,this.apiUrl(`${B.agents}/${encodeURIComponent(e)}/archive`))}getConversation(e){return this.request(F.GET,this.resolveUrl("agentConversation",`${B.conversations}/${encodeURIComponent(e)}`,e))}async chat(e,s,a={}){const r=!!(a.uploadFiles&&a.uploadFiles.length>0),c=await this.fetchImpl(this.resolveUrl("agentChat",`${B.agents}/${encodeURIComponent(e)}/chat`,e),{method:F.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:ce.acceptEventStream,...r?{}:{"Content-Type":ce.contentTypeJson}},body:r?kn(s,a.uploadFiles??[]):JSON.stringify(s),signal:a.signal});if(!c.ok)throw await this.toError(c);if(!c.body)throw new ie(c.status,null,"Chat response contained no stream body");return this.consumeSse(c.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(e){return`${this.baseUrl}${pn}${e}`}resolveUrl(e,s,a){const r=this.urls[e];return r?a?r.replace(fn,encodeURIComponent(a)):r:this.apiUrl(s)}async request(e,s,a){const r=await this.fetchImpl(s,{method:e,headers:{...this.customHeaders,...this.authHeaders(),Accept:ce.acceptJson,...a===void 0?{}:{"Content-Type":ce.contentTypeJson}},...a===void 0?{}:{body:JSON.stringify(a)}});if(!r.ok)throw await this.toError(r);if(r.status!==204)return await r.json()}async toError(e){let s=null;try{s=await e.json()}catch{}return new ie(e.status,s,`Agent service request failed (${e.status} ${e.statusText})`)}async consumeSse(e,s){const a=e.getReader(),r=new TextDecoder;let c="",i;const g=l=>{const{event:p,data:_}=xn(l);if(_===null)return;if(p===mn.error){const f=et(_);throw new ie(502,f,(f==null?void 0:f.message)??"Chat stream error")}const u=et(_);u&&(i=u,s==null||s(u))};for(;;){const{done:l,value:p}=await a.read();if(l)break;c+=r.decode(p,{stream:!0});const _=c.split(`
|
|
2
2
|
|
|
3
|
-
`);
|
|
4
|
-
`)){const
|
|
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;
|
|
3
|
+
`);c=_.pop()??"";for(const u of _)g(u)}if(c.trim()&&g(c),!i)throw new ie(502,null,"Chat stream ended without any events");return i}}const xn=t=>{let e=null;const s=[];for(const a of t.split(`
|
|
4
|
+
`)){const r=a.trimEnd();r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&s.push(r.slice(5).trim())}return{event:e,data:s.length>0?s.join(`
|
|
5
|
+
`):null}},et=t=>{try{return JSON.parse(t)}catch{return}};function kn(t,e){const s=new FormData;s.append("body",JSON.stringify(t));for(const a of e)s.append("files",a,a.name);return s}const ut=t=>{switch(t){case Xe.cancelled:return C.failed;case Xe.archived:return C.complete;case C.hitl:case C.complete:case C.failed:case C["generating-a-response"]:return t;default:return C["generating-a-response"]}},ht=t=>{switch(t){case $e.requires_attention:return $.hitl;case $e.in_progress:case $e.available:return $["generating-a-response"];case $.failed:case $.complete:case $.hitl:case $["generating-a-response"]:return t;default:return $["generating-a-response"]}},qe=t=>({ref:t.name,display_name:t.display_name,agent_intent:t.agent_intent??"",description:t.description}),yn=t=>({id:t.id,name:t.name,...t.has_run_before?{hasRunBefore:t.has_run_before}:{}}),Nn=new Set(Object.values(re)),Sn=t=>t&&Nn.has(t)?t:re.LINK,pt=t=>({uri:t.uri??"",type:Sn(t.type),name:t.name??"",description:t.description??""}),Ke=t=>(Array.isArray(t)?t:t.resources??[]).map(pt),mt=t=>({actionLog:(t.action_log??[]).map(e=>({timestamp:e.timestamp,type:e.type,entry:e.entry,origin:e.origin})),chatSessions:(t.chat_sessions??[]).map(e=>({sessionId:e.session_id,timestamp:e.timestamp}))}),ze=t=>{var s;const e=t.invocation_id??t.id;return{id:t.id,invocation_id:e,agent_definition_ref:t.agent_definition_ref,...t.agent_intent?{agent_intent:t.agent_intent}:{},invocation_name:((s=t.invocation_name)==null?void 0:s.trim())||t.agent_definition_ref,application_id:t.application_id,...t.application_name?{application_name:t.application_name}:{},created_by:t.created_by,status:ut(t.status),context_ref:t.context_ref??null,checklist_ref:t.checklist_ref??null}},We=t=>{var e;return{task:t.task??t.name??t.label??Ut,status:ht(t.status),description:t.description??"",...t.prompt?{prompt:t.prompt}:{},...(e=t.follow_up_prompts)!=null&&e.length?{clarificationPrompts:t.follow_up_prompts}:{}}},jn=t=>Array.isArray(t)?t:t.checklist_items??t.checklist??t.items??[],Je=(t,e,s)=>{var c;const a=!Array.isArray(e)&&(e.opening_message||(c=e.opening_follow_up_prompts)!=null&&c.length)?e:s,r=a?xe(a):void 0;return{invocation_id:t,checklist:jn(e).map(We),...r?{openingMessage:r}:{}}},_t=(t,e)=>{const s=xe(e);return{invocation_id:e.invocation_id??t,checklist:(e.checklist_items??[]).map(We),...s?{openingMessage:s}:{}}},xe=t=>{var s,a;const e=(s=t.opening_message)==null?void 0:s.trim();if(e)return{id:ot,author:X.agent,text:e,...(a=t.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:t.opening_follow_up_prompts}:{}}},ft=t=>t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.length>0&&e.message_type!=="tool_request").map(e=>({id:e.message_id,author:e.role==="user"?X.user:X.agent,text:e.content})),An={id:ot,author:X.agent,text:"Type a question or upload a file. You can ask it how it's progressing, or send an instruction and it'll act on it."};let tt=0;const Cn=t=>(tt+=1,`${t}-${Date.now()}-${tt}`),bn=t=>{const e=t.destination?` to ${t.destination}`:"";return`Let's get started on ${t.tripName.trim()||t.destination.trim()||"this task"}${e}. What will you do first?`};class vt{constructor(e,s,a={}){this.seededChecklist=[],this.client=e,this.agentId=s,this.chatId=a.chatId??s,this.opening=a.openingMessage??An,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const e=await this.client.getConversation(this.chatId),s=ft(e.messages);return s.length===0?[this.opening]:s}async start(e){return{...await this.exchange(bn(e)),phase:U.running}}sendMessage(e,s){return this.exchange(e,s)}async stop(){}seedChecklist(e){this.seededChecklist=e}async exchange(e,s){var i;const a=[{role:_n.user,content:e}],r=await this.client.chat(this.agentId,{messages:a,chat_id:this.chatId,...this.model?{model:this.model}:{},moderation_enabled:!0,meta:{feature_id:"agent_view",source:"agent_view_frontend"}},...s&&s.length>0?[{uploadFiles:s}]:[]),c={id:r.event_id||Cn("msg-agent"),author:X.agent,text:r.message.content,...(i=r.follow_up_prompts)!=null&&i.length?{followUpPrompts:r.follow_up_prompts}:{}};try{const g=await this.client.getAgent(this.agentId),{checklist:l}=_t(this.agentId,g);return this.seededChecklist=l,{message:c,checklist:l}}catch{return{message:c,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const Ve=(t,e)=>s=>{var a,r;return new vt(t,s.invocation_id,{model:e==null?void 0:e.model,chatId:((a=e==null?void 0:e.resolveChatId)==null?void 0:a.call(e,s))??(e==null?void 0:e.chatId)??s.invocation_id,openingMessage:((r=e==null?void 0:e.resolveOpeningMessage)==null?void 0:r.call(e,s))??(e==null?void 0:e.openingMessage)})},wt=t=>t instanceof ie?t.message:t instanceof TypeError?"Network error while contacting the agent service.":t instanceof Error&&t.message?t.message:ct,En=t=>{const e={};for(const s of t){const a=xe(s);if(!a)continue;const r=s.invocation_id??s.id;e[r]=a,e[s.id]=a}return e},Tn=t=>JSON.stringify(t),Fe=(t,e)=>JSON.stringify(t)===JSON.stringify(e),xt=t=>{const{jwt:e,headers:s,urls:a}=t,r=JSON.stringify(s??{}),c=Tn(a),i=o.useMemo(()=>new Re({token:e,headers:s,urls:a}),[e,c]);o.useLayoutEffect(()=>{i.setHeaders(s)},[i,r]);const[g,l]=o.useState([]),[p,_]=o.useState([]),[u,f]=o.useState({}),[j,v]=o.useState("loading"),[E,A]=o.useState(null),[M,x]=o.useState(0),k=o.useCallback((I,b)=>{const D=I.map(ze),G=b.map(qe),K=En(I);l(R=>Fe(R,D)?R:D),_(R=>Fe(R,G)?R:G),f(R=>Fe(R,K)?R:K),v("idle"),A(null)},[]);o.useEffect(()=>{let I=!1;return v("loading"),A(null),(async()=>{try{const[b,D]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);if(I)return;k(b,D)}catch(b){if(I)return;l([]),_([]),f({}),v("error"),A(wt(b))}})(),()=>{I=!0}},[k,i,M]);const m=o.useCallback(()=>{x(I=>I+1)},[]),T=o.useCallback(async()=>{try{const[I,b]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);k(I,b)}catch{}},[k,i]),P=o.useCallback(async I=>{const[b,D]=await Promise.all([i.getAgentChecklist(I),i.getAgent(I).catch(()=>null)]);return Je(I,b,D??void 0)},[i]),N=o.useCallback(async I=>{const b=await i.getAgentResources(I);return Ke(b)},[i]),L=o.useCallback(async({definition:I,invocationName:b})=>{const D=await i.createAgent(I.ref,{invocationName:b}),G=await i.getAgent(D.id),K=ze(G),R=xe(G);return l(q=>[K,...q]),R&&f(q=>({...q,[K.invocation_id]:R,[K.id]:R})),K},[i]),V=o.useMemo(()=>Ve(i,{resolveOpeningMessage:I=>u[I.invocation_id]??u[I.id]}),[i,u]);return{agents:g,agentDefinitions:p,loadState:j,loadError:E,reload:m,refresh:T,fetchAgentChecklist:P,fetchAgentResources:N,createAgent:L,chatConnector:V}},In=t=>JSON.stringify(t),kt=t=>{const{agent:e,jwt:s,headers:a,urls:r,chatId:c}=t,i=JSON.stringify(a??{}),g=In(r),l=o.useMemo(()=>new Re({token:s,headers:a,urls:{agent:r.agentUrl,agentChecklist:r.agentChecklistUrl,...r.agentResourcesUrl?{agentResources:r.agentResourcesUrl}:{},...r.agentTimelineUrl?{agentTimeline:r.agentTimelineUrl}:{},agentChat:r.agentChatUrl,agentConversation:r.agentConversationUrl}}),[s,g]);o.useLayoutEffect(()=>{l.setHeaders(a)},[l,i]);const p=o.useCallback(async j=>{const[v,E]=await Promise.all([l.getAgentChecklist(j),l.getAgent(j).catch(()=>null)]);return Je(j,v,E??void 0)},[l]),_=o.useCallback(async j=>{const v=await l.getAgentResources(j);return Ke(v)},[l]),u=o.useCallback(async j=>{const v=await l.getAgentTimeline(j);return mt(v)},[l]);return{connector:o.useMemo(()=>Ve(l,{chatId:c??e.invocation_id})(e),[l,e.invocation_id,c]),fetchAgentChecklist:p,fetchAgentResources:_,fetchAgentTimeline:u}},Rn=3e4,On=(t,e)=>{const s=t.hasRunBefore?e||"This trip":t.tripName.trim()||"A new trip",a=t.destination?` to ${t.destination}`:"",r=t.hasRunBefore?" It has run before.":"";return`${s}${a}.${r}`.trim()},Ln=t=>{switch(t){case C.failed:return U.stopped;case C.complete:return U.complete;default:return U.running}},nt=(t,e)=>{e([ae(t)])},Mn=(t,e)=>t.length===e.length&&t.every((s,a)=>{const r=e[a];return r!==void 0&&s.id===r.id&&s.text===r.text}),yt=({agent:t,invocationId:e,open:s,onClose:a,jwt:r,headers:c,agentUrl:i,agentChecklistUrl:g,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:_,agentConversationUrl:u,chatId:f,enableUpload:j,initialBrief:v,initialPhase:E,initialChecklist:A})=>{const[M,x]=o.useState(f??e),[k,m]=o.useState("chat"),[T,P]=o.useState(!1),{connector:N,fetchAgentChecklist:L,fetchAgentResources:V,fetchAgentTimeline:I}=kt({agent:{...t,invocation_id:e},jwt:r,headers:c,chatId:M,urls:{agentUrl:i,agentChecklistUrl:g,agentResourcesUrl:l,agentTimelineUrl:p,agentChatUrl:_,agentConversationUrl:u}}),b=o.useRef(N),[D,G]=o.useState(E??(v?U.running:Ln(t.status))),[K,R]=o.useState([]),[q,Z]=o.useState(0),[Oe,de]=o.useState(),[ne,ge]=o.useState(null),[se,Le]=o.useState([]),[ke,Q]=o.useState(!1),[ye,ue]=o.useState(null),[Ne,Se]=o.useState(null),[Me,he]=o.useState(!1),[Pe,pe]=o.useState(null),[De,me]=o.useState(A??null),[Ue,_e]=o.useState(!1),[je,h]=o.useState(null),[S,y]=o.useState(!1),[H,ee]=o.useState(!1),[Y,te]=o.useState(!1),fe=o.useRef(S);o.useEffect(()=>{b.current=N},[N]),o.useEffect(()=>{fe.current=S},[S]),o.useEffect(()=>{x(f??e),m("chat"),P(!1),R([]),Z(w=>w+1)},[e,f]),o.useEffect(()=>{if(!s||v)return;const w=b.current.bootstrapConversation;if(!w){nt(b.current.openingMessage(),R);return}let O=!1;return y(!0),(async()=>{try{const W=await w.call(b.current);if(O)return;R(W.map(ae))}catch{O||nt(b.current.openingMessage(),R)}finally{O||y(!1)}})(),()=>{O=!0}},[s,v,e,M]),o.useEffect(()=>{if(!s||v)return;const w=window.setInterval(()=>{const O=b.current.bootstrapConversation;O&&(async()=>{try{const W=await O.call(b.current);if(fe.current)return;const ve=W.map(ae);R(Ye=>Mn(Ye,ve)?Ye:ve)}catch{}})()},Rn);return()=>{window.clearInterval(w)}},[s,v,e,M]);const jt=o.useCallback(w=>{w.checklist&&me(w.checklist),w.phase&&G(w.phase)},[]);o.useEffect(()=>{var w,O;!s||v||A&&A.length>0&&((O=(w=b.current).seedChecklist)==null||O.call(w,A))},[s,v,A]),o.useEffect(()=>{if(!s||v)return;let w=!1;return _e(!(A!=null&&A.length)),h(null),(async()=>{var O,W;try{const ve=await L(e);if(w)return;A!=null&&A.length||(me(ve.checklist),(W=(O=b.current).seedChecklist)==null||W.call(O,ve.checklist))}catch{!w&&!(A!=null&&A.length)&&h(be)}finally{w||_e(!1)}})(),()=>{w=!0}},[s,e,v,A,L]),o.useEffect(()=>{if(!s||!l)return;let w=!1;return Q(!0),ue(null),(async()=>{try{const O=await V(e);w||Le(O)}catch{w||ue(Pt)}finally{w||Q(!1)}})(),()=>{w=!0}},[s,e,l,V]),o.useEffect(()=>{if(!s||!p)return;let w=!1;return he(!0),pe(null),(async()=>{try{const O=await I(e);w||Se(O)}catch{w||pe(it)}finally{w||he(!1)}})(),()=>{w=!0}},[s,e,p,I]),o.useEffect(()=>{if(!s||!v)return;let w=!1;const O={id:`user-brief-${Date.now()}`,author:X.user,text:On(v,t.invocation_name)};return(async()=>{const W=await b.current.start(v);w||(R([ae(b.current.openingMessage()),ae(O),ae(W.message)]),W.checklist&&me(W.checklist),G(W.phase??U.running))})(),()=>{w=!0}},[s,v,t.invocation_name,e]);const At=o.useCallback(w=>{ge(hn(w))},[]),Ct=o.useCallback(w=>{x(w),P(!0),m("chat"),R([]),Z(O=>O+1)},[]),bt=o.useCallback(()=>{m("chat"),P(!1),x(f??e),R([]),Z(w=>w+1)},[e,f]),Et=o.useCallback(w=>{ge(null),de(w),Z(O=>O+1)},[]),Tt=o.useCallback(async()=>{await b.current.stop(),G(U.stopped)},[]),It=De;return n.jsxs(d.Modal,{open:s,closeHandler:a,hideCloseButton:!0,className:"agent-workspace",children:[n.jsxs(d.Modal.Header,{className:"agent-workspace__header",children:[n.jsxs("div",{className:"agent-workspace__header-title",children:[n.jsx("span",{className:"agent-workspace__header-avatar","aria-hidden":"true",children:n.jsx(d.Icon,{name:"ask-arbor",size:24})}),n.jsx(d.Modal.Title,{children:t.invocation_name}),n.jsx("span",{className:z("agent-workspace__phase",`agent-workspace__phase--${D}`),children:$t[D]})]}),n.jsxs("div",{className:"agent-workspace__header-actions",children:[n.jsx(d.Button,{variant:H?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!H,onClick:()=>ee(w=>!w),children:"Checklist"}),n.jsx(d.Button,{variant:Y?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Y,onClick:()=>te(w=>!w),children:"Resources"}),n.jsx(d.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),n.jsxs(d.Modal.Body,{className:z("agent-workspace__body",{"agent-workspace__body--no-checklist":H,"agent-workspace__body--no-resources":Y}),children:[" ",n.jsxs("section",{className:z("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!p&&k==="timeline"}),"aria-label":"Agent",children:[n.jsxs("div",{className:"agent-workspace__panel-header",children:[n.jsx(d.Heading,{level:4,children:"Agent"}),D===U.running&&n.jsx(d.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Stop",onClick:()=>void Tt(),children:"Stop agent"})]}),p&&n.jsxs(d.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[n.jsx(d.Tabs.Item,{active:k==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>m("chat")},children:"Chat"}),n.jsx(d.Tabs.Item,{active:k==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>m("timeline")},children:"Timeline"})]}),p&&k==="chat"&&T&&n.jsx("div",{className:"agent-workspace__center-back",children:n.jsx(d.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:bt,children:"Back to main chat"})}),p&&k==="timeline"&&n.jsx(gn,{timeline:Ne,isLoading:Me,error:Pe,onOpenChatSession:Ct}),n.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!p&&k!=="chat",children:n.jsx(Zt,{connector:N,phase:D,chatHistory:K,chatSessionKey:q,startQuery:Oe,clarificationMessage:ne,enableUpload:j,onTurn:jt,onAwaitingChange:y,onClarificationPrompt:Et,onDismissClarification:()=>ge(null)})})]}),!H&&n.jsx(en,{checklist:It,isLoading:Ue,error:je,phase:D,canRequestInput:D===U.running&&!S,onAttentionItemClick:At}),!Y&&n.jsx(nn,{resources:se,isLoading:ke,error:ye})]})]})},Pn="Unable to load agent definitions. Please try again.",Dn="Unable to start the agent.",st="Loading agents…",Nt=({open:t,onClose:e,onStart:s,agentDefinitions:a,definitionsState:r="idle",definitionsError:c=null,onRetryDefinitions:i,embedded:g=!1})=>{const l=a[0],[p,_]=o.useState(l),[u,f]=o.useState(""),[j,v]=o.useState(!1),[E,A]=o.useState(null),M=[...a].sort((N,L)=>N.agent_intent.localeCompare(L.agent_intent)).map(N=>({value:N.ref,label:N.agent_intent}));o.useEffect(()=>{t&&(_(l),f(""),v(!1),A(null))},[t,l]);const x=p!==void 0&&u.trim().length>0,k=o.useCallback(N=>{const L=a.find(V=>V.ref===N[0]);L&&_(L)},[a]),m=o.useCallback(async()=>{if(!(!p||!x||j)){v(!0),A(null);try{await s({definition:p,invocationName:u.trim()})}catch(N){A(N instanceof Error?N.message:Dn)}finally{v(!1)}}},[x,p,u,j,s]);if(r==="idle"&&a.length===0||!t)return null;const T=n.jsxs("div",{className:"new-agent__header-title",children:[n.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:n.jsx(d.Icon,{name:"ask-arbor",size:24})}),g?n.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):n.jsx(d.Modal.Title,{children:"Start an agent"})]});let P;return r==="loading"?P=n.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:st}),n.jsx("p",{className:"new-agent__state-message",children:st})]}):r==="error"?P=n.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[n.jsx(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"new-agent__state-message",children:c??Pn}),i?n.jsx(d.Button,{variant:"secondary",size:"S",onClick:i,children:"Try again"}):null]}):p?P=n.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:N=>{N.preventDefault(),x&&!j&&m()},children:[n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:"What would you like your agent to do?"}),n.jsx(d.SelectDropdown,{id:"new-agent-type",placeholder:"Choose an intent",options:M,selectedValues:[p.ref],onSelectionChange:k}),n.jsx("p",{className:"new-agent__type-description",children:p.description})]}),n.jsxs("div",{className:"new-agent__type-field",children:[n.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:"Name"}),n.jsx(d.TextInput,{id:"new-agent-invocation-name",value:u,placeholder:"What would you like to call your agent?",onChange:N=>f(N.target.value)})]}),E?n.jsx("p",{className:"new-agent__error",role:"alert",children:E}):null,n.jsx("div",{className:"new-agent__actions",children:n.jsx(d.Button,{type:"submit",variant:"primary",disabled:!x||j,iconLeftName:j?"loader":"sparkles",iconLeftScreenReaderText:j?"Starting":void 0,children:j?"Starting…":"Start"})})]}):P=null,g?n.jsxs("div",{className:z("new-agent","new-agent--embedded"),children:[n.jsx("div",{className:"new-agent__header",children:T}),n.jsx("div",{className:"new-agent__body",children:P})]}):n.jsxs(d.Modal,{open:t,closeHandler:e,className:"new-agent",children:[n.jsx(d.Modal.Header,{className:"new-agent__header",children:T}),n.jsx(d.Modal.Body,{className:"new-agent__body",children:P})]})},at=t=>{window.location.assign(t)},Un=({open:t,authToken:e,headers:s,agentDefinitionsUrl:a,agentsUrl:r,closeUrl:c,successUrl:i,onClose:g,onStart:l,embedded:p=!1})=>{const _=JSON.stringify(s??{}),u=o.useMemo(()=>new Re({token:e,headers:s,urls:{agentDefinitions:a,agents:r}}),[e,a,r,_]),[f,j]=o.useState([]),[v,E]=o.useState("loading"),[A,M]=o.useState(null),[x,k]=o.useState(0);o.useEffect(()=>{if(!t)return;let N=!1;return E("loading"),M(null),(async()=>{try{const L=await u.listAgentDefinitions();if(N)return;j(L.map(qe)),E("idle")}catch(L){if(N)return;j([]),M(wt(L)),E("error")}})(),()=>{N=!0}},[u,t,x]);const m=o.useCallback(()=>{g==null||g(),c&&at(c)},[c,g]),T=o.useCallback(async N=>{await u.createAgent(N.definition.ref,{invocationName:N.invocationName}),l==null||l(N),i&&at(i)},[u,l,i]),P=o.useCallback(()=>{k(N=>N+1)},[]);return n.jsx(Nt,{open:t,onClose:m,onStart:T,agentDefinitions:f,definitionsState:v,definitionsError:A,onRetryDefinitions:P,embedded:p})},$n=t=>"agentDefinitionsUrl"in t,St=t=>$n(t)?n.jsx(Un,{...t}):n.jsx(Nt,{...t}),Hn=t=>t!==void 0&&t.some(e=>e.status===$.hitl),Bn=(t,e)=>Hn(e)?C.hitl:t.status,Fn=({column:t,label:e})=>t.statusIcon?n.jsx("span",{className:"agent-view__status-indicator",children:n.jsx(d.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,className:z({"agent-view__progress-icon--spinning":t.statusIcon.spin}),screenReaderText:e})}):n.jsx("span",{className:z("agent-view__dot",{[`agent-view__dot--${t.dotModifier}`]:t.dotModifier}),children:n.jsx(d.Dot,{colour:t.dotColour,label:e})}),zn=({agent:t,agentName:e,column:s,isExpanded:a,isLoading:r,checklist:c,error:i,onToggle:g,onViewAgent:l})=>{const{id:p,invocation_name:_}=t,u=`agent-card-${p}-header`,f=`agent-card-${p}-progress`;return n.jsx("li",{className:z("agent-view__card",{"agent-view__card--expanded":a}),children:n.jsxs(d.Card,{spacing:"dense",children:[n.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":f,"aria-label":_,id:u,onClick:()=>g(p),children:n.jsxs("div",{className:"agent-view__card-content",children:[n.jsx(Fn,{column:s}),n.jsx("span",{className:"agent-view__card-invocation-name",children:_}),n.jsx("span",{className:"agent-view__card-agent-name",children:e}),n.jsx(d.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&n.jsxs("div",{id:f,"aria-labelledby":u,className:"agent-view__card-progress",children:[r&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:oe}),n.jsx("span",{children:oe})]}),!r&&i&&n.jsx("p",{className:"agent-view__progress-error",role:"alert",children:i}),!r&&!i&&c!==null&&n.jsx(Yt,{checklist:c}),!r&&!i&&c===null&&n.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:oe}),n.jsx("span",{children:oe})]}),n.jsx("div",{className:"agent-view__card-actions",children:n.jsx(d.Button,{variant:"secondary",size:"S",onClick:()=>l==null?void 0:l(t),children:"View agent"})})]})]})})},rt=({column:t,agents:e,expandedAgentId:s,loadingAgentId:a,checklistByInvocationId:r,errorByAgentId:c,definitionNameByRef:i,onToggleAgent:g,onViewAgent:l,isSplit:p=!1})=>n.jsxs("section",{className:z("agent-view__column",{"agent-view__column--split":p}),"aria-label":t.title,children:[n.jsxs("div",{className:"agent-view__column-header",children:[n.jsx(d.Heading,{level:4,children:t.title}),n.jsx("span",{className:"agent-view__column-count",children:e.length})]}),n.jsx("ul",{className:"agent-view__card-list",children:e.map(_=>n.jsx(zn,{agent:_,agentName:Ge(_,i),column:t,isExpanded:s===_.id,isLoading:a===_.id,checklist:r[_.invocation_id]??null,error:c[_.id]??null,onToggle:g,onViewAgent:l},_.id))})]}),Ge=(t,e)=>e.get(t.agent_definition_ref)??t.agent_definition_ref.replace(/_/g," "),Gn=({jwt:t,headers:e,agentDefinitionsUrl:s,agentsUrl:a,agentUrl:r,agentChecklistUrl:c,agentResourcesUrl:i,agentTimelineUrl:g,agentChatUrl:l,agentConversationUrl:p,enableUpload:_,showHeader:u=!1,institutions:f})=>{var je;const j=o.useMemo(()=>({agentDefinitions:s,agents:a,agent:r,agentChecklist:c,...i?{agentResources:i}:{},...g?{agentTimeline:g}:{},agentChat:l,agentConversation:p}),[s,a,r,c,i,g,l,p]),[v,E]=o.useState(null),A=v?(je=f==null?void 0:f.find(h=>h.applicationId===v.application_id))==null?void 0:je.applicationUrl:void 0,M=o.useMemo(()=>{const h={...e??{}};return A?h[ce.arborApplicationUrl]=A:delete h[ce.arborApplicationUrl],h},[e,A]),{agents:x,agentDefinitions:k,loadState:m,loadError:T,reload:P,refresh:N,fetchAgentChecklist:L,createAgent:V}=xt({jwt:t,headers:M,urls:j}),[I,b]=o.useState(!1),[D,G]=o.useState(null),[K,R]=o.useState(null),[q,Z]=o.useState({}),[Oe,de]=o.useState({}),[ne,ge]=o.useState([]),[se,Le]=o.useState([]),ke=o.useMemo(()=>{const h=new Set(x.map(y=>y.application_id)),S=new Map((f??[]).map(y=>[y.applicationId,y.name]));return[...h].sort((y,H)=>(S.get(y)??y).localeCompare(S.get(H)??H)).map(y=>({value:y,label:S.get(y)??y}))},[x,f]),Q=o.useMemo(()=>new Map(k.map(h=>[h.ref,h.display_name])),[k]),ye=o.useMemo(()=>[...new Set(x.map(S=>Ge(S,Q)))].sort((S,y)=>S.localeCompare(y)).map(S=>({value:S,label:S})),[x,Q]),ue=o.useMemo(()=>x.filter(h=>!(ne.length>0&&!ne.includes(h.application_id)||se.length>0&&!se.includes(Ge(h,Q)))),[x,Q,se,ne]),Ne=ke.length>1,Se=ye.length>1,Me=Ne||Se;o.useEffect(()=>{const h=window.setInterval(()=>{N()},6e4);return()=>{window.clearInterval(h)}},[N]),o.useEffect(()=>{if(x.length===0)return;let h=!1;return(async()=>{const S=await Promise.allSettled(x.map(async y=>{const H=await L(y.invocation_id);return{agentId:y.id,invocationId:y.invocation_id,checklist:H.checklist}}));h||(Z(y=>{const H={...y};let ee=!1;for(const Y of S){if(Y.status!=="fulfilled")continue;const{invocationId:te,checklist:fe}=Y.value;JSON.stringify(y[te])!==JSON.stringify(fe)&&(H[te]=fe,ee=!0)}return ee?H:y}),de(y=>{const H={...y};let ee=!1;return S.forEach((Y,te)=>{Y.status==="rejected"&&H[x[te].id]!==be&&(H[x[te].id]=be,ee=!0)}),ee?H:y}))})(),()=>{h=!0}},[x,L]);const he=o.useCallback(async h=>{if(!q[h.invocation_id]){R(h.id),de(S=>{const y={...S};return delete y[h.id],y});try{const S=await L(h.invocation_id);Z(y=>({...y,[h.invocation_id]:S.checklist}))}catch{de(S=>({...S,[h.id]:be}))}finally{R(S=>S===h.id?null:S)}}},[L,q]),Pe=o.useCallback(h=>{if(D===h){G(null);return}const S=x.find(({id:y})=>y===h);S&&(G(h),he(S))},[x,D,he]),pe=o.useMemo(()=>{const h={};for(const S of ue){const y=Bn(S,q[S.invocation_id]);(h[y]??(h[y]=[])).push(S)}return h},[ue,q]),De=o.useCallback(h=>{E(h)},[]),me=o.useCallback(async h=>{const S=await V(h);E(S),b(!1)},[V]),Ue=o.useCallback(()=>{E(null)},[]),_e={expandedAgentId:D,loadingAgentId:K,checklistByInvocationId:q,errorByAgentId:Oe,definitionNameByRef:Q,onToggleAgent:Pe,onViewAgent:De};return n.jsxs("div",{className:"agent-view-frontend agent-view",children:[u&&n.jsxs("div",{className:"agent-view__header",children:[n.jsx(d.Heading,{level:1,children:"Agents"}),n.jsx(d.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>b(!0),children:"Start an agent"})]}),x.length>0&&Me&&n.jsxs("div",{className:"agent-view__filters",children:[Ne&&n.jsxs("div",{className:"agent-view__filter",children:[n.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-institution-filter",children:"Institution"}),n.jsx(d.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:ke,value:ne,onValueChange:ge,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Se&&n.jsxs("div",{className:"agent-view__filter",children:[n.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-agent-filter",children:"Agent"}),n.jsx(d.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:ye,value:se,onValueChange:Le,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),m==="error"?n.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[n.jsx(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),n.jsx("p",{className:"agent-view__state-message",children:T??ct}),n.jsx(d.Button,{variant:"secondary",size:"S",onClick:P,children:"Try again"})]}):m==="loading"&&x.length===0?n.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[n.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:Qe}),n.jsx("p",{className:"agent-view__state-message",children:Qe})]}):x.length===0?n.jsx(Gt,{}):n.jsxs("div",{className:"agent-view__board",children:[Rt.map(h=>n.jsx(rt,{column:Ee[h],agents:pe[h]??[],..._e},h)),n.jsx("div",{className:"agent-view__split-column",children:Ot.map(h=>n.jsx(rt,{column:Ee[h],agents:pe[h]??[],isSplit:!0,..._e},h))})]}),v&&n.jsx(yt,{agent:v,invocationId:v.invocation_id,open:!0,jwt:t,headers:M,agentUrl:r,agentChecklistUrl:c,agentResourcesUrl:i,agentTimelineUrl:g,agentChatUrl:l,agentConversationUrl:p,enableUpload:_,initialChecklist:q[v.invocation_id]??null,onClose:Ue},v.id),n.jsx(St,{open:I,onClose:()=>b(!1),onStart:me,agentDefinitions:k})]})},qn=(t,e)=>{const s=Date.now(),a=e.trim()||t.agent_intent;return{id:`agent-${s}`,invocation_id:`inv-${s}`,agent_definition_ref:t.ref,agent_intent:t.agent_intent,invocation_name:a,application_id:Lt,created_by:Mt,status:C["generating-a-response"],context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=Gn;exports.AgentServiceClient=Re;exports.AgentServiceError=ie;exports.AgentView=yt;exports.HttpChatConnector=vt;exports.NewAgentModal=St;exports.buildAgentFromDefinition=qn;exports.createHttpChatConnectorFactory=Ve;exports.mapApiAgent=ze;exports.mapApiAgentDefinition=qe;exports.mapApiAgentStatus=ut;exports.mapApiAgentTimelineResponse=mt;exports.mapApiChecklistEndpointResponse=Je;exports.mapApiChecklistItem=We;exports.mapApiChecklistResponse=_t;exports.mapApiChecklistStatus=ht;exports.mapApiConversationMessages=ft;exports.mapApiOpeningMessage=xe;exports.mapApiResource=pt;exports.mapApiResourcesEndpointResponse=Ke;exports.mapApiTripOption=yn;exports.useAgentService=xt;exports.useAgentWorkspace=kt;
|
package/dist/index.d.ts
CHANGED
|
@@ -185,25 +185,22 @@ declare type AgentTimelineChatSession = {
|
|
|
185
185
|
timestamp: string;
|
|
186
186
|
};
|
|
187
187
|
|
|
188
|
-
export declare const AgentView: ({ agent, open, onClose, jwt, headers, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, chatId, enableUpload, initialBrief, initialPhase, initialChecklist, }: AgentViewProps) => JSX_2.Element;
|
|
188
|
+
export declare const AgentView: ({ agent, invocationId, open, onClose, jwt, headers, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, chatId, enableUpload, initialBrief, initialPhase, initialChecklist, }: AgentViewProps) => JSX_2.Element;
|
|
189
189
|
|
|
190
190
|
export declare type AgentViewProps = {
|
|
191
191
|
agent: Agent;
|
|
192
|
+
invocationId: string;
|
|
192
193
|
open: boolean;
|
|
193
194
|
onClose: () => void;
|
|
194
195
|
jwt?: string;
|
|
195
196
|
headers?: Record<string, string>;
|
|
196
197
|
agentUrl: string;
|
|
197
198
|
agentChecklistUrl: string;
|
|
198
|
-
/** Optional — omit when the backend has no /resources route. */
|
|
199
199
|
agentResourcesUrl?: string;
|
|
200
|
-
/** Optional — omit when the backend has no /agent-timeline route. */
|
|
201
200
|
agentTimelineUrl?: string;
|
|
202
201
|
agentChatUrl: string;
|
|
203
202
|
agentConversationUrl: string;
|
|
204
|
-
/** Timeline/conversation session id for chat turns. Defaults to agent.invocation_id. */
|
|
205
203
|
chatId?: string;
|
|
206
|
-
/** When true, enables chat file uploads (posted to agentChatUrl). */
|
|
207
204
|
enableUpload?: boolean;
|
|
208
205
|
initialBrief?: AgentBrief;
|
|
209
206
|
initialPhase?: WorkspacePhase;
|