@arbor-education/agent-view-frontend 0.4.9 → 0.4.11-alpha.2
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 +14 -12
- package/dist/index.cjs +7 -4
- package/dist/index.d.ts +50 -5
- package/dist/index.js +1792 -1614
- package/dist/style.css +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -58,24 +58,26 @@ You can also configure the demo without opening the debug panel:
|
|
|
58
58
|
# Via URL query params (token is stripped from the address bar after load)
|
|
59
59
|
http://localhost:4174/?serviceUrl=http://localhost:3001&token=your-bearer-token
|
|
60
60
|
|
|
61
|
-
# Via environment variables
|
|
62
|
-
|
|
63
|
-
|
|
61
|
+
# Via environment variables (or copy `demo/.env.example` → `demo/.env`)
|
|
62
|
+
AGENT_SERVICE_URL=https://ai-agent-service.qa.arbor.engineering \
|
|
63
|
+
AGENT_SERVICE_TOKEN=your-bearer-token \
|
|
64
64
|
make demo
|
|
65
65
|
```
|
|
66
66
|
|
|
67
67
|
| Variable | Default | Purpose |
|
|
68
68
|
|---|---|---|
|
|
69
69
|
| `MOCK_SERVER_PORT` | `3001` | Port for the mock agent service |
|
|
70
|
-
| `
|
|
71
|
-
| `
|
|
72
|
-
| `
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
70
|
+
| `AGENT_SERVICE_PROXY_TARGET` | `http://localhost:3001` | Where the demo proxies `/api/ai-agent-service` |
|
|
71
|
+
| `AGENT_SERVICE_URL` | `/api/ai-agent-service` | Initial service URL for the demo (overridable in Debug options) |
|
|
72
|
+
| `AGENT_SERVICE_TOKEN` | _(empty)_ | Initial bearer token for the demo |
|
|
73
|
+
| `PUSHER_REPOLL` | auto if key+cluster set | `true`/`false` — enable Pusher REPOLL in AgentView (no Debug UI control) |
|
|
74
|
+
| `PUSHER_KEY` | _(empty)_ | Public Pusher app key (client subscribe) |
|
|
75
|
+
| `PUSHER_CLUSTER` | _(empty)_ | Pusher cluster (e.g. `eu`) |
|
|
76
|
+
| `PUSHER_CHANNEL_PREFIX` | `arbor-agent-` | Channel prefix; full channel is `{prefix}{agent.id}` |
|
|
77
|
+
| `PUSHER_SECRET` | _(empty)_ | **Not** exposed to the browser — use only in local trigger scripts |
|
|
78
|
+
| `PUSHER_APP_ID` | _(empty)_ | Same as above; for server-side `pusher` package scripts |
|
|
79
|
+
|
|
80
|
+
Copy `demo/.env.example` to `demo/.env` and fill Pusher credentials. There are no Pusher fields in the Debug UI — configure via env only. Vite loads env from the demo root; only an allowlisted set of prefixes is exposed to the client (`PUSHER_SECRET` is excluded).
|
|
79
81
|
|
|
80
82
|
---
|
|
81
83
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),o=require("react"),J=require("classnames"),d=require("@arbor-education/design-system.components"),me=require("@arbor-education/ask-arbor-chat-panel"),A={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},B={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},H={briefing:"briefing",running:"running",stopped:"stopped",complete:"complete"},Z={agent:"agent",user:"user",system:"system"},re={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",link:"link"},gt={cancelled:"cancelled",archived:"archived"},Xe={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},V={[B.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[B.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[B.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[B["generating-a-response"]]:{label:"Generating a response",icon:"sparkles",color:"var(--color-brand-600)"}},He={[A["generating-a-response"]]:{status:A["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:V["generating-a-response"].icon,color:V["generating-a-response"].color}},[A.hitl]:{status:A.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:V.hitl.icon,color:V.hitl.color}},[A.complete]:{status:A.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:V.complete.icon,color:V.complete.color}},[A.failed]:{status:A.failed,title:"Failed",dotColour:"salmon",statusIcon:{name:V.failed.icon,color:V.failed.color}}},Zt=[A["generating-a-response"],A.hitl],es=[A.complete,A.failed],ts="m4",ss="1",yt="msg-opening",$e="Unable to load agent tasks. Please try again.",ns="Unable to load the resources for this agent",as="Unable to load this document. Please try again.",St="Unable to load the timeline for this agent",rs="Something went wrong. Please try again.",Nt="Unable to load agents. Please try again.",he="Loading tasks…",ht="Loading agents…",os="Task",is={[H.briefing]:"Briefing",[H.running]:"Working",[H.stopped]:"Stopped",[H.complete]:"Complete"},ls=[A["generating-a-response"],A.hitl,A.complete,A.failed],cs={[A["generating-a-response"]]:"Agents currently working on tasks for you.",[A.hitl]:"Agents that need your input before they can continue.",[A.complete]:"Agents that have finished their work.",[A.failed]:"Agents that failed or were stopped."},ds=()=>s.jsxs("svg",{className:"agent-view__empty-illustration",viewBox:"0 0 360 240",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Preview of the agents board layout",children:[s.jsx("rect",{x:"0",y:"0",width:"360",height:"240",rx:"12",fill:"var(--color-grey-100)"}),s.jsx("rect",{x:"16",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"130",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"244",y:"16",width:"100",height:"100",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"244",y:"124",width:"100",height:"100",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"28",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("rect",{x:"28",y:"96",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("rect",{x:"142",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-semantic-warning-050)"}),s.jsx("circle",{cx:"40",cy:"70",r:"4",fill:"var(--color-brand-600)"}),s.jsx("circle",{cx:"40",cy:"114",r:"4",fill:"var(--color-brand-600)"}),s.jsx("circle",{cx:"154",cy:"70",r:"4",fill:"var(--color-semantic-warning-600)"}),s.jsx("circle",{cx:"256",cy:"52",r:"4",fill:"var(--color-grey-400)"}),s.jsx("circle",{cx:"256",cy:"160",r:"4",fill:"var(--color-semantic-destructive-500)"})]}),us=({status:t})=>{const e=He[t];return e.statusIcon?s.jsx(d.Icon,{name:e.statusIcon.name,size:16,color:e.statusIcon.color,screenReaderText:e.title}):s.jsx(d.Dot,{colour:e.dotColour,label:e.title})},gs=()=>s.jsxs("section",{className:"agent-view__empty","aria-label":"About the agents board",children:[s.jsxs("div",{className:"agent-view__empty-content",children:[s.jsx(d.Heading,{level:4,children:"Your agents board"}),s.jsx("p",{className:"agent-view__empty-lead",children:"When you start an agent, it appears here so you can track progress at a glance. Agents move between columns as their status changes."}),s.jsx("ul",{className:"agent-view__empty-columns",children:ls.map(t=>{const e=He[t];return s.jsxs("li",{className:"agent-view__empty-column",children:[s.jsx("span",{className:"agent-view__empty-column-indicator",children:s.jsx(us,{status:t})}),s.jsxs("span",{className:"agent-view__empty-column-text",children:[s.jsx("span",{className:"agent-view__empty-column-title",children:e.title}),s.jsx("span",{className:"agent-view__empty-column-description",children:cs[t]})]})]},t)})}),s.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",s.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),s.jsx("div",{className:"agent-view__empty-visual",children:s.jsx(ds,{})})]}),hs=(t,e)=>({...t,...e.length>0?{children:e}:{}}),jt=t=>{const e=[],n=[];for(const a of t){const r=a.children?jt(a.children):{needsInput:[],tasks:[]};if(e.push(...r.needsInput),a.status===B.hitl){e.push({...a,children:void 0});continue}n.push(hs(a,r.tasks))}return{needsInput:e,tasks:n}},ps=t=>t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{const a=e.item.status===B.hitl,r=n.item.status===B.hitl;return a!==r?a?-1:1:e.index-n.index}).map(({item:e})=>e),Qe=2,ms=t=>{if(!t)return{canScrollUp:!1,canScrollDown:!1};const e=t.scrollHeight-t.clientHeight;return e<=Qe?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:t.scrollTop>Qe,canScrollDown:t.scrollTop<e-Qe}},_s=(t,e)=>{if(!t||!e)return null;const n=t.getBoundingClientRect(),a=e.getBoundingClientRect();return{top:a.top-n.top,left:a.left-n.left,width:a.width,height:a.height}},ze=({children:t,className:e,contentClassName:n,scrollSelector:a,style:r,"aria-label":l})=>{const i=o.useRef(null),u=o.useRef(null),[c,v]=o.useState(!1),[f,h]=o.useState(!1),[p,O]=o.useState(null),w=()=>{var y;return a?((y=i.current)==null?void 0:y.querySelector(a))??null:u.current},j=()=>{const y=w(),k=ms(y);if(v(_=>_===k.canScrollUp?_:k.canScrollUp),h(_=>_===k.canScrollDown?_:k.canScrollDown),a){const _=_s(i.current,y);O(C=>(C==null?void 0:C.top)===(_==null?void 0:_.top)&&(C==null?void 0:C.left)===(_==null?void 0:_.left)&&(C==null?void 0:C.width)===(_==null?void 0:_.width)&&(C==null?void 0:C.height)===(_==null?void 0:_.height)?C:_)}else O(_=>_===null?_:null)};o.useLayoutEffect(()=>{j()}),o.useEffect(()=>{const y=i.current;if(!y)return;let k=null,_=null;const C=()=>{k==null||k.removeEventListener("scroll",j),_==null||_.disconnect(),_=null,k=null},R=M=>{if(M===k){j();return}if(C(),k=M,!k){j();return}k.addEventListener("scroll",j,{passive:!0}),_=new ResizeObserver(()=>j()),_.observe(k),k.firstElementChild instanceof HTMLElement&&_.observe(k.firstElementChild),j()};R(w());const T=new MutationObserver(()=>{R(w())});return T.observe(y,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",j),()=>{window.removeEventListener("resize",j),T.disconnect(),C()}},[a]);const N=y=>{const k=w();if(!k)return;const _=Math.max(k.clientHeight*.75,120);k.scrollBy({top:y==="up"?-_:_,behavior:"smooth"})},P=s.jsxs(s.Fragment,{children:[c&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--top","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--top","aria-label":"Scroll up",onClick:()=>N("up"),children:s.jsx(d.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),f&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>N("down"),children:s.jsx(d.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return s.jsx("div",{ref:i,className:J("scrollable-region",e),style:r,"aria-label":l,children:a?s.jsxs(s.Fragment,{children:[t,p&&(c||f)&&s.jsx("div",{className:"scrollable-region__overlay",style:{top:p.top,left:p.left,width:p.width,height:p.height},children:P})]}):s.jsxs(s.Fragment,{children:[P,s.jsx("div",{ref:u,className:J("scrollable-region__viewport",n),children:t})]})})},fs=48,vs=({checklist:t})=>{const e=o.useRef(null),n=o.useRef(!1);return o.useLayoutEffect(()=>{const a=e.current;if(!a)return;const r=a.scrollHeight-a.scrollTop-a.clientHeight;(!n.current||r<=fs)&&(a.scrollTop=a.scrollHeight,n.current=!0)},[t]),t.length===0?s.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):s.jsx(ze,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:s.jsx("ul",{ref:e,className:"agent-view__progress-list","aria-label":"Agent tasks",children:ps(t).map(a=>{const r=V[a.status];return s.jsxs("li",{className:J("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[s.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`}),s.jsxs("div",{className:"agent-view__progress-item-content",children:[s.jsx("span",{className:"agent-view__progress-label",children:a.task}),a.status!==B.complete&&s.jsx("span",{className:"agent-view__progress-description",children:a.description})]})]},a.task)})})})},ws=({prompts:t,classNamePrefix:e="agent-workspace",onSelect:n})=>t.length===0?null:s.jsx("div",{className:`${e}__chips`,children:t.map(a=>s.jsx("button",{type:"button",className:`${e}__chip`,onClick:()=>n(a),children:a},a))});class xs{constructor(e,n){this.connector=e,this.canSend=n.canSend,this.onTurn=n.onTurn,this.onAwaitingChange=n.onAwaitingChange}get canRate(){return!1}get canLoadHistory(){return!1}get canListInteractions(){return!1}get canSendNotification(){return!1}get ratingPopupUrls(){return{}}async sendMessage(e){var n,a;if(!this.canSend())return null;(n=this.onAwaitingChange)==null||n.call(this,!0);try{const r=await this.connector.sendMessage(e.userMessage,e.uploadFiles);return this.onTurn(r),{id:r.message.id,text:r.message.text,type:me.CHAT_RESPONSE_TYPE_AGENT,...r.message.followUpPrompts?{followUpPrompts:r.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:rs,type:me.CHAT_RESPONSE_TYPE_ERROR}}finally{(a=this.onAwaitingChange)==null||a.call(this,!1)}}async loadHistory(e){return null}async listInteractions(){return null}async rateMessage(e){}async sendNotification(e){return!1}}const ks=({connector:t,phase:e,chatHistory:n,chatSessionKey:a,startQuery:r,clarificationMessage:l,enableUpload:i=!1,onTurn:u,onAwaitingChange:c,onClarificationPrompt:v,onDismissClarification:f})=>{const h=o.useMemo(()=>new xs(t,{canSend:()=>e===H.running,onTurn:u,onAwaitingChange:c}),[t,e,u,c]),p=e!==H.running,O=e===H.running;return s.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[l&&s.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[s.jsx("p",{className:"agent-workspace__clarification-text",children:l.text}),l.followUpPrompts&&s.jsx(ws,{prompts:l.followUpPrompts,onSelect:v}),s.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:f,children:"Dismiss"})]}),s.jsx("div",{className:"agent-workspace__ask-arbor",children:s.jsx(ze,{scrollSelector:".chat-panel-message-list",children:s.jsx(me.ChatPanel,{connector:h,chatHistory:n,startQuery:r,lockConversation:p,enableUpload:i,speechEnabled:O,speechLanguage:"en-GB",speechSubmissionDelay:1e3,slashMenuItems:[],menuContent:[],introHeading:"Message your agent",introBody:"Ask questions, share trip details, or paste a link. The agent will update the checklist as it works.",placeholder:O?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)})}),e===H.stopped&&s.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[s.jsx(d.Icon,{name:"circle-alert",size:16,color:"var(--color-semantic-warning-600)"}),s.jsx("span",{children:"You stopped the agent. Its progress is saved in the checklist on the left."})]}),e===H.complete&&s.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[s.jsx(d.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),s.jsx("span",{children:"The agent has finished."})]})]})},bt=({item:t,depth:e,canRequestInput:n,onAttentionItemClick:a})=>{const r=V[t.status],l=t.status.replace(/_/g,"-"),i=t.status===B.hitl&&n&&a,u=s.jsxs("div",{className:"agent-workspace__task-row",children:[s.jsx(d.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`}),s.jsxs("div",{className:"agent-workspace__task-content",children:[s.jsx("span",{className:"agent-workspace__task-label",children:t.task}),t.status!==B.complete&&t.description&&s.jsx("span",{className:"agent-workspace__task-description",children:t.description})]})]});return s.jsxs("li",{className:J("agent-workspace__task",`agent-workspace__task--${l}`,{"agent-workspace__task--child":e>0}),children:[i?s.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${t.task}`,onClick:()=>a(t),children:u}):u,t.children&&t.children.length>0&&s.jsx("ul",{className:"agent-workspace__task-children",children:t.children.map(c=>s.jsx(bt,{item:c,depth:e+1,canRequestInput:n,onAttentionItemClick:a},c.task))})]})},pt=({items:t,ariaLabel:e,canRequestInput:n,onAttentionItemClick:a})=>s.jsx("ul",{className:"agent-workspace__task-list","aria-label":e,children:t.map(r=>s.jsx(bt,{item:r,depth:0,canRequestInput:n,onAttentionItemClick:a},r.task))}),ys=({checklist:t,isLoading:e,error:n,phase:a,canRequestInput:r,onAttentionItemClick:l})=>{const i=o.useMemo(()=>t?jt(t):null,[t]);return s.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--checklist","aria-label":"Checklist",children:[s.jsx("div",{className:"agent-workspace__panel-header",children:s.jsx(d.Heading,{level:4,children:"Checklist"})}),s.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:s.jsxs(ze,{children:[e&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:he}),s.jsx("span",{children:he})]}),!e&&n&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:n}),!e&&!n&&i&&s.jsxs(s.Fragment,{children:[i.needsInput.length>0&&s.jsxs("div",{className:"agent-workspace__task-group",children:[s.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),s.jsx(pt,{items:i.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:r,onAttentionItemClick:l})]}),i.tasks.length>0&&s.jsxs("div",{className:J("agent-workspace__task-group",{"agent-workspace__task-group--following":i.needsInput.length>0}),children:[i.needsInput.length>0&&s.jsx("p",{className:"agent-workspace__task-group-label",children:"Other tasks"}),s.jsx(pt,{items:i.tasks,ariaLabel:"Agent tasks",canRequestInput:r,onAttentionItemClick:l})]})]}),!e&&!n&&(!i||i.needsInput.length===0&&i.tasks.length===0)&&s.jsx("p",{className:"agent-workspace__empty",children:a===H.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})]})},Ss=({resource:t,html:e,isLoading:n,error:a,onClose:r})=>{o.useEffect(()=>{if(!t)return;const i=d.SlideoverUtils.removeSlideover;return d.SlideoverUtils.removeSlideover=()=>{i(),r()},()=>{d.SlideoverUtils.removeSlideover=i}},[t,r]),o.useEffect(()=>{if(!t)return;const i=u=>{u.key==="Escape"&&d.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[t]);const l=o.useMemo(()=>t?[{centerHeaderText:!1,children:s.jsxs("div",{className:"resource-preview-slideover__body",children:[n&&s.jsxs("div",{className:"resource-preview-slideover__status",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading document"}),s.jsx("span",{children:"Loading document…"})]}),!n&&a&&s.jsx("p",{className:"resource-preview-slideover__error",role:"alert",children:a}),!n&&!a&&e!==null&&s.jsx("iframe",{className:"resource-preview-slideover__frame",title:t.title,sandbox:"",srcDoc:e})]})}]:[],[t,e,n,a]);return s.jsx("div",{className:"resource-preview-slideover",children:s.jsx(d.SlideoverManager,{slideovers:l})})},Ns={[re.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[re.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[re.file]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[re.workflow]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[re.link]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},js=({resources:t,isLoading:e=!1,error:n=null,onOpenResource:a})=>s.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--documents","aria-label":"Resources",children:[s.jsxs("div",{className:"agent-workspace__panel-header",children:[s.jsx(d.Heading,{level:4,children:"Resources"}),s.jsx("span",{className:"agent-workspace__panel-count",children:t.length})]}),s.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:s.jsxs(ze,{children:[e&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading resources"}),s.jsx("span",{children:"Loading resources…"})]}),!e&&n&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:n}),!e&&!n&&t.length>0&&s.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:t.map(r=>{const l=Ns[r.type],i=r.misRecordUrl;return s.jsx("li",{className:"agent-workspace__resource",children:i?s.jsx("a",{className:"agent-workspace__resource-card",href:i,target:"_blank",rel:"noreferrer",onClick:u=>{u.preventDefault(),a(r)},children:s.jsx(mt,{resource:r,config:l,external:!0})}):s.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>a(r),children:s.jsx(mt,{resource:r,config:l})})},r.id)})}),!e&&!n&&t.length===0&&s.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),mt=({resource:t,config:e,external:n=!1})=>s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${t.type}`,children:s.jsx(d.Icon,{name:e.icon,size:16,color:e.color,screenReaderText:`${e.label}:`})}),s.jsx("span",{className:"agent-workspace__resource-content",children:s.jsxs("span",{className:"agent-workspace__resource-top",children:[s.jsx("span",{className:"agent-workspace__resource-name",children:t.title}),s.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${t.type}`,children:e.label})]})}),n&&s.jsx(d.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]}),Be=t=>{const e=Date.parse(t);return Number.isFinite(e)?e:0},bs=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),Ze=t=>{const e=new Date(t);return Number.isFinite(e.getTime())?bs.format(e):t},Ue=t=>t.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,e=>e.split(/[_-]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" ")),Ne=(t,e)=>e<=1?0:t/(e-1)*100,At=t=>Math.max(t,0)+2,As=t=>t+1,Cs=(t,e)=>{if(e.length===0)return 50;const n=At(e.length),a=Ne(1,n),r=Ne(e.length,n),l=e.map(f=>Be(f.timestamp)),i=Math.min(...l),u=Math.max(...l);if(u<=i)return a;const c=(Be(t.timestamp)-i)/(u-i),v=Math.min(1,Math.max(0,c));return a+v*(r-a)},Es=8,Ts=20,Rs=(t,e=Es,n=Ts)=>{const a=new Map;if(t.length===0)return a;const r=[...t].sort((i,u)=>i.leftPercent-u.leftPercent||i.timestampMs-u.timestampMs||i.id.localeCompare(u.id)),l=[];for(const i of r){const u=l[l.length-1];u&&i.leftPercent-u[u.length-1].leftPercent<e?u.push(i):l.push([i])}for(const i of l){const u=[...i].sort((v,f)=>v.timestampMs-f.timestampMs||v.id.localeCompare(f.id)),c=(u.length-1)/2;u.forEach((v,f)=>{a.set(v.id,(f-c)*n)})}return a},De=(t,e=0)=>({left:`calc(${t/100} * (100% - var(--agent-timeline-node-size)) + (var(--agent-timeline-node-size) / 2) + ${e}px)`,transform:"translateX(-50%)"}),Is=t=>t.type!=="message-sent",Os=({timeline:t,isLoading:e,error:n,onOpenChatSession:a})=>{const r=((t==null?void 0:t.actionLog)??[]).filter(Is),l=(t==null?void 0:t.chatSessions)??[],i=!e&&!n&&r.length===0&&l.length===0,u=At(r.length),c=r.map((h,p)=>({id:`action-${h.timestamp}-${p}`,leftPercent:Ne(As(p),u),timestampMs:Be(h.timestamp)})),v=l.map(h=>({id:h.sessionId,leftPercent:Cs(h,r),timestampMs:Be(h.timestamp)})),f=Rs([...c,...v]);return s.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[e&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),n&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:n||St}),i&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!e&&!n&&!i&&s.jsxs("div",{className:"agent-timeline",children:[s.jsx("div",{className:"agent-timeline__track","aria-hidden":"true"}),s.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:De(Ne(0,u)),children:[s.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:s.jsx(d.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})}),s.jsx("span",{className:"agent-timeline__terminus-label",children:"Start"})]}),r.map((h,p)=>{const O=`action-${h.timestamp}-${p}`,w=c[p].leftPercent,j=h.type==="checklist-updated",N=h.type==="status-transition",P=j?"checklist":N?"status":"note";return s.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${P}`,style:De(w,f.get(O)??0),children:[s.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${P}`,"aria-label":`${Ue(h.type)}: ${Ue(h.entry)}`,children:[j&&s.jsx(d.Icon,{name:"check-solid",size:16,color:"currentColor"}),N&&s.jsx(d.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]}),s.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[s.jsx("strong",{className:"agent-timeline__pill-type",children:Ue(h.type)}),s.jsx("span",{className:"agent-timeline__pill-entry",children:Ue(h.entry)}),s.jsx("span",{className:"agent-timeline__pill-entry",children:Ze(h.timestamp)})]})]},O)}),s.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",style:De(Ne(u-1,u)),children:[s.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:s.jsx(d.Icon,{name:"flag",size:16,color:"currentColor"})}),s.jsx("span",{className:"agent-timeline__terminus-label",children:"Finish"})]}),l.map((h,p)=>{const O=v[p].leftPercent;return s.jsxs("div",{className:"agent-timeline__chat-station",style:De(O,f.get(h.sessionId)??0),children:[s.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${Ze(h.timestamp)}`,onClick:()=>a(h.sessionId),children:s.jsx(d.Icon,{name:"sparkles",size:16,color:"currentColor"})}),s.jsxs("div",{className:"agent-timeline__pill",role:"tooltip",children:[s.jsx("strong",{className:"agent-timeline__pill-type",children:"Chat session"}),s.jsx("span",{className:"agent-timeline__pill-entry",children:Ze(h.timestamp)})]})]},h.sessionId)})]})]})},Ps=["I'll get the details and come back to you","Skip this for now"],Ls=t=>{var n;const e=(n=t.prompt)!=null&&n.trim()?t.prompt.trim():`I need a bit more from you on "${t.task}". ${t.description} What can you tell me?`;return{id:`clarification-${Date.now()}`,author:Z.agent,text:e,followUpPrompts:t.clarificationPrompts??Ps}},ge=t=>({id:t.id,text:t.text,type:t.author===Z.user?me.CHAT_RESPONSE_TYPE_USER:t.author===Z.system?me.CHAT_RESPONSE_TYPE_INFO:me.CHAT_RESPONSE_TYPE_AGENT,...t.followUpPrompts?{followUpPrompts:t.followUpPrompts}:{}});class pe extends Error{constructor(e,n,a){super(a??`Agent service request failed (${e})`),this.name="AgentServiceError",this.status=e,this.detail=n}}const Ms="/api/v1",$={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},F={GET:"GET",POST:"POST"},Us={error:"error"},Ds={user:"user"},oe={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},$s=100,Ct=t=>{switch(t){case gt.cancelled:return A.failed;case gt.archived:return A.complete;case A.hitl:case A.complete:case A.failed:case A["generating-a-response"]:return t;default:return A["generating-a-response"]}},Et=t=>{switch(t){case Xe.requires_attention:return B.hitl;case Xe.in_progress:case Xe.available:return B["generating-a-response"];case B.failed:case B.complete:case B.hitl:case B["generating-a-response"]:return t;default:return B["generating-a-response"]}},nt=t=>({ref:t.name,display_name:t.display_name,agent_intent:t.agent_intent??"",description:t.description}),Hs=t=>({id:t.id,name:t.name,...t.has_run_before?{hasRunBefore:t.has_run_before}:{}}),Bs=new Set(Object.values(re)),zs=t=>Bs.has(t)?t:re.document_html,Tt=t=>({id:t.id,type:zs(t.type),title:t.title,createdDatetime:t.created_datetime,lastUpdatedDatetime:t.last_updated_datetime,misRecordUrl:t.mis_record_url}),Rt=t=>({resources:t.resources.map(Tt),pageNumber:t.page_number,pageSize:t.page_size,totalRecords:t.total_records}),It=t=>({actionLog:(t.action_log??[]).map(e=>({timestamp:e.timestamp,type:e.type,entry:e.entry,origin:e.origin})),chatSessions:(t.chat_sessions??[]).map(e=>({sessionId:e.session_id,timestamp:e.timestamp}))}),tt=t=>{var n;const e=t.invocation_id??t.id;return{id:t.id,invocation_id:e,agent_definition_ref:t.agent_definition_ref,...t.agent_intent?{agent_intent:t.agent_intent}:{},invocation_name:((n=t.invocation_name)==null?void 0:n.trim())||t.agent_definition_ref,application_id:t.application_id,...t.application_name?{application_name:t.application_name}:{},created_by:t.created_by,status:Ct(t.status),context_ref:t.context_ref??null,checklist_ref:t.checklist_ref??null}},at=t=>{var e;return{task:t.task??t.name??t.label??os,status:Et(t.status),description:t.description??"",...t.prompt?{prompt:t.prompt}:{},...(e=t.follow_up_prompts)!=null&&e.length?{clarificationPrompts:t.follow_up_prompts}:{}}},Fs=t=>Array.isArray(t)?t:t.checklist_items??t.checklist??t.items??[],rt=(t,e,n)=>{var l;const a=!Array.isArray(e)&&(e.opening_message||(l=e.opening_follow_up_prompts)!=null&&l.length)?e:n,r=a?je(a):void 0;return{invocation_id:t,checklist:Fs(e).map(at),...r?{openingMessage:r}:{}}},Ot=(t,e)=>{const n=je(e);return{invocation_id:e.invocation_id??t,checklist:(e.checklist_items??[]).map(at),...n?{openingMessage:n}:{}}},je=t=>{var n,a;const e=(n=t.opening_message)==null?void 0:n.trim();if(e)return{id:yt,author:Z.agent,text:e,...(a=t.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:t.opening_follow_up_prompts}:{}}},Pt=t=>t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.length>0&&e.message_type!=="tool_request").map(e=>({id:e.message_id,author:e.role==="user"?Z.user:Z.agent,text:e.content})),qs=/:invocationId\b/g,Gs=/:resourceId\b/g,Js=t=>t.trim().replace(/^Bearer\s+/i,""),Ks=t=>t.endsWith("/")?t.slice(0,-1):t;class Fe{constructor(e){var a;this.baseUrl=Ks(e.baseUrl??"");const n=(a=e.token)==null?void 0:a.trim();this.token=n?Js(n):void 0,this.customHeaders=e.headers,this.urls=e.urls??{},this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis)}setHeaders(e){this.customHeaders=e}async listAgentDefinitions(){return(await this.request(F.GET,this.resolveUrl("agentDefinitions",$.agentDefinitions))).agent_definitions??[]}getAgentDefinition(e){return this.request(F.GET,this.apiUrl(`${$.agentDefinitions}/${encodeURIComponent(e)}`))}listTripOptions(){return this.request(F.GET,this.apiUrl($.tripOptions))}getDataset(){return this.request(F.GET,this.apiUrl($.demoDataset))}setDataset(e){return this.request(F.POST,this.apiUrl($.demoDataset),{dataset:e})}listAgents(e={}){const n=new URLSearchParams;e.status&&n.set("status",e.status),e.agentDefinitionRef&&n.set("agent_definition_ref",e.agentDefinitionRef);const a=n.toString()?`?${n.toString()}`:"";return this.request(F.GET,`${this.resolveUrl("agents",$.agents)}${a}`)}createAgent(e,n={}){var i,u;const a={agent_definition_ref:e},r=(i=n.invocationName)==null?void 0:i.trim(),l=(u=n.agentIntent)==null?void 0:u.trim();return r&&(a.invocation_name=r),l&&(a.agent_intent=l),this.request(F.POST,this.resolveUrl("agents",$.agents),a)}getAgent(e){return this.request(F.GET,this.resolveUrl("agent",`${$.agents}/${encodeURIComponent(e)}`,e))}getAgentChecklist(e){return this.request(F.GET,this.resolveUrl("agentChecklist",`${$.agents}/${encodeURIComponent(e)}/checklist`,e))}getAgentResources(e,n={}){const a=new URLSearchParams;n.pageNumber!==void 0&&a.set("page_number",String(n.pageNumber)),n.pageSize!==void 0&&a.set("page_size",String(n.pageSize)),n.type&&a.set("type",n.type);const r=a.toString(),l=this.resolveUrl("agentResources",`${$.agents}/${encodeURIComponent(e)}/resources`,e);return this.request(F.GET,r?`${l}?${r}`:l)}async listAllAgentResources(e){const n=$s;let a=1;const r=[];let l=Number.POSITIVE_INFINITY;for(;r.length<l;){const i=Rt(await this.getAgentResources(e,{pageNumber:a,pageSize:n}));if(l=i.totalRecords,i.resources.length===0||(r.push(...i.resources),r.length>=l))break;a+=1}return r}getAgentResourceHtml(e,n){return this.requestText(F.GET,this.resolveResourceHtmlUrl(e,n))}getAgentTimeline(e){return this.request(F.GET,this.resolveUrl("agentTimeline",`${$.agents}/${encodeURIComponent(e)}/agent-timeline`,e))}getAgentContext(e){return this.request(F.GET,this.apiUrl(`${$.agents}/${encodeURIComponent(e)}/context`))}cancelAgent(e){return this.request(F.POST,this.apiUrl(`${$.agents}/${encodeURIComponent(e)}/cancel`))}archiveAgent(e){return this.request(F.POST,this.apiUrl(`${$.agents}/${encodeURIComponent(e)}/archive`))}getConversation(e){return this.request(F.GET,this.resolveUrl("agentConversation",`${$.conversations}/${encodeURIComponent(e)}`,e))}async chat(e,n,a={}){const r=!!(a.uploadFiles&&a.uploadFiles.length>0),l=await this.fetchImpl(this.resolveUrl("agentChat",`${$.agents}/${encodeURIComponent(e)}/chat`,e),{method:F.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:oe.acceptEventStream,...r?{}:{"Content-Type":oe.contentTypeJson}},body:r?Vs(n,a.uploadFiles??[]):JSON.stringify(n),signal:a.signal});if(!l.ok)throw await this.toError(l);if(!l.body)throw new pe(l.status,null,"Chat response contained no stream body");return this.consumeSse(l.body,a.onEvent)}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}apiUrl(e){return`${this.baseUrl}${Ms}${e}`}resolveUrl(e,n,a,r){const l=this.urls[e];if(!l)return this.apiUrl(n);let i=l;return a&&(i=i.replace(qs,encodeURIComponent(a))),r&&(i=i.replace(Gs,encodeURIComponent(r))),i}resolveResourceHtmlUrl(e,n){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${$.agents}/${encodeURIComponent(e)}/resources/${encodeURIComponent(n)}`,e,n):this.urls.agentResources?`${this.resolveUrl("agentResources",`${$.agents}/${encodeURIComponent(e)}/resources`,e).replace(/\/$/,"")}/${encodeURIComponent(n)}`:this.apiUrl(`${$.agents}/${encodeURIComponent(e)}/resources/${encodeURIComponent(n)}`)}async request(e,n,a){const r=await this.fetchImpl(n,{method:e,headers:{...this.customHeaders,...this.authHeaders(),Accept:oe.acceptJson,...a===void 0?{}:{"Content-Type":oe.contentTypeJson}},...a===void 0?{}:{body:JSON.stringify(a)}});if(!r.ok)throw await this.toError(r);if(r.status!==204)return await r.json()}async requestText(e,n){const a=await this.fetchImpl(n,{method:e,headers:{...this.customHeaders,...this.authHeaders(),Accept:oe.acceptHtml}});if(!a.ok)throw await this.toError(a);return a.text()}async toError(e){let n=null;try{n=await e.json()}catch{}return new pe(e.status,n,`Agent service request failed (${e.status} ${e.statusText})`)}async consumeSse(e,n){const a=e.getReader(),r=new TextDecoder;let l="",i;const u=c=>{const{event:v,data:f}=Ws(c);if(f===null)return;if(v===Us.error){const p=_t(f);throw new pe(502,p,(p==null?void 0:p.message)??"Chat stream error")}const h=_t(f);h&&(i=h,n==null||n(h))};for(;;){const{done:c,value:v}=await a.read();if(c)break;l+=r.decode(v,{stream:!0});const f=l.split(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),i=require("react"),z=require("classnames"),u=require("@arbor-education/design-system.components"),ve=require("@arbor-education/ask-arbor-chat-panel"),A={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},U={"generating-a-response":"generating-a-response",hitl:"hitl",complete:"complete",failed:"failed"},H={briefing:"briefing",running:"running",stopped:"stopped",complete:"complete"},X={agent:"agent",user:"user",system:"system"},ie={document_html:"document_html",mis_record:"mis_record",workflow:"workflow",file:"file",user_file:"user_file",link:"link"},_s={user_file:"user_file"},xt={cancelled:"cancelled",archived:"archived"},tt={in_progress:"in_progress",requires_attention:"requires_attention",available:"available"},Y={[U.complete]:{label:"Complete",icon:"circle-check",color:"var(--color-semantic-success-600)"},[U.failed]:{label:"Failed",icon:"circle-x",color:"var(--color-semantic-destructive-600)"},[U.hitl]:{label:"Requires attention",icon:"triangle-alert",color:"var(--color-semantic-warning-600)"},[U["generating-a-response"]]:{label:"Generating a response",icon:"sparkles",color:"var(--color-brand-600)"}},qe={[A["generating-a-response"]]:{status:A["generating-a-response"],title:"Active",dotColour:"green",statusIcon:{name:Y["generating-a-response"].icon,color:Y["generating-a-response"].color}},[A.hitl]:{status:A.hitl,title:"Requires attention",dotColour:"orange",statusIcon:{name:Y.hitl.icon,color:Y.hitl.color}},[A.complete]:{status:A.complete,title:"Complete",dotColour:"green",dotModifier:"grey-dark",statusIcon:{name:Y.complete.icon,color:Y.complete.color}},[A.failed]:{status:A.failed,title:"Failed",dotColour:"salmon",statusIcon:{name:Y.failed.icon,color:Y.failed.color}}},fs=[A["generating-a-response"],A.hitl],vs=[A.complete,A.failed],ws="m4",xs="1",Lt="msg-opening",ze="Unable to load agent tasks. Please try again.",ks="Unable to load the resources for this agent",ys="Unable to load this document. Please try again.",Ot="Unable to load the timeline for this agent",Ss="Something went wrong. Please try again.",Mt="Unable to load agents. Please try again.",_e="Loading tasks…",kt="Loading agents…",bs="Task",Ns={[H.briefing]:"Briefing",[H.running]:"Working",[H.stopped]:"Stopped",[H.complete]:"Complete"},As=[A["generating-a-response"],A.hitl,A.complete,A.failed],js={[A["generating-a-response"]]:"Agents currently working on tasks for you.",[A.hitl]:"Agents that need your input before they can continue.",[A.complete]:"Agents that have finished their work.",[A.failed]:"Agents that failed or were stopped."},Cs=()=>s.jsxs("svg",{className:"agent-view__empty-illustration",viewBox:"0 0 360 240",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Preview of the agents board layout",children:[s.jsx("rect",{x:"0",y:"0",width:"360",height:"240",rx:"12",fill:"var(--color-grey-100)"}),s.jsx("rect",{x:"16",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"130",y:"16",width:"100",height:"208",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"244",y:"16",width:"100",height:"100",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"244",y:"124",width:"100",height:"100",rx:"8",fill:"var(--card-default-color-background)",stroke:"var(--card-default-color-border)"}),s.jsx("rect",{x:"28",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("rect",{x:"28",y:"96",width:"76",height:"36",rx:"6",fill:"var(--color-grey-050)"}),s.jsx("rect",{x:"142",y:"52",width:"76",height:"36",rx:"6",fill:"var(--color-semantic-warning-050)"}),s.jsx("circle",{cx:"40",cy:"70",r:"4",fill:"var(--color-brand-600)"}),s.jsx("circle",{cx:"40",cy:"114",r:"4",fill:"var(--color-brand-600)"}),s.jsx("circle",{cx:"154",cy:"70",r:"4",fill:"var(--color-semantic-warning-600)"}),s.jsx("circle",{cx:"256",cy:"52",r:"4",fill:"var(--color-grey-400)"}),s.jsx("circle",{cx:"256",cy:"160",r:"4",fill:"var(--color-semantic-destructive-500)"})]}),Es=({status:e})=>{const t=qe[e];return t.statusIcon?s.jsx(u.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,screenReaderText:t.title}):s.jsx(u.Dot,{colour:t.dotColour,label:t.title})},Rs=()=>s.jsxs("section",{className:"agent-view__empty","aria-label":"About the agents board",children:[s.jsxs("div",{className:"agent-view__empty-content",children:[s.jsx(u.Heading,{level:4,children:"Your agents board"}),s.jsx("p",{className:"agent-view__empty-lead",children:"When you start an agent, it appears here so you can track progress at a glance. Agents move between columns as their status changes."}),s.jsx("ul",{className:"agent-view__empty-columns",children:As.map(e=>{const t=qe[e];return s.jsxs("li",{className:"agent-view__empty-column",children:[s.jsx("span",{className:"agent-view__empty-column-indicator",children:s.jsx(Es,{status:e})}),s.jsxs("span",{className:"agent-view__empty-column-text",children:[s.jsx("span",{className:"agent-view__empty-column-title",children:t.title}),s.jsx("span",{className:"agent-view__empty-column-description",children:js[e]})]})]},e)})}),s.jsxs("p",{className:"agent-view__empty-hint",children:["Use ",s.jsx("strong",{children:"Start an agent"})," above to begin."]})]}),s.jsx("div",{className:"agent-view__empty-visual",children:s.jsx(Cs,{})})]}),Ts=()=>({needsInput:[],complete:[],failed:[],tasks:[]}),Is=(e,t)=>({...e,...t.length>0?{children:t}:{}}),Ut=e=>{const t=[],n=[],a=[],r=[];for(const l of e){const o=l.children?Ut(l.children):Ts();if(t.push(...o.needsInput),n.push(...o.complete),a.push(...o.failed),l.status===U.hitl){t.push({...l,children:void 0});continue}if(l.status===U.complete){n.push({...l,children:void 0});continue}if(l.status===U.failed){a.push({...l,children:void 0});continue}r.push(Is(l,o.tasks))}return{needsInput:t,complete:n,failed:a,tasks:r}},yt=e=>e===U.hitl?0:e===U.complete?1:e===U.failed?2:3,Ls=e=>e.map((t,n)=>({item:t,index:n})).sort((t,n)=>{const a=yt(t.item.status)-yt(n.item.status);return a!==0?a:t.index-n.index}).map(({item:t})=>t),st=2,Os=e=>{if(!e)return{canScrollUp:!1,canScrollDown:!1};const t=e.scrollHeight-e.clientHeight;return t<=st?{canScrollUp:!1,canScrollDown:!1}:{canScrollUp:e.scrollTop>st,canScrollDown:e.scrollTop<t-st}},Ms=(e,t)=>{if(!e||!t)return null;const n=e.getBoundingClientRect(),a=t.getBoundingClientRect();return{top:a.top-n.top,left:a.left-n.left,width:a.width,height:a.height}},Je=({children:e,className:t,contentClassName:n,scrollSelector:a,style:r,"aria-label":l})=>{const o=i.useRef(null),p=i.useRef(null),[c,g]=i.useState(!1),[_,y]=i.useState(!1),[x,E]=i.useState(null),T=()=>{var R;return a?((R=o.current)==null?void 0:R.querySelector(a))??null:p.current},f=()=>{const R=T(),S=Os(R);if(g(m=>m===S.canScrollUp?m:S.canScrollUp),y(m=>m===S.canScrollDown?m:S.canScrollDown),a){const m=Ms(o.current,R);E(b=>(b==null?void 0:b.top)===(m==null?void 0:m.top)&&(b==null?void 0:b.left)===(m==null?void 0:m.left)&&(b==null?void 0:b.width)===(m==null?void 0:m.width)&&(b==null?void 0:b.height)===(m==null?void 0:m.height)?b:m)}else E(m=>m===null?m:null)};i.useLayoutEffect(()=>{f()}),i.useEffect(()=>{const R=o.current;if(!R)return;let S=null,m=null;const b=()=>{S==null||S.removeEventListener("scroll",f),m==null||m.disconnect(),m=null,S=null},v=P=>{if(P===S){f();return}if(b(),S=P,!S){f();return}S.addEventListener("scroll",f,{passive:!0}),m=new ResizeObserver(()=>f()),m.observe(S),S.firstElementChild instanceof HTMLElement&&m.observe(S.firstElementChild),f()};v(T());const C=new MutationObserver(()=>{v(T())});return C.observe(R,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",f),()=>{window.removeEventListener("resize",f),C.disconnect(),b()}},[a]);const G=R=>{const S=T();if(!S)return;const m=Math.max(S.clientHeight*.75,120);S.scrollBy({top:R==="up"?-m:m,behavior:"smooth"})},j=s.jsxs(s.Fragment,{children:[c&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--top","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--top","aria-label":"Scroll up",onClick:()=>G("up"),children:s.jsx(u.Icon,{name:"chevron-up",size:16,color:"currentColor"})})]}),_&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scrollable-region__fade scrollable-region__fade--bottom","aria-hidden":"true"}),s.jsx("button",{type:"button",className:"scrollable-region__edge scrollable-region__edge--bottom","aria-label":"Scroll down",onClick:()=>G("down"),children:s.jsx(u.Icon,{name:"chevron-down",size:16,color:"currentColor"})})]})]});return s.jsx("div",{ref:o,className:z("scrollable-region",t),style:r,"aria-label":l,children:a?s.jsxs(s.Fragment,{children:[e,x&&(c||_)&&s.jsx("div",{className:"scrollable-region__overlay",style:{top:x.top,left:x.left,width:x.width,height:x.height},children:j})]}):s.jsxs(s.Fragment,{children:[j,s.jsx("div",{ref:p,className:z("scrollable-region__viewport",n),children:e})]})})},Us=48,Ps=({checklist:e})=>{const t=i.useRef(null),n=i.useRef(!1);return i.useLayoutEffect(()=>{const a=t.current;if(!a)return;const r=a.scrollHeight-a.scrollTop-a.clientHeight;(!n.current||r<=Us)&&(a.scrollTop=a.scrollHeight,n.current=!0)},[e]),e.length===0?s.jsx("p",{className:"agent-view__progress-empty",children:"No tasks to display."}):s.jsx(Je,{className:"agent-view__progress-scroll",scrollSelector:".agent-view__progress-list",children:s.jsx("ul",{ref:t,className:"agent-view__progress-list","aria-label":"Agent tasks",children:Ls(e).map(a=>{const r=Y[a.status];return s.jsxs("li",{className:z("agent-view__progress-item",`agent-view__progress-item--${a.status.replace(/_/g,"-")}`),children:[s.jsx(u.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`}),s.jsxs("div",{className:"agent-view__progress-item-content",children:[s.jsx("span",{className:"agent-view__progress-label",children:a.task}),a.status!==U.complete&&s.jsx("span",{className:"agent-view__progress-description",children:a.description})]})]},a.task)})})})},Ds=({prompts:e,classNamePrefix:t="agent-workspace",onSelect:n})=>e.length===0?null:s.jsx("div",{className:`${t}__chips`,children:e.map(a=>s.jsx("button",{type:"button",className:`${t}__chip`,onClick:()=>n(a),children:a},a))});class $s{constructor(t,n){this.connector=t,this.canSend=n.canSend,this.onTurn=n.onTurn,this.onAwaitingChange=n.onAwaitingChange}get canRate(){return!1}get canLoadHistory(){return!1}get canListInteractions(){return!1}get canSendNotification(){return!1}get ratingPopupUrls(){return{}}async sendMessage(t){var n,a;if(!this.canSend())return null;(n=this.onAwaitingChange)==null||n.call(this,!0);try{const r=await this.connector.sendMessage(t.userMessage,t.uploadFiles);return this.onTurn(r),{id:r.message.id,text:r.message.text,type:ve.CHAT_RESPONSE_TYPE_AGENT,...r.message.followUpPrompts?{followUpPrompts:r.message.followUpPrompts}:{}}}catch{return{id:`error-${Date.now()}`,text:Ss,type:ve.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 Hs=({connector:e,phase:t,chatHistory:n,chatSessionKey:a,startQuery:r,clarificationMessage:l,enableUpload:o=!1,onTurn:p,onAwaitingChange:c,onClarificationPrompt:g,onDismissClarification:_})=>{const y=i.useMemo(()=>new $s(e,{canSend:()=>t===H.running,onTurn:p,onAwaitingChange:c}),[e,t,p,c]),x=t!==H.running,E=t===H.running;return s.jsxs("section",{className:"agent-workspace__chat-body","aria-label":"Chat",children:[l&&s.jsxs("div",{className:"agent-workspace__clarification",role:"region","aria-label":"Agent question",children:[s.jsx("p",{className:"agent-workspace__clarification-text",children:l.text}),l.followUpPrompts&&s.jsx(Ds,{prompts:l.followUpPrompts,onSelect:g}),s.jsx("button",{type:"button",className:"agent-workspace__clarification-dismiss",onClick:_,children:"Dismiss"})]}),s.jsx("div",{className:"agent-workspace__ask-arbor",children:s.jsx(Je,{scrollSelector:".chat-panel-message-list",children:s.jsx(ve.ChatPanel,{connector:y,chatHistory:n,startQuery:r,lockConversation:x,enableUpload:o,speechEnabled:E,speechLanguage:"en-GB",speechSubmissionDelay:1e3,slashMenuItems:[],menuContent:[],introHeading:"Message your agent",introBody:"Ask questions, share trip details, or paste a link. The agent will update the checklist as it works.",placeholder:E?"Message the agent, paste a link, or attach a file…":"The agent is not accepting messages."},a)})}),t===H.stopped&&s.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[s.jsx(u.Icon,{name:"circle-alert",size:16,color:"var(--color-semantic-warning-600)"}),s.jsx("span",{children:"You stopped the agent. Its progress is saved in the checklist."})]}),t===H.complete&&s.jsxs("div",{className:"agent-workspace__notice",role:"status",children:[s.jsx(u.Icon,{name:"party-popper",size:16,color:"var(--color-semantic-success-600)"}),s.jsx("span",{children:"The agent has finished."})]})]})},Pt=({item:e,depth:t,canRequestInput:n,onAttentionItemClick:a})=>{const r=Y[e.status],l=e.status.replace(/_/g,"-"),o=e.status===U.hitl&&n&&a,p=s.jsxs("div",{className:"agent-workspace__task-row",children:[s.jsx(u.Icon,{name:r.icon,size:16,color:r.color,screenReaderText:`${r.label}:`}),s.jsxs("div",{className:"agent-workspace__task-content",children:[s.jsx("span",{className:"agent-workspace__task-label",children:e.task}),e.status!==U.complete&&e.description&&s.jsx("span",{className:"agent-workspace__task-description",children:e.description})]})]});return s.jsxs("li",{className:z("agent-workspace__task",`agent-workspace__task--${l}`,{"agent-workspace__task--child":t>0}),children:[o?s.jsx("button",{type:"button",className:"agent-workspace__task-button","aria-label":`Provide input for ${e.task}`,onClick:()=>a(e),children:p}):p,e.children&&e.children.length>0&&s.jsx("ul",{className:"agent-workspace__task-children",children:e.children.map(c=>s.jsx(Pt,{item:c,depth:t+1,canRequestInput:n,onAttentionItemClick:a},c.task))})]})},Ge=({items:e,ariaLabel:t,canRequestInput:n,onAttentionItemClick:a})=>s.jsx("ul",{className:"agent-workspace__task-list","aria-label":t,children:e.map(r=>s.jsx(Pt,{item:r,depth:0,canRequestInput:n,onAttentionItemClick:a},r.task))}),Fs=({checklist:e,isLoading:t,error:n,phase:a,canRequestInput:r,onAttentionItemClick:l})=>{const o=i.useMemo(()=>e?Ut(e):null,[e]);return s.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--checklist","aria-label":"Checklist",children:[s.jsx("div",{className:"agent-workspace__panel-header",children:s.jsx(u.Heading,{level:4,children:"Checklist"})}),s.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:s.jsxs(Je,{children:[t&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:_e}),s.jsx("span",{children:_e})]}),!t&&n&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:n}),!t&&!n&&o&&s.jsxs(s.Fragment,{children:[o.needsInput.length>0&&s.jsxs("div",{className:"agent-workspace__task-group",children:[s.jsx("p",{className:"agent-workspace__task-group-label",children:"Needs your input"}),s.jsx(Ge,{items:o.needsInput,ariaLabel:"Tasks needing your input",canRequestInput:r,onAttentionItemClick:l})]}),o.complete.length>0&&s.jsxs("div",{className:z("agent-workspace__task-group",{"agent-workspace__task-group--following":o.needsInput.length>0}),children:[(o.needsInput.length>0||o.failed.length>0||o.tasks.length>0)&&s.jsx("p",{className:"agent-workspace__task-group-label",children:"Completed"}),s.jsx(Ge,{items:o.complete,ariaLabel:"Completed tasks",canRequestInput:r,onAttentionItemClick:l})]}),o.failed.length>0&&s.jsxs("div",{className:z("agent-workspace__task-group",{"agent-workspace__task-group--following":o.needsInput.length>0||o.complete.length>0}),children:[(o.needsInput.length>0||o.complete.length>0||o.tasks.length>0)&&s.jsx("p",{className:"agent-workspace__task-group-label",children:"Failed"}),s.jsx(Ge,{items:o.failed,ariaLabel:"Failed tasks",canRequestInput:r,onAttentionItemClick:l})]}),o.tasks.length>0&&s.jsxs("div",{className:z("agent-workspace__task-group",{"agent-workspace__task-group--following":o.needsInput.length>0||o.complete.length>0||o.failed.length>0}),children:[(o.needsInput.length>0||o.complete.length>0||o.failed.length>0)&&s.jsx("p",{className:"agent-workspace__task-group-label",children:"Working on"}),s.jsx(Ge,{items:o.tasks,ariaLabel:"Agent tasks",canRequestInput:r,onAttentionItemClick:l})]})]}),!t&&!n&&(!o||o.needsInput.length===0&&o.complete.length===0&&o.failed.length===0&&o.tasks.length===0)&&s.jsx("p",{className:"agent-workspace__empty",children:a===H.briefing?"Tasks will appear here once the agent starts.":"No tasks to display."})]})})]})},Bs=({resource:e,html:t,isLoading:n,error:a,onClose:r})=>{i.useEffect(()=>{if(!e)return;const o=u.SlideoverUtils.removeSlideover;return u.SlideoverUtils.removeSlideover=()=>{o(),r()},()=>{u.SlideoverUtils.removeSlideover=o}},[e,r]),i.useEffect(()=>{if(!e)return;const o=p=>{p.key==="Escape"&&u.SlideoverUtils.removeSlideover()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[e]);const l=i.useMemo(()=>e?[{centerHeaderText:!1,children:s.jsxs("div",{className:"resource-preview-slideover__body",children:[n&&s.jsxs("div",{className:"resource-preview-slideover__status",children:[s.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading document"}),s.jsx("span",{children:"Loading document…"})]}),!n&&a&&s.jsx("p",{className:"resource-preview-slideover__error",role:"alert",children:a}),!n&&!a&&t!==null&&s.jsx("iframe",{className:"resource-preview-slideover__frame",title:e.title,sandbox:"",srcDoc:t})]})}]:[],[e,t,n,a]);return s.jsx("div",{className:"resource-preview-slideover",children:s.jsx(u.SlideoverManager,{slideovers:l})})},Gs={[ie.mis_record]:{icon:"table",label:"Arbor MIS",color:"var(--color-brand-600)"},[ie.document_html]:{icon:"file",label:"Document",color:"var(--color-semantic-caution-800)"},[ie.file]:{icon:"file",label:"File",color:"var(--color-semantic-caution-800)"},[ie.user_file]:{icon:"upload",label:"File upload",color:"var(--color-semantic-caution-800)"},[ie.workflow]:{icon:"list-tree",label:"Workflow",color:"var(--color-semantic-warning-700)"},[ie.link]:{icon:"link",label:"Link",color:"var(--color-semantic-info-700)"}},zs=({resources:e,isLoading:t=!1,error:n=null,onOpenResource:a})=>s.jsxs("section",{className:"agent-workspace__panel agent-workspace__panel--documents","aria-label":"Resources",children:[s.jsxs("div",{className:"agent-workspace__panel-header",children:[s.jsx(u.Heading,{level:4,children:"Resources"}),s.jsx("span",{className:"agent-workspace__panel-count",children:e.length})]}),s.jsx("div",{className:"agent-workspace__panel-body","aria-live":"polite",children:s.jsxs(Je,{children:[t&&s.jsxs("div",{className:"agent-workspace__loading",children:[s.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-workspace__task-icon--spinning",screenReaderText:"Loading resources"}),s.jsx("span",{children:"Loading resources…"})]}),!t&&n&&s.jsx("p",{className:"agent-workspace__error",role:"alert",children:n}),!t&&!n&&e.length>0&&s.jsx("ul",{className:"agent-workspace__resource-list","aria-label":"Agent resources",children:e.map(r=>{const l=Gs[r.type],o=r.misRecordUrl;return s.jsx("li",{className:"agent-workspace__resource",children:o?s.jsx("a",{className:"agent-workspace__resource-card",href:o,target:"_blank",rel:"noreferrer",onClick:p=>{p.preventDefault(),a(r)},children:s.jsx(St,{resource:r,config:l,external:!0})}):s.jsx("button",{type:"button",className:"agent-workspace__resource-card",onClick:()=>a(r),children:s.jsx(St,{resource:r,config:l})})},r.id)})}),!t&&!n&&e.length===0&&s.jsx("p",{className:"agent-workspace__empty",children:"No resources yet."})]})})]}),St=({resource:e,config:t,external:n=!1})=>s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`agent-workspace__resource-icon agent-workspace__resource-icon--${e.type}`,children:s.jsx(u.Icon,{name:t.icon,size:16,color:t.color,screenReaderText:`${t.label}:`})}),s.jsx("span",{className:"agent-workspace__resource-content",children:s.jsxs("span",{className:"agent-workspace__resource-top",children:[s.jsx("span",{className:"agent-workspace__resource-name",children:e.title}),s.jsx("span",{className:`agent-workspace__resource-badge agent-workspace__resource-badge--${e.type}`,children:t.label})]})}),n&&s.jsx(u.Icon,{name:"external-link",size:12,color:"var(--color-grey-500)",screenReaderText:"Opens in a new tab",className:"agent-workspace__resource-open"})]}),bt=e=>{const t=Date.parse(e);return Number.isFinite(t)?t:0},qs=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"long",year:"numeric",hour:"numeric",minute:"2-digit"}),nt=e=>{const t=new Date(e);return Number.isFinite(t.getTime())?qs.format(t):e},Nt=e=>e.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,t=>t.split(/[_-]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" ")),At=e=>{const n=e.replace(/[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)+/g,a=>a.split(/[_-]/).map(r=>r.toLowerCase()).join(" ")).toLowerCase();return n&&n.charAt(0).toUpperCase()+n.slice(1)},Js=60*60*1e3,Dt=60*60*1e3,Re=24*Dt,rt=7*Re,Ks=e=>e.type!=="message-sent",Ws=(e,t)=>{const n=e.filter(Ks).map((r,l)=>({kind:"action",id:`action-${r.timestamp}-${l}`,timestampMs:bt(r.timestamp),item:r})),a=t.map(r=>({kind:"chat",id:r.sessionId,timestampMs:bt(r.timestamp),session:r}));return[...n,...a].sort((r,l)=>r.timestampMs-l.timestampMs||r.id.localeCompare(l.id))},Vs=e=>e>=rt?"weeks":e>=Re?"days":"hours",Ys=e=>{if(e<Re){const a=Math.max(1,Math.round(e/Dt));return a===1?"1 hour later":`${a} hours later`}if(e<rt){const a=Math.max(1,Math.round(e/Re));return a===1?"1 day later":`${a} days later`}const t=Math.max(1,Math.round(e/rt));if(t<5)return t===1?"1 week later":`${t} weeks later`;const n=Math.max(1,Math.round(e/(30*Re)));return n===1?"1 month later":`${n} months later`},Xs=(e,t=Js)=>{if(e.length===0)return[];const n=[e[0]];for(let a=1;a<e.length;a+=1){const r=e[a-1],l=e[a],o=l.timestampMs-r.timestampMs;o>=t&&n.push({kind:"gap",id:`gap-${r.id}-${l.id}`,durationMs:o,label:Ys(o),size:Vs(o)}),n.push(l)}return n},Zs=e=>e.type==="checklist-updated"?"checklist":e.type==="status-transition"?"status":"note",Qs=({timeline:e,isLoading:t,error:n,onOpenChatSession:a})=>{const r=(e==null?void 0:e.actionLog)??[],l=(e==null?void 0:e.chatSessions)??[],o=Ws(r,l),p=Xs(o),c=!t&&!n&&o.length===0;return s.jsxs("section",{className:"agent-workspace__timeline","aria-label":"Agent timeline",children:[t&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"Loading timeline…"}),n&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"alert",children:n||Ot}),c&&s.jsx("p",{className:"agent-workspace__timeline-status",role:"status",children:"No timeline activity yet."}),!t&&!n&&!c&&s.jsxs("div",{className:"agent-timeline",children:[s.jsx("div",{className:"agent-timeline__track","aria-hidden":"true"}),s.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",children:[s.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:s.jsx(u.Icon,{name:"arrow-right-from-line",size:16,color:"currentColor"})}),s.jsx("div",{className:"agent-timeline__label",children:s.jsx("strong",{className:"agent-timeline__label-type",children:"Start"})})]}),p.map(g=>{if(g.kind==="gap")return s.jsxs("div",{className:`agent-timeline__gap agent-timeline__gap--${g.size}`,role:"separator","aria-label":g.label,children:[s.jsx("span",{className:"agent-timeline__gap-rail","aria-hidden":"true",children:s.jsx("span",{className:"agent-timeline__gap-dot"})}),s.jsx("span",{className:"agent-timeline__gap-label",children:g.label})]},g.id);if(g.kind==="chat")return s.jsxs("div",{className:"agent-timeline__chat-station",children:[s.jsx("button",{type:"button",className:"agent-timeline__chat-node","aria-label":`Open chat session from ${nt(g.session.timestamp)}`,onClick:()=>a(g.session.sessionId),children:s.jsx(u.Icon,{name:"sparkles",size:16,color:"currentColor"})}),s.jsxs("div",{className:"agent-timeline__label",children:[s.jsx("strong",{className:"agent-timeline__label-type",children:"Chat session"}),s.jsx("span",{className:"agent-timeline__label-time",children:nt(g.session.timestamp)})]})]},g.id);const{item:_}=g,y=Zs(_),x=y==="checklist",E=y==="status";return s.jsxs("div",{className:`agent-timeline__station agent-timeline__station--${y}`,children:[s.jsxs("button",{type:"button",className:`agent-timeline__station-node agent-timeline__station-node--${y}`,"aria-label":`${Nt(_.type)}: ${At(_.entry)}`,children:[x&&s.jsx(u.Icon,{name:"check-solid",size:16,color:"currentColor"}),E&&s.jsx(u.Icon,{name:"iteration-ccw",size:16,color:"currentColor"})]}),s.jsxs("div",{className:"agent-timeline__label",children:[s.jsx("strong",{className:"agent-timeline__label-type",children:Nt(_.type)}),s.jsx("span",{className:"agent-timeline__label-entry",children:At(_.entry)}),s.jsx("span",{className:"agent-timeline__label-time",children:nt(_.timestamp)})]})]},g.id)}),s.jsxs("div",{className:"agent-timeline__station agent-timeline__station--terminus",children:[s.jsx("span",{className:"agent-timeline__station-node agent-timeline__station-node--terminus","aria-hidden":"true",children:s.jsx(u.Icon,{name:"flag",size:16,color:"currentColor"})}),s.jsx("div",{className:"agent-timeline__label",children:s.jsx("strong",{className:"agent-timeline__label-type",children:"Finish"})})]})]})]})},en=["I'll get the details and come back to you","Skip this for now"],tn=e=>{var n;const t=(n=e.prompt)!=null&&n.trim()?e.prompt.trim():`I need a bit more from you on "${e.task}". ${e.description} What can you tell me?`;return{id:`clarification-${Date.now()}`,author:X.agent,text:t,followUpPrompts:e.clarificationPrompts??en}},me=e=>({id:e.id,text:e.text,type:e.author===X.user?ve.CHAT_RESPONSE_TYPE_USER:e.author===X.system?ve.CHAT_RESPONSE_TYPE_INFO:ve.CHAT_RESPONSE_TYPE_AGENT,...e.followUpPrompts?{followUpPrompts:e.followUpPrompts}:{}}),it="MESSAGE_TYPE_REPOLL",ot="agentMessage:new_message",dt="arbor-agent-",oe={all:"ALL",checklist:"CHECKLIST",resources:"RESOURCES",chat:"CHAT",timeline:"TIMELINE"},sn=new Set(Object.values(oe)),$t=(e,t)=>`${e.endsWith("-")?e:`${e}-`}${t}`,nn=e=>typeof e=="string"&&sn.has(e)?e:oe.all,an=e=>{if(!e||typeof e!="object")return null;const t=e;return t.type!==it?null:{type:it,target:nn(t.target)}},Ht=e=>{const t=Array.isArray(e)?e:[e],n=[];for(const a of t){const r=an(a);r&&n.push(r)}return n},rn=({enabled:e,channelPrefix:t,agentId:n,subscribeToPusher:a,onRepoll:r})=>{const l=i.useRef(r);i.useEffect(()=>{l.current=r},[r]),i.useEffect(()=>{if(!e||!(t!=null&&t.trim())||!a||!n)return;const o=$t(t.trim(),n),p=a(o,ot,c=>{console.log("[agent-view pusher] message received",{channel:o,event:ot,payload:c});for(const g of Ht(c))l.current(g.target)});return()=>{p()}},[e,t,n,a])};class fe extends Error{constructor(t,n,a){super(a??`Agent service request failed (${t})`),this.name="AgentServiceError",this.status=t,this.detail=n}}const on="/api/v1",$={agentDefinitions:"/agent-definitions",agents:"/agents",conversations:"/conversations",tripOptions:"/trip-options",demoDataset:"/demo/dataset"},B={GET:"GET",POST:"POST"},ln={error:"error"},cn={user:"user"},ue={acceptJson:"application/json",acceptHtml:"text/html",acceptEventStream:"text/event-stream",contentTypeJson:"application/json",arborApplicationUrl:"X-Arbor-Application-Url"},dn=100,Ft=e=>{switch(e){case xt.cancelled:return A.failed;case xt.archived:return A.complete;case A.hitl:case A.complete:case A.failed:case A["generating-a-response"]:return e;default:return A["generating-a-response"]}},Bt=e=>{switch(e){case tt.requires_attention:return U.hitl;case tt.in_progress:case tt.available:return U["generating-a-response"];case U.failed:case U.complete:case U.hitl:case U["generating-a-response"]:return e;default:return U["generating-a-response"]}},ut=e=>({ref:e.name,display_name:e.display_name,agent_intent:e.agent_intent??"",description:e.description}),un=e=>({id:e.id,name:e.name,...e.has_run_before?{hasRunBefore:e.has_run_before}:{}}),gn=new Set(Object.values(ie)),hn=e=>gn.has(e)?e:ie.document_html,Gt=e=>({id:e.id,type:hn(e.type),title:e.title,createdDatetime:e.created_datetime,lastUpdatedDatetime:e.last_updated_datetime,misRecordUrl:e.mis_record_url}),zt=e=>({resources:e.resources.map(Gt),pageNumber:e.page_number,pageSize:e.page_size,totalRecords:e.total_records}),qt=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}))}),lt=e=>{var n;const t=e.invocation_id??e.id;return{id:e.id,invocation_id:t,agent_definition_ref:e.agent_definition_ref,...e.agent_intent?{agent_intent:e.agent_intent}:{},invocation_name:((n=e.invocation_name)==null?void 0:n.trim())||e.agent_definition_ref,application_id:e.application_id,...e.application_name?{application_name:e.application_name}:{},created_by:e.created_by,status:Ft(e.status),context_ref:e.context_ref??null,checklist_ref:e.checklist_ref??null}},gt=e=>{var t;return{task:e.item??e.task??e.name??e.label??bs,status:Bt(e.status),description:e.description??"",...e.prompt?{prompt:e.prompt}:{},...(t=e.follow_up_prompts)!=null&&t.length?{clarificationPrompts:e.follow_up_prompts}:{}}},pn=e=>Array.isArray(e)?e:e.checklist_items??e.checklist??e.items??[],ht=(e,t,n)=>{var l;const a=!Array.isArray(t)&&(t.opening_message||(l=t.opening_follow_up_prompts)!=null&&l.length)?t:n,r=a?Te(a):void 0;return{invocation_id:e,checklist:pn(t).map(gt),...r?{openingMessage:r}:{}}},Jt=(e,t)=>{const n=Te(t);return{invocation_id:t.invocation_id??e,checklist:(t.checklist_items??[]).map(gt),...n?{openingMessage:n}:{}}},Te=e=>{var n,a;const t=(n=e.opening_message)==null?void 0:n.trim();if(t)return{id:Lt,author:X.agent,text:t,...(a=e.opening_follow_up_prompts)!=null&&a.length?{followUpPrompts:e.opening_follow_up_prompts}:{}}},Kt=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)){const n=t.filter(a=>!!a&&typeof a=="object"&&typeof a.text=="string").map(a=>a.text);if(n.length>0)return n.join(`
|
|
2
|
+
`)}}catch{}return e},Wt=e=>{const t=e.trim();return t.length>0?`File upload
|
|
2
3
|
|
|
3
|
-
`);l=
|
|
4
|
-
|
|
5
|
-
`):null}},_t=t=>{try{return JSON.parse(t)}catch{return}};function Vs(t,e){const n=new FormData;n.append("body",JSON.stringify(t));for(const a of e)n.append("files",a,a.name);return n}const Ys={id:yt,author:Z.agent,text:"Type a question or upload a file. You can ask it how it's progressing, or send an instruction and it'll act on it."};let ft=0;const Xs=t=>(ft+=1,`${t}-${Date.now()}-${ft}`),Qs=t=>{const e=t.destination?` to ${t.destination}`:"";return`Let's get started on ${t.tripName.trim()||t.destination.trim()||"this task"}${e}. What will you do first?`};class Lt{constructor(e,n,a={}){this.seededChecklist=[],this.client=e,this.agentId=n,this.chatId=a.chatId??n,this.opening=a.openingMessage??Ys,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const e=await this.client.getConversation(this.chatId),n=Pt(e.messages);return n.length===0?[this.opening]:n}async start(e){return{...await this.exchange(Qs(e)),phase:H.running}}sendMessage(e,n){return this.exchange(e,n)}async stop(){}seedChecklist(e){this.seededChecklist=e}async exchange(e,n){var i;const a=[{role:Ds.user,content:e}],r=await this.client.chat(this.agentId,{messages:a,chat_id:this.chatId,...this.model?{model:this.model}:{},moderation_enabled:!0,meta:{feature_id:"agent_view",source:"agent_view_frontend"}},...n&&n.length>0?[{uploadFiles:n}]:[]),l={id:r.event_id||Xs("msg-agent"),author:Z.agent,text:r.message.content,...(i=r.follow_up_prompts)!=null&&i.length?{followUpPrompts:r.follow_up_prompts}:{}};try{const u=await this.client.getAgent(this.agentId),{checklist:c}=Ot(this.agentId,u);return this.seededChecklist=c,{message:l,checklist:c}}catch{return{message:l,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const ot=(t,e)=>n=>{var a,r;return new Lt(t,n.invocation_id,{model:e==null?void 0:e.model,chatId:((a=e==null?void 0:e.resolveChatId)==null?void 0:a.call(e,n))??(e==null?void 0:e.chatId)??n.invocation_id,openingMessage:((r=e==null?void 0:e.resolveOpeningMessage)==null?void 0:r.call(e,n))??(e==null?void 0:e.openingMessage)})},Mt=t=>t instanceof pe?t.message:t instanceof TypeError?"Network error while contacting the agent service.":t instanceof Error&&t.message?t.message:Nt,Zs=t=>{const e={};for(const n of t){const a=je(n);if(!a)continue;const r=n.invocation_id??n.id;e[r]=a,e[n.id]=a}return e},en=t=>JSON.stringify(t),et=(t,e)=>JSON.stringify(t)===JSON.stringify(e),Ut=t=>{const{jwt:e,headers:n,urls:a}=t,r=JSON.stringify(n??{}),l=en(a),i=o.useMemo(()=>new Fe({token:e,headers:n,urls:a}),[e,l]);o.useLayoutEffect(()=>{i.setHeaders(n)},[i,r]);const[u,c]=o.useState([]),[v,f]=o.useState([]),[h,p]=o.useState({}),[O,w]=o.useState("loading"),[j,N]=o.useState(null),[P,y]=o.useState(0),k=o.useCallback((I,U)=>{const E=I.map(tt),q=U.map(nt),K=Zs(I);c(z=>et(z,E)?z:E),f(z=>et(z,q)?z:q),p(z=>et(z,K)?z:K),w("idle"),N(null)},[]);o.useEffect(()=>{let I=!1;return w("loading"),N(null),(async()=>{try{const[U,E]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);if(I)return;k(U,E)}catch(U){if(I)return;c([]),f([]),p({}),w("error"),N(Mt(U))}})(),()=>{I=!0}},[k,i,P]);const _=o.useCallback(()=>{y(I=>I+1)},[]),C=o.useCallback(async()=>{try{const[I,U]=await Promise.all([i.listAgents(),i.listAgentDefinitions()]);k(I,U)}catch{}},[k,i]),R=o.useCallback(async I=>{const[U,E]=await Promise.all([i.getAgentChecklist(I),i.getAgent(I).catch(()=>null)]);return rt(I,U,E??void 0)},[i]),T=o.useCallback(async I=>i.listAllAgentResources(I),[i]),M=o.useCallback(async({definition:I,invocationName:U})=>{const E=await i.createAgent(I.ref,{invocationName:U}),q=await i.getAgent(E.id),K=tt(q),z=je(q);return c(D=>[K,...D]),z&&p(D=>({...D,[K.invocation_id]:z,[K.id]:z})),K},[i]),Y=o.useMemo(()=>ot(i,{resolveOpeningMessage:I=>h[I.invocation_id]??h[I.id]}),[i,h]);return{agents:u,agentDefinitions:v,loadState:O,loadError:j,reload:_,refresh:C,fetchAgentChecklist:R,fetchAgentResources:T,createAgent:M,chatConnector:Y}},tn=t=>JSON.stringify(t),Dt=t=>{const{agent:e,jwt:n,headers:a,urls:r,chatId:l}=t,i=JSON.stringify(a??{}),u=tn(r),c=o.useMemo(()=>new Fe({token:n,headers:a,urls:{agent:r.agentUrl,agentChecklist:r.agentChecklistUrl,...r.agentResourcesUrl?{agentResources:r.agentResourcesUrl}:{},...r.agentTimelineUrl?{agentTimeline:r.agentTimelineUrl}:{},agentChat:r.agentChatUrl,agentConversation:r.agentConversationUrl}}),[n,u]);o.useLayoutEffect(()=>{c.setHeaders(a)},[c,i]);const v=o.useCallback(async w=>{const[j,N]=await Promise.all([c.getAgentChecklist(w),c.getAgent(w).catch(()=>null)]);return rt(w,j,N??void 0)},[c]),f=o.useCallback(async w=>c.listAllAgentResources(w),[c]),h=o.useCallback(async(w,j)=>c.getAgentResourceHtml(w,j),[c]),p=o.useCallback(async w=>{const j=await c.getAgentTimeline(w);return It(j)},[c]);return{connector:o.useMemo(()=>ot(c,{chatId:l??e.invocation_id})(e),[c,e.invocation_id,l]),fetchAgentChecklist:v,fetchAgentResources:f,fetchAgentResourceHtml:h,fetchAgentTimeline:p}},sn=3e4,nn=(t,e)=>{const n=t.hasRunBefore?e||"This trip":t.tripName.trim()||"A new trip",a=t.destination?` to ${t.destination}`:"",r=t.hasRunBefore?" It has run before.":"";return`${n}${a}.${r}`.trim()},an=t=>{switch(t){case A.failed:return H.stopped;case A.complete:return H.complete;default:return H.running}},vt=(t,e)=>{e([ge(t)])},rn=(t,e)=>t.length===e.length&&t.every((n,a)=>{const r=e[a];return r!==void 0&&n.id===r.id&&n.text===r.text}),$t=({agent:t,invocationId:e,open:n,onClose:a,jwt:r,headers:l,agentUrl:i,agentChecklistUrl:u,agentResourcesUrl:c,agentTimelineUrl:v,agentChatUrl:f,agentConversationUrl:h,chatId:p,enableUpload:O,initialBrief:w,initialPhase:j,initialChecklist:N})=>{const[P,y]=o.useState(p??e),[k,_]=o.useState("chat"),[C,R]=o.useState(!1),{connector:T,fetchAgentChecklist:M,fetchAgentResources:Y,fetchAgentResourceHtml:I,fetchAgentTimeline:U}=Dt({agent:{...t,invocation_id:e},jwt:r,headers:l,chatId:P,urls:{agentUrl:i,agentChecklistUrl:u,agentResourcesUrl:c,agentTimelineUrl:v,agentChatUrl:f,agentConversationUrl:h}}),E=o.useRef(T),[q,K]=o.useState(j??(w?H.running:an(t.status))),[z,D]=o.useState([]),[be,ie]=o.useState(0),[_e,le]=o.useState(),[qe,ee]=o.useState(null),[Ge,fe]=o.useState([]),[ne,ve]=o.useState(!1),[Ae,ce]=o.useState(null),[Ce,Ee]=o.useState(null),[Te,we]=o.useState(null),[Re,xe]=o.useState(!1),[Je,ke]=o.useState(null),[te,ye]=o.useState(null),[m,b]=o.useState(!1),[S,G]=o.useState(null),[X,Q]=o.useState(N??null),[ae,Se]=o.useState(!1),[zt,Ke]=o.useState(null),[Ie,We]=o.useState(!1),[Oe,Ft]=o.useState(!1),[Pe,qt]=o.useState(!1),it=o.useRef(Ie),lt=o.useRef(0),ct=o.useRef(0);o.useEffect(()=>{E.current=T},[T]),o.useEffect(()=>{it.current=Ie},[Ie]),o.useEffect(()=>{y(p??e),_("chat"),R(!1),D([]),ie(g=>g+1)},[e,p]),o.useEffect(()=>{if(!n||w)return;const g=E.current.bootstrapConversation;if(!g){vt(E.current.openingMessage(),D);return}let x=!1;return We(!0),(async()=>{try{const L=await g.call(E.current);if(x)return;D(L.map(ge))}catch{x||vt(E.current.openingMessage(),D)}finally{x||We(!1)}})(),()=>{x=!0}},[n,w,e,P]);const de=o.useCallback(()=>{const g=++lt.current;(async()=>{var x,L;try{const W=await M(e);if(g!==lt.current)return;Q(se=>JSON.stringify(se)===JSON.stringify(W.checklist)?se:W.checklist),Ke(null),(L=(x=E.current).seedChecklist)==null||L.call(x,W.checklist)}catch{}})()},[M,e]),Le=o.useCallback(()=>{c&&(async()=>{try{const g=await Y(e);fe(g),ce(null)}catch{}})()},[c,Y,e]),ue=o.useCallback(()=>{if(!v)return;const g=++ct.current;(async()=>{try{const x=await U(e);if(g!==ct.current)return;ye(L=>JSON.stringify(L)===JSON.stringify(x)?L:x),G(null)}catch{}})()},[v,U,e]);o.useEffect(()=>{if(!n||w)return;const g=window.setInterval(()=>{const x=E.current.bootstrapConversation;x&&(async()=>{try{const L=await x.call(E.current);if(it.current)return;const W=L.map(ge);let se=!1;D(ut=>rn(ut,W)?ut:(se=!0,W)),se&&(de(),ue())}catch{}})()},sn);return()=>{window.clearInterval(g)}},[n,w,e,P,de,ue]);const Gt=o.useCallback(g=>{var x,L;g.checklist?(Q(g.checklist),(L=(x=E.current).seedChecklist)==null||L.call(x,g.checklist)):de(),g.phase&&K(g.phase),Le(),ue()},[de,Le,ue]);o.useEffect(()=>{var g,x;!n||w||N&&N.length>0&&((x=(g=E.current).seedChecklist)==null||x.call(g,N))},[n,w,N]),o.useEffect(()=>{if(!n||w)return;let g=!1;return Se(x=>N!=null&&N.length?!1:x||X===null||X.length===0),Ke(null),(async()=>{var x,L;try{const W=await M(e);if(g)return;N!=null&&N.length||(Q(W.checklist),(L=(x=E.current).seedChecklist)==null||L.call(x,W.checklist))}catch{!g&&!(N!=null&&N.length)&&Ke($e)}finally{g||Se(!1)}})(),()=>{g=!0}},[n,e,w,N,M]),o.useEffect(()=>{if(!n||!c)return;let g=!1;return ve(!0),ce(null),(async()=>{try{const x=await Y(e);g||fe(x)}catch{g||ce(ns)}finally{g||ve(!1)}})(),()=>{g=!0}},[n,e,c,Y]);const Jt=o.useCallback(()=>{Ee(null),we(null),ke(null),xe(!1)},[]),Kt=o.useCallback(g=>{if(g.misRecordUrl){window.open(g.misRecordUrl,"_blank","noopener,noreferrer");return}Ee(g),we(null),ke(null),xe(!0),(async()=>{try{const x=await I(e,g.id);we(x)}catch{ke(as)}finally{xe(!1)}})()},[I,e]);o.useEffect(()=>{if(!n||!v)return;let g=!1;return b(x=>x||te===null),G(null),(async()=>{try{const x=await U(e);g||ye(x)}catch{g||G(St)}finally{g||b(!1)}})(),()=>{g=!0}},[n,e,v,U]),o.useEffect(()=>{if(!n||!w)return;let g=!1;const x={id:`user-brief-${Date.now()}`,author:Z.user,text:nn(w,t.invocation_name)};return(async()=>{var W,se;const L=await E.current.start(w);g||(D([ge(E.current.openingMessage()),ge(x),ge(L.message)]),L.checklist?(Q(L.checklist),(se=(W=E.current).seedChecklist)==null||se.call(W,L.checklist)):de(),K(L.phase??H.running),Le(),ue())})(),()=>{g=!0}},[n,w,t.invocation_name,e,de,Le,ue]);const Wt=o.useCallback(g=>{ee(Ls(g))},[]),Ve=p??e,Me=te==null?void 0:te.chatSessions,dt=Me!=null&&Me.length?Me.reduce((g,x)=>Date.parse(x.timestamp)<Date.parse(g.timestamp)?x:g).sessionId:void 0,Ye=o.useCallback(()=>{_("chat"),R(!1),P!==Ve&&(y(Ve),D([]),ie(g=>g+1))},[P,Ve]),Vt=o.useCallback(g=>{if(g===dt){Ye();return}y(g),R(!0),_("chat"),D([]),ie(x=>x+1)},[dt,Ye]),Yt=o.useCallback(g=>{ee(null),le(g),ie(x=>x+1)},[]),Xt=o.useCallback(async()=>{await E.current.stop(),K(H.stopped)},[]),Qt=X;return s.jsxs(d.Modal,{open:n,closeHandler:a,hideCloseButton:!0,className:"agent-workspace",children:[s.jsxs(d.Modal.Header,{className:"agent-workspace__header",children:[s.jsxs("div",{className:"agent-workspace__header-title",children:[s.jsx("span",{className:"agent-workspace__header-avatar","aria-hidden":"true",children:s.jsx(d.Icon,{name:"ask-arbor",size:24})}),s.jsx(d.Modal.Title,{children:t.invocation_name}),s.jsx("span",{className:J("agent-workspace__phase",`agent-workspace__phase--${q}`),children:is[q]})]}),s.jsxs("div",{className:"agent-workspace__header-actions",children:[s.jsx(d.Button,{variant:Oe?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!Oe,onClick:()=>Ft(g=>!g),children:"Checklist"}),s.jsx(d.Button,{variant:Pe?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Pe,onClick:()=>qt(g=>!g),children:"Resources"}),s.jsx(d.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),s.jsxs(d.Modal.Body,{className:J("agent-workspace__body",{"agent-workspace__body--no-checklist":Oe,"agent-workspace__body--no-resources":Pe}),children:[" ",s.jsxs("section",{className:J("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!v&&k==="timeline"}),"aria-label":"Agent",children:[s.jsxs("div",{className:"agent-workspace__panel-header",children:[s.jsx(d.Heading,{level:4,children:"Agent"}),q===H.running&&s.jsx(d.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Stop",onClick:()=>void Xt(),children:"Stop agent"})]}),v&&s.jsxs(d.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[s.jsx(d.Tabs.Item,{active:k==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>_("chat")},children:"Chat"}),s.jsx(d.Tabs.Item,{active:k==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>_("timeline")},children:"Timeline"})]}),v&&k==="chat"&&C&&s.jsx("div",{className:"agent-workspace__center-back",children:s.jsx(d.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:Ye,children:"Back to main chat"})}),v&&k==="timeline"&&s.jsx(Os,{timeline:te,isLoading:m,error:S,onOpenChatSession:Vt}),s.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!v&&k!=="chat",children:s.jsx(ks,{connector:T,phase:q,chatHistory:z,chatSessionKey:be,startQuery:_e,clarificationMessage:qe,enableUpload:O,onTurn:Gt,onAwaitingChange:We,onClarificationPrompt:Yt,onDismissClarification:()=>ee(null)})})]}),!Oe&&s.jsx(ys,{checklist:Qt,isLoading:ae,error:zt,phase:q,canRequestInput:q===H.running&&!Ie,onAttentionItemClick:Wt}),!Pe&&s.jsx(js,{resources:Ge,isLoading:ne,error:Ae,onOpenResource:Kt}),s.jsx(Ss,{resource:Ce,html:Te,isLoading:Re,error:Je,onClose:Jt})]})]})},on="Unable to load agent definitions. Please try again.",ln="Unable to start the agent.",wt="Loading agents…",Ht=({open:t,onClose:e,onStart:n,agentDefinitions:a,definitionsState:r="idle",definitionsError:l=null,onRetryDefinitions:i,embedded:u=!1})=>{const[c,v]=o.useState(void 0),[f,h]=o.useState(""),[p,O]=o.useState(!1),[w,j]=o.useState(null),N=[...a].sort((R,T)=>R.display_name.localeCompare(T.display_name)).map(R=>({value:R.ref,label:R.display_name}));o.useEffect(()=>{t&&(v(void 0),h(""),O(!1),j(null))},[t]);const P=c!==void 0&&f.trim().length>0,y=o.useCallback(R=>{const T=a.find(M=>M.ref===R[0]);T&&v(T)},[a]),k=o.useCallback(async()=>{if(!(!c||!P||p)){O(!0),j(null);try{await n({definition:c,invocationName:f.trim()})}catch(R){j(R instanceof Error?R.message:ln)}finally{O(!1)}}},[P,c,f,p,n]);if(r==="idle"&&a.length===0||!t)return null;const _=s.jsxs("div",{className:"new-agent__header-title",children:[s.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:s.jsx(d.Icon,{name:"ask-arbor",size:24})}),u?s.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):s.jsx(d.Modal.Title,{children:"Start an agent"})]});let C;return r==="loading"?C=s.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[s.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:wt}),s.jsx("p",{className:"new-agent__state-message",children:wt})]}):r==="error"?C=s.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[s.jsx(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),s.jsx("p",{className:"new-agent__state-message",children:l??on}),i?s.jsx(d.Button,{variant:"secondary",size:"S",onClick:i,children:"Try again"}):null]}):C=s.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:R=>{R.preventDefault(),P&&!p&&k()},children:[s.jsxs("div",{className:"new-agent__type-field",children:[s.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:"What would you like your agent to do?"}),s.jsx(d.SelectDropdown,{id:"new-agent-type",placeholder:"Which agent would you like to start?",options:N,selectedValues:c?[c.ref]:[],onSelectionChange:y})]}),s.jsxs("div",{className:"new-agent__type-field",children:[s.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:"Name"}),s.jsx(d.TextInput,{id:"new-agent-invocation-name",value:f,placeholder:"What would you like to call your agent?",onChange:R=>h(R.target.value)})]}),w?s.jsx("p",{className:"new-agent__error",role:"alert",children:w}):null,s.jsx("div",{className:"new-agent__actions",children:s.jsx(d.Button,{type:"submit",variant:"primary",className:J("new-agent__start-button",{"new-agent__start-button--starting":p}),disabled:!P||p,iconLeftName:p?"loader":"sparkles",iconLeftScreenReaderText:p?"Starting":void 0,children:p?"Starting…":"Start"})})]}),u?s.jsxs("div",{className:J("new-agent","new-agent--embedded"),children:[s.jsx("div",{className:"new-agent__header",children:_}),s.jsx("div",{className:"new-agent__body",children:C})]}):s.jsxs(d.Modal,{open:t,closeHandler:e,className:"new-agent",children:[s.jsx(d.Modal.Header,{className:"new-agent__header",children:_}),s.jsx(d.Modal.Body,{className:"new-agent__body",children:C})]})},xt=t=>{window.location.assign(t)},cn=({open:t,authToken:e,headers:n,agentDefinitionsUrl:a,agentsUrl:r,closeUrl:l,successUrl:i,onClose:u,onStart:c,embedded:v=!1})=>{const f=JSON.stringify(n??{}),h=o.useMemo(()=>new Fe({token:e,headers:n,urls:{agentDefinitions:a,agents:r}}),[e,a,r,f]),[p,O]=o.useState([]),[w,j]=o.useState("loading"),[N,P]=o.useState(null),[y,k]=o.useState(0);o.useEffect(()=>{if(!t)return;let T=!1;return j("loading"),P(null),(async()=>{try{const M=await h.listAgentDefinitions();if(T)return;O(M.map(nt)),j("idle")}catch(M){if(T)return;O([]),P(Mt(M)),j("error")}})(),()=>{T=!0}},[h,t,y]);const _=o.useCallback(()=>{u==null||u(),l&&xt(l)},[l,u]),C=o.useCallback(async T=>{await h.createAgent(T.definition.ref,{invocationName:T.invocationName}),c==null||c(T),i&&xt(i)},[h,c,i]),R=o.useCallback(()=>{k(T=>T+1)},[]);return s.jsx(Ht,{open:t,onClose:_,onStart:C,agentDefinitions:p,definitionsState:w,definitionsError:N,onRetryDefinitions:R,embedded:v})},dn=t=>"agentDefinitionsUrl"in t,Bt=t=>dn(t)?s.jsx(cn,{...t}):s.jsx(Ht,{...t}),un=t=>t!==void 0&&t.some(e=>e.status===B.hitl),gn=(t,e)=>un(e)?A.hitl:t.status,hn=({column:t,label:e})=>t.statusIcon?s.jsx("span",{className:"agent-view__status-indicator",children:s.jsx(d.Icon,{name:t.statusIcon.name,size:16,color:t.statusIcon.color,className:J({"agent-view__progress-icon--spinning":t.statusIcon.spin}),screenReaderText:e})}):s.jsx("span",{className:J("agent-view__dot",{[`agent-view__dot--${t.dotModifier}`]:t.dotModifier}),children:s.jsx(d.Dot,{colour:t.dotColour,label:e})}),pn=({agent:t,agentName:e,column:n,isExpanded:a,isLoading:r,checklist:l,error:i,onToggle:u,onViewAgent:c})=>{const{id:v,invocation_name:f}=t,h=`agent-card-${v}-header`,p=`agent-card-${v}-progress`;return s.jsx("li",{className:J("agent-view__card",{"agent-view__card--expanded":a}),children:s.jsxs(d.Card,{spacing:"dense",children:[s.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":p,"aria-label":f,id:h,onClick:()=>u(v),children:s.jsxs("div",{className:"agent-view__card-content",children:[s.jsx(hn,{column:n}),s.jsx("span",{className:"agent-view__card-invocation-name",children:f}),s.jsx("span",{className:"agent-view__card-agent-name",children:e}),s.jsx(d.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&s.jsxs("div",{id:p,"aria-labelledby":h,className:"agent-view__card-progress",children:[r&&s.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:he}),s.jsx("span",{children:he})]}),!r&&i&&s.jsx("p",{className:"agent-view__progress-error",role:"alert",children:i}),!r&&!i&&l!==null&&s.jsx(vs,{checklist:l}),!r&&!i&&l===null&&s.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[s.jsx(d.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:he}),s.jsx("span",{children:he})]}),s.jsx("div",{className:"agent-view__card-actions",children:s.jsx(d.Button,{variant:"secondary",size:"S",onClick:()=>c==null?void 0:c(t),children:"View agent"})})]})]})})},kt=({column:t,agents:e,expandedAgentId:n,loadingAgentId:a,checklistByInvocationId:r,errorByAgentId:l,definitionNameByRef:i,onToggleAgent:u,onViewAgent:c,isSplit:v=!1})=>s.jsxs("section",{className:J("agent-view__column",{"agent-view__column--split":v}),"aria-label":t.title,children:[s.jsxs("div",{className:"agent-view__column-header",children:[s.jsx(d.Heading,{level:4,children:t.title}),s.jsx("span",{className:"agent-view__column-count",children:e.length})]}),s.jsx("ul",{className:"agent-view__card-list",children:e.map(f=>s.jsx(pn,{agent:f,agentName:st(f,i),column:t,isExpanded:n===f.id,isLoading:a===f.id,checklist:r[f.invocation_id]??null,error:l[f.id]??null,onToggle:u,onViewAgent:c},f.id))})]}),st=(t,e)=>e.get(t.agent_definition_ref)??t.agent_definition_ref.replace(/_/g," "),mn=({jwt:t,headers:e,agentDefinitionsUrl:n,agentsUrl:a,agentUrl:r,agentChecklistUrl:l,agentResourcesUrl:i,agentTimelineUrl:u,agentChatUrl:c,agentConversationUrl:v,enableUpload:f,showHeader:h=!1,institutions:p})=>{var ye;const O=o.useMemo(()=>({agentDefinitions:n,agents:a,agent:r,agentChecklist:l,...i?{agentResources:i}:{},...u?{agentTimeline:u}:{},agentChat:c,agentConversation:v}),[n,a,r,l,i,u,c,v]),[w,j]=o.useState(null),N=w?(ye=p==null?void 0:p.find(m=>m.applicationId===w.application_id))==null?void 0:ye.applicationUrl:void 0,P=o.useMemo(()=>{const m={...e??{}};return N?m[oe.arborApplicationUrl]=N:delete m[oe.arborApplicationUrl],m},[e,N]),{agents:y,agentDefinitions:k,loadState:_,loadError:C,reload:R,refresh:T,fetchAgentChecklist:M,createAgent:Y}=Ut({jwt:t,headers:P,urls:O}),[I,U]=o.useState(!1),[E,q]=o.useState(null),[K,z]=o.useState(null),[D,be]=o.useState({}),[ie,_e]=o.useState({}),[le,qe]=o.useState([]),[ee,Ge]=o.useState([]),fe=o.useMemo(()=>{const m=new Set(y.map(S=>S.application_id)),b=new Map((p??[]).map(S=>[S.applicationId,S.name]));return[...m].sort((S,G)=>(b.get(S)??S).localeCompare(b.get(G)??G)).map(S=>({value:S,label:b.get(S)??S}))},[y,p]),ne=o.useMemo(()=>new Map(k.map(m=>[m.ref,m.display_name])),[k]),ve=o.useMemo(()=>[...new Set(y.map(b=>st(b,ne)))].sort((b,S)=>b.localeCompare(S)).map(b=>({value:b,label:b})),[y,ne]),Ae=o.useMemo(()=>y.filter(m=>!(le.length>0&&!le.includes(m.application_id)||ee.length>0&&!ee.includes(st(m,ne)))),[y,ne,ee,le]),ce=fe.length>1,Ce=ve.length>1,Ee=ce||Ce;o.useEffect(()=>{const m=window.setInterval(()=>{T()},6e4);return()=>{window.clearInterval(m)}},[T]),o.useEffect(()=>{if(y.length===0)return;let m=!1;return(async()=>{const b=await Promise.allSettled(y.map(async S=>{const G=await M(S.invocation_id);return{agentId:S.id,invocationId:S.invocation_id,checklist:G.checklist}}));m||(be(S=>{const G={...S};let X=!1;for(const Q of b){if(Q.status!=="fulfilled")continue;const{invocationId:ae,checklist:Se}=Q.value;JSON.stringify(S[ae])!==JSON.stringify(Se)&&(G[ae]=Se,X=!0)}return X?G:S}),_e(S=>{const G={...S};let X=!1;return b.forEach((Q,ae)=>{Q.status==="rejected"&&G[y[ae].id]!==$e&&(G[y[ae].id]=$e,X=!0)}),X?G:S}))})(),()=>{m=!0}},[y,M]);const Te=o.useCallback(async m=>{if(!D[m.invocation_id]){z(m.id),_e(b=>{const S={...b};return delete S[m.id],S});try{const b=await M(m.invocation_id);be(S=>({...S,[m.invocation_id]:b.checklist}))}catch{_e(b=>({...b,[m.id]:$e}))}finally{z(b=>b===m.id?null:b)}}},[M,D]),we=o.useCallback(m=>{if(E===m){q(null);return}const b=y.find(({id:S})=>S===m);b&&(q(m),Te(b))},[y,E,Te]),Re=o.useMemo(()=>{const m={};for(const b of Ae){const S=gn(b,D[b.invocation_id]);(m[S]??(m[S]=[])).push(b)}return m},[Ae,D]),xe=o.useCallback(m=>{j(m)},[]),Je=o.useCallback(async m=>{const b=await Y(m);j(b),U(!1)},[Y]),ke=o.useCallback(()=>{j(null)},[]),te={expandedAgentId:E,loadingAgentId:K,checklistByInvocationId:D,errorByAgentId:ie,definitionNameByRef:ne,onToggleAgent:we,onViewAgent:xe};return s.jsxs("div",{className:"agent-view-frontend agent-view",children:[h&&s.jsxs("div",{className:"agent-view__header",children:[s.jsx(d.Heading,{level:1,children:"Agents"}),s.jsx(d.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>U(!0),children:"Start an agent"})]}),y.length>0&&Ee&&s.jsxs("div",{className:"agent-view__filters",children:[ce&&s.jsxs("div",{className:"agent-view__filter",children:[s.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-institution-filter",children:"Institution"}),s.jsx(d.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:fe,value:le,onValueChange:qe,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Ce&&s.jsxs("div",{className:"agent-view__filter",children:[s.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-agent-filter",children:"Agent"}),s.jsx(d.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:ve,value:ee,onValueChange:Ge,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),_==="error"?s.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[s.jsx(d.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),s.jsx("p",{className:"agent-view__state-message",children:C??Nt}),s.jsx(d.Button,{variant:"secondary",size:"S",onClick:R,children:"Try again"})]}):_==="loading"&&y.length===0?s.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[s.jsx(d.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:ht}),s.jsx("p",{className:"agent-view__state-message",children:ht})]}):y.length===0?s.jsx(gs,{}):s.jsxs("div",{className:"agent-view__board",children:[Zt.map(m=>s.jsx(kt,{column:He[m],agents:Re[m]??[],...te},m)),s.jsx("div",{className:"agent-view__split-column",children:es.map(m=>s.jsx(kt,{column:He[m],agents:Re[m]??[],isSplit:!0,...te},m))})]}),w&&s.jsx($t,{agent:w,invocationId:w.invocation_id,open:!0,jwt:t,headers:P,agentUrl:r,agentChecklistUrl:l,agentResourcesUrl:i,agentTimelineUrl:u,agentChatUrl:c,agentConversationUrl:v,enableUpload:f,initialChecklist:D[w.invocation_id]??null,onClose:ke},w.id),s.jsx(Bt,{open:I,onClose:()=>U(!1),onStart:Je,agentDefinitions:k})]})},_n=(t,e)=>{const n=Date.now(),a=e.trim()||t.agent_intent;return{id:`agent-${n}`,invocation_id:`inv-${n}`,agent_definition_ref:t.ref,agent_intent:t.agent_intent,invocation_name:a,application_id:ts,created_by:ss,status:A["generating-a-response"],context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=mn;exports.AgentServiceClient=Fe;exports.AgentServiceError=pe;exports.AgentView=$t;exports.HttpChatConnector=Lt;exports.NewAgentModal=Bt;exports.buildAgentFromDefinition=_n;exports.createHttpChatConnectorFactory=ot;exports.mapApiAgent=tt;exports.mapApiAgentDefinition=nt;exports.mapApiAgentStatus=Ct;exports.mapApiAgentTimelineResponse=It;exports.mapApiChecklistEndpointResponse=rt;exports.mapApiChecklistItem=at;exports.mapApiChecklistResponse=Ot;exports.mapApiChecklistStatus=Et;exports.mapApiConversationMessages=Pt;exports.mapApiOpeningMessage=je;exports.mapApiResource=Tt;exports.mapApiResourcesEndpointResponse=Rt;exports.mapApiTripOption=Hs;exports.useAgentService=Ut;exports.useAgentWorkspace=Dt;
|
|
4
|
+
${t}`:"File upload"},Vt=e=>e.filter(t=>t.message_type==="user_file"&&t.role==="user"?!0:(t.role==="user"||t.role==="assistant")&&typeof t.content=="string"&&t.content.length>0&&t.message_type!=="tool_request").map(t=>{if(t.message_type==="user_file"){const n=typeof t.content=="string"?t.content:"",a=Kt(n);return{id:t.message_id,author:X.user,kind:_s.user_file,text:Wt(a)}}return{id:t.message_id,author:t.role==="user"?X.user:X.agent,text:t.content}}),mn=/:invocationId\b/g,_n=/:resourceId\b/g,fn=e=>e.trim().replace(/^Bearer\s+/i,""),vn=e=>e.endsWith("/")?e.slice(0,-1):e;class Ke{constructor(t){var a;this.baseUrl=vn(t.baseUrl??"");const n=(a=t.token)==null?void 0:a.trim();this.token=n?fn(n):void 0,this.customHeaders=t.headers,this.urls=t.urls??{},this.fetchImpl=t.fetch??globalThis.fetch.bind(globalThis)}setHeaders(t){this.customHeaders=t}async listAgentDefinitions(){return(await this.request(B.GET,this.resolveUrl("agentDefinitions",$.agentDefinitions))).agent_definitions??[]}getAgentDefinition(t){return this.request(B.GET,this.apiUrl(`${$.agentDefinitions}/${encodeURIComponent(t)}`))}listTripOptions(){return this.request(B.GET,this.apiUrl($.tripOptions))}getDataset(){return this.request(B.GET,this.apiUrl($.demoDataset))}setDataset(t){return this.request(B.POST,this.apiUrl($.demoDataset),{dataset:t})}listAgents(t={}){const n=new URLSearchParams;t.status&&n.set("status",t.status),t.agentDefinitionRef&&n.set("agent_definition_ref",t.agentDefinitionRef);const a=n.toString()?`?${n.toString()}`:"";return this.request(B.GET,`${this.resolveUrl("agents",$.agents)}${a}`)}createAgent(t,n={}){var o,p;const a={agent_definition_ref:t},r=(o=n.invocationName)==null?void 0:o.trim(),l=(p=n.agentIntent)==null?void 0:p.trim();return r&&(a.invocation_name=r),l&&(a.agent_intent=l),this.request(B.POST,this.resolveUrl("agents",$.agents),a)}getAgent(t){return this.request(B.GET,this.resolveUrl("agent",`${$.agents}/${encodeURIComponent(t)}`,t))}getAgentChecklist(t){return this.request(B.GET,this.resolveUrl("agentChecklist",`${$.agents}/${encodeURIComponent(t)}/checklist`,t))}getAgentResources(t,n={}){const a=new URLSearchParams;n.pageNumber!==void 0&&a.set("page_number",String(n.pageNumber)),n.pageSize!==void 0&&a.set("page_size",String(n.pageSize)),n.type&&a.set("type",n.type);const r=a.toString(),l=this.resolveUrl("agentResources",`${$.agents}/${encodeURIComponent(t)}/resources`,t);return this.request(B.GET,r?`${l}?${r}`:l)}async listAllAgentResources(t){const n=dn;let a=1;const r=[];let l=Number.POSITIVE_INFINITY;for(;r.length<l;){const o=zt(await this.getAgentResources(t,{pageNumber:a,pageSize:n}));if(l=o.totalRecords,o.resources.length===0||(r.push(...o.resources),r.length>=l))break;a+=1}return r}getAgentResourceHtml(t,n){return this.requestText(B.GET,this.resolveResourceHtmlUrl(t,n))}getAgentTimeline(t){return this.request(B.GET,this.resolveUrl("agentTimeline",`${$.agents}/${encodeURIComponent(t)}/agent-timeline`,t))}getAgentContext(t){return this.request(B.GET,this.apiUrl(`${$.agents}/${encodeURIComponent(t)}/context`))}cancelAgent(t){return this.request(B.POST,this.resolveUrl("stopAgent",`${$.agents}/${encodeURIComponent(t)}/cancel`,t))}archiveAgent(t){return this.request(B.POST,this.apiUrl(`${$.agents}/${encodeURIComponent(t)}/archive`))}getConversation(t){return this.request(B.GET,this.resolveUrl("agentConversation",`${$.conversations}/${encodeURIComponent(t)}`,t))}async chat(t,n,a={}){const r=!!(a.uploadFiles&&a.uploadFiles.length>0),l=await this.fetchImpl(this.resolveUrl("agentChat",`${$.agents}/${encodeURIComponent(t)}/chat`,t),{method:B.POST,headers:{...this.customHeaders,...this.authHeaders(),Accept:ue.acceptEventStream,...r?{}:{"Content-Type":ue.contentTypeJson}},body:r?xn(n,a.uploadFiles??[]):JSON.stringify(n),signal:a.signal});if(!l.ok)throw await this.toError(l);if(!l.body)throw new fe(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}${on}${t}`}resolveUrl(t,n,a,r){const l=this.urls[t];if(!l)return this.apiUrl(n);let o=l;return a&&(o=o.replace(mn,encodeURIComponent(a))),r&&(o=o.replace(_n,encodeURIComponent(r))),o}resolveResourceHtmlUrl(t,n){return this.urls.agentResourceHtml?this.resolveUrl("agentResourceHtml",`${$.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(n)}`,t,n):this.urls.agentResources?`${this.resolveUrl("agentResources",`${$.agents}/${encodeURIComponent(t)}/resources`,t).replace(/\/$/,"")}/${encodeURIComponent(n)}`:this.apiUrl(`${$.agents}/${encodeURIComponent(t)}/resources/${encodeURIComponent(n)}`)}async request(t,n,a){const r=await this.fetchImpl(n,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:ue.acceptJson,...a===void 0?{}:{"Content-Type":ue.contentTypeJson}},...a===void 0?{}:{body:JSON.stringify(a)}});if(!r.ok)throw await this.toError(r);if(r.status!==204)return await r.json()}async requestText(t,n){const a=await this.fetchImpl(n,{method:t,headers:{...this.customHeaders,...this.authHeaders(),Accept:ue.acceptHtml}});if(!a.ok)throw await this.toError(a);return a.text()}async toError(t){let n=null;try{n=await t.json()}catch{}return new fe(t.status,n,`Agent service request failed (${t.status} ${t.statusText})`)}async consumeSse(t,n){const a=t.getReader(),r=new TextDecoder;let l="",o;const p=c=>{const{event:g,data:_}=wn(c);if(_===null)return;if(g===ln.error){const x=jt(_);throw new fe(502,x,(x==null?void 0:x.message)??"Chat stream error")}const y=jt(_);y&&(o=y,n==null||n(y))};for(;;){const{done:c,value:g}=await a.read();if(c)break;l+=r.decode(g,{stream:!0});const _=l.split(`
|
|
5
|
+
|
|
6
|
+
`);l=_.pop()??"";for(const y of _)p(y)}if(l.trim()&&p(l),!o)throw new fe(502,null,"Chat stream ended without any events");return o}}const wn=e=>{let t=null;const n=[];for(const a of e.split(`
|
|
7
|
+
`)){const r=a.trimEnd();r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&n.push(r.slice(5).trim())}return{event:t,data:n.length>0?n.join(`
|
|
8
|
+
`):null}},jt=e=>{try{return JSON.parse(e)}catch{return}};function xn(e,t){const n=new FormData;n.append("body",JSON.stringify(e));for(const a of t)n.append("files",a,a.name);return n}const kn={id:Lt,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 Ct=0;const yn=e=>(Ct+=1,`${e}-${Date.now()}-${Ct}`),Sn=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 Yt{constructor(t,n,a={}){this.seededChecklist=[],this.client=t,this.agentId=n,this.chatId=a.chatId??n,this.opening=a.openingMessage??kn,this.model=a.model}openingMessage(){return this.opening}async bootstrapConversation(){const t=await this.client.getConversation(this.chatId),n=Vt(t.messages);return n.length===0?[this.opening]:n}async start(t){return{...await this.exchange(Sn(t)),phase:H.running}}sendMessage(t,n){return this.exchange(t,n)}async stop(){await this.client.cancelAgent(this.agentId)}seedChecklist(t){this.seededChecklist=t}async exchange(t,n){var o;const a=[{role:cn.user,content:t}],r=await this.client.chat(this.agentId,{messages:a,chat_id:this.chatId,...this.model?{model:this.model}:{},moderation_enabled:!0,meta:{feature_id:"agent_view",source:"agent_view_frontend"}},...n&&n.length>0?[{uploadFiles:n}]:[]),l={id:r.event_id||yn("msg-agent"),author:X.agent,text:r.message.content,...(o=r.follow_up_prompts)!=null&&o.length?{followUpPrompts:r.follow_up_prompts}:{}};try{const p=await this.client.getAgent(this.agentId),{checklist:c}=Jt(this.agentId,p);return this.seededChecklist=c,{message:l,checklist:c}}catch{return{message:l,...this.seededChecklist.length?{checklist:this.seededChecklist}:{}}}}}const pt=(e,t)=>n=>{var a,r;return new Yt(e,n.invocation_id,{model:t==null?void 0:t.model,chatId:((a=t==null?void 0:t.resolveChatId)==null?void 0:a.call(t,n))??(t==null?void 0:t.chatId)??n.invocation_id,openingMessage:((r=t==null?void 0:t.resolveOpeningMessage)==null?void 0:r.call(t,n))??(t==null?void 0:t.openingMessage)})},Xt=e=>e instanceof fe?e.message:e instanceof TypeError?"Network error while contacting the agent service.":e instanceof Error&&e.message?e.message:Mt,bn=e=>{const t={};for(const n of e){const a=Te(n);if(!a)continue;const r=n.invocation_id??n.id;t[r]=a,t[n.id]=a}return t},Nn=e=>JSON.stringify(e),at=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Zt=e=>{const{jwt:t,headers:n,urls:a}=e,r=JSON.stringify(n??{}),l=Nn(a),o=i.useMemo(()=>new Ke({token:t,headers:n,urls:a}),[t,l]);i.useLayoutEffect(()=>{o.setHeaders(n)},[o,r]);const[p,c]=i.useState([]),[g,_]=i.useState([]),[y,x]=i.useState({}),[E,T]=i.useState("loading"),[f,G]=i.useState(null),[j,R]=i.useState(0),S=i.useCallback((I,D)=>{const F=I.map(lt),K=D.map(ut),W=bn(I);c(O=>at(O,F)?O:F),_(O=>at(O,K)?O:K),x(O=>at(O,W)?O:W),T("idle"),G(null)},[]);i.useEffect(()=>{let I=!1;return T("loading"),G(null),(async()=>{try{const[D,F]=await Promise.all([o.listAgents(),o.listAgentDefinitions()]);if(I)return;S(D,F)}catch(D){if(I)return;c([]),_([]),x({}),T("error"),G(Xt(D))}})(),()=>{I=!0}},[S,o,j]);const m=i.useCallback(()=>{R(I=>I+1)},[]),b=i.useCallback(async()=>{try{const[I,D]=await Promise.all([o.listAgents(),o.listAgentDefinitions()]);S(I,D)}catch{}},[S,o]),v=i.useCallback(async I=>{const[D,F]=await Promise.all([o.getAgentChecklist(I),o.getAgent(I).catch(()=>null)]);return ht(I,D,F??void 0)},[o]),C=i.useCallback(async I=>o.listAllAgentResources(I),[o]),P=i.useCallback(async({definition:I,invocationName:D})=>{const F=await o.createAgent(I.ref,{invocationName:D}),K=await o.getAgent(F.id),W=lt(K),O=Te(K);return c(L=>[W,...L]),O&&x(L=>({...L,[W.invocation_id]:O,[W.id]:O})),W},[o]),we=i.useMemo(()=>pt(o,{resolveOpeningMessage:I=>y[I.invocation_id]??y[I.id]}),[o,y]);return{agents:p,agentDefinitions:g,loadState:E,loadError:f,reload:m,refresh:b,fetchAgentChecklist:v,fetchAgentResources:C,createAgent:P,chatConnector:we}},An=e=>JSON.stringify(e),Qt=e=>{const{agent:t,jwt:n,headers:a,urls:r,chatId:l}=e,o=JSON.stringify(a??{}),p=An(r),c=i.useMemo(()=>new Ke({token:n,headers:a,urls:{agent:r.agentUrl,agentChecklist:r.agentChecklistUrl,...r.agentResourcesUrl?{agentResources:r.agentResourcesUrl}:{},...r.agentTimelineUrl?{agentTimeline:r.agentTimelineUrl}:{},agentChat:r.agentChatUrl,agentConversation:r.agentConversationUrl,...r.stopAgentUrl?{stopAgent:r.stopAgentUrl}:{}}}),[n,p]);i.useLayoutEffect(()=>{c.setHeaders(a)},[c,o]);const g=i.useCallback(async T=>{const[f,G]=await Promise.all([c.getAgentChecklist(T),c.getAgent(T).catch(()=>null)]);return ht(T,f,G??void 0)},[c]),_=i.useCallback(async T=>c.listAllAgentResources(T),[c]),y=i.useCallback(async(T,f)=>c.getAgentResourceHtml(T,f),[c]),x=i.useCallback(async T=>{const f=await c.getAgentTimeline(T);return qt(f)},[c]);return{connector:i.useMemo(()=>pt(c,{chatId:l??t.invocation_id})(t),[c,t.invocation_id,l]),fetchAgentChecklist:g,fetchAgentResources:_,fetchAgentResourceHtml:y,fetchAgentTimeline:x}},es=e=>{const t=document.querySelector(e);t instanceof HTMLElement&&t.removeAttribute("aria-describedby")},jn=3e4,Cn=(e,t)=>{const n=e.hasRunBefore?t||"This trip":e.tripName.trim()||"A new trip",a=e.destination?` to ${e.destination}`:"",r=e.hasRunBefore?" It has run before.":"";return`${n}${a}.${r}`.trim()},En=e=>{switch(e){case A.failed:return H.stopped;case A.complete:return H.complete;default:return H.running}},Et=(e,t)=>{t([me(e)])},Rn=(e,t)=>e.length===t.length&&e.every((n,a)=>{const r=t[a];return r!==void 0&&n.id===r.id&&n.text===r.text}),ts=({agent:e,invocationId:t,open:n,onClose:a,jwt:r,headers:l,agentUrl:o,agentChecklistUrl:p,agentResourcesUrl:c,agentTimelineUrl:g,agentChatUrl:_,agentConversationUrl:y,stopAgentUrl:x,chatId:E,enableUpload:T,initialBrief:f,initialPhase:G,initialChecklist:j,usePusherToRepoll:R=!1,pusherChannelPrefix:S=dt,subscribeToPusher:m})=>{const[b,v]=i.useState(E??t),[C,P]=i.useState("chat"),[we,I]=i.useState(!1),{connector:D,fetchAgentChecklist:F,fetchAgentResources:K,fetchAgentResourceHtml:W,fetchAgentTimeline:O}=Qt({agent:{...e,invocation_id:t},jwt:r,headers:l,chatId:b,urls:{agentUrl:o,agentChecklistUrl:p,agentResourcesUrl:c,agentTimelineUrl:g,agentChatUrl:_,agentConversationUrl:y,stopAgentUrl:x}}),L=i.useRef(D),[Z,xe]=i.useState(G??(f?H.running:En(e.status))),[Ie,q]=i.useState([]),[Le,ge]=i.useState(0),[ke,he]=i.useState(),[We,ne]=i.useState(null),[Ve,ye]=i.useState([]),[le,Se]=i.useState(!1),[Oe,pe]=i.useState(null),[Me,Ue]=i.useState(null),[Pe,be]=i.useState(null),[De,Ne]=i.useState(!1),[Ye,Ae]=i.useState(null),[ae,je]=i.useState(null),[h,N]=i.useState(!1),[k,J]=i.useState(null),[Q,ee]=i.useState(j??null),[ce,Ce]=i.useState(!1),[as,Xe]=i.useState(null),[$e,Ze]=i.useState(!1),[He,rs]=i.useState(!1),[Fe,is]=i.useState(!1),mt=i.useRef($e),_t=i.useRef(0),ft=i.useRef(0);i.useEffect(()=>{L.current=D},[D]),i.useLayoutEffect(()=>{n&&es(".agent-workspace")},[n]),i.useEffect(()=>{mt.current=$e},[$e]),i.useEffect(()=>{v(E??t),P("chat"),I(!1),q([]),ge(d=>d+1)},[t,E]),i.useEffect(()=>{if(!n||f)return;const d=L.current.bootstrapConversation;if(!d){Et(L.current.openingMessage(),q);return}let w=!1;return Ze(!0),(async()=>{try{const M=await d.call(L.current);if(w)return;q(M.map(me))}catch{w||Et(L.current.openingMessage(),q)}finally{w||Ze(!1)}})(),()=>{w=!0}},[n,f,t,b]);const te=i.useCallback(()=>{const d=++_t.current;(async()=>{var w,M;try{const V=await F(t);if(d!==_t.current)return;ee(re=>JSON.stringify(re)===JSON.stringify(V.checklist)?re:V.checklist),Xe(null),(M=(w=L.current).seedChecklist)==null||M.call(w,V.checklist)}catch{}})()},[F,t]),de=i.useCallback(()=>{c&&(async()=>{try{const d=await K(t);ye(d),pe(null)}catch{}})()},[c,K,t]),se=i.useCallback(()=>{if(!g)return;const d=++ft.current;(async()=>{try{const w=await O(t);if(d!==ft.current)return;je(M=>JSON.stringify(M)===JSON.stringify(w)?M:w),J(null)}catch{}})()},[g,O,t]),Ee=i.useCallback(d=>{const w=L.current.bootstrapConversation;w&&(async()=>{try{const M=await w.call(L.current);if(mt.current)return;const V=M.map(me);let re=!1;q(wt=>Rn(wt,V)?wt:(re=!0,V)),re&&(d!=null&&d.refreshSidePanelsOnChange)&&(te(),se())}catch{}})()},[te,se]),os=i.useCallback(d=>{switch(d){case oe.checklist:te();return;case oe.resources:de();return;case oe.chat:Ee();return;case oe.timeline:se();return;case oe.all:default:te(),de(),Ee(),se()}},[te,Ee,de,se]);rn({enabled:n&&R,channelPrefix:S,agentId:e.id,subscribeToPusher:m,onRepoll:os}),i.useEffect(()=>{if(!n||f||R)return;const d=window.setInterval(()=>{Ee({refreshSidePanelsOnChange:!0})},jn);return()=>{window.clearInterval(d)}},[n,f,R,t,b,Ee]);const ls=i.useCallback(d=>{var w,M;d.checklist?(ee(d.checklist),(M=(w=L.current).seedChecklist)==null||M.call(w,d.checklist)):te(),d.phase&&xe(d.phase),de(),se()},[te,de,se]);i.useEffect(()=>{var d,w;!n||f||j&&j.length>0&&((w=(d=L.current).seedChecklist)==null||w.call(d,j))},[n,f,j]),i.useEffect(()=>{if(!n||f)return;let d=!1;return Ce(w=>j!=null&&j.length?!1:w||Q===null||Q.length===0),Xe(null),(async()=>{var w,M;try{const V=await F(t);if(d)return;j!=null&&j.length||(ee(V.checklist),(M=(w=L.current).seedChecklist)==null||M.call(w,V.checklist))}catch{!d&&!(j!=null&&j.length)&&Xe(ze)}finally{d||Ce(!1)}})(),()=>{d=!0}},[n,t,f,j,F]),i.useEffect(()=>{if(!n||!c)return;let d=!1;return Se(!0),pe(null),(async()=>{try{const w=await K(t);d||ye(w)}catch{d||pe(ks)}finally{d||Se(!1)}})(),()=>{d=!0}},[n,t,c,K]);const cs=i.useCallback(()=>{Ue(null),be(null),Ae(null),Ne(!1)},[]),ds=i.useCallback(d=>{if(d.misRecordUrl){window.open(d.misRecordUrl,"_blank","noopener,noreferrer");return}Ue(d),be(null),Ae(null),Ne(!0),(async()=>{try{const w=await W(t,d.id);be(w)}catch{Ae(ys)}finally{Ne(!1)}})()},[W,t]);i.useEffect(()=>{if(!n||!g)return;let d=!1;return N(w=>w||ae===null),J(null),(async()=>{try{const w=await O(t);d||je(w)}catch{d||J(Ot)}finally{d||N(!1)}})(),()=>{d=!0}},[n,t,g,O]),i.useEffect(()=>{if(!n||!f)return;let d=!1;const w={id:`user-brief-${Date.now()}`,author:X.user,text:Cn(f,e.invocation_name)};return(async()=>{var V,re;const M=await L.current.start(f);d||(q([me(L.current.openingMessage()),me(w),me(M.message)]),M.checklist?(ee(M.checklist),(re=(V=L.current).seedChecklist)==null||re.call(V,M.checklist)):te(),xe(M.phase??H.running),de(),se())})(),()=>{d=!0}},[n,f,e.invocation_name,t,te,de,se]);const us=i.useCallback(d=>{ne(tn(d))},[]),Qe=E??t,Be=ae==null?void 0:ae.chatSessions,vt=Be!=null&&Be.length?Be.reduce((d,w)=>Date.parse(w.timestamp)<Date.parse(d.timestamp)?w:d).sessionId:void 0,et=i.useCallback(()=>{P("chat"),I(!1),b!==Qe&&(v(Qe),q([]),ge(d=>d+1))},[b,Qe]),gs=i.useCallback(d=>{if(d===vt){et();return}v(d),I(!0),P("chat"),q([]),ge(w=>w+1)},[vt,et]),hs=i.useCallback(d=>{ne(null),he(d),ge(w=>w+1)},[]),ps=i.useCallback(async()=>{await L.current.stop(),xe(H.stopped)},[]),ms=Q;return s.jsxs(u.Modal,{open:n,closeHandler:a,hideCloseButton:!0,className:"agent-workspace",children:[s.jsxs(u.Modal.Header,{className:"agent-workspace__header",children:[s.jsxs("div",{className:"agent-workspace__header-title",children:[s.jsx("span",{className:"agent-workspace__header-avatar","aria-hidden":"true",children:s.jsx(u.Icon,{name:"ask-arbor",size:24})}),s.jsx(u.Modal.Title,{children:e.invocation_name}),s.jsx("span",{className:z("agent-workspace__phase",`agent-workspace__phase--${Z}`),children:Ns[Z]})]}),s.jsxs("div",{className:"agent-workspace__header-actions",children:[s.jsx(u.Button,{variant:He?"secondary":"primary",size:"S",iconLeftName:"clipboard-list",iconLeftScreenReaderText:"Toggle checklist","aria-pressed":!He,onClick:()=>rs(d=>!d),children:"Checklist"}),s.jsx(u.Button,{variant:Fe?"secondary":"primary",size:"S",iconLeftName:"files",iconLeftScreenReaderText:"Toggle resources","aria-pressed":!Fe,onClick:()=>is(d=>!d),children:"Resources"}),s.jsx(u.Button,{variant:"secondary",size:"S",iconLeftName:"x",iconLeftScreenReaderText:"Close",onClick:a,children:"Close"})]})]}),s.jsxs(u.Modal.Body,{className:z("agent-workspace__body",{"agent-workspace__body--no-checklist":He,"agent-workspace__body--no-resources":Fe}),children:[" ",s.jsxs("section",{className:z("agent-workspace__panel","agent-workspace__panel--chat",{"agent-workspace__panel--timeline":!!g&&C==="timeline"}),"aria-label":"Agent",children:[s.jsxs("div",{className:"agent-workspace__panel-header",children:[s.jsx(u.Heading,{level:4,children:"Agent"}),x&&Z===H.running&&s.jsx(u.Button,{className:"agent-workspace__panel-header-action",variant:"secondary-destructive",size:"S",iconLeftName:"circle-x",iconLeftScreenReaderText:"Stop",onClick:()=>void ps(),children:"Stop agent"})]}),g&&s.jsxs(u.Tabs,{className:"agent-workspace__center-tabs","aria-label":"Center panel",children:[s.jsx(u.Tabs.Item,{active:C==="chat",tabElementProps:{id:"agent-center-tab-chat",onClick:()=>P("chat")},children:"Chat"}),s.jsx(u.Tabs.Item,{active:C==="timeline",tabElementProps:{id:"agent-center-tab-timeline",onClick:()=>P("timeline")},children:"Timeline"})]}),g&&C==="chat"&&we&&s.jsx("div",{className:"agent-workspace__center-back",children:s.jsx(u.Button,{variant:"tertiary",size:"S",iconLeftName:"arrow-left",iconLeftScreenReaderText:"Back to main chat",onClick:et,children:"Back to main chat"})}),g&&C==="timeline"&&s.jsx(Qs,{timeline:ae,isLoading:h,error:k,onOpenChatSession:gs}),s.jsx("div",{className:"agent-workspace__chat-keep-alive",hidden:!!g&&C!=="chat",children:s.jsx(Hs,{connector:D,phase:Z,chatHistory:Ie,chatSessionKey:Le,startQuery:ke,clarificationMessage:We,enableUpload:T,onTurn:ls,onAwaitingChange:Ze,onClarificationPrompt:hs,onDismissClarification:()=>ne(null)})})]}),!He&&s.jsx(Fs,{checklist:ms,isLoading:ce,error:as,phase:Z,canRequestInput:Z===H.running&&!$e,onAttentionItemClick:us}),!Fe&&s.jsx(zs,{resources:Ve,isLoading:le,error:Oe,onOpenResource:ds}),s.jsx(Bs,{resource:Me,html:Pe,isLoading:De,error:Ye,onClose:cs})]})]})},Tn="Unable to load agent definitions. Please try again.",In="Unable to start the agent.",Rt="Loading agents…",ss=({open:e,onClose:t,onStart:n,agentDefinitions:a,definitionsState:r="idle",definitionsError:l=null,onRetryDefinitions:o,embedded:p=!1})=>{const[c,g]=i.useState(void 0),[_,y]=i.useState(""),[x,E]=i.useState(!1),[T,f]=i.useState(null),G=[...a].sort((v,C)=>v.display_name.localeCompare(C.display_name)).map(v=>({value:v.ref,label:v.display_name}));i.useEffect(()=>{e&&(g(void 0),y(""),E(!1),f(null))},[e]),i.useLayoutEffect(()=>{!e||p||es(".new-agent")},[e,p]);const j=c!==void 0&&_.trim().length>0,R=i.useCallback(v=>{const C=a.find(P=>P.ref===v[0]);C&&g(C)},[a]),S=i.useCallback(async()=>{if(!(!c||!j||x)){E(!0),f(null);try{await n({definition:c,invocationName:_.trim()})}catch(v){f(v instanceof Error?v.message:In)}finally{E(!1)}}},[j,c,_,x,n]);if(r==="idle"&&a.length===0||!e)return null;const m=s.jsxs("div",{className:"new-agent__header-title",children:[s.jsx("span",{className:"new-agent__header-avatar","aria-hidden":"true",children:s.jsx(u.Icon,{name:"ask-arbor",size:24})}),p?s.jsx("h2",{className:"new-agent__title",children:"Start an agent"}):s.jsx(u.Modal.Title,{children:"Start an agent"})]});let b;return r==="loading"?b=s.jsxs("div",{className:"new-agent__state","aria-live":"polite",children:[s.jsx(u.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"new-agent__spinner",screenReaderText:Rt}),s.jsx("p",{className:"new-agent__state-message",children:Rt})]}):r==="error"?b=s.jsxs("div",{className:"new-agent__state new-agent__state--error",role:"alert",children:[s.jsx(u.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),s.jsx("p",{className:"new-agent__state-message",children:l??Tn}),o?s.jsx(u.Button,{variant:"secondary",size:"S",onClick:o,children:"Try again"}):null]}):b=s.jsxs("form",{className:"new-agent__form","aria-label":"Start an agent",onSubmit:v=>{v.preventDefault(),j&&!x&&S()},children:[s.jsxs("div",{className:"new-agent__type-field",children:[s.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-type",children:"What would you like your agent to do?"}),s.jsx(u.SelectDropdown,{id:"new-agent-type",placeholder:"Which agent would you like to start?",options:G,selectedValues:c?[c.ref]:[],onSelectionChange:R})]}),s.jsxs("div",{className:"new-agent__type-field",children:[s.jsx("label",{className:"new-agent__type-label",htmlFor:"new-agent-invocation-name",children:"Name"}),s.jsx(u.TextInput,{id:"new-agent-invocation-name",value:_,placeholder:"What would you like to call your agent?",onChange:v=>y(v.target.value)})]}),T?s.jsx("p",{className:"new-agent__error",role:"alert",children:T}):null,s.jsx("div",{className:"new-agent__actions",children:s.jsx(u.Button,{type:"submit",variant:"primary",className:z("new-agent__start-button",{"new-agent__start-button--starting":x}),disabled:!j||x,iconLeftName:x?"loader":"sparkles",iconLeftScreenReaderText:x?"Starting":void 0,children:x?"Starting…":"Start"})})]}),p?s.jsxs("div",{className:z("new-agent","new-agent--embedded"),children:[s.jsx("div",{className:"new-agent__header",children:m}),s.jsx("div",{className:"new-agent__body",children:b})]}):s.jsxs(u.Modal,{open:e,closeHandler:t,className:"new-agent",children:[s.jsx(u.Modal.Header,{className:"new-agent__header",children:m}),s.jsx(u.Modal.Body,{className:"new-agent__body",children:b})]})},Tt=e=>{window.location.assign(e)},Ln=({open:e,authToken:t,headers:n,agentDefinitionsUrl:a,agentsUrl:r,closeUrl:l,successUrl:o,onClose:p,onStart:c,embedded:g=!1})=>{const _=JSON.stringify(n??{}),y=i.useMemo(()=>new Ke({token:t,headers:n,urls:{agentDefinitions:a,agents:r}}),[t,a,r,_]),[x,E]=i.useState([]),[T,f]=i.useState("loading"),[G,j]=i.useState(null),[R,S]=i.useState(0);i.useEffect(()=>{if(!e)return;let C=!1;return f("loading"),j(null),(async()=>{try{const P=await y.listAgentDefinitions();if(C)return;E(P.map(ut)),f("idle")}catch(P){if(C)return;E([]),j(Xt(P)),f("error")}})(),()=>{C=!0}},[y,e,R]);const m=i.useCallback(()=>{p==null||p(),l&&Tt(l)},[l,p]),b=i.useCallback(async C=>{await y.createAgent(C.definition.ref,{invocationName:C.invocationName}),c==null||c(C),o&&Tt(o)},[y,c,o]),v=i.useCallback(()=>{S(C=>C+1)},[]);return s.jsx(ss,{open:e,onClose:m,onStart:b,agentDefinitions:x,definitionsState:T,definitionsError:G,onRetryDefinitions:v,embedded:g})},On=e=>"agentDefinitionsUrl"in e,ns=e=>On(e)?s.jsx(Ln,{...e}):s.jsx(ss,{...e}),Mn=e=>e!==void 0&&e.some(t=>t.status===U.hitl),Un=(e,t)=>Mn(t)?A.hitl:e.status,Pn=({column:e,label:t})=>e.statusIcon?s.jsx("span",{className:"agent-view__status-indicator",children:s.jsx(u.Icon,{name:e.statusIcon.name,size:16,color:e.statusIcon.color,className:z({"agent-view__progress-icon--spinning":e.statusIcon.spin}),screenReaderText:t})}):s.jsx("span",{className:z("agent-view__dot",{[`agent-view__dot--${e.dotModifier}`]:e.dotModifier}),children:s.jsx(u.Dot,{colour:e.dotColour,label:t})}),Dn=({agent:e,agentName:t,column:n,isExpanded:a,isLoading:r,checklist:l,error:o,onToggle:p,onViewAgent:c})=>{const{id:g,invocation_name:_}=e,y=`agent-card-${g}-header`,x=`agent-card-${g}-progress`;return s.jsx("li",{className:z("agent-view__card",{"agent-view__card--expanded":a}),children:s.jsxs(u.Card,{spacing:"dense",children:[s.jsx("button",{type:"button",className:"agent-view__card-toggle","aria-expanded":a,"aria-controls":x,"aria-label":_,id:y,onClick:()=>p(g),children:s.jsxs("div",{className:"agent-view__card-content",children:[s.jsx(Pn,{column:n}),s.jsx("span",{className:"agent-view__card-invocation-name",children:_}),s.jsx("span",{className:"agent-view__card-agent-name",children:t}),s.jsx(u.Icon,{name:a?"chevron-up":"chevron-down",size:16,className:"agent-view__card-chevron"})]})}),a&&s.jsxs("div",{id:x,"aria-labelledby":y,className:"agent-view__card-progress",children:[r&&s.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[s.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:_e}),s.jsx("span",{children:_e})]}),!r&&o&&s.jsx("p",{className:"agent-view__progress-error",role:"alert",children:o}),!r&&!o&&l!==null&&s.jsx(Ps,{checklist:l}),!r&&!o&&l===null&&s.jsxs("div",{className:"agent-view__progress-loading","aria-live":"polite",children:[s.jsx(u.Icon,{name:"loader",size:16,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:_e}),s.jsx("span",{children:_e})]}),s.jsx("div",{className:"agent-view__card-actions",children:s.jsx(u.Button,{variant:"secondary",size:"S",onClick:()=>c==null?void 0:c(e),children:"View agent"})})]})]})})},It=({column:e,agents:t,expandedAgentId:n,loadingAgentId:a,checklistByInvocationId:r,errorByAgentId:l,definitionNameByRef:o,onToggleAgent:p,onViewAgent:c,isSplit:g=!1})=>s.jsxs("section",{className:z("agent-view__column",{"agent-view__column--split":g}),"aria-label":e.title,children:[s.jsxs("div",{className:"agent-view__column-header",children:[s.jsx(u.Heading,{level:4,children:e.title}),s.jsx("span",{className:"agent-view__column-count",children:t.length})]}),s.jsx("ul",{className:"agent-view__card-list",children:t.map(_=>s.jsx(Dn,{agent:_,agentName:ct(_,o),column:e,isExpanded:n===_.id,isLoading:a===_.id,checklist:r[_.invocation_id]??null,error:l[_.id]??null,onToggle:p,onViewAgent:c},_.id))})]}),ct=(e,t)=>t.get(e.agent_definition_ref)??e.agent_definition_ref.replace(/_/g," "),$n=({jwt:e,headers:t,agentDefinitionsUrl:n,agentsUrl:a,agentUrl:r,agentChecklistUrl:l,agentResourcesUrl:o,agentTimelineUrl:p,agentChatUrl:c,agentConversationUrl:g,stopAgentUrl:_,enableUpload:y,showHeader:x=!1,institutions:E,usePusherToRepoll:T=!1,pusherChannelPrefix:f=dt,subscribeToPusher:G})=>{var je;const j=i.useMemo(()=>({agentDefinitions:n,agents:a,agent:r,agentChecklist:l,...o?{agentResources:o}:{},...p?{agentTimeline:p}:{},agentChat:c,agentConversation:g}),[n,a,r,l,o,p,c,g]),[R,S]=i.useState(null),m=R?(je=E==null?void 0:E.find(h=>h.applicationId===R.application_id))==null?void 0:je.applicationUrl:void 0,b=i.useMemo(()=>{const h={...t??{}};return m?h[ue.arborApplicationUrl]=m:delete h[ue.arborApplicationUrl],h},[t,m]),{agents:v,agentDefinitions:C,loadState:P,loadError:we,reload:I,refresh:D,fetchAgentChecklist:F,createAgent:K}=Zt({jwt:e,headers:b,urls:j}),[W,O]=i.useState(!1),[L,Z]=i.useState(null),[xe,Ie]=i.useState(null),[q,Le]=i.useState({}),[ge,ke]=i.useState({}),[he,We]=i.useState([]),[ne,Ve]=i.useState([]),ye=i.useMemo(()=>{const h=new Set(v.map(k=>k.application_id)),N=new Map((E??[]).map(k=>[k.applicationId,k.name]));return[...h].sort((k,J)=>(N.get(k)??k).localeCompare(N.get(J)??J)).map(k=>({value:k,label:N.get(k)??k}))},[v,E]),le=i.useMemo(()=>new Map(C.map(h=>[h.ref,h.display_name])),[C]),Se=i.useMemo(()=>[...new Set(v.map(N=>ct(N,le)))].sort((N,k)=>N.localeCompare(k)).map(N=>({value:N,label:N})),[v,le]),Oe=i.useMemo(()=>v.filter(h=>!(he.length>0&&!he.includes(h.application_id)||ne.length>0&&!ne.includes(ct(h,le)))),[v,le,ne,he]),pe=ye.length>1,Me=Se.length>1,Ue=pe||Me;i.useEffect(()=>{const h=window.setInterval(()=>{D()},6e4);return()=>{window.clearInterval(h)}},[D]),i.useEffect(()=>{if(v.length===0)return;let h=!1;return(async()=>{const N=await Promise.allSettled(v.map(async k=>{const J=await F(k.invocation_id);return{agentId:k.id,invocationId:k.invocation_id,checklist:J.checklist}}));h||(Le(k=>{const J={...k};let Q=!1;for(const ee of N){if(ee.status!=="fulfilled")continue;const{invocationId:ce,checklist:Ce}=ee.value;JSON.stringify(k[ce])!==JSON.stringify(Ce)&&(J[ce]=Ce,Q=!0)}return Q?J:k}),ke(k=>{const J={...k};let Q=!1;return N.forEach((ee,ce)=>{ee.status==="rejected"&&J[v[ce].id]!==ze&&(J[v[ce].id]=ze,Q=!0)}),Q?J:k}))})(),()=>{h=!0}},[v,F]);const Pe=i.useCallback(async h=>{if(!q[h.invocation_id]){Ie(h.id),ke(N=>{const k={...N};return delete k[h.id],k});try{const N=await F(h.invocation_id);Le(k=>({...k,[h.invocation_id]:N.checklist}))}catch{ke(N=>({...N,[h.id]:ze}))}finally{Ie(N=>N===h.id?null:N)}}},[F,q]),be=i.useCallback(h=>{if(L===h){Z(null);return}const N=v.find(({id:k})=>k===h);N&&(Z(h),Pe(N))},[v,L,Pe]),De=i.useMemo(()=>{const h={};for(const N of Oe){const k=Un(N,q[N.invocation_id]);(h[k]??(h[k]=[])).push(N)}return h},[Oe,q]),Ne=i.useCallback(h=>{S(h)},[]),Ye=i.useCallback(async h=>{const N=await K(h);S(N),O(!1)},[K]),Ae=i.useCallback(()=>{S(null)},[]),ae={expandedAgentId:L,loadingAgentId:xe,checklistByInvocationId:q,errorByAgentId:ge,definitionNameByRef:le,onToggleAgent:be,onViewAgent:Ne};return s.jsxs("div",{className:"agent-view-frontend agent-view",children:[x&&s.jsxs("div",{className:"agent-view__header",children:[s.jsx(u.Heading,{level:1,children:"Agents"}),s.jsx(u.Button,{variant:"primary",size:"S",iconLeftName:"sparkles",iconLeftScreenReaderText:"Start an agent",onClick:()=>O(!0),children:"Start an agent"})]}),v.length>0&&Ue&&s.jsxs("div",{className:"agent-view__filters",children:[pe&&s.jsxs("div",{className:"agent-view__filter",children:[s.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-institution-filter",children:"Institution"}),s.jsx(u.Combobox,{id:"agent-view-institution-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All institutions",options:ye,value:he,onValueChange:We,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear institutions"})]}),Me&&s.jsxs("div",{className:"agent-view__filter",children:[s.jsx("label",{className:"agent-view__filter-label",htmlFor:"agent-view-agent-filter",children:"Agent"}),s.jsx(u.Combobox,{id:"agent-view-agent-filter",triggerVariant:"button",multiple:!0,searchType:"substring",placeholder:"All agents",options:Se,value:ne,onValueChange:Ve,showSelectionCountBadge:!0,showClearAll:!0,clearAllLabel:"Clear agents"})]})]}),P==="error"?s.jsxs("div",{className:"agent-view__state agent-view__state--error",role:"alert",children:[s.jsx(u.Icon,{name:"triangle-alert",size:24,color:"var(--color-semantic-destructive-600)"}),s.jsx("p",{className:"agent-view__state-message",children:we??Mt}),s.jsx(u.Button,{variant:"secondary",size:"S",onClick:I,children:"Try again"})]}):P==="loading"&&v.length===0?s.jsxs("div",{className:"agent-view__state","aria-live":"polite",children:[s.jsx(u.Icon,{name:"loader",size:24,color:"var(--color-brand-600)",className:"agent-view__progress-icon--spinning",screenReaderText:kt}),s.jsx("p",{className:"agent-view__state-message",children:kt})]}):v.length===0?s.jsx(Rs,{}):s.jsxs("div",{className:"agent-view__board",children:[fs.map(h=>s.jsx(It,{column:qe[h],agents:De[h]??[],...ae},h)),s.jsx("div",{className:"agent-view__split-column",children:vs.map(h=>s.jsx(It,{column:qe[h],agents:De[h]??[],isSplit:!0,...ae},h))})]}),R&&s.jsx(ts,{agent:R,invocationId:R.invocation_id,open:!0,jwt:e,headers:b,agentUrl:r,agentChecklistUrl:l,agentResourcesUrl:o,agentTimelineUrl:p,agentChatUrl:c,agentConversationUrl:g,stopAgentUrl:_,enableUpload:y,initialChecklist:q[R.invocation_id]??null,usePusherToRepoll:T,pusherChannelPrefix:f,subscribeToPusher:G,onClose:Ae},R.id),s.jsx(ns,{open:W,onClose:()=>O(!1),onStart:Ye,agentDefinitions:C})]})},Hn=(e,t)=>{const n=Date.now(),a=t.trim()||e.agent_intent;return{id:`agent-${n}`,invocation_id:`inv-${n}`,agent_definition_ref:e.ref,agent_intent:e.agent_intent,invocation_name:a,application_id:ws,created_by:xs,status:A["generating-a-response"],context_ref:null,checklist_ref:null}};exports.AgentMonitorKanban=$n;exports.AgentServiceClient=Ke;exports.AgentServiceError=fe;exports.AgentView=ts;exports.DEFAULT_PUSHER_CHANNEL_PREFIX=dt;exports.HttpChatConnector=Yt;exports.MESSAGE_TYPE_REPOLL=it;exports.NewAgentModal=ns;exports.PUSHER_AGENT_MESSAGE_EVENT=ot;exports.REPOLL_TARGET=oe;exports.buildAgentFromDefinition=Hn;exports.buildAgentPusherChannel=$t;exports.createHttpChatConnectorFactory=pt;exports.formatUserFileChatCardText=Wt;exports.mapApiAgent=lt;exports.mapApiAgentDefinition=ut;exports.mapApiAgentStatus=Ft;exports.mapApiAgentTimelineResponse=qt;exports.mapApiChecklistEndpointResponse=ht;exports.mapApiChecklistItem=gt;exports.mapApiChecklistResponse=Jt;exports.mapApiChecklistStatus=Bt;exports.mapApiConversationMessages=Vt;exports.mapApiOpeningMessage=Te;exports.mapApiResource=Gt;exports.mapApiResourcesEndpointResponse=zt;exports.mapApiTripOption=un;exports.parseConversationContentCaption=Kt;exports.parseRepollMessages=Ht;exports.useAgentService=Zt;exports.useAgentWorkspace=Qt;
|
package/dist/index.d.ts
CHANGED
|
@@ -62,7 +62,7 @@ export declare type AgentDefinition = {
|
|
|
62
62
|
description: string;
|
|
63
63
|
};
|
|
64
64
|
|
|
65
|
-
export declare const AgentMonitorKanban: ({ jwt, headers, agentDefinitionsUrl, agentsUrl, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, enableUpload, showHeader, institutions, }: AgentMonitorKanbanProps) => JSX_2.Element;
|
|
65
|
+
export declare const AgentMonitorKanban: ({ jwt, headers, agentDefinitionsUrl, agentsUrl, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, stopAgentUrl, enableUpload, showHeader, institutions, usePusherToRepoll, pusherChannelPrefix, subscribeToPusher, }: AgentMonitorKanbanProps) => JSX_2.Element;
|
|
66
66
|
|
|
67
67
|
export declare type AgentMonitorKanbanProps = {
|
|
68
68
|
jwt?: string;
|
|
@@ -77,10 +77,14 @@ export declare type AgentMonitorKanbanProps = {
|
|
|
77
77
|
agentTimelineUrl?: string;
|
|
78
78
|
agentChatUrl: string;
|
|
79
79
|
agentConversationUrl: string;
|
|
80
|
+
stopAgentUrl?: string;
|
|
80
81
|
enableUpload?: boolean;
|
|
81
82
|
/** When true, renders the Agents heading and Start an agent button. Defaults to false. */
|
|
82
83
|
showHeader?: boolean;
|
|
83
84
|
institutions?: InstitutionConfig[];
|
|
85
|
+
usePusherToRepoll?: boolean;
|
|
86
|
+
pusherChannelPrefix?: string;
|
|
87
|
+
subscribeToPusher?: SubscribeToPusher;
|
|
84
88
|
};
|
|
85
89
|
|
|
86
90
|
export declare type AgentResource = {
|
|
@@ -99,7 +103,7 @@ export declare type AgentResourcesPage = {
|
|
|
99
103
|
totalRecords: number;
|
|
100
104
|
};
|
|
101
105
|
|
|
102
|
-
export declare type AgentResourceType = 'document_html' | 'mis_record' | 'workflow' | 'file' | 'link';
|
|
106
|
+
export declare type AgentResourceType = 'document_html' | 'mis_record' | 'workflow' | 'file' | 'user_file' | 'link';
|
|
103
107
|
|
|
104
108
|
export declare class AgentServiceClient {
|
|
105
109
|
private readonly baseUrl;
|
|
@@ -176,6 +180,7 @@ export declare type AgentServiceUrlOverrides = {
|
|
|
176
180
|
agentTimeline?: string;
|
|
177
181
|
agentChat?: string;
|
|
178
182
|
agentConversation?: string;
|
|
183
|
+
stopAgent?: string;
|
|
179
184
|
};
|
|
180
185
|
|
|
181
186
|
export declare type AgentServiceUrls = AgentServiceUrlOverrides;
|
|
@@ -199,7 +204,7 @@ declare type AgentTimelineChatSession = {
|
|
|
199
204
|
timestamp: string;
|
|
200
205
|
};
|
|
201
206
|
|
|
202
|
-
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;
|
|
207
|
+
export declare const AgentView: ({ agent, invocationId, open, onClose, jwt, headers, agentUrl, agentChecklistUrl, agentResourcesUrl, agentTimelineUrl, agentChatUrl, agentConversationUrl, stopAgentUrl, chatId, enableUpload, initialBrief, initialPhase, initialChecklist, usePusherToRepoll, pusherChannelPrefix, subscribeToPusher, }: AgentViewProps) => JSX_2.Element;
|
|
203
208
|
|
|
204
209
|
export declare type AgentViewProps = {
|
|
205
210
|
agent: Agent;
|
|
@@ -214,11 +219,15 @@ export declare type AgentViewProps = {
|
|
|
214
219
|
agentTimelineUrl?: string;
|
|
215
220
|
agentChatUrl: string;
|
|
216
221
|
agentConversationUrl: string;
|
|
222
|
+
stopAgentUrl?: string;
|
|
217
223
|
chatId?: string;
|
|
218
224
|
enableUpload?: boolean;
|
|
219
225
|
initialBrief?: AgentBrief;
|
|
220
226
|
initialPhase?: WorkspacePhase;
|
|
221
227
|
initialChecklist?: AgentChecklistItem[] | null;
|
|
228
|
+
usePusherToRepoll?: boolean;
|
|
229
|
+
pusherChannelPrefix?: string;
|
|
230
|
+
subscribeToPusher?: SubscribeToPusher;
|
|
222
231
|
};
|
|
223
232
|
|
|
224
233
|
export declare type AgentWorkspaceUrls = {
|
|
@@ -228,6 +237,7 @@ export declare type AgentWorkspaceUrls = {
|
|
|
228
237
|
agentTimelineUrl?: string;
|
|
229
238
|
agentChatUrl: string;
|
|
230
239
|
agentConversationUrl: string;
|
|
240
|
+
stopAgentUrl?: string;
|
|
231
241
|
};
|
|
232
242
|
|
|
233
243
|
export declare type ApiAgentDefinition = {
|
|
@@ -281,7 +291,7 @@ export declare type ApiAgentResource = {
|
|
|
281
291
|
last_updated_datetime: string;
|
|
282
292
|
};
|
|
283
293
|
|
|
284
|
-
export declare type ApiAgentResourceType = 'document_html' | 'mis_record' | 'workflow' | 'file' | 'link';
|
|
294
|
+
export declare type ApiAgentResourceType = 'document_html' | 'mis_record' | 'workflow' | 'file' | 'user_file' | 'link';
|
|
285
295
|
|
|
286
296
|
export declare type ApiAgentTimelineActionLogEntry = {
|
|
287
297
|
timestamp: string;
|
|
@@ -348,6 +358,7 @@ declare type ApiChecklistEndpointResponse = ApiChecklistItem[] | {
|
|
|
348
358
|
|
|
349
359
|
export declare type ApiChecklistItem = {
|
|
350
360
|
id?: string;
|
|
361
|
+
item?: string;
|
|
351
362
|
task?: string;
|
|
352
363
|
name?: string;
|
|
353
364
|
label?: string;
|
|
@@ -373,7 +384,7 @@ export declare type ApiConversationMessage = {
|
|
|
373
384
|
|
|
374
385
|
export declare type ApiConversationMessageRole = 'system' | 'user' | 'assistant' | 'tool';
|
|
375
386
|
|
|
376
|
-
export declare type ApiConversationMessageType = 'system' | 'user' | 'assistant' | 'tool_request' | 'tool_response';
|
|
387
|
+
export declare type ApiConversationMessageType = 'system' | 'user' | 'assistant' | 'user_file' | 'tool_request' | 'tool_response';
|
|
377
388
|
|
|
378
389
|
export declare type ApiConversationResponse = {
|
|
379
390
|
session_id: string;
|
|
@@ -418,6 +429,8 @@ export declare type ApiTripOption = {
|
|
|
418
429
|
|
|
419
430
|
export declare const buildAgentFromDefinition: (definition: AgentDefinition, invocationName: string) => Agent;
|
|
420
431
|
|
|
432
|
+
export declare const buildAgentPusherChannel: (prefix: string, agentId: string) => string;
|
|
433
|
+
|
|
421
434
|
export declare interface ChatConnector {
|
|
422
435
|
openingMessage(): ChatMessage;
|
|
423
436
|
start(brief: AgentBrief): Promise<ChatTurn>;
|
|
@@ -431,12 +444,15 @@ export declare type ChatMessage = {
|
|
|
431
444
|
id: string;
|
|
432
445
|
author: ChatMessageAuthor;
|
|
433
446
|
text: string;
|
|
447
|
+
kind?: ChatMessageKind;
|
|
434
448
|
followUpPrompts?: string[];
|
|
435
449
|
pending?: boolean;
|
|
436
450
|
};
|
|
437
451
|
|
|
438
452
|
export declare type ChatMessageAuthor = 'agent' | 'user' | 'system';
|
|
439
453
|
|
|
454
|
+
export declare type ChatMessageKind = 'user_file';
|
|
455
|
+
|
|
440
456
|
export declare type ChatOptions = {
|
|
441
457
|
onEvent?: (event: ApiChatStreamEvent) => void;
|
|
442
458
|
signal?: AbortSignal;
|
|
@@ -464,8 +480,12 @@ export declare const createHttpChatConnectorFactory: (client: AgentServiceClient
|
|
|
464
480
|
invocation_id: string;
|
|
465
481
|
}) => HttpChatConnector;
|
|
466
482
|
|
|
483
|
+
export declare const DEFAULT_PUSHER_CHANNEL_PREFIX = "arbor-agent-";
|
|
484
|
+
|
|
467
485
|
declare type FetchLike = typeof fetch;
|
|
468
486
|
|
|
487
|
+
export declare const formatUserFileChatCardText: (caption: string) => string;
|
|
488
|
+
|
|
469
489
|
export declare class HttpChatConnector implements ChatConnector {
|
|
470
490
|
private readonly client;
|
|
471
491
|
private readonly agentId;
|
|
@@ -530,6 +550,8 @@ export declare const mapApiTripOption: (record: ApiTripOption) => {
|
|
|
530
550
|
name: string;
|
|
531
551
|
};
|
|
532
552
|
|
|
553
|
+
export declare const MESSAGE_TYPE_REPOLL: "MESSAGE_TYPE_REPOLL";
|
|
554
|
+
|
|
533
555
|
export declare const NewAgentModal: (props: NewAgentModalProps) => JSX_2.Element;
|
|
534
556
|
|
|
535
557
|
export declare type NewAgentModalControlledProps = {
|
|
@@ -570,6 +592,29 @@ export declare type NewAgentStartPayload = {
|
|
|
570
592
|
invocationName: string;
|
|
571
593
|
};
|
|
572
594
|
|
|
595
|
+
export declare const parseConversationContentCaption: (content: string) => string;
|
|
596
|
+
|
|
597
|
+
export declare const parseRepollMessages: (payload: unknown) => RepollMessage[];
|
|
598
|
+
|
|
599
|
+
export declare const PUSHER_AGENT_MESSAGE_EVENT: "agentMessage:new_message";
|
|
600
|
+
|
|
601
|
+
export declare const REPOLL_TARGET: {
|
|
602
|
+
readonly all: "ALL";
|
|
603
|
+
readonly checklist: "CHECKLIST";
|
|
604
|
+
readonly resources: "RESOURCES";
|
|
605
|
+
readonly chat: "CHAT";
|
|
606
|
+
readonly timeline: "TIMELINE";
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
export declare type RepollMessage = {
|
|
610
|
+
type: typeof MESSAGE_TYPE_REPOLL;
|
|
611
|
+
target: RepollTarget;
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
export declare type RepollTarget = (typeof REPOLL_TARGET)[keyof typeof REPOLL_TARGET];
|
|
615
|
+
|
|
616
|
+
export declare type SubscribeToPusher = (channel: string, event: string, handler: (payload: unknown) => void) => () => void;
|
|
617
|
+
|
|
573
618
|
export declare type TripOption = {
|
|
574
619
|
id: string;
|
|
575
620
|
name: string;
|