@useago/sdk 1.4.4 → 1.5.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +63 -1
  2. package/dist/AgoClient-5VGybmvz.cjs +8 -0
  3. package/dist/AgoClient-DXrH2AMi.js +964 -0
  4. package/dist/angular.cjs +1 -1
  5. package/dist/angular.d.cts +124 -5
  6. package/dist/angular.d.ts +124 -5
  7. package/dist/angular.js +5 -1
  8. package/dist/autoContinue-CC8K9mBU.js +63 -0
  9. package/dist/autoContinue-CP9pJR-V.cjs +1 -0
  10. package/dist/{createConversationSession-CUkNp6mZ.cjs → createConversationSession-0WTqcCLK.cjs} +1 -1
  11. package/dist/{createConversationSession-QIBN0gLx.js → createConversationSession-DPrrr70o.js} +1 -1
  12. package/dist/createFormCollector-1GKKwQV_.cjs +1 -0
  13. package/dist/{createFormCollector-F3YJfsbg.js → createFormCollector-DYh90kiG.js} +97 -91
  14. package/dist/devtools.d.cts +82 -5
  15. package/dist/devtools.d.ts +82 -5
  16. package/dist/functions-CPs7omgM.cjs +1 -0
  17. package/dist/helpers.cjs +1 -1
  18. package/dist/helpers.d.cts +5 -0
  19. package/dist/helpers.d.ts +5 -0
  20. package/dist/helpers.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.d.cts +147 -7
  23. package/dist/index.d.ts +147 -7
  24. package/dist/index.js +45 -43
  25. package/dist/react.cjs +3 -3
  26. package/dist/react.d.cts +191 -21
  27. package/dist/react.d.ts +191 -21
  28. package/dist/react.js +666 -529
  29. package/dist/testing.cjs +1 -1
  30. package/dist/testing.d.cts +82 -5
  31. package/dist/testing.d.ts +82 -5
  32. package/dist/testing.js +1 -1
  33. package/dist/vue.cjs +1 -1
  34. package/dist/vue.d.cts +82 -5
  35. package/dist/vue.d.ts +82 -5
  36. package/dist/vue.js +1 -1
  37. package/dist/widget.cjs +4 -4
  38. package/dist/widget.d.cts +82 -5
  39. package/dist/widget.d.ts +82 -5
  40. package/dist/widget.js +437 -423
  41. package/llms-full.txt +100 -6
  42. package/package.json +1 -1
  43. package/dist/AgoClient-CLmtYTJx.cjs +0 -8
  44. package/dist/AgoClient-Ozz2b1dQ.js +0 -912
  45. package/dist/createFormCollector-DHT1ObOb.cjs +0 -1
  46. package/dist/functions-Djnq-JAo.cjs +0 -1
  47. package/dist/rolldown-runtime-16Nf8qvH.cjs +0 -1
  48. /package/dist/{createMockClient-BSr-UV8R.cjs → createMockClient-C-wrjb2C.cjs} +0 -0
  49. /package/dist/{createMockClient-bAZ9KBHC.js → createMockClient-we-XoPom.js} +0 -0
  50. /package/dist/{functions-CApuQZ2b.js → functions-tzyOZNp6.js} +0 -0
package/dist/index.js CHANGED
@@ -1,37 +1,38 @@
1
- import { a as h, c as A, d as y, f as C, i as E, l as S, m as b, o as v, p as F, r as M, s as I, t as k, u as T } from "./functions-CApuQZ2b.js";
2
- import { _ as G, a as O, c as _, d as q, f as x, g as L, h as N, l as D, m as d, n as H, o as J, p as R, r as j, s as z, t as c, u as B } from "./AgoClient-Ozz2b1dQ.js";
3
- import { i as $, n as K, r as Q, t as V } from "./createFormCollector-F3YJfsbg.js";
4
- import { t as X } from "./createConversationSession-QIBN0gLx.js";
5
- import { t as Z } from "./createMockClient-bAZ9KBHC.js";
1
+ import { a as h, c as A, d as C, f as y, i as E, l as S, m as b, o as v, p as F, r as M, s as I, t as k, u as T } from "./functions-tzyOZNp6.js";
2
+ import { _ as G, a as N, c as O, d as _, f as q, g as x, h as L, l as D, m as d, n as H, o as J, p as R, r as j, s as z, t as c, u as B } from "./AgoClient-DXrH2AMi.js";
3
+ import { t as $ } from "./autoContinue-CC8K9mBU.js";
4
+ import { i as Q, n as V, r as W, t as X } from "./createFormCollector-DYh90kiG.js";
5
+ import { t as Z } from "./createConversationSession-DPrrr70o.js";
6
+ import { t as oe } from "./createMockClient-we-XoPom.js";
6
7
  import "./testing.js";
7
- function oe(e) {
8
+ function re(e) {
8
9
  return e;
9
10
  }
10
- function te(e, o) {
11
+ function ne(e, o) {
11
12
  return e.on("message:complete", o), () => e.off("message:complete", o);
12
13
  }
13
- function re(e, o) {
14
+ function ae(e, o) {
14
15
  return e.on("message:chunk", o), () => e.off("message:chunk", o);
15
16
  }
16
- function ne(e, o) {
17
+ function se(e, o) {
17
18
  return e.on("message:start", o), () => e.off("message:start", o);
18
19
  }
19
- function ae(e, o) {
20
+ function ie(e, o) {
20
21
  return e.on("message:error", o), () => e.off("message:error", o);
21
22
  }
22
- function se(e, o) {
23
+ function ue(e, o) {
23
24
  return e.on("toolCall:received", o), () => e.off("toolCall:received", o);
24
25
  }
25
- function ie(e, o) {
26
+ function ge(e, o) {
26
27
  return e.on("form:submitted", o), () => e.off("form:submitted", o);
27
28
  }
28
- function ue(e, o) {
29
+ function fe(e, o) {
29
30
  return e.on("form:error", o), () => e.off("form:error", o);
30
31
  }
31
- function ge(e, o) {
32
+ function me(e, o) {
32
33
  return e.on("function:invoke", o), () => e.off("function:invoke", o);
33
34
  }
34
- async function* fe(e, o, u) {
35
+ async function* le(e, o, u) {
35
36
  const n = [];
36
37
  let r = null, a = !1;
37
38
  const g = (s) => {
@@ -94,12 +95,12 @@ function p(e) {
94
95
  debug: f
95
96
  } : null;
96
97
  }
97
- function me(e) {
98
+ function de(e) {
98
99
  const o = p(e);
99
100
  if (!o) throw new d('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.', "config_missing_base_url");
100
101
  return new c(o);
101
102
  }
102
- function le(e, o) {
103
+ function ce(e, o) {
103
104
  return {
104
105
  ...e,
105
106
  handler: o
@@ -109,49 +110,50 @@ export {
109
110
  R as AgoApiError,
110
111
  c as AgoClient,
111
112
  d as AgoError,
112
- N as AgoFunctionError,
113
- L as AgoNetworkError,
113
+ L as AgoFunctionError,
114
+ x as AgoNetworkError,
114
115
  G as AgoStreamError,
115
116
  B as ClientContextRegistry,
116
117
  j as EventEmitter,
117
- q as FunctionRegistry,
118
- _ as SSEHandler,
118
+ _ as FunctionRegistry,
119
+ O as SSEHandler,
120
+ $ as attachAutoContinueAfterNavigation,
119
121
  p as autoDetectConfig,
120
- O as canInlineImage,
122
+ N as canInlineImage,
121
123
  k as copyToClipboard,
122
- me as createAgo,
123
- X as createConversationSession,
124
- V as createFormCollector,
125
- fe as createMessageStream,
126
- Z as createMockClient,
127
- $ as createStore,
128
- oe as defineFunction,
129
- K as deriveFormStatus,
124
+ de as createAgo,
125
+ Z as createConversationSession,
126
+ X as createFormCollector,
127
+ le as createMessageStream,
128
+ oe as createMockClient,
129
+ Q as createStore,
130
+ re as defineFunction,
131
+ V as deriveFormStatus,
130
132
  J as formatFileSize,
131
133
  M as getLocalStorage,
132
134
  E as getUserLocation,
133
135
  h as highlightElement,
134
136
  D as isStreamNetworkError,
135
- Q as loadFormCollector,
136
- x as logger,
137
- ue as onFormError,
138
- ie as onFormSubmitted,
139
- ge as onFunctionInvoke,
140
- te as onMessage,
141
- re as onMessageChunk,
142
- ae as onMessageError,
143
- ne as onMessageStart,
144
- se as onToolCall,
137
+ W as loadFormCollector,
138
+ q as logger,
139
+ fe as onFormError,
140
+ ge as onFormSubmitted,
141
+ me as onFunctionInvoke,
142
+ ne as onMessage,
143
+ ae as onMessageChunk,
144
+ ie as onMessageError,
145
+ se as onMessageStart,
146
+ ue as onToolCall,
145
147
  v as openUrl,
146
148
  z as safeAttachmentUrl,
147
149
  I as scrollToElement,
148
150
  A as setLocalStorage,
149
151
  S as setTheme,
150
152
  T as showConfirmDialog,
151
- y as showNotification,
152
- C as showToast,
153
+ C as showNotification,
154
+ y as showToast,
153
155
  F as submitForm,
154
156
  b as trackEvent,
155
157
  H as validateConfig,
156
- le as withHandler
158
+ ce as withHandler
157
159
  };
package/dist/react.cjs CHANGED
@@ -1,7 +1,7 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("./rolldown-runtime-16Nf8qvH.cjs"),F=require("./AgoClient-CLmtYTJx.cjs"),M=require("./createFormCollector-DHT1ObOb.cjs"),V=require("./createMockClient-BSr-UV8R.cjs");let s=require("react");s=W.__toESM(s,1);let o=require("react/jsx-runtime"),P=require("react-markdown");P=W.__toESM(P,1);let T=require("remark-gfm");T=W.__toESM(T,1);function H(e){const[n,r]=(0,s.useState)(!1),t=(0,s.useRef)(null),a=(0,s.useMemo)(()=>{if(t.current&&(t.current.destroy(),t.current=null),!e)return null;const l=new F.AgoClient(e);return t.current=l,l},[e?.baseUrl,e?.widgetId]);return(0,s.useEffect)(()=>(r(!0),()=>{t.current?.destroy(),t.current=null}),[a]),(0,s.useEffect)(()=>{t.current&&e&&t.current.updateConfig({agent:e.agent,defaultAgentId:e.defaultAgentId,permission:e.permission,userEmail:e.userEmail,userJwt:e.userJwt,debug:e.debug,warnOnEmptyReply:e.warnOnEmptyReply})},[e?.agent,e?.defaultAgentId,e?.permission,e?.userEmail,e?.userJwt,e?.debug,e?.warnOnEmptyReply]),{client:a,isReady:n}}var D=(0,s.createContext)(null),Y=({children:e,client:n,tools:r,helpers:t,pageContext:a,...l})=>{const{client:d}=H(n?null:l),c=n||d;return(0,s.useEffect)(()=>{if(!(!r||r.length===0)){for(const p of r)c.register(p);return()=>{for(const p of r)c.unregisterFunction(p.name)}}},[c,r]),(0,s.useEffect)(()=>{if(!t)return;const p=[];return Promise.resolve().then(()=>require("./functions-Djnq-JAo.cjs")).then(u=>u.functions_exports).then(u=>{for(const[b,v]of Object.entries(t)){const I=u[b];if(!I){console.warn(`[AGO] Unknown helper: "${b}"`);continue}const g=v===!0?I:{...I,handler:v};c.register(g),p.push(g.name)}}),()=>{for(const u of p)c.unregisterFunction(u)}},[c,t]),(0,s.useEffect)(()=>{a==="auto"&&c.enableAutoPageContext()},[c,a]),(0,o.jsx)(D.Provider,{value:c,children:e})};function E(){const e=(0,s.useContext)(D);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function _(){return(0,s.useContext)(D)}function L({client:e,conversationId:n}={}){const r=_(),t=e||r;if(!t)throw new Error("useMessages requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[a,l]=(0,s.useState)([]),[d,c]=(0,s.useState)(n),[p,u]=(0,s.useState)(!1),[b,v]=(0,s.useState)(null);(0,s.useEffect)(()=>{n&&n!==d&&(c(n),I(n))},[n]);const I=async g=>{try{l((await t.getMessages(g)).filter(m=>!m.hidden))}catch(m){v(m instanceof Error?m:new Error("Failed to load messages"))}};return(0,s.useEffect)(()=>{const g=f=>f==="IN_PROGRESS"||f==="WAITING_CLIENT",m=f=>{d||c(f.conversationId),u(!0),l(x=>{const C=x.findIndex(h=>h.id===f.messageId);return C>=0?x.map((h,N)=>N===C?{...h,status:"IN_PROGRESS"}:h):x.some(h=>h.role==="assistant"&&g(h.status))?x:[...x,{id:f.messageId,conversationId:f.conversationId,content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}]})},S=f=>{l(x=>{const C=x.findIndex(h=>h.id===f.messageId);return C<0?x:x.map((h,N)=>N===C?{...h,content:h.content+f.content}:h)})},w=f=>{l(x=>{let C=-1;for(let h=x.length-1;h>=0;h--)if(x[h].role==="assistant"&&g(x[h].status)){C=h;break}return C<0?x:[...x.slice(0,C),{...x[C],...f},...x.slice(C+1)]})},i=f=>{l(x=>{const C=x.findIndex(h=>h.id===f.id);return C>=0?[...x.slice(0,C),f,...x.slice(C+1)]:[...x,f]}),u(!1)},y=f=>{v(new Error(f.error)),u(!1)};return t.on("message:start",m),t.on("message:chunk",S),t.on("message:answer-complete",w),t.on("message:complete",i),t.on("message:error",y),()=>{t.off("message:start",m),t.off("message:chunk",S),t.off("message:answer-complete",w),t.off("message:complete",i),t.off("message:error",y)}},[t,d]),{messages:a,isLoading:p,error:b,sendMessage:(0,s.useCallback)(async(g,m)=>{u(!0),v(null);const S={id:`temp-${Date.now()}`,conversationId:d||"",content:g,role:"user",status:"DONE",attachments:m&&m.length>0?F.attachmentsFromFiles(m):void 0,createdAt:new Date},w={id:`temp-assistant-${Date.now()}`,conversationId:d||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};l(i=>[...i,S,w]);try{const i=await t.sendMessage(g,{conversationId:d,files:m});return i.conversationId&&!d&&c(i.conversationId),l(y=>{const f=y.filter(C=>!C.id.startsWith("temp-")),x={...S,id:S.id.replace("temp-","user-"),conversationId:i.conversationId};return f.some(C=>C.id===i.id)?[...f,x].sort((C,h)=>new Date(C.createdAt).getTime()-new Date(h.createdAt).getTime()):[...f,x,i]}),i}catch(i){return v(i instanceof Error?i:new Error("Failed to send message")),u(!1),l(y=>y.filter(f=>!f.id.startsWith("temp-"))),null}},[t,d]),clearMessages:(0,s.useCallback)(()=>{l([]),c(void 0),v(null)},[]),conversationId:d}}var q=({onSend:e,disabled:n=!1,placeholder:r="Type a message...",allowFiles:t=!1,className:a=""})=>{const[l,d]=(0,s.useState)(""),[c,p]=(0,s.useState)([]),u=(0,s.useRef)(null),b=(0,s.useRef)(null),v=(0,s.useCallback)(()=>{const i=b.current;if(!i)return;const y=110;i.style.height="auto",i.style.height=`${Math.min(i.scrollHeight+2,y)}px`,i.style.overflowY=i.scrollHeight+2>y?"auto":"hidden"},[]),I=(0,s.useCallback)(i=>{i.preventDefault(),(l.trim()||c.length>0)&&(e(l.trim(),c.length>0?c:void 0),d(""),p([]),requestAnimationFrame(v))},[l,c,e,v]),g=(0,s.useCallback)(i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),I(i))},[I]),m=(0,s.useCallback)(i=>{const y=Array.from(i.target.files||[]);p(f=>[...f,...y])},[]),S=(0,s.useCallback)(i=>{p(y=>y.filter((f,x)=>x!==i))},[]),w=l.trim()||c.length>0;return(0,o.jsxs)("form",{onSubmit:I,className:`ago-chat-input ${a}`,style:{display:"flex",flexDirection:"column",gap:"8px",padding:"12px 16px",borderTop:"1px solid #dee3e8",backgroundColor:"#fff"},children:[c.length>0&&(0,o.jsx)("div",{className:"ago-chat-input__files",style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:c.map((i,y)=>(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",backgroundColor:"#f0f2f5",borderRadius:"6px",fontSize:"12px",color:"#30373e"},children:[(0,o.jsx)("span",{style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.name}),(0,o.jsx)("button",{type:"button",onClick:()=>S(y),"aria-label":`Remove ${i.name}`,style:{border:"none",background:"none",cursor:"pointer",padding:"0",color:"#6b6d6f",fontSize:"14px",lineHeight:1},children:"×"})]},y))}),(0,o.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"flex-end"},children:[t&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{type:"button",onClick:()=>u.current?.click(),disabled:n,"aria-label":"Attach file",style:{padding:"8px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:n?"not-allowed":"pointer",color:"#6b6d6f",fontSize:"16px",lineHeight:1},children:"+"}),(0,o.jsx)("input",{ref:u,type:"file",multiple:!0,onChange:m,style:{display:"none"}})]}),(0,o.jsx)("textarea",{ref:b,value:l,onChange:i=>{d(i.target.value),v()},onKeyDown:g,placeholder:r,"aria-label":r,disabled:n,rows:1,style:{flex:1,padding:"10px 14px",border:"1px solid #dee3e8",borderRadius:"20px",resize:"none",outline:"none",boxSizing:"border-box",maxHeight:"110px",overflowY:"hidden",fontFamily:"inherit",fontSize:"16px",lineHeight:1.4,color:"#30373e",backgroundColor:"#f8f8f8",transition:"border-color 0.15s"},onFocus:i=>{i.currentTarget.style.borderColor="#1b5fc4"},onBlur:i=>{i.currentTarget.style.borderColor="#dee3e8"}}),(0,o.jsx)("button",{type:"submit",disabled:n||!w,style:{padding:"10px 18px",border:"none",borderRadius:"20px",backgroundColor:n||!w?"#b5bfc8":"#03182f",color:"#fff",cursor:n||!w?"not-allowed":"pointer",fontWeight:500,fontSize:"16px",transition:"background-color 0.15s"},children:"Send"})]})]})},X=({href:e,children:n,...r})=>(0,o.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"#1b5fc4",textDecoration:"underline"},...r,children:n}),Q=({children:e,...n})=>(0,o.jsx)("p",{style:{margin:"0 0 8px 0",lineHeight:"1.6"},...n,children:e}),R=(e,n)=>{const r=({children:t,...a})=>s.default.createElement(`h${e}`,{style:{margin:"16px 0 8px 0",fontSize:n,fontWeight:600,lineHeight:"1.3"},...a},t);return r.displayName=`MarkdownHeading${e}`,r},Z=({children:e,...n})=>(0,o.jsx)("ul",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"disc",listStylePosition:"outside"},...n,children:e}),ee=({children:e,...n})=>(0,o.jsx)("ol",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"decimal",listStylePosition:"outside"},...n,children:e}),te=({children:e,...n})=>(0,o.jsx)("li",{style:{display:"list-item",margin:"2px 0",lineHeight:"1.6"},...n,children:e}),ne=({className:e,children:n,...r})=>e!==void 0||String(n).includes(`
2
- `)?(0,o.jsx)("code",{style:{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:'"IBM Plex Mono", monospace'},...r,children:n}):(0,o.jsx)("code",{style:{background:"#f0f2f5",padding:"2px 5px",borderRadius:"4px",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},...r,children:n}),re=({children:e,...n})=>(0,o.jsx)("pre",{style:{margin:"0 0 8px 0"},...n,children:e}),oe=({children:e,...n})=>(0,o.jsx)("blockquote",{style:{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"},...n,children:e}),se=({children:e,...n})=>(0,o.jsx)("div",{style:{overflowX:"auto",margin:"0 0 8px 0"},children:(0,o.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"13px"},...n,children:e})}),ae=({children:e,...n})=>(0,o.jsx)("th",{style:{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:600},...n,children:e}),ie=({children:e,...n})=>(0,o.jsx)("td",{style:{border:"1px solid #dee3e8",padding:"6px 10px"},...n,children:e}),le=({alt:e,...n})=>(0,o.jsx)("img",{alt:e??"",style:{maxWidth:"100%",borderRadius:"8px",margin:"4px 0"},...n}),ce=e=>(0,o.jsx)("hr",{style:{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"},...e}),de={a:X,p:Q,h1:R(1,"20px"),h2:R(2,"18px"),h3:R(3,"16px"),h4:R(4,"15px"),h5:R(5,"14px"),h6:R(6,"13px"),ul:Z,ol:ee,li:te,code:ne,pre:re,blockquote:oe,table:se,th:ae,td:ie,img:le,hr:ce},ue=[T.default],$=({content:e})=>(0,o.jsx)(P.default,{remarkPlugins:ue,components:de,children:e}),fe=({attachment:e,isUser:n})=>{const r=F.safeAttachmentUrl(e.url);if(F.canInlineImage(e))return(0,o.jsx)("a",{href:r,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-block",textDecoration:"none"},children:(0,o.jsx)("img",{src:r,alt:e.name,loading:"lazy",style:{maxWidth:"180px",maxHeight:"160px",objectFit:"cover",borderRadius:"10px",border:"1px solid #dee3e8",display:"block"}})});const t=F.formatFileSize(e.fileSize),a=(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{style:{fontSize:"16px",lineHeight:1,flexShrink:0},"aria-hidden":!0,children:"📄"}),(0,o.jsxs)("span",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[(0,o.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"160px"},title:e.name,children:e.name}),t&&(0,o.jsx)("span",{style:{fontSize:"11px",color:"#6b6d6f"},children:t})]})]}),l={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"10px",border:"1px solid #dee3e8",backgroundColor:n?"rgba(255,255,255,0.12)":"#fff",color:n?"#fff":"#30373e",fontSize:"13px",textDecoration:"none",maxWidth:"220px"};return r?(0,o.jsx)("a",{href:r,target:"_blank",rel:"noopener noreferrer",style:l,children:a}):(0,o.jsx)("div",{style:l,children:a})},ge=({source:e,index:n})=>{const r=(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px",width:"100%",minWidth:0},children:[(0,o.jsx)("div",{style:{flexShrink:0,width:"18px",height:"18px",borderRadius:"3px",border:"1px solid #1b5fc4",color:"#1b5fc4",fontSize:"11px",fontWeight:500,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f0f4ff"},children:n+1}),(0,o.jsx)("div",{style:{fontSize:"12px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#30373e"},title:e.title,children:e.title})]}),t={display:"flex",alignItems:"center",padding:"8px 10px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:e.url?"pointer":"default",textDecoration:"none",color:"inherit",minWidth:0,transition:"border-color 0.15s"};return e.url?(0,o.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",style:t,onMouseEnter:a=>{a.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:a=>{a.currentTarget.style.borderColor="#dee3e8"},children:r}):(0,o.jsx)("div",{style:t,children:r})},pe=()=>(0,o.jsxs)("div",{style:{display:"flex",gap:"4px",padding:"4px 0"},children:[[0,1,2].map(e=>(0,o.jsx)("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#b5bfc8",animation:"ago-pulse 1.2s ease-in-out infinite",animationDelay:`${e*.2}s`}},e)),(0,o.jsx)("style",{children:`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var Z=Object.create,T=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,ee=Object.getOwnPropertyNames,te=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,re=(e,t)=>{let n={};for(var o in e)T(n,o,{get:e[o],enumerable:!0});return t||T(n,Symbol.toStringTag,{value:"Module"}),n},oe=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var r=ee(t),i=0,g=r.length,c;i<g;i++)c=r[i],!ne.call(e,c)&&c!==n&&T(e,c,{get:(p=>t[p]).bind(null,c),enumerable:!(o=Q(t,c))||o.enumerable});return e},W=(e,t,n)=>(n=e!=null?Z(te(e)):{},oe(t||!e||!e.__esModule?T(n,"default",{value:e,enumerable:!0}):n,e));const F=require("./AgoClient-5VGybmvz.cjs"),se=require("./autoContinue-CP9pJR-V.cjs"),E=require("./createFormCollector-1GKKwQV_.cjs"),ae=require("./createMockClient-C-wrjb2C.cjs");let s=require("react");s=W(s,1);let a=require("react/jsx-runtime"),D=require("react-markdown");D=W(D,1);let O=require("remark-gfm");O=W(O,1);function B(e){const[t,n]=(0,s.useState)(!1),o=(0,s.useRef)(null),r=(0,s.useMemo)(()=>{if(o.current&&(o.current.destroy(),o.current=null),!e)return null;const i=new F.AgoClient(e);return o.current=i,i},[e?.baseUrl,e?.widgetId]);return(0,s.useEffect)(()=>(n(!0),()=>{o.current?.destroy(),o.current=null}),[r]),(0,s.useEffect)(()=>{o.current&&e&&o.current.updateConfig({agent:e.agent,defaultAgentId:e.defaultAgentId,permission:e.permission,userEmail:e.userEmail,userJwt:e.userJwt,debug:e.debug,warnOnEmptyReply:e.warnOnEmptyReply})},[e?.agent,e?.defaultAgentId,e?.permission,e?.userEmail,e?.userJwt,e?.debug,e?.warnOnEmptyReply]),{client:r,isReady:t}}var q=(0,s.createContext)(null),ie=({children:e,client:t,tools:n,helpers:o,pageContext:r,...i})=>{const{client:g}=B(t?null:i),c=t||g;return(0,s.useEffect)(()=>{if(!(!n||n.length===0)){for(const p of n)c.register(p);return()=>{for(const p of n)c.unregisterFunction(p.name)}}},[c,n]),(0,s.useEffect)(()=>{if(!o)return;const p=[];return Promise.resolve().then(()=>require("./functions-CPs7omgM.cjs")).then(f=>f.functions_exports).then(f=>{for(const[x,S]of Object.entries(o)){const I=f[x];if(!I){console.warn(`[AGO] Unknown helper: "${x}"`);continue}const k=S===!0?I:{...I,handler:S};c.register(k),p.push(k.name)}}),()=>{for(const f of p)c.unregisterFunction(f)}},[c,o]),(0,s.useEffect)(()=>{r==="auto"&&c.enableAutoPageContext()},[c,r]),(0,a.jsx)(q.Provider,{value:c,children:e})};function R(){const e=(0,s.useContext)(q);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function P(){return(0,s.useContext)(q)}function L({client:e,conversationId:t}={}){const n=P(),o=e||n;if(!o)throw new Error("useMessages requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[r,i]=(0,s.useState)([]),[g,c]=(0,s.useState)(t),[p,f]=(0,s.useState)(!1),[x,S]=(0,s.useState)(null);(0,s.useEffect)(()=>{t&&t!==g&&(c(t),I(t))},[t]);const I=async k=>{try{i((await o.getMessages(k)).filter(A=>!A.hidden))}catch(A){S(A instanceof Error?A:new Error("Failed to load messages"))}};return(0,s.useEffect)(()=>{const k=u=>u==="IN_PROGRESS"||u==="WAITING_CLIENT",A=u=>{g||c(u.conversationId),f(!0),i(y=>{const w=y.findIndex(C=>C.id===u.messageId);return w>=0?y.map((C,_)=>_===w?{...C,status:"IN_PROGRESS"}:C):y.some(C=>C.role==="assistant"&&k(C.status))?y:[...y,{id:u.messageId,conversationId:u.conversationId,content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}]})},d=u=>{i(y=>{const w=y.findIndex(C=>C.id===u.messageId);return w<0?y:y.map((C,_)=>_===w?{...C,content:C.content+u.content}:C)})},h=u=>{i(y=>{let w=-1;for(let C=y.length-1;C>=0;C--)if(y[C].role==="assistant"&&k(y[C].status)){w=C;break}return w<0?y:[...y.slice(0,w),{...y[w],...u},...y.slice(w+1)]})},l=u=>{i(y=>{const w=y.findIndex(C=>C.id===u.id);return w>=0?[...y.slice(0,w),u,...y.slice(w+1)]:[...y,u]}),f(!1)},b=u=>{S(new Error(u.error)),f(!1)};return o.on("message:start",A),o.on("message:chunk",d),o.on("message:answer-complete",h),o.on("message:complete",l),o.on("message:error",b),()=>{o.off("message:start",A),o.off("message:chunk",d),o.off("message:answer-complete",h),o.off("message:complete",l),o.off("message:error",b)}},[o,g]),{messages:r,isLoading:p,error:x,sendMessage:(0,s.useCallback)(async(k,A)=>{f(!0),S(null);const d={id:`temp-${Date.now()}`,conversationId:g||"",content:k,role:"user",status:"DONE",attachments:A&&A.length>0?F.attachmentsFromFiles(A):void 0,createdAt:new Date},h={id:`temp-assistant-${Date.now()}`,conversationId:g||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};i(l=>[...l,d,h]);try{const l=await o.sendMessage(k,{conversationId:g,files:A});return l.conversationId&&!g&&c(l.conversationId),i(b=>{const u=b.filter(w=>!w.id.startsWith("temp-")),y={...d,id:d.id.replace("temp-","user-"),conversationId:l.conversationId};return u.some(w=>w.id===l.id)?[...u,y].sort((w,C)=>new Date(w.createdAt).getTime()-new Date(C.createdAt).getTime()):[...u,y,l]}),l}catch(l){return S(l instanceof Error?l:new Error("Failed to send message")),f(!1),i(b=>b.filter(u=>!u.id.startsWith("temp-"))),null}},[o,g]),clearMessages:(0,s.useCallback)(()=>{i([]),c(void 0),S(null)},[]),conversationId:g}}var G=({onSend:e,disabled:t=!1,placeholder:n="Type a message...",allowFiles:o=!1,className:r=""})=>{const[i,g]=(0,s.useState)(""),[c,p]=(0,s.useState)([]),f=(0,s.useRef)(null),x=(0,s.useRef)(null),S=(0,s.useCallback)(()=>{const l=x.current;if(!l)return;const b=110;l.style.height="auto",l.style.height=`${Math.min(l.scrollHeight+2,b)}px`,l.style.overflowY=l.scrollHeight+2>b?"auto":"hidden"},[]),I=(0,s.useCallback)(l=>{l.preventDefault(),(i.trim()||c.length>0)&&(e(i.trim(),c.length>0?c:void 0),g(""),p([]),requestAnimationFrame(S))},[i,c,e,S]),k=(0,s.useCallback)(l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),I(l))},[I]),A=(0,s.useCallback)(l=>{const b=Array.from(l.target.files||[]);p(u=>[...u,...b])},[]),d=(0,s.useCallback)(l=>{p(b=>b.filter((u,y)=>y!==l))},[]),h=i.trim()||c.length>0;return(0,a.jsxs)("form",{onSubmit:I,className:`ago-chat-input ${r}`,style:{display:"flex",flexDirection:"column",gap:"8px",padding:"12px 16px",borderTop:"1px solid #dee3e8",backgroundColor:"#fff"},children:[c.length>0&&(0,a.jsx)("div",{className:"ago-chat-input__files",style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:c.map((l,b)=>(0,a.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",backgroundColor:"#f0f2f5",borderRadius:"6px",fontSize:"12px",color:"#30373e"},children:[(0,a.jsx)("span",{style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l.name}),(0,a.jsx)("button",{type:"button",onClick:()=>d(b),"aria-label":`Remove ${l.name}`,style:{border:"none",background:"none",cursor:"pointer",padding:"0",color:"#6b6d6f",fontSize:"14px",lineHeight:1},children:"×"})]},b))}),(0,a.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"flex-end"},children:[o&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("button",{type:"button",onClick:()=>f.current?.click(),disabled:t,"aria-label":"Attach file",style:{padding:"8px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:t?"not-allowed":"pointer",color:"#6b6d6f",fontSize:"16px",lineHeight:1},children:"+"}),(0,a.jsx)("input",{ref:f,type:"file",multiple:!0,onChange:A,style:{display:"none"}})]}),(0,a.jsx)("textarea",{ref:x,value:i,onChange:l=>{g(l.target.value),S()},onKeyDown:k,placeholder:n,"aria-label":n,disabled:t,rows:1,style:{flex:1,padding:"10px 14px",border:"1px solid #dee3e8",borderRadius:"20px",resize:"none",outline:"none",boxSizing:"border-box",maxHeight:"110px",overflowY:"hidden",fontFamily:"inherit",fontSize:"16px",lineHeight:1.4,color:"#30373e",backgroundColor:"#f8f8f8",transition:"border-color 0.15s"},onFocus:l=>{l.currentTarget.style.borderColor="#1b5fc4"},onBlur:l=>{l.currentTarget.style.borderColor="#dee3e8"}}),(0,a.jsx)("button",{type:"submit",disabled:t||!h,style:{padding:"10px 18px",border:"none",borderRadius:"20px",backgroundColor:t||!h?"#b5bfc8":"#03182f",color:"#fff",cursor:t||!h?"not-allowed":"pointer",fontWeight:500,fontSize:"16px",transition:"background-color 0.15s"},children:"Send"})]})]})},le=({href:e,children:t,...n})=>(0,a.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"#1b5fc4",textDecoration:"underline"},...n,children:t}),ce=({children:e,...t})=>(0,a.jsx)("p",{style:{margin:"0 0 8px 0",lineHeight:"1.6"},...t,children:e}),M=(e,t)=>{const n=({children:o,...r})=>s.default.createElement(`h${e}`,{style:{margin:"16px 0 8px 0",fontSize:t,fontWeight:600,lineHeight:"1.3"},...r},o);return n.displayName=`MarkdownHeading${e}`,n},ue=({children:e,...t})=>(0,a.jsx)("ul",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"disc",listStylePosition:"outside"},...t,children:e}),de=({children:e,...t})=>(0,a.jsx)("ol",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"decimal",listStylePosition:"outside"},...t,children:e}),fe=({children:e,...t})=>(0,a.jsx)("li",{style:{display:"list-item",margin:"2px 0",lineHeight:"1.6"},...t,children:e}),ge=({className:e,children:t,...n})=>e!==void 0||String(t).includes(`
2
+ `)?(0,a.jsx)("code",{style:{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:'"IBM Plex Mono", monospace'},...n,children:t}):(0,a.jsx)("code",{style:{background:"#f0f2f5",padding:"2px 5px",borderRadius:"4px",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},...n,children:t}),pe=({children:e,...t})=>(0,a.jsx)("pre",{style:{margin:"0 0 8px 0"},...t,children:e}),me=({children:e,...t})=>(0,a.jsx)("blockquote",{style:{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"},...t,children:e}),xe=({children:e,...t})=>(0,a.jsx)("div",{style:{overflowX:"auto",margin:"0 0 8px 0"},children:(0,a.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"13px"},...t,children:e})}),he=({children:e,...t})=>(0,a.jsx)("th",{style:{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:600},...t,children:e}),ye=({children:e,...t})=>(0,a.jsx)("td",{style:{border:"1px solid #dee3e8",padding:"6px 10px"},...t,children:e}),ve=({alt:e,...t})=>(0,a.jsx)("img",{alt:e??"",style:{maxWidth:"100%",borderRadius:"8px",margin:"4px 0"},...t}),be=e=>(0,a.jsx)("hr",{style:{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"},...e}),Ce={a:le,p:ce,h1:M(1,"20px"),h2:M(2,"18px"),h3:M(3,"16px"),h4:M(4,"15px"),h5:M(5,"14px"),h6:M(6,"13px"),ul:ue,ol:de,li:fe,code:ge,pre:pe,blockquote:me,table:xe,th:he,td:ye,img:ve,hr:be},we=[O.default],K=({content:e})=>(0,a.jsx)(D.default,{remarkPlugins:we,components:Ce,children:e}),Se=({attachment:e,isUser:t})=>{const n=F.safeAttachmentUrl(e.url);if(F.canInlineImage(e))return(0,a.jsx)("a",{href:n,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-block",textDecoration:"none"},children:(0,a.jsx)("img",{src:n,alt:e.name,loading:"lazy",style:{maxWidth:"180px",maxHeight:"160px",objectFit:"cover",borderRadius:"10px",border:"1px solid #dee3e8",display:"block"}})});const o=F.formatFileSize(e.fileSize),r=(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)("span",{style:{fontSize:"16px",lineHeight:1,flexShrink:0},"aria-hidden":!0,children:"📄"}),(0,a.jsxs)("span",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[(0,a.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"160px"},title:e.name,children:e.name}),o&&(0,a.jsx)("span",{style:{fontSize:"11px",color:"#6b6d6f"},children:o})]})]}),i={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"10px",border:"1px solid #dee3e8",backgroundColor:t?"rgba(255,255,255,0.12)":"#fff",color:t?"#fff":"#30373e",fontSize:"13px",textDecoration:"none",maxWidth:"220px"};return n?(0,a.jsx)("a",{href:n,target:"_blank",rel:"noopener noreferrer",style:i,children:r}):(0,a.jsx)("div",{style:i,children:r})},ke=({source:e,index:t})=>{const n=(0,a.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px",width:"100%",minWidth:0},children:[(0,a.jsx)("div",{style:{flexShrink:0,width:"18px",height:"18px",borderRadius:"3px",border:"1px solid #1b5fc4",color:"#1b5fc4",fontSize:"11px",fontWeight:500,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f0f4ff"},children:t+1}),(0,a.jsx)("div",{style:{fontSize:"12px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#30373e"},title:e.title,children:e.title})]}),o={display:"flex",alignItems:"center",padding:"8px 10px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:e.url?"pointer":"default",textDecoration:"none",color:"inherit",minWidth:0,transition:"border-color 0.15s"};return e.url?(0,a.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",style:o,onMouseEnter:r=>{r.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:r=>{r.currentTarget.style.borderColor="#dee3e8"},children:n}):(0,a.jsx)("div",{style:o,children:n})},Ae=()=>(0,a.jsxs)("div",{style:{display:"flex",gap:"4px",padding:"4px 0"},children:[[0,1,2].map(e=>(0,a.jsx)("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#b5bfc8",animation:"ago-pulse 1.2s ease-in-out infinite",animationDelay:`${e*.2}s`}},e)),(0,a.jsx)("style",{children:`
3
3
  @keyframes ago-pulse {
4
4
  0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); }
5
5
  40% { opacity: 1; transform: scale(1); }
6
6
  }
7
- `})]}),B=({message:e,className:n="",showAgentName:r=!1,isLast:t=!1,onFollowUpClick:a})=>{const l=e.role==="user",d=e.status==="IN_PROGRESS"||e.status==="WAITING_CLIENT";return(0,o.jsxs)("div",{className:`ago-message ago-message--${e.role} ${n}`,style:{display:"flex",flexDirection:"column",alignItems:l?"flex-end":"flex-start",marginBottom:"16px"},children:[!l&&r&&e.agent&&(0,o.jsx)("div",{className:"ago-message__agent",style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"13px",fontWeight:500,color:"#30373e",marginBottom:"6px",padding:"0 4px"},children:e.agent.displayName||e.agent.name}),!l&&e.sources&&e.sources.length>0&&(0,o.jsx)("div",{className:"ago-message__sources",style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px",marginBottom:"10px",width:"100%",maxWidth:"85%"},children:e.sources.map((c,p)=>(0,o.jsx)(ge,{source:c,index:p},c.id))}),e.attachments&&e.attachments.length>0&&(0,o.jsx)("div",{className:"ago-message__attachments",style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"6px",justifyContent:l?"flex-end":"flex-start",maxWidth:"75%"},children:e.attachments.map(c=>(0,o.jsx)(fe,{attachment:c,isUser:l},c.id))}),(e.content||d)&&(0,o.jsx)("div",{className:"ago-message__content",style:{maxWidth:l?"75%":"100%",padding:l?"10px 14px":"2px 8px",borderRadius:l?"16px":"0",backgroundColor:l?"#03182f":"transparent",color:l?"#fff":"#30373e",wordBreak:"break-word",fontSize:"16px",lineHeight:"1.6"},children:e.content?(0,o.jsx)($,{content:e.content}):d&&(0,o.jsx)(pe,{})}),t&&e.followUpReplies&&e.followUpReplies.length>0&&(0,o.jsx)("div",{className:"ago-message__followups",style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"10px"},children:e.followUpReplies.map((c,p)=>(0,o.jsx)("button",{type:"button",className:"ago-message__followup-btn",disabled:!a,onClick:a?()=>a(c):void 0,style:{minHeight:"36px",padding:"6px 14px",fontSize:"13px",borderRadius:"16px",border:"1px solid #dee3e8",backgroundColor:"#fff",color:"#30373e",cursor:a?"pointer":"default",transition:"border-color 0.15s"},onMouseEnter:u=>{u.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:u=>{u.currentTarget.style.borderColor="#dee3e8"},children:c},p))})]})},xe=({client:e,conversationId:n,title:r="Chat",welcomeMessage:t="Hello! How can I help you today?",placeholder:a="Type a message...",allowFiles:l=!1,height:d=500,logoUrl:c,showAgentName:p=!1,forms:u,onFollowUpClick:b,className:v="",onMessageSent:I,onMessageReceived:g})=>{const m=(0,s.useRef)(null),S=_(),w=e??S,{messages:i,isLoading:y,error:f,sendMessage:x}=L({client:e,conversationId:n});(0,s.useEffect)(()=>{if(!w||!u||u.length===0)return;let k=!1;const A=[];return Promise.all(u.map(j=>j.schema!=null?Promise.resolve(M.createFormCollector(j)):M.loadFormCollector(w,j))).then(j=>{if(!k)for(const J of j)A.push(J.install(w))}).catch(()=>{}),()=>{k=!0,A.forEach(j=>j())}},[w,u?JSON.stringify(u.map(k=>[k.name,k.schema??null,k.submit??!1,k.description??null])):""]),(0,s.useEffect)(()=>{m.current?.scrollIntoView({behavior:"smooth"})},[i]),(0,s.useEffect)(()=>{const k=i[i.length-1];k&&k.role==="assistant"&&k.status==="DONE"&&g&&g({id:k.id,content:k.content})},[i,g]);const C=async(k,A)=>{I?.(k),await x(k,A)},h=i[i.length-1],N=y&&h?.role==="assistant"&&(h.status==="IN_PROGRESS"||h.status==="WAITING_CLIENT"),K=b===!1?void 0:b??(k=>C(k));return(0,o.jsxs)("div",{className:`ago-chat-widget ${v}`,style:{display:"flex",flexDirection:"column",height:typeof d=="number"?`${d}px`:d,border:"1px solid #dee3e8",borderRadius:"16px",overflow:"hidden",backgroundColor:"#fff",fontFamily:'"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',textAlign:"left",boxShadow:"rgba(15, 15, 15, 0.08) 0px 2px 16px 0px"},children:[(0,o.jsxs)("div",{className:"ago-chat-widget__header",style:{padding:"14px 16px",borderBottom:"1px solid #dee3e8",backgroundColor:"#03182f",color:"#e8f0fe",display:"flex",alignItems:"center",gap:"10px"},children:[c&&(0,o.jsx)("img",{src:c,alt:"Logo",style:{height:"24px",width:"auto"}}),(0,o.jsx)("h3",{style:{margin:0,fontSize:"15px",fontWeight:600},children:r})]}),(0,o.jsxs)("div",{className:"ago-chat-widget__messages",role:"log","aria-live":"polite","aria-relevant":"additions text","aria-atomic":!1,style:{flex:1,overflow:"auto",padding:"16px",backgroundColor:"#fbfbfb"},children:[i.length===0?(0,o.jsx)("div",{style:{textAlign:"center",color:"#6b6d6f",padding:"24px 16px",fontSize:"16px",lineHeight:"1.5"},children:t}):i.map((k,A)=>(0,o.jsx)(B,{message:k,showAgentName:p,isLast:A===i.length-1,onFollowUpClick:K},k.id)),f&&(0,o.jsx)("div",{role:"alert",style:{padding:"10px 14px",backgroundColor:"#fef2f2",color:"#dc2626",borderRadius:"12px",marginTop:"8px",fontSize:"13px",border:"1px solid #fecaca"},children:f.message}),(0,o.jsx)("div",{ref:m})]}),(0,o.jsx)(q,{onSend:C,disabled:N,placeholder:a,allowFiles:l})]})};function G({client:e,autoLoad:n=!0}={}){const r=_(),t=e||r;if(!t)throw new Error("useConversation requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[a,l]=(0,s.useState)([]),[d,c]=(0,s.useState)(null),[p,u]=(0,s.useState)(!1),[b,v]=(0,s.useState)(null),I=(0,s.useCallback)(async()=>{u(!0),v(null);try{l(await t.getConversations())}catch(S){v(S instanceof Error?S:new Error("Failed to load conversations"))}finally{u(!1)}},[t]),g=(0,s.useCallback)(async S=>{u(!0),v(null);try{c(await t.getConversation(S))}catch(w){v(w instanceof Error?w:new Error("Failed to load conversation"))}finally{u(!1)}},[t]),m=(0,s.useCallback)(()=>{c(null)},[]);return(0,s.useEffect)(()=>{n&&I()},[n,I]),{conversations:a,currentConversation:d,isLoading:p,error:b,selectConversation:g,startNewConversation:m,refreshConversations:I}}function me(e={}){const n=_(),r=e.client||n;if(!r)throw new Error("useChat requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const t=L({client:r,conversationId:e.conversationId}),a=G({client:r,autoLoad:e.autoLoad});return{messages:t.messages,isLoading:t.isLoading,error:t.error||a.error,sendMessage:t.sendMessage,clearMessages:t.clearMessages,conversationId:t.conversationId,conversations:a.conversations,currentConversation:a.currentConversation,isConversationsLoading:a.isLoading,selectConversation:a.selectConversation,startNewConversation:a.startNewConversation,refreshConversations:a.refreshConversations}}function he(e,n){const r=E(),{name:t,description:a,parameters:l,handler:d,maxResultBytes:c}=typeof e=="string"?{name:e,...n}:e,p=(0,s.useRef)(d);p.current=d,(0,s.useEffect)(()=>{const u=b=>p.current(b);return r.registerFunction(t,u,{description:a,parameters:l,maxResultBytes:c}),()=>{r.unregisterFunction(t)}},[r,t,a,l,c])}function ye(e,n){const r=E(),t=(0,s.useRef)(e);t.current=e,(0,s.useEffect)(()=>(r.registerNavigationFunction(a=>t.current(a),n),()=>{r.unregisterNavigationFunction()}),[r,n])}function be(e,n){const r=E(),t=n?.functionName??"setPageState",a=(0,s.useRef)(e);a.current=e,(0,s.useEffect)(()=>{const l=a.current.map(d=>{const c=()=>a.current.find(p=>p.name===d.name)??d;return{name:d.name,description:d.description,schema:d.schema,get:d.get?()=>c().get?.():void 0,set:p=>c().set(p)}});return r.registerPageStateFunction(l,{functionName:t}),()=>{r.unregisterPageStateFunction(t)}},[r,t])}var ve="You have navigated the user to a new page. That page now exposes its editable state through the available setPageState function, and its current values in the page context. If the user's latest request also asked to change something on this page, call setPageState now to apply exactly those changes and nothing else. Otherwise, reply with a short confirmation only.";function z(e){return{navigationFunctions:e?.navigationFunctions??["navigateToPage"],pageStateFunctionName:e?.pageStateFunctionName??"setPageState",continuationPrompt:e?.continuationPrompt??ve,maxDepth:e?.maxDepth??1,readinessTimeoutMs:e?.readinessTimeoutMs??4e3,settleMs:e?.settleMs??150,enabled:e?.enabled??!0}}function Ce(e){const n=E(),r=(0,s.useRef)(z(e));r.current=z(e),(0,s.useEffect)(()=>{const t={navigated:!1,pausedTurnNavigated:!1,depth:0,runId:0,ourSendPending:!1},a=()=>n.getRegisteredFunctions().some(g=>g.name===r.current.pageStateFunctionName),l=g=>new Promise(m=>{let S=!1;const w=x=>{S||(S=!0,clearTimeout(f),n.off("context:changed",y),m(x))},i=()=>setTimeout(()=>w(g===t.runId&&a()),r.current.settleMs),y=()=>{if(g!==t.runId)return w(!1);a()&&(n.off("context:changed",y),i())},f=setTimeout(()=>w(!1),r.current.readinessTimeoutMs);a()?i():n.on("context:changed",y)}),d=async g=>{const m=++t.runId;if(!(!await l(m)||m!==t.runId)){t.depth+=1,t.ourSendPending=!0;try{await n.sendMessage(r.current.continuationPrompt,{conversationId:g,hidden:!0})}catch{t.ourSendPending=!1}}},c=g=>{r.current.navigationFunctions.includes(g.functionName)&&(t.navigated=!0)},p=n.registerResumeGate(async()=>{r.current.enabled&&t.pausedTurnNavigated&&(t.pausedTurnNavigated=!1,await l(++t.runId))}),u=()=>{t.pausedTurnNavigated=t.navigated,t.navigated=!1},b=()=>{t.ourSendPending||(t.depth=0,t.runId+=1)},v=g=>{t.ourSendPending=!1;const m=t.navigated;t.navigated=!1,r.current.enabled&&m&&(t.depth>=r.current.maxDepth||d(g.conversationId))},I=()=>{t.ourSendPending=!1};return n.on("function:invoke",c),n.on("message:start",b),n.on("message:waiting-client",u),n.on("message:complete",v),n.on("message:error",I),()=>{t.runId+=1,p(),n.off("function:invoke",c),n.off("message:start",b),n.off("message:waiting-client",u),n.off("message:complete",v),n.off("message:error",I)}},[n])}function we(e,n){const r=E(),t=(0,s.useId)(),a=n??t,l=(0,s.useRef)(e);l.current=e;const d=typeof e=="function";(0,s.useEffect)(()=>{if(typeof l.current=="function"){const c=()=>l.current();return r.addDynamicContext(a,c),()=>{r.removeDynamicContext(a)}}return r.setContext(a,l.current),()=>{r.removeContext(a)}},[r,a,d,d?"":JSON.stringify(e)])}function U(e){return(0,s.useSyncExternalStore)(e.subscribe,e.get,e.get)}var O={missing:[],complete:!1};function Se(e){const n=E(),r=e.schema!=null,t=JSON.stringify(e.schema??null),a=e.submit,l=a?typeof a=="string"?`client:${a}`:a.via==="backend"?"backend":"handler"in a?"client:handler":`client:${a.url}`:"none",d=JSON.stringify(e.initialValues??null),c=(0,s.useMemo)(()=>r?M.createFormCollector(e):null,[r,e.name,t,l,d,e.autoSubmit]),[p,u]=(0,s.useState)({collector:null,loading:!r,error:null});(0,s.useEffect)(()=>{if(r)return;let y=!1;return u({collector:null,loading:!0,error:null}),M.loadFormCollector(n,e).then(f=>{y||u({collector:f,loading:!1,error:null})}).catch(f=>{y||u({collector:null,loading:!1,error:f instanceof Error?f:new Error(String(f))})}),()=>{y=!0}},[n,r,e.name,l,d,e.autoSubmit]);const b=r?c:p.collector,v=r?!1:p.loading,I=r?null:p.error;(0,s.useEffect)(()=>{if(b)return b.install(n)},[n,b]);const g=(0,s.useMemo)(()=>M.createStore({values:e.initialValues??{},submitted:!1}),[d]),m=U(b?.store??g),S=(0,s.useMemo)(()=>b?.getStatus()??O,[m,b]),w=(0,s.useMemo)(()=>({...m,...S}),[m,S]),i=(0,s.useMemo)(()=>({name:e.name,store:g,functions:[],contextKey:`form:${e.name}`,contextProvider:()=>({name:`Form: ${e.name}`,description:""}),install:()=>()=>{},hydrate:()=>{},submit:async()=>({ok:!1,error:"Form definition not loaded yet."}),getValues:()=>g.get().values,setValues:()=>{},reset:()=>{},getStatus:()=>O}),[e.name,g]);return{...b??i,state:w,loading:v,error:I}}exports.AgoProvider=Y;exports.ChatInput=q;exports.ChatWidget=xe;exports.Markdown=$;exports.Message=B;exports.createFormCollector=M.createFormCollector;exports.createMockClient=V.createMockClient;exports.deriveFormStatus=M.deriveFormStatus;exports.loadFormCollector=M.loadFormCollector;exports.useAgo=H;exports.useAgoAutoContinueAfterNavigation=Ce;exports.useAgoClient=E;exports.useAgoContext=we;exports.useAgoFunction=he;exports.useAgoNavigation=ye;exports.useAgoPageState=be;exports.useAgoStore=U;exports.useChat=me;exports.useConversation=G;exports.useFormCollector=Se;exports.useMessages=L;exports.useOptionalAgoClient=_;
7
+ `})]}),U=({message:e,className:t="",showAgentName:n=!1,isLast:o=!1,onFollowUpClick:r})=>{const i=e.role==="user",g=e.status==="IN_PROGRESS"||e.status==="WAITING_CLIENT";return(0,a.jsxs)("div",{className:`ago-message ago-message--${e.role} ${t}`,style:{display:"flex",flexDirection:"column",alignItems:i?"flex-end":"flex-start",marginBottom:"16px"},children:[!i&&n&&e.agent&&(0,a.jsx)("div",{className:"ago-message__agent",style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"13px",fontWeight:500,color:"#30373e",marginBottom:"6px",padding:"0 4px"},children:e.agent.displayName||e.agent.name}),!i&&e.sources&&e.sources.length>0&&(0,a.jsx)("div",{className:"ago-message__sources",style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px",marginBottom:"10px",width:"100%",maxWidth:"85%"},children:e.sources.map((c,p)=>(0,a.jsx)(ke,{source:c,index:p},c.id))}),e.attachments&&e.attachments.length>0&&(0,a.jsx)("div",{className:"ago-message__attachments",style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"6px",justifyContent:i?"flex-end":"flex-start",maxWidth:"75%"},children:e.attachments.map(c=>(0,a.jsx)(Se,{attachment:c,isUser:i},c.id))}),(e.content||g)&&(0,a.jsx)("div",{className:"ago-message__content",style:{maxWidth:i?"75%":"100%",padding:i?"10px 14px":"2px 8px",borderRadius:i?"16px":"0",backgroundColor:i?"#03182f":"transparent",color:i?"#fff":"#30373e",wordBreak:"break-word",fontSize:"16px",lineHeight:"1.6"},children:e.content?(0,a.jsx)(K,{content:e.content}):g&&(0,a.jsx)(Ae,{})}),o&&e.followUpReplies&&e.followUpReplies.length>0&&(0,a.jsx)("div",{className:"ago-message__followups",style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"10px"},children:e.followUpReplies.map((c,p)=>(0,a.jsx)("button",{type:"button",className:"ago-message__followup-btn",disabled:!r,onClick:r?()=>r(c):void 0,style:{minHeight:"36px",padding:"6px 14px",fontSize:"13px",borderRadius:"16px",border:"1px solid #dee3e8",backgroundColor:"#fff",color:"#30373e",cursor:r?"pointer":"default",transition:"border-color 0.15s"},onMouseEnter:f=>{f.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:f=>{f.currentTarget.style.borderColor="#dee3e8"},children:c},p))})]})},je=({client:e,conversationId:t,title:n="Chat",welcomeMessage:o="Hello! How can I help you today?",placeholder:r="Type a message...",allowFiles:i=!1,height:g=500,logoUrl:c,showAgentName:p=!1,forms:f,onFollowUpClick:x,className:S="",onMessageSent:I,onMessageReceived:k})=>{const A=(0,s.useRef)(null),d=P(),h=e??d,{messages:l,isLoading:b,error:u,sendMessage:y}=L({client:e,conversationId:t});(0,s.useEffect)(()=>{if(!h||!f||f.length===0)return;let m=!1;const j=[];return Promise.all(f.map(N=>N.schema!=null?Promise.resolve(E.createFormCollector(N)):E.loadFormCollector(h,N))).then(N=>{if(!m)for(const X of N)j.push(X.install(h))}).catch(()=>{}),()=>{m=!0,j.forEach(N=>N())}},[h,f?JSON.stringify(f.map(m=>[m.name,m.schema??null,m.submit??!1,m.description??null])):""]),(0,s.useEffect)(()=>{A.current?.scrollIntoView({behavior:"smooth"})},[l]),(0,s.useEffect)(()=>{const m=l[l.length-1];m&&m.role==="assistant"&&m.status==="DONE"&&k&&k({id:m.id,content:m.content})},[l,k]);const w=async(m,j)=>{I?.(m),await y(m,j)},C=l[l.length-1],_=b&&C?.role==="assistant"&&(C.status==="IN_PROGRESS"||C.status==="WAITING_CLIENT"),v=x===!1?void 0:x??(m=>w(m));return(0,a.jsxs)("div",{className:`ago-chat-widget ${S}`,style:{display:"flex",flexDirection:"column",height:typeof g=="number"?`${g}px`:g,border:"1px solid #dee3e8",borderRadius:"16px",overflow:"hidden",backgroundColor:"#fff",fontFamily:'"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',textAlign:"left",boxShadow:"rgba(15, 15, 15, 0.08) 0px 2px 16px 0px"},children:[(0,a.jsxs)("div",{className:"ago-chat-widget__header",style:{padding:"14px 16px",borderBottom:"1px solid #dee3e8",backgroundColor:"#03182f",color:"#e8f0fe",display:"flex",alignItems:"center",gap:"10px"},children:[c&&(0,a.jsx)("img",{src:c,alt:"Logo",style:{height:"24px",width:"auto"}}),(0,a.jsx)("h3",{style:{margin:0,fontSize:"15px",fontWeight:600},children:n})]}),(0,a.jsxs)("div",{className:"ago-chat-widget__messages",role:"log","aria-live":"polite","aria-relevant":"additions text","aria-atomic":!1,style:{flex:1,overflow:"auto",padding:"16px",backgroundColor:"#fbfbfb"},children:[l.length===0?(0,a.jsx)("div",{style:{textAlign:"center",color:"#6b6d6f",padding:"24px 16px",fontSize:"16px",lineHeight:"1.5"},children:o}):l.map((m,j)=>(0,a.jsx)(U,{message:m,showAgentName:p,isLast:j===l.length-1,onFollowUpClick:v},m.id)),u&&(0,a.jsx)("div",{role:"alert",style:{padding:"10px 14px",backgroundColor:"#fef2f2",color:"#dc2626",borderRadius:"12px",marginTop:"8px",fontSize:"13px",border:"1px solid #fecaca"},children:u.message}),(0,a.jsx)("div",{ref:A})]}),(0,a.jsx)(G,{onSend:w,disabled:_,placeholder:r,allowFiles:i})]})};function J({client:e,autoLoad:t=!0}={}){const n=P(),o=e||n;if(!o)throw new Error("useConversation requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[r,i]=(0,s.useState)([]),[g,c]=(0,s.useState)(null),[p,f]=(0,s.useState)(!1),[x,S]=(0,s.useState)(null),I=(0,s.useCallback)(async()=>{f(!0),S(null);try{i(await o.getConversations())}catch(d){S(d instanceof Error?d:new Error("Failed to load conversations"))}finally{f(!1)}},[o]),k=(0,s.useCallback)(async d=>{f(!0),S(null);try{c(await o.getConversation(d))}catch(h){S(h instanceof Error?h:new Error("Failed to load conversation"))}finally{f(!1)}},[o]),A=(0,s.useCallback)(()=>{c(null)},[]);return(0,s.useEffect)(()=>{t&&I()},[t,I]),{conversations:r,currentConversation:g,isLoading:p,error:x,selectConversation:k,startNewConversation:A,refreshConversations:I}}function Ie(e={}){const t=P(),n=e.client||t;if(!n)throw new Error("useChat requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const o=L({client:n,conversationId:e.conversationId}),r=J({client:n,autoLoad:e.autoLoad});return{messages:o.messages,isLoading:o.isLoading,error:o.error||r.error,sendMessage:o.sendMessage,clearMessages:o.clearMessages,conversationId:o.conversationId,conversations:r.conversations,currentConversation:r.currentConversation,isConversationsLoading:r.isLoading,selectConversation:r.selectConversation,startNewConversation:r.startNewConversation,refreshConversations:r.refreshConversations}}function Ne(e,t){const n=R(),{name:o,description:r,parameters:i,handler:g,maxResultBytes:c,requiresApproval:p}=typeof e=="string"?{name:e,...t}:e,f=(0,s.useRef)(g);f.current=g,(0,s.useEffect)(()=>{const x=S=>f.current(S);return n.registerFunction(o,x,{description:r,parameters:i,maxResultBytes:c,requiresApproval:p}),()=>{n.unregisterFunction(o)}},[n,o,r,i,c,p])}function _e(e,t){const n=R(),o=(0,s.useRef)(e);o.current=e,(0,s.useEffect)(()=>(n.registerNavigationFunction(r=>o.current(r),t),()=>{n.unregisterNavigationFunction()}),[n,t])}function Ee(e,t){const n=R(),o=t?.functionName??"setPageState",r=t?.requiresApproval,i=(0,s.useRef)(e);i.current=e,(0,s.useEffect)(()=>{const g=i.current.map(c=>{const p=()=>i.current.find(f=>f.name===c.name)??c;return{name:c.name,description:c.description,schema:c.schema,get:c.get?()=>p().get?.():void 0,set:f=>p().set(f)}});return n.registerPageStateFunction(g,{functionName:o,requiresApproval:r}),()=>{n.unregisterPageStateFunction(o)}},[n,o,r])}function Re(e){const t=R(),n=(0,s.useRef)(e);n.current=e,(0,s.useEffect)(()=>se.attachAutoContinueAfterNavigation(t,()=>n.current),[t])}var Me=new Set(["awaiting-approval"]);function V(e){switch(e){case"progress_indicator":return"progress";case"reasoning":return"reasoning";case"confirmation_input":return"confirmation";case"form":return"form";default:return"status"}}function Fe(e){return e.type==="client_function"?e.functionName==="navigateToPage"?"navigation":"action":V(e.type)}function z(e,t){const n=(e??"").toLowerCase();return n.includes("reject")?"rejected":n.includes("error")||n.includes("fail")?"error":n.includes("done")||n.includes("complet")?"done":(n.includes("waiting")||n.includes("pending"))&&(t==="confirmation"||t==="form")?"awaiting-approval":"running"}function H(e){return typeof e!="string"||!e?"page":e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase()).trim()}function Pe(e){switch(e.kind){case"navigation":return`Navigating to ${H(e.arguments?.page)}`;case"action":return e.functionName==="setPageState"?"Updating the page":e.functionName==="openFilteredConversations"?"Opening conversations":e.toolDisplayName||e.message||H(e.functionName)||"Working";case"progress":return e.message||"Working";case"reasoning":return e.message||"Thinking";case"confirmation":return e.message||"Waiting for your confirmation";case"form":return e.message||e.toolDisplayName||"Please fill in the form";default:return e.message||e.toolDisplayName||e.toolName||"Working"}}function Te(e={}){const{includeReasoning:t=!1,labelFor:n}=e,o=P(),r=e.client||o;if(!r)throw new F.AgoError("useAgoActivity requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.","provider_missing_client");const[i,g]=(0,s.useState)([]),c=(0,s.useRef)(new Set),p=(0,s.useRef)(void 0),f=(0,s.useRef)(n);f.current=n;const x=(0,s.useCallback)((d,h)=>{g(l=>{const b=l.findIndex(y=>y.id===d),u={...b>=0?l[b]:{id:d,kind:"status",label:"",status:"running",requiresApproval:!1,createdAt:new Date},...h};return u.label=f.current?.(u)??Pe(u),b>=0?[...l.slice(0,b),u,...l.slice(b+1)]:[...l,u]})},[]);(0,s.useEffect)(()=>{const d=v=>{p.current=v.messageId},h=v=>{const m=V(v.type);m==="reasoning"&&!t||x(v.id,{kind:m,status:z(v.status,m),messageId:p.current,toolName:v.toolName,toolDisplayName:v.toolDisplayName,message:v.message,data:v.data,formSchema:v.formSchema,requiresApproval:m==="confirmation"||m==="form"})},l=v=>{v.invocationId&&x(v.invocationId,{kind:v.functionName==="navigateToPage"?"navigation":"action",status:"running",messageId:p.current,functionName:v.functionName,arguments:v.arguments})},b=v=>{v.invocationId&&x(v.invocationId,{kind:v.functionName==="navigateToPage"?"navigation":"action",status:"awaiting-approval",messageId:p.current,functionName:v.functionName,arguments:v.arguments,requiresApproval:!0})},u=v=>{if(!v.invocationId)return;const m=v.result,j=typeof v.result=="object"&&m!==null&&m.approved===!1&&m.reason==="user_rejected";x(v.invocationId,{status:v.error?"error":j?"rejected":"done",requiresApproval:!1})},y=v=>{for(const m of v.messages??[])if(m.role==="assistant")for(const j of m.toolCalls??[]){const N=Fe(j);N==="reasoning"&&!t||/waiting/i.test(j.status??"")||x(j.id,{kind:N,status:z(j.status,N),messageId:m.id,toolName:j.toolName,toolDisplayName:j.toolDisplayName,functionName:j.functionName,arguments:j.arguments,message:j.message,data:j.data,formSchema:j.formSchema,requiresApproval:N==="confirmation"||N==="form"})}},w=v=>{g(m=>m.map(j=>j.status==="running"||j.status==="awaiting-approval"?{...j,status:v}:j))},C=()=>w("done"),_=()=>w("error");return r.on("message:start",d),r.on("toolCall:received",h),r.on("function:invoke",l),r.on("function:awaiting-approval",b),r.on("function:result",u),r.on("conversation:loaded",y),r.on("message:complete",C),r.on("message:error",_),()=>{r.off("message:start",d),r.off("toolCall:received",h),r.off("function:invoke",l),r.off("function:awaiting-approval",b),r.off("function:result",u),r.off("conversation:loaded",y),r.off("message:complete",C),r.off("message:error",_)}},[r,t,x]);const S=(0,s.useCallback)(async d=>{const h=i.find(l=>l.id===d);!h||h.status!=="awaiting-approval"||c.current.has(d)||h.kind!=="form"&&(c.current.add(d),x(d,{status:"running",requiresApproval:!1}),h.functionName?await r.approveFunction(d):await r.confirmToolCall(d))},[r,i,x]),I=(0,s.useCallback)(async d=>{const h=i.find(l=>l.id===d);!h||h.status!=="awaiting-approval"||c.current.has(d)||(c.current.add(d),x(d,{status:"rejected",requiresApproval:!1}),h.functionName?await r.rejectFunction(d):await r.rejectToolCall(d))},[r,i,x]),k=(0,s.useCallback)(async(d,h)=>{x(d,{status:"running",requiresApproval:!1}),await r.submitToolCallForm(d,h),x(d,{status:"done"})},[r,x]),A=(0,s.useCallback)(()=>{c.current.clear(),g([])},[]);return{items:i,latest:i.length>0?i[i.length-1]:void 0,isAwaitingApproval:i.some(d=>Me.has(d.status)),approve:S,reject:I,submitForm:k,clear:A}}function De(e,t){const n=R(),o=(0,s.useId)(),r=t??o,i=(0,s.useRef)(e);i.current=e;const g=typeof e=="function";(0,s.useEffect)(()=>{if(typeof i.current=="function"){const c=()=>i.current();return n.addDynamicContext(r,c),()=>{n.removeDynamicContext(r)}}return n.setContext(r,i.current),()=>{n.removeContext(r)}},[n,r,g,g?"":JSON.stringify(e)])}function Y(e){return(0,s.useSyncExternalStore)(e.subscribe,e.get,e.get)}var $={missing:[],complete:!1};function Oe(e){const t=R(),n=e.schema!=null,o=JSON.stringify(e.schema??null),r=e.submit,i=r?typeof r=="string"?`client:${r}`:r.via==="backend"?"backend":"handler"in r?"client:handler":`client:${r.url}`:"none",g=JSON.stringify(e.initialValues??null),c=(0,s.useMemo)(()=>n?E.createFormCollector(e):null,[n,e.name,o,i,g,e.autoSubmit]),[p,f]=(0,s.useState)({collector:null,loading:!n,error:null});(0,s.useEffect)(()=>{if(n)return;let b=!1;return f({collector:null,loading:!0,error:null}),E.loadFormCollector(t,e).then(u=>{b||f({collector:u,loading:!1,error:null})}).catch(u=>{b||f({collector:null,loading:!1,error:u instanceof Error?u:new Error(String(u))})}),()=>{b=!0}},[t,n,e.name,i,g,e.autoSubmit]);const x=n?c:p.collector,S=n?!1:p.loading,I=n?null:p.error;(0,s.useEffect)(()=>{if(x)return x.install(t)},[t,x]);const k=(0,s.useMemo)(()=>E.createStore({values:e.initialValues??{},submitted:!1}),[g]),A=Y(x?.store??k),d=(0,s.useMemo)(()=>x?.getStatus()??$,[A,x]),h=(0,s.useMemo)(()=>({...A,...d}),[A,d]),l=(0,s.useMemo)(()=>({name:e.name,store:k,functions:[],contextKey:`form:${e.name}`,contextProvider:()=>({name:`Form: ${e.name}`,description:""}),definitionContextKey:`form:${e.name}:definition`,definitionContextProvider:()=>({name:`Form definition: ${e.name}`,description:"",stable:!0}),install:()=>()=>{},hydrate:()=>{},submit:async()=>({ok:!1,error:"Form definition not loaded yet."}),getValues:()=>k.get().values,setValues:()=>{},reset:()=>{},getStatus:()=>$}),[e.name,k]);return{...x??l,state:h,loading:S,error:I}}exports.AgoProvider=ie;exports.ChatInput=G;exports.ChatWidget=je;exports.Markdown=K;exports.Message=U;exports.__exportAll=re;exports.createFormCollector=E.createFormCollector;exports.createMockClient=ae.createMockClient;exports.deriveFormStatus=E.deriveFormStatus;exports.loadFormCollector=E.loadFormCollector;exports.useAgo=B;exports.useAgoActivity=Te;exports.useAgoAutoContinueAfterNavigation=Re;exports.useAgoClient=R;exports.useAgoContext=De;exports.useAgoFunction=Ne;exports.useAgoNavigation=_e;exports.useAgoPageState=Ee;exports.useAgoStore=Y;exports.useChat=Ie;exports.useConversation=J;exports.useFormCollector=Oe;exports.useMessages=L;exports.useOptionalAgoClient=P;
package/dist/react.d.cts CHANGED
@@ -1,5 +1,41 @@
1
1
  import { default as default_2 } from 'react';
2
2
 
3
+ /**
4
+ * One normalized entry in the agent's activity feed. Merges a tool call
5
+ * (`toolCall:received`) or a client-function invocation (`function:invoke` /
6
+ * `function:awaiting-approval` / `function:result`) into a single shape.
7
+ */
8
+ export declare interface AgoActivityItem {
9
+ /** Stable id — the tool-call id or the function invocationId. */
10
+ id: string;
11
+ kind: AgoActivityKind;
12
+ /** Human label, e.g. "Navigating to Products". Override via `labelFor`. */
13
+ label: string;
14
+ status: AgoActivityStatus;
15
+ /** The assistant message this activity belongs to (when known). */
16
+ messageId?: string;
17
+ toolName?: string;
18
+ toolDisplayName?: string;
19
+ functionName?: string;
20
+ arguments?: Record<string, unknown>;
21
+ message?: string;
22
+ data?: Record<string, unknown>;
23
+ formSchema?: FormSchema;
24
+ /** True when this item waits on the user before it runs. */
25
+ requiresApproval: boolean;
26
+ createdAt: Date;
27
+ }
28
+
29
+ /**
30
+ * The kind of thing the agent is doing, normalized across the two wire sources
31
+ * (tool calls and client-function invocations) into one vocabulary the UI can
32
+ * switch on.
33
+ */
34
+ export declare type AgoActivityKind = "navigation" | "action" | "status" | "progress" | "reasoning" | "confirmation" | "form";
35
+
36
+ /** Where the item is in its lifecycle. */
37
+ export declare type AgoActivityStatus = "running" | "done" | "error" | "awaiting-approval" | "rejected";
38
+
3
39
  /**
4
40
  * Agent information
5
41
  */
@@ -60,6 +96,12 @@ declare class AgoClient {
60
96
  private warnedEmptyConversations;
61
97
  /** Paused turns awaiting auto-resume, keyed by assistant message id. */
62
98
  private pendingResumes;
99
+ /**
100
+ * Client function invocations held pending user approval, keyed by
101
+ * invocationId (the tool-call id). Populated when {@link requiresApproval}
102
+ * matches; drained by {@link approveFunction} / {@link rejectFunction}.
103
+ */
104
+ private pendingApprovals;
63
105
  /** App-provided gate deciding WHEN a paused turn resumes (see {@link registerResumeGate}). */
64
106
  private resumeGate;
65
107
  constructor(config: AgoConfig);
@@ -110,6 +152,24 @@ declare class AgoClient {
110
152
  */
111
153
  private maybeFlagEmptyReply;
112
154
  private handleClientFunctionInvocation;
155
+ /**
156
+ * Whether a client function invocation must wait for explicit user approval.
157
+ * True when the {@link AgoConfig.approvalPolicy} returns true OR the function
158
+ * was registered with `requiresApproval: true` — the two OR together.
159
+ */
160
+ private requiresApproval;
161
+ /**
162
+ * Approve a client function call held by the approval gate: run it, submit its
163
+ * result, and let the paused turn resume. No-op if the invocation is unknown
164
+ * (already handled, or never gated).
165
+ */
166
+ approveFunction(invocationId: string): Promise<void>;
167
+ /**
168
+ * Reject a client function call held by the approval gate: submit a rejection
169
+ * result so the agent sees the user declined, and let the paused turn resume
170
+ * (the agent decides what to do next). No-op if the invocation is unknown.
171
+ */
172
+ rejectFunction(invocationId: string): Promise<void>;
113
173
  /**
114
174
  * Get list of conversations
115
175
  */
@@ -139,8 +199,10 @@ declare class AgoClient {
139
199
  *
140
200
  * Opt-in on purpose — re-running functions on reload can be surprising (e.g. a
141
201
  * navigation function would navigate again), so the app decides. Returns the
142
- * resumed turn's final message, or `null` when there was nothing to resume or
143
- * some waiting function is not registered on this page.
202
+ * resumed turn's final message, or `null` when there was nothing to resume,
203
+ * some waiting function is not registered on this page, or a waiting call is
204
+ * gated by the approval policy (it is held for `approveFunction` /
205
+ * `rejectFunction` and the turn stays paused, exactly as on the live stream).
144
206
  */
145
207
  resumePendingClientFunctions(conversation: Conversation): Promise<AgoMessage | null>;
146
208
  /**
@@ -435,6 +497,15 @@ declare interface AgoClientEvents {
435
497
  "toolCall:received": ToolCallData;
436
498
  "toolCall:form": ToolCallData;
437
499
  "function:invoke": ClientFunctionInvocation;
500
+ /**
501
+ * A client function call is held pending the user's approval (pause mode +
502
+ * an {@link AgoConfig.approvalPolicy}/`requiresApproval` match). The turn stays
503
+ * at `WAITING_CLIENT`; call `approveFunction(invocationId)` to run it and
504
+ * resume, or `rejectFunction(invocationId)` to decline. Fires after
505
+ * `function:invoke` (which still fires for every call) and instead of the
506
+ * call running immediately.
507
+ */
508
+ "function:awaiting-approval": ClientFunctionInvocation;
438
509
  "function:result": {
439
510
  invocationId: string;
440
511
  result: unknown;
@@ -495,14 +566,28 @@ export declare interface AgoConfig {
495
566
  warnOnEmptyReply?: boolean;
496
567
  /**
497
568
  * How the agent loop treats client function calls (requires backend support):
498
- * - `"placeholder"` (default): the turn continues immediately on a placeholder
499
- * result; the real result is only visible to the agent on later turns.
500
- * - `"pause"`: the turn stops on client function call(s) with status
569
+ * - `"pause"` (default): the turn stops on client function call(s) with status
501
570
  * `WAITING_CLIENT`; once every result is submitted, the SDK resumes the SAME
502
571
  * turn via `POST /messages/{id}/continue`, so the agent sees the real results.
572
+ * - `"placeholder"` (legacy): the turn continues immediately on a placeholder
573
+ * result; the real result is only visible to the agent on later turns.
503
574
  * Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
504
575
  */
505
576
  clientFunctionsMode?: ClientFunctionsMode;
577
+ /**
578
+ * Gate client function calls behind explicit user approval. Return `true` for
579
+ * an invocation the user must approve/reject before it runs; return `false`
580
+ * (or omit the policy) to let it run immediately as before.
581
+ *
582
+ * Only effective in pause mode (`clientFunctionsMode: "pause"`) — a gated call
583
+ * holds at `WAITING_CLIENT`, the SDK emits `function:awaiting-approval`, and it
584
+ * runs (and the turn resumes) only after `approveFunction(invocationId)`; a
585
+ * `rejectFunction(invocationId)` submits a rejection so the agent sees the
586
+ * decline. In placeholder mode there is no pause to hold, so the policy is a
587
+ * no-op and the call runs normally. A per-function `requiresApproval: true`
588
+ * also gates a call; the policy and the flag OR together.
589
+ */
590
+ approvalPolicy?: (invocation: ClientFunctionInvocation) => boolean;
506
591
  /**
507
592
  * Max serialized size (bytes) of a client function result before the SDK
508
593
  * replaces it with a flagged, truncated preview. Everything a handler
@@ -560,6 +645,11 @@ export declare interface AgoMessage {
560
645
  export declare interface AgoPageStateOptions {
561
646
  /** Name of the synthesized client function. Defaults to "setPageState". */
562
647
  functionName?: string;
648
+ /**
649
+ * Require explicit user approval before this state change runs. See
650
+ * {@link AgoConfig.approvalPolicy} — pause mode only. Defaults to `false`.
651
+ */
652
+ requiresApproval?: boolean;
563
653
  }
564
654
 
565
655
  /**
@@ -728,6 +818,11 @@ declare interface ClientFunctionDefinition {
728
818
  * `Infinity` disables the guard for this function.
729
819
  */
730
820
  maxResultBytes?: number;
821
+ /**
822
+ * Require explicit user approval before this function runs. See
823
+ * {@link AgoConfig.approvalPolicy} — pause mode only. ORs with the policy.
824
+ */
825
+ requiresApproval?: boolean;
731
826
  }
732
827
 
733
828
  /**
@@ -754,6 +849,11 @@ declare type ClientFunctionRegisterOptions = Omit<ClientFunctionSchema, "name">
754
849
  * disables the guard for this function.
755
850
  */
756
851
  maxResultBytes?: number;
852
+ /**
853
+ * Require explicit user approval before this function runs. See
854
+ * {@link AgoConfig.approvalPolicy} — pause mode only. ORs with the policy.
855
+ */
856
+ requiresApproval?: boolean;
757
857
  };
758
858
 
759
859
  /**
@@ -794,6 +894,19 @@ declare interface ContextEntry {
794
894
  description?: string;
795
895
  /** Arbitrary structured data the AI should know about */
796
896
  data?: Record<string, unknown>;
897
+ /**
898
+ * Marks the entry as constant for the whole conversation. The backend then
899
+ * pins it right after the system prompt, where LLM providers cache it across
900
+ * turns, instead of re-processing it next to every new user message.
901
+ *
902
+ * Only set this when the entry's content is byte-identical on every message
903
+ * of a conversation (a schema, a capability list, static instructions). A
904
+ * stable entry that changes between messages invalidates the provider's
905
+ * cache for the entire conversation history, which costs more than leaving
906
+ * the flag off. Default: `false` (re-sent near the newest user message).
907
+ * Backends that don't know the flag ignore it.
908
+ */
909
+ stable?: boolean;
797
910
  }
798
911
 
799
912
  /**
@@ -898,10 +1011,22 @@ export declare interface FormCollector<V = Record<string, unknown>> {
898
1011
  store: Store<FormCollectorState<V>>;
899
1012
  /** Client functions to register: `[update]` or `[update, submit]`. */
900
1013
  functions: ClientFunctionDefinition[];
901
- /** Dynamic-context key under which the form state is exposed. */
1014
+ /** Dynamic-context key under which the live form state is exposed. */
902
1015
  contextKey: string;
903
- /** Dynamic-context provider — re-read on every message. */
1016
+ /**
1017
+ * Dynamic-context provider for the live form state (phase, values, missing)
1018
+ * — re-read on every message. The schema itself rides in the companion
1019
+ * {@link definitionContextProvider} entry.
1020
+ */
904
1021
  contextProvider: () => ContextEntry;
1022
+ /** Context key of the stable form definition (`<contextKey>:definition`). */
1023
+ definitionContextKey: string;
1024
+ /**
1025
+ * Provider for the form's definition (description + schema): identical on
1026
+ * every message and marked `stable: true`, so the backend can pin it in the
1027
+ * cacheable part of the prompt. Registered/removed by `install` alongside `contextProvider`.
1028
+ */
1029
+ definitionContextProvider: () => ContextEntry;
905
1030
  /** Register the functions + dynamic context on a client. Returns an uninstall fn. */
906
1031
  install: (client: AgoClient) => () => void;
907
1032
  /**
@@ -1308,23 +1433,63 @@ export declare function useAgo(config: UseAgoOptions | null): {
1308
1433
  };
1309
1434
 
1310
1435
  /**
1311
- * Auto-continue the agent after it navigates, so a "go to page B and change X"
1312
- * request completes in one user gesture. Mount this once inside `AgoProvider`.
1436
+ * A live, normalized feed of what the agent is doing — navigations, state
1437
+ * changes, forms, confirmations, status, progress — plus the controls to
1438
+ * approve/reject/submit the items that wait on the user.
1313
1439
  *
1314
- * Two mechanisms, picked by the turn's client-functions mode:
1440
+ * Client functions surface via `function:invoke` (they're filtered out of
1441
+ * `toolCall:received`); everything else via `toolCall:received`. Reasoning is
1442
+ * suppressed unless `includeReasoning` is set. Approvals require the client's
1443
+ * approval gate (`AgoConfig.approvalPolicy` / `requiresApproval`, pause mode).
1315
1444
  *
1316
- * - **Pause mode** (`clientFunctionsMode: "pause"`): the backend pauses the turn
1317
- * on the navigation call (`message:waiting-client`) and the SDK resumes it once
1318
- * the result is submitted. This hook only registers a *resume gate* that delays
1319
- * the resume until the destination page's `useAgoPageState` registered (plus a
1320
- * settle delay), so the continued turn ships the new page's `setPageState` and
1321
- * current state. Same turn, no extra prompt, backend budget as the guardrail —
1322
- * `continuationPrompt` and `maxDepth` are unused here.
1445
+ * ```tsx
1446
+ * const { items, latest, approve, reject } = useAgoActivity({
1447
+ * labelFor: (i) =>
1448
+ * i.kind === "navigation" ? routeLabels[i.arguments?.page as string] : undefined,
1449
+ * });
1450
+ * ```
1451
+ */
1452
+ export declare function useAgoActivity(options?: UseAgoActivityOptions): UseAgoActivityResult;
1453
+
1454
+ export declare interface UseAgoActivityOptions {
1455
+ /** The AGO client. If omitted, reads from AgoProvider context. */
1456
+ client?: AgoClient;
1457
+ /**
1458
+ * Include the model's `reasoning` items in the feed. Off by default — the
1459
+ * chain-of-thought is noisy for an activity display.
1460
+ */
1461
+ includeReasoning?: boolean;
1462
+ /**
1463
+ * Override the default label for an item. Return a string to replace it, or
1464
+ * `undefined` to keep the default. Use this to map route names / function
1465
+ * names to friendly copy, e.g. `navigateToPage` → "Navigating to Products".
1466
+ */
1467
+ labelFor?: (item: AgoActivityItem) => string | undefined;
1468
+ }
1469
+
1470
+ export declare interface UseAgoActivityResult {
1471
+ /** Time-ordered activity for the current/most-recent turn. */
1472
+ items: AgoActivityItem[];
1473
+ /** The most recent item — handy for a collapsed "latest action" line. */
1474
+ latest?: AgoActivityItem;
1475
+ /** True while any item is waiting on the user (approval or form). */
1476
+ isAwaitingApproval: boolean;
1477
+ /** Approve an awaiting item (client function or confirmation). */
1478
+ approve: (id: string) => Promise<void>;
1479
+ /** Reject an awaiting item (client function or confirmation). */
1480
+ reject: (id: string) => Promise<void>;
1481
+ /** Submit form data for a `form` item. */
1482
+ submitForm: (id: string, values: Record<string, unknown>) => Promise<void>;
1483
+ /** Drop all items (e.g. when starting a new conversation). */
1484
+ clear: () => void;
1485
+ }
1486
+
1487
+ /**
1488
+ * Auto-continue the agent after it navigates, so a "go to page B and change X"
1489
+ * request completes in one user gesture. Mount this once inside `AgoProvider`.
1323
1490
  *
1324
- * - **Placeholder mode** (legacy default): when the agent calls the navigation
1325
- * function and that turn ends, this waits for the destination page's state to
1326
- * register, then sends a hidden continuation message; the agent applies the
1327
- * state in a second turn (requires backend support for the `hidden` flag).
1491
+ * React binding of {@link attachAutoContinueAfterNavigation} — see it for the
1492
+ * pause-mode / placeholder-mode mechanics.
1328
1493
  *
1329
1494
  * ```tsx
1330
1495
  * function AppShell() {
@@ -1433,6 +1598,11 @@ export declare interface UseAgoFunctionOptions {
1433
1598
  * `Infinity` disables the guard for this function.
1434
1599
  */
1435
1600
  maxResultBytes?: number;
1601
+ /**
1602
+ * Require explicit user approval before this function runs (pause mode only).
1603
+ * See `AgoConfig.approvalPolicy`.
1604
+ */
1605
+ requiresApproval?: boolean;
1436
1606
  }
1437
1607
 
1438
1608
  /**