@useago/sdk 1.4.2 → 1.4.3
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 +4 -1
- package/dist/AgoClient-CMDVqNaH.cjs +8 -0
- package/dist/{AgoClient-BdtuHX7k.js → AgoClient-S8oeNnAE.js} +273 -157
- package/dist/angular.cjs +1 -1
- package/dist/angular.d.cts +121 -4
- package/dist/angular.d.ts +121 -4
- package/dist/angular.js +1 -1
- package/dist/{createConversationSession-B8zfTL78.cjs → createConversationSession-CmBq7uGi.cjs} +1 -1
- package/dist/{createConversationSession-CWpf4u6I.js → createConversationSession-DoUHdVNR.js} +1 -1
- package/dist/{createFormCollector-BB_l0Sia.cjs → createFormCollector-Bz_0IJ0Q.cjs} +1 -1
- package/dist/{createFormCollector-B4n0_diV.js → createFormCollector-vy-QvFja.js} +1 -1
- package/dist/createMockClient-BSr-UV8R.cjs +1 -0
- package/dist/{createMockClient-d-arlmCq.js → createMockClient-bAZ9KBHC.js} +18 -15
- package/dist/devtools.d.cts +120 -3
- package/dist/devtools.d.ts +120 -3
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +132 -3
- package/dist/index.d.ts +132 -3
- package/dist/index.js +4 -4
- package/dist/react.cjs +3 -3
- package/dist/react.d.cts +134 -9
- package/dist/react.d.ts +134 -9
- package/dist/react.js +440 -429
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +120 -3
- package/dist/testing.d.ts +120 -3
- package/dist/testing.js +1 -1
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +127 -4
- package/dist/vue.d.ts +127 -4
- package/dist/vue.js +1 -1
- package/dist/widget.cjs +3 -3
- package/dist/widget.d.cts +120 -3
- package/dist/widget.d.ts +120 -3
- package/dist/widget.js +120 -120
- package/package.json +1 -1
- package/dist/AgoClient-CRAnT4qE.cjs +0 -8
- package/dist/createMockClient-ucPENDzz.cjs +0 -1
package/dist/vue.d.ts
CHANGED
|
@@ -47,12 +47,45 @@ declare class AgoClient {
|
|
|
47
47
|
private config;
|
|
48
48
|
/** Conversations already warned about an empty reply (one warning each). */
|
|
49
49
|
private warnedEmptyConversations;
|
|
50
|
+
/** Paused turns awaiting auto-resume, keyed by assistant message id. */
|
|
51
|
+
private pendingResumes;
|
|
52
|
+
/** App-provided gate deciding WHEN a paused turn resumes (see {@link registerResumeGate}). */
|
|
53
|
+
private resumeGate;
|
|
50
54
|
constructor(config: AgoConfig);
|
|
51
55
|
/**
|
|
52
56
|
* Send a message and receive a streaming response
|
|
53
57
|
*/
|
|
54
58
|
sendMessage(content: string, options?: SendMessageOptions): Promise<AgoMessage>;
|
|
55
59
|
private processSSEResponse;
|
|
60
|
+
private resolveClientFunctionsMode;
|
|
61
|
+
/**
|
|
62
|
+
* Register a gate deciding WHEN a paused turn resumes. The SDK still decides
|
|
63
|
+
* *whether* (it resumes once every waiting result is submitted); the gate only
|
|
64
|
+
* delays the continue call — e.g. `useAgoAutoContinueAfterNavigation` waits for
|
|
65
|
+
* the destination page to register its page state. One gate at a time (last
|
|
66
|
+
* registration wins). Returns an unregister function.
|
|
67
|
+
*/
|
|
68
|
+
registerResumeGate(gate: ResumeGate): () => void;
|
|
69
|
+
/**
|
|
70
|
+
* Resume a turn paused on client function results (`WAITING_CLIENT`).
|
|
71
|
+
*
|
|
72
|
+
* Sends the CURRENT page's registered functions and context — the page may
|
|
73
|
+
* have changed since the pause (that's the point of pausing on a navigation) —
|
|
74
|
+
* and streams the continuation through the same event pipeline as
|
|
75
|
+
* `sendMessage`, so `message:chunk` / `message:complete` (or another
|
|
76
|
+
* `message:waiting-client` for chained pauses) fire as usual.
|
|
77
|
+
*
|
|
78
|
+
* The SDK calls this automatically after submitting the waiting results; call
|
|
79
|
+
* it manually only for custom flows (e.g. after restoring a reloaded page via
|
|
80
|
+
* {@link resumePendingClientFunctions}).
|
|
81
|
+
*/
|
|
82
|
+
continueMessage(messageId: string): Promise<AgoMessage>;
|
|
83
|
+
/**
|
|
84
|
+
* Record one of the two auto-resume preconditions for a paused turn and fire
|
|
85
|
+
* the resume when both are in (see {@link PendingResume}).
|
|
86
|
+
*/
|
|
87
|
+
private markResumeSignal;
|
|
88
|
+
private runAutoResume;
|
|
56
89
|
/**
|
|
57
90
|
* Detect a reply that completed as DONE with no content and no activity —
|
|
58
91
|
* today's backend answers an unknown `agent` slug with an empty 200, which
|
|
@@ -85,9 +118,25 @@ declare class AgoClient {
|
|
|
85
118
|
*/
|
|
86
119
|
getMessages(conversationId: string): Promise<AgoMessage[]>;
|
|
87
120
|
/**
|
|
88
|
-
*
|
|
121
|
+
* Resume a turn left paused on client function results by a page reload.
|
|
122
|
+
*
|
|
123
|
+
* A paused turn (pause mode) survives a full reload: the backend keeps the
|
|
124
|
+
* assistant message in `WAITING_CLIENT` with its waiting tool calls. After
|
|
125
|
+
* restoring the conversation (`getConversation`) and re-registering the page's
|
|
126
|
+
* functions, call this: it re-executes each waiting client function through the
|
|
127
|
+
* registry, submits the results, and continues the turn.
|
|
128
|
+
*
|
|
129
|
+
* Opt-in on purpose — re-running functions on reload can be surprising (e.g. a
|
|
130
|
+
* navigation function would navigate again), so the app decides. Returns the
|
|
131
|
+
* resumed turn's final message, or `null` when there was nothing to resume or
|
|
132
|
+
* some waiting function is not registered on this page.
|
|
133
|
+
*/
|
|
134
|
+
resumePendingClientFunctions(conversation: Conversation): Promise<AgoMessage | null>;
|
|
135
|
+
/**
|
|
136
|
+
* Submit form data for a tool call. The response's `resume` field (pause mode
|
|
137
|
+
* only) tells whether the paused turn is ready to be resumed.
|
|
89
138
|
*/
|
|
90
|
-
submitToolCallForm(toolCallId: string, formData: Record<string, unknown>): Promise<
|
|
139
|
+
submitToolCallForm(toolCallId: string, formData: Record<string, unknown>): Promise<SubmitToolCallResult>;
|
|
91
140
|
/**
|
|
92
141
|
* Confirm a tool call
|
|
93
142
|
*/
|
|
@@ -160,6 +209,12 @@ declare class AgoClient {
|
|
|
160
209
|
* the agent know *where* it is after it navigates (e.g. so auto-continuation
|
|
161
210
|
* can apply page state on the destination), not just how to navigate away.
|
|
162
211
|
*
|
|
212
|
+
* Routes may contain `:param` placeholders (`/users/:id`). Each distinct
|
|
213
|
+
* placeholder becomes a top-level string argument of `navigateToPage`
|
|
214
|
+
* (`{ page: "userDetail", id: "42" }`), so one route covers every detail
|
|
215
|
+
* page of an entity. Flat arguments only: nested object parameters are not
|
|
216
|
+
* reliably rendered to the model, so placeholders must not be named `page`.
|
|
217
|
+
*
|
|
163
218
|
* @param navigate - A callback that performs the navigation (e.g. react-router's navigate)
|
|
164
219
|
* @param routes - Map of route names to paths, with descriptions for the LLM
|
|
165
220
|
*/
|
|
@@ -327,6 +382,19 @@ declare interface AgoClientEvents {
|
|
|
327
382
|
*/
|
|
328
383
|
"message:answer-complete": AgoMessage;
|
|
329
384
|
"message:complete": AgoMessage;
|
|
385
|
+
/**
|
|
386
|
+
* The turn paused on client function call(s) (pause mode): the stream closed
|
|
387
|
+
* with status `WAITING_CLIENT` instead of `DONE`. `message:complete` does NOT
|
|
388
|
+
* fire for this stream — it fires when the resumed turn concludes, so one
|
|
389
|
+
* logical turn still emits exactly one `message:complete`. The SDK submits the
|
|
390
|
+
* function results and resumes automatically; listen to this to know the agent
|
|
391
|
+
* is waiting on the page (e.g. to keep a "working…" indicator up).
|
|
392
|
+
*/
|
|
393
|
+
"message:waiting-client": {
|
|
394
|
+
conversationId: string;
|
|
395
|
+
messageId: string;
|
|
396
|
+
waitingToolCallIds: string[];
|
|
397
|
+
};
|
|
330
398
|
/**
|
|
331
399
|
* A reply finished as `DONE` with empty content and no tool calls, client
|
|
332
400
|
* functions, or follow-up replies — usually an unknown `agent` slug (the
|
|
@@ -414,6 +482,16 @@ export declare interface AgoConfig {
|
|
|
414
482
|
* event fires regardless of this setting.
|
|
415
483
|
*/
|
|
416
484
|
warnOnEmptyReply?: boolean;
|
|
485
|
+
/**
|
|
486
|
+
* How the agent loop treats client function calls (requires backend support):
|
|
487
|
+
* - `"placeholder"` (default): the turn continues immediately on a placeholder
|
|
488
|
+
* result; the real result is only visible to the agent on later turns.
|
|
489
|
+
* - `"pause"`: the turn stops on client function call(s) with status
|
|
490
|
+
* `WAITING_CLIENT`; once every result is submitted, the SDK resumes the SAME
|
|
491
|
+
* turn via `POST /messages/{id}/continue`, so the agent sees the real results.
|
|
492
|
+
* Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
|
|
493
|
+
*/
|
|
494
|
+
clientFunctionsMode?: ClientFunctionsMode;
|
|
417
495
|
}
|
|
418
496
|
|
|
419
497
|
declare type AgoEventHandler<K extends AgoEventName> = (data: AgoClientEvents[K]) => void;
|
|
@@ -565,6 +643,9 @@ declare interface ClientFunctionSchema {
|
|
|
565
643
|
};
|
|
566
644
|
}
|
|
567
645
|
|
|
646
|
+
/** See {@link AgoConfig.clientFunctionsMode}. */
|
|
647
|
+
declare type ClientFunctionsMode = "placeholder" | "pause";
|
|
648
|
+
|
|
568
649
|
/**
|
|
569
650
|
* A single piece of context the client wants the LLM to know about.
|
|
570
651
|
*/
|
|
@@ -706,9 +787,32 @@ declare interface FormSchema {
|
|
|
706
787
|
required?: string[];
|
|
707
788
|
}
|
|
708
789
|
|
|
709
|
-
declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCELED"
|
|
790
|
+
declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCELED"
|
|
791
|
+
/**
|
|
792
|
+
* The turn paused on client function call(s) (pause mode): the agent waits for
|
|
793
|
+
* every waiting call to be submitted, then the turn resumes via
|
|
794
|
+
* `continueMessage`. Not a final state.
|
|
795
|
+
*/
|
|
796
|
+
| "WAITING_CLIENT";
|
|
797
|
+
|
|
798
|
+
declare type MessageStatus_2 = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCELED"
|
|
799
|
+
/**
|
|
800
|
+
* The turn paused on client function call(s) (pause mode): the agent waits for
|
|
801
|
+
* every waiting call to be submitted, then the turn resumes via
|
|
802
|
+
* `continueMessage`. Not a final state.
|
|
803
|
+
*/
|
|
804
|
+
| "WAITING_CLIENT";
|
|
710
805
|
|
|
711
|
-
|
|
806
|
+
/**
|
|
807
|
+
* Hook run before a paused turn is resumed, so the app controls WHEN the
|
|
808
|
+
* continuation fires (e.g. wait for the destination page to mount after a
|
|
809
|
+
* navigation). It must resolve — throwing or hanging blocks the resume; on
|
|
810
|
+
* timeout-style situations resolve anyway and let the agent conclude.
|
|
811
|
+
*/
|
|
812
|
+
declare type ResumeGate = (info: {
|
|
813
|
+
conversationId: string;
|
|
814
|
+
messageId: string;
|
|
815
|
+
}) => Promise<void> | void;
|
|
712
816
|
|
|
713
817
|
/**
|
|
714
818
|
* Options for sending a message
|
|
@@ -727,6 +831,8 @@ declare interface SendMessageOptions {
|
|
|
727
831
|
* Requires backend support for the `hidden` flag; older backends ignore it.
|
|
728
832
|
*/
|
|
729
833
|
hidden?: boolean;
|
|
834
|
+
/** Per-message override of {@link AgoConfig.clientFunctionsMode}. */
|
|
835
|
+
clientFunctionsMode?: ClientFunctionsMode;
|
|
730
836
|
}
|
|
731
837
|
|
|
732
838
|
/**
|
|
@@ -768,6 +874,8 @@ declare interface SSEChunkData {
|
|
|
768
874
|
follow_up_replies?: string[];
|
|
769
875
|
satisfaction_feedback?: unknown;
|
|
770
876
|
ask_to_talk_to_human?: boolean;
|
|
877
|
+
/** Tool call ids still awaiting a client result, sent with the final `WAITING_CLIENT` event. */
|
|
878
|
+
waiting_tool_call_ids?: string[];
|
|
771
879
|
}
|
|
772
880
|
|
|
773
881
|
/**
|
|
@@ -813,6 +921,21 @@ declare type SubmitConfig<V = Record<string, unknown>> = string | {
|
|
|
813
921
|
destination?: string;
|
|
814
922
|
} | false;
|
|
815
923
|
|
|
924
|
+
/**
|
|
925
|
+
* Response of `POST /tool-calls/{id}/submit`. `resume` is only present when the
|
|
926
|
+
* tool call belongs to a turn paused on client functions (pause mode): `ready`
|
|
927
|
+
* flips to `true` once ALL waiting calls of that message are submitted, meaning
|
|
928
|
+
* the turn can be resumed via `continueMessage(resume.message_id)`.
|
|
929
|
+
*/
|
|
930
|
+
declare interface SubmitToolCallResult {
|
|
931
|
+
status: string;
|
|
932
|
+
result?: unknown;
|
|
933
|
+
resume?: {
|
|
934
|
+
message_id: string;
|
|
935
|
+
ready: boolean;
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
|
|
816
939
|
/**
|
|
817
940
|
* Tool call data from SSE stream
|
|
818
941
|
*/
|
package/dist/vue.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as A } from "./AgoClient-
|
|
1
|
+
import { t as A } from "./AgoClient-S8oeNnAE.js";
|
|
2
2
|
import { computed as M, inject as F, onMounted as f, onScopeDispose as S, onUnmounted as h, ref as c, shallowRef as y } from "vue";
|
|
3
3
|
var N = /* @__PURE__ */ Symbol("ago-client"), b = { install(t, n) {
|
|
4
4
|
const e = new A(n);
|
package/dist/widget.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se=require("./AgoClient-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se=require("./AgoClient-CMDVqNaH.cjs"),ct=require("./createFormCollector-Bz_0IJ0Q.cjs"),Gt=require("./createConversationSession-CmBq7uGi.cjs");var jt='"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',Re=`var(--ago-font, ${jt})`,pt={font:"--ago-font",radius:"--ago-radius",messageRadius:"--ago-message-radius",brand:"--ago-brand-color",brandText:"--ago-brand-text-color",headerBg:"--ago-header-background",headerText:"--ago-header-text-color",panelBg:"--ago-panel-background",messagesBg:"--ago-messages-background",text:"--ago-text-color",mutedText:"--ago-muted-text-color",border:"--ago-border-color",accent:"--ago-accent-color",agentBubbleBg:"--ago-agent-bubble-background"},Ae="var(--ago-brand-color, #03182f)",_e="var(--ago-brand-text-color, #fff)",Vt="var(--ago-header-background, var(--ago-brand-color, #03182f))",ft="var(--ago-header-text-color, #e8f0fe)",ee="var(--ago-panel-background, #fff)",xt="var(--ago-messages-background, #fbfbfb)",J="var(--ago-text-color, #30373e)",bt="var(--ago-muted-text-color, #6b6d6f)",L="var(--ago-border-color, #dee3e8)",De="var(--ago-accent-color, #1b5fc4)",ut="var(--ago-agent-bubble-background, #f1f3f5)",qt="var(--ago-radius, 16px)",ze="var(--ago-message-radius, 16px)",Kt="var(--ago-message-radius, 20px)";function Xt(n,o){if(o)for(const i of Object.keys(pt)){const r=o[i];r!=null&&n.style.setProperty(pt[i],r)}}function v(n,o){Object.assign(n.style,o)}function h(n={}){const o=document.createElement("div");return v(o,n),o}var mt="ago-chat-widget-keyframes";function Qt(){if(typeof document>"u"||document.getElementById(mt))return;const n=document.createElement("style");n.id=mt,n.textContent="@keyframes ago-pulse { 0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); } 40% { opacity: 1; transform: scale(1); } }@keyframes ago-spin { to { transform: rotate(360deg); } }",document.head.appendChild(n)}function Yt(n){let o=[];const i=document.createElement("form");v(i,{display:"flex",flexDirection:"column",gap:"8px",padding:"12px",borderTop:`1px solid ${L}`,backgroundColor:ee}),i.className="ago-chat-input";const r=h({display:"flex",flexWrap:"wrap",gap:"6px"}),b=h({display:"flex",gap:"8px",alignItems:"flex-end"}),a=document.createElement("textarea");a.placeholder=n.placeholder,a.setAttribute("aria-label",n.placeholder),a.rows=1,v(a,{flex:"1",resize:"none",boxSizing:"border-box",padding:"10px 12px",border:`1px solid ${L}`,borderRadius:"12px",fontSize:"16px",fontFamily:Re,lineHeight:"1.4",maxHeight:"110px",overflowY:"hidden"});const C=()=>{a.style.height="auto";const c=Math.min(a.scrollHeight+2,110);a.style.height=`${c}px`,a.style.overflowY=a.scrollHeight+2>110?"auto":"hidden"};a.addEventListener("input",()=>{C(),A()});const m='<svg width="18" height="18" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-160v-487L216-423l-56-57 320-320 320 320-56 57-224-224v487h-80Z"/></svg>',x='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="animation: ago-spin 0.8s linear infinite"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',p=document.createElement("button");p.type="submit",p.setAttribute("aria-label","Send"),p.innerHTML=m,v(p,{flexShrink:"0",width:"40px",height:"40px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:Ae,color:_e,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"});let f=!1;const A=()=>{const s=a.value.trim()!==""||o.length>0,c=f||!s;p.disabled=c,p.innerHTML=f?x:m,p.style.opacity=c&&!f?"0.5":"1",p.style.cursor=c?"default":"pointer"};let R=null,_=null;n.allowFiles&&(R=document.createElement("input"),R.type="file",R.multiple=!0,v(R,{display:"none"}),_=document.createElement("button"),_.type="button",_.setAttribute("aria-label","Attach file"),_.textContent="📎",v(_,{padding:"10px 12px",border:`1px solid ${L}`,borderRadius:"12px",backgroundColor:ee,cursor:"pointer",fontSize:"14px"}),_.addEventListener("click",()=>R?.click()),R.addEventListener("change",()=>{o=[...o,...Array.from(R?.files??[])],Y()}));function Y(){r.replaceChildren(),o.forEach((s,c)=>{const w=h({display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#f0f4ff",border:`1px solid ${L}`,borderRadius:"8px",fontSize:"12px"}),$=document.createElement("span");$.textContent=s.name;const I=document.createElement("button");I.type="button",I.setAttribute("aria-label",`Remove ${s.name}`),I.textContent="×",v(I,{border:"none",background:"transparent",cursor:"pointer",fontSize:"14px",lineHeight:"1"}),I.addEventListener("click",()=>{o=o.filter((j,V)=>V!==c),Y()}),w.append($,I),r.appendChild(w)}),A()}const D=()=>{const s=a.value,c=o;return a.value="",C(),o=[],Y(),{content:s,files:c}},g=()=>{const{content:s,files:c}=D();(s.trim()||c.length>0)&&n.onSend(s.trim(),c.length>0?c:void 0)};return i.addEventListener("submit",s=>{s.preventDefault(),g()}),a.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),g())}),_&&b.appendChild(_),b.append(a,p),R&&i.appendChild(R),i.append(r,b),A(),{inputRow:i,getValueAndClear:D,setDisabled:s=>{a.disabled=s,f=s,A()},focus:()=>a.focus()}}var Zt={"&":"&","<":"<",">":">",'"':""","'":"'"};function ae(n){return n.replace(/[&<>"']/g,o=>Zt[o])}function gt(n){const o=n.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(o)||!/^[a-z][a-z0-9+.-]*:/i.test(o)?o:null}var vt='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',Se="";function te(n){const o=[],i=b=>(o.push(b),`${Se}${o.length-1}${Se}`);let r=n;return r=r.replace(/`([^`]+)`/g,(b,a)=>i(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${vt}">${ae(a)}</code>`)),r=r.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(b,a,C)=>{const m=gt(C);return m?i(`<img alt="${ae(a)}" src="${ae(m)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):b}),r=r.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(b,a,C)=>{const m=gt(C);return m?i(`<a href="${ae(m)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${te(a)}</a>`):b}),r=ae(r),r=r.replace(/\*\*([^*]+?)\*\*/g,"<strong>$1</strong>").replace(/__([^_]+?)__/g,"<strong>$1</strong>").replace(/~~([^~]+?)~~/g,"<del>$1</del>").replace(/(^|[^*])\*(?!\s)([^*]+?)\*/g,"$1<em>$2</em>").replace(/(^|[^\w_])_(?!\s)([^_]+?)_/g,"$1<em>$2</em>"),r=r.replace(new RegExp(`${Se}(\\d+)${Se}`,"g"),(b,a)=>o[Number(a)]),r}function B(n,o,i){const r=document.createElement(n);return Object.assign(r.style,o),i!==void 0&&(r.innerHTML=i),r}var yt=/^ {0,3}([-*_])( *\1){2,} *$/,wt=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,Ct=/^ {0,3}(```+|~~~+)/,Ie=/^ {0,3}>\s?/,le=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,Jt=["20px","18px","16px","15px","14px","13px"],Fe=n=>n.match(/^\s*/)?.[0].length??0;function en(n){return n.trim()===""||yt.test(n)||wt.test(n)||Ct.test(n)||Ie.test(n)||le.test(n)}function Et(n){const o=n[0].match(le),i=o[1].length,r=/\d/.test(o[2]),b=B(r?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:r?"decimal":"disc",listStylePosition:"outside"});let a=0;for(;a<n.length;){const C=n[a].match(le),m=[];for(a++;a<n.length&&Fe(n[a])>i;)m.push(n[a]),a++;const x=B("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),p=C[3].match(/^\[([ xX])\]\s+(.*)$/);p?(x.style.listStyleType="none",x.style.marginLeft="-20px",x.innerHTML=`<span style="margin-right:6px">${p[1].toLowerCase()==="x"?"☑":"☐"}</span>${te(p[2])}`):x.innerHTML=te(C[3]),m.filter(f=>le.test(f)).length>0&&x.appendChild(Et(m.filter(f=>f.trim()!==""))),b.appendChild(x)}return b}function tn(n){const o=m=>m.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(x=>x.trim()),i=B("div",{overflowX:"auto",margin:"0 0 8px 0"}),r=B("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),b=document.createElement("thead"),a=document.createElement("tr");for(const m of o(n[0]))a.appendChild(B("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},te(m)));b.appendChild(a),r.appendChild(b);const C=document.createElement("tbody");for(const m of n.slice(2)){const x=document.createElement("tr");for(const p of o(m))x.appendChild(B("td",{border:"1px solid #dee3e8",padding:"6px 10px"},te(p)));C.appendChild(x)}return r.appendChild(C),i.appendChild(r),i}var nn=n=>!!n&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(n);function ke(n){const o=document.createDocumentFragment(),i=n.replace(/\r\n?/g,`
|
|
2
2
|
`).split(`
|
|
3
3
|
`);let r=0;for(;r<i.length;){const a=i[r];if(a.trim()===""){r++;continue}const C=a.match(Ct);if(C){const p=C[1][0],f=[];for(r++;r<i.length&&!new RegExp(`^ {0,3}${p==="`"?"`{3,}":"~{3,}"}\\s*$`).test(i[r]);)f.push(i[r]),r++;r++;const A=B("pre",{margin:"0 0 8px 0"});A.appendChild(B("code",{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:vt,whiteSpace:"pre"},ae(f.join(`
|
|
4
|
-
`)))),o.appendChild(A);continue}if(yt.test(a)){o.appendChild(B("hr",{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"})),r++;continue}const m=a.match(wt);if(m){const p=m[1].length;o.appendChild(B(`h${p}`,{margin:"16px 0 8px 0",fontSize:Jt[p-1],fontWeight:"600",lineHeight:"1.3"},te(m[2]))),r++;continue}if(
|
|
5
|
-
`))),o.appendChild(f);continue}if(a.includes("|")&&nn(i[r+1])){const p=[a,i[r+1]];for(r+=2;r<i.length&&i[r].includes("|")&&i[r].trim();)p.push(i[r]),r++;o.appendChild(tn(p));continue}if(le.test(a)){const p=[],f=Fe(a);for(;r<i.length&&i[r].trim()!=="";)if(le.test(i[r])||Fe(i[r])>f)p.push(i[r]),r++;else break;o.appendChild(Et(p));continue}const x=[a];for(r++;r<i.length&&!en(i[r]);)x.push(i[r]),r++;o.appendChild(B("p",{margin:"0 0 8px 0",lineHeight:"1.6"},x.map(p=>te(p)).join("<br>")))}const b=o.lastElementChild;return b&&(b.style.marginBottom="0"),o}function on(n,o){const{isLast:i,isLastOfBlock:r,bubbleStyle:b,showAgentName:a,agentBubble:C,followUpEnabled:m,followUpHandler:x,isMobile:p}=o,f=n.role==="user",A=b==="imessage",R=h({display:"flex",flexDirection:"column",alignItems:f?"flex-end":"flex-start",marginBottom:A&&!r?"2px":"16px"});if(R.className=`ago-message ago-message--${n.role}`,!f&&a&&n.agent){const g=h({fontSize:"13px",fontWeight:"500",color:J,marginBottom:"6px",padding:"0 4px"});g.className="ago-message__agent",g.textContent=n.agent.displayName||n.agent.name,R.appendChild(g)}if(!f&&n.sources&&n.sources.length>0){const g=h({display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px",marginBottom:"10px",width:"100%",maxWidth:"85%"});g.className="ago-message__sources",n.sources.forEach((s,c)=>{const y=s.url?document.createElement("a"):document.createElement("div");s.url&&y instanceof HTMLAnchorElement&&(y.href=s.url,y.target="_blank",y.rel="noopener noreferrer"),v(y,{display:"flex",alignItems:"center",gap:"8px",padding:"8px 10px",border:`1px solid ${L}`,borderRadius:"8px",backgroundColor:ee,textDecoration:"none",color:J,fontSize:"12px",overflow:"hidden"});const T=h({flexShrink:"0",width:"18px",height:"18px",borderRadius:"3px",border:`1px solid ${De}`,color:De,fontSize:"11px",fontWeight:"500",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f0f4ff"});T.textContent=String(c+1);const k=h({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});k.textContent=s.title,k.title=s.title,y.append(T,k),g.appendChild(y)}),R.appendChild(g)}if(n.attachments&&n.attachments.length>0){const g=h({display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"6px",justifyContent:f?"flex-end":"flex-start",maxWidth:"75%"});g.className="ago-message__attachments";for(const s of n.attachments){const c=se.safeAttachmentUrl(s.url);if(se.canInlineImage(s)&&c){const M=document.createElement("a");M.href=c,M.target="_blank",M.rel="noopener noreferrer",v(M,{display:"inline-block",textDecoration:"none"});const q=document.createElement("img");q.src=c,q.alt=s.name,q.loading="lazy",v(q,{maxWidth:"180px",maxHeight:"160px",objectFit:"cover",borderRadius:"10px",border:`1px solid ${L}`,display:"block"}),M.appendChild(q),g.appendChild(M);continue}const y=c?document.createElement("a"):document.createElement("div");c&&y instanceof HTMLAnchorElement&&(y.href=c,y.target="_blank",y.rel="noopener noreferrer"),v(y,{display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"10px",border:`1px solid ${L}`,backgroundColor:f?"rgba(255,255,255,0.12)":ee,color:f?_e:J,fontSize:"13px",textDecoration:"none",maxWidth:"220px"});const T=document.createElement("span");T.textContent="📄",T.setAttribute("aria-hidden","true"),v(T,{fontSize:"16px",lineHeight:"1",flexShrink:"0"});const k=h({display:"flex",flexDirection:"column",minWidth:"0"}),j=h({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"160px"});j.textContent=s.name,j.title=s.name,k.appendChild(j);const V=se.formatFileSize(s.fileSize);if(V){const M=h({fontSize:"11px",color:bt});M.textContent=V,k.appendChild(M)}y.append(T,k),g.appendChild(y)}R.appendChild(g)}const _=f||C||A,Y=!!n.content||n.status==="IN_PROGRESS",D=h({maxWidth:_?A||f?p?"88%":"75%":p?"92%":"85%":"100%",padding:_?"10px 14px":"2px 8px",borderRadius:A?Kt:_?ze:"0",backgroundColor:f?Ae:_?ut:"transparent",color:f?_e:J,overflowWrap:"break-word",textWrap:"pretty",fontSize:"16px",lineHeight:"1.6"});if(D.className="ago-message__content",A&&r){D.style.position="relative";const g=h({position:"absolute",zIndex:"0",bottom:"-2px",width:"20px",height:"20px",background:f?Ae:ut});g.className="ago-message__tail";const s=h({position:"absolute",zIndex:"1",bottom:"-2px",width:"10px",height:"20px",background:xt});s.className="ago-message__tail-mask",f?(g.style.right="-8px",g.style.borderBottomLeftRadius="16px 14px",s.style.right="-10px",s.style.borderBottomLeftRadius="10px"):(g.style.left="-7px",g.style.borderBottomRightRadius="16px 14px",s.style.left="-10px",s.style.borderBottomRightRadius="10px"),D.append(g,s)}if(n.content?D.appendChild(Ie(n.content)):n.status==="IN_PROGRESS"&&D.appendChild(an()),Y&&R.appendChild(D),i&&n.followUpReplies&&n.followUpReplies.length>0){const g=h({display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"10px"});g.className="ago-message__followups";for(const s of n.followUpReplies){const c=document.createElement("button");c.type="button",c.className="ago-message__followup-btn",c.textContent=s,c.disabled=!m,v(c,{minHeight:"36px",padding:"6px 14px",fontSize:"14px",borderRadius:ze,border:`1px solid ${L}`,backgroundColor:ee,color:J,cursor:m?"pointer":"default",transition:"border-color 0.15s"}),x&&c.addEventListener("click",()=>x(s)),c.addEventListener("mouseenter",()=>{c.style.borderColor=De}),c.addEventListener("mouseleave",()=>{c.style.borderColor=L}),g.appendChild(c)}R.appendChild(g)}return R}function rn(n){const o=h({display:"flex",alignItems:"center",gap:"8px",padding:"10px 14px",backgroundColor:"#f0fdf4",color:"#15803d",borderRadius:ze,marginTop:"8px",fontSize:"13px",border:"1px solid #bbf7d0"});o.className="ago-form-notice",o.setAttribute("role","status");const i=document.createElement("span");i.textContent="✓",i.setAttribute("aria-hidden","true"),v(i,{fontWeight:"700"});const r=document.createElement("span");return r.textContent=n,o.append(i,r),o}function an(){const n=h({display:"flex",gap:"4px",padding:"4px 0"});for(let o=0;o<3;o++){const i=h({width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#b5bfc8",animation:"ago-pulse 1.2s ease-in-out infinite",animationDelay:`${o*.2}s`});n.appendChild(i)}return n}function sn(){const n="http://www.w3.org/2000/svg",o=document.createElementNS(n,"svg");o.setAttribute("width","26"),o.setAttribute("height","26"),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none");const i=document.createElementNS(n,"path");return i.setAttribute("d","M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.5 8.5 0 0 1-3.8-.9L3 21l1.9-5.7a8.5 8.5 0 0 1-.9-3.8 8.38 8.38 0 0 1 8.5-8.5 8.38 8.38 0 0 1 8.5 8.5z"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),o.appendChild(i),o}var ht="Form submitted.";function ln(n){if(typeof n=="string")return n||null;if(!n||typeof n!="object")return null;const o=n;if(typeof o.message=="string"&&o.message)return o.message;const i=o.result;if(typeof i=="string"&&i)return i;if(i&&typeof i=="object"){const r=i.message;if(typeof r=="string"&&r)return r}return null}var dn=0;function cn(n){const o=typeof n=="string"?document.querySelector(n):n;if(!o)throw new Error(`mountChatWidget: target "${String(n)}" not found.`);return o}function pn(n,o){const{title:i="Chat",welcomeMessage:r="Hello! How can I help you today?",placeholder:b="Type a message...",allowFiles:a=!1,height:C=500,placement:m="inline",width:x=400,defaultOpen:p=!1,logoUrl:f,showAgentName:A=!1,agentBubble:R=!1,bubbleStyle:_="default",showHeader:Y=!0,theme:D,loadThreads:g=!1,forms:s,formSubmittedMessage:c=ht,onFollowUpClick:y,onMessageSent:T,onMessageReceived:k,onFormSubmitted:j,onFormError:V,onOpen:M,onClose:q}=o,ne=typeof r=="string"?{message:r,mode:"static"}:r,He=ne.message,Pe=ne.mode??"static",St="speed"in ne&&ne.speed||45,Ue="followUpReplies"in ne&&ne.followUpReplies||void 0;if(!o.client&&!o.config?.baseUrl)throw new se.AgoError("mountChatWidget requires either `client` or `config` (with a baseUrl).","config_missing_base_url");const E=o.client??new se.AgoClient(o.config),We=cn(n),z=m==="left"||m==="right",Rt=z&&(o.launcher??!0);let oe=z?p:!0;const kt=o.mobile?.breakpoint??768,$e=o.mobile?.trigger??"tap",Ge=typeof window<"u"&&!!window.matchMedia,O=Ge?window.matchMedia(`(max-width: ${kt}px)`):void 0,At=Ge?window.matchMedia("(prefers-reduced-motion: reduce)"):void 0,re=!z&&!!O,Le=o.persistConversation,ge=Le?Gt.createConversationSession(Le===!0?{}:Le):void 0;let P=o.conversationId??ge?.getLastActiveThread()??void 0,u=[],Z=!1,de=null,K;const je=[];function _t(e){if(typeof c=="function"){const l=c(e);if(typeof l=="string"&&l)return l}const t=ln(e);return t||(typeof c=="string"?c:ht)}const he=[],d=h({display:"flex",flexDirection:"column",height:z?"100%":typeof C=="number"?`${C}px`:C,border:`1px solid ${L}`,borderRadius:qt,overflow:"hidden",backgroundColor:ee,fontFamily:Re,textAlign:"left",boxShadow:"rgba(15, 15, 15, 0.08) 0px 2px 16px 0px"});d.className="ago-chat-widget",Xt(d,D);let F;if(Y){if(F=h({padding:"14px 16px",borderBottom:`1px solid ${L}`,backgroundColor:Vt,color:ft,display:"flex",alignItems:"center",gap:"10px"}),F.className="ago-chat-widget__header",f){const t=document.createElement("img");t.src=f,t.alt="Logo",v(t,{height:"24px",width:"auto"}),F.appendChild(t)}const e=document.createElement("h3");if(e.textContent=i,v(e,{margin:"0",fontSize:"15px",fontWeight:"600"}),F.appendChild(e),z){const t=document.createElement("button");t.type="button",t.className="ago-chat-widget__close",t.setAttribute("aria-label","Close"),t.textContent="×",v(t,{marginLeft:"auto",background:"transparent",border:"none",color:ft,fontSize:"22px",lineHeight:"1",cursor:"pointer",padding:"0 2px"}),t.addEventListener("click",()=>Be()),F.appendChild(t)}}const I=h({flex:"1",overflow:"auto",padding:"16px",backgroundColor:xt});I.className="ago-chat-widget__messages",I.setAttribute("role","log"),I.setAttribute("aria-live","polite"),I.setAttribute("aria-relevant","additions text"),I.setAttribute("aria-atomic","false");const{inputRow:Ne,setDisabled:It,focus:xe}=Yt({placeholder:b,allowFiles:a,onSend:(e,t)=>{we(e,t)}});Qt(),d.append(...F?[F]:[],I,Ne);let be=d,U,N;const ve=m==="left"?"left":"right";if(z&&(U=h({position:"fixed",top:"0",bottom:"0",[ve]:"0",width:typeof x=="number"?`${x}px`:x,maxWidth:"100vw",display:"flex",zIndex:"2147483000",transition:"transform 0.3s ease",boxShadow:"rgba(15, 15, 15, 0.18) 0px 0px 24px 0px"}),U.className="ago-chat-widget-panel",v(d,{height:"100%",width:"100%",borderRadius:"0",border:"none",boxShadow:"none",[ve==="left"?"borderRight":"borderLeft"]:`1px solid ${L}`}),U.appendChild(d),be=U),Rt){if(N=document.createElement("button"),N.type="button",N.className="ago-chat-widget-launcher",N.setAttribute("aria-label",`Open ${i}`),v(N,{position:"fixed",bottom:"20px",[ve]:"20px",width:"56px",height:"56px",borderRadius:"50%",border:"none",backgroundColor:Ae,color:_e,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"2147483000",boxShadow:"rgba(15, 15, 15, 0.2) 0px 4px 14px 0px",fontFamily:Re}),f){const e=document.createElement("img");e.src=f,e.alt="",v(e,{width:"26px",height:"26px",objectFit:"contain"}),N.appendChild(e)}else N.appendChild(sn());N.addEventListener("click",()=>Oe())}const ce=re?`ago-vt-${++dn}`:"",Ve=52;let W=!1,pe=0,ie=0,H,fe,X;const ye={height:d.style.height,border:d.style.border,borderRadius:d.style.borderRadius,boxShadow:d.style.boxShadow};We.appendChild(be),N&&We.appendChild(N),Ce(),re&&(H=Pt(),d.insertBefore(H,d.firstChild),fe=document.createElement("style"),fe.id=ce,fe.textContent=`::view-transition-group(${ce}),::view-transition-group(${ce}-bar){animation-duration:0.3s;animation-timing-function:cubic-bezier(0.4,0,0.2,1)}`,document.head.appendChild(fe),($e==="focus"||$e==="tap")&&(d.addEventListener("pointerdown",e=>{if(W||!O?.matches)return;const t=Ne.contains(e.target);if($e==="tap"){if((e.target instanceof Element?e.target:null)?.closest("button,a[href],[role='button']"))return}else if(!t)return;t&&e.preventDefault(),ue()},!0),d.addEventListener("focusin",e=>{O?.matches&&Ne.contains(e.target)&&ue()})),document.addEventListener("keydown",nt)),O&&O.addEventListener("change",ot);const $t=y!==!1,Lt=y===!1?void 0:y??(e=>{re&&O?.matches&&!W?ue().then(()=>we(e)):we(e)});function $(){if(I.replaceChildren(),u.length===0){if(Pe==="static"){const t=h({textAlign:"center",color:bt,padding:"24px 16px",fontSize:"16px",lineHeight:"1.5"});t.appendChild(Ie(He)),I.appendChild(t)}}else u.forEach((t,l)=>{const S=l===u.length-1||u[l+1].role!==t.role;I.appendChild(on(t,{isLast:l===u.length-1,isLastOfBlock:S,bubbleStyle:_,showAgentName:A,agentBubble:R,followUpEnabled:$t,followUpHandler:Lt,isMobile:!!O?.matches}))});for(const t of je)I.appendChild(rn(t));if(de){const t=h({padding:"10px 14px",backgroundColor:"#fef2f2",color:"#dc2626",borderRadius:"12px",marginTop:"8px",fontSize:"13px",border:"1px solid #fecaca"});t.setAttribute("role","alert"),t.textContent=de,I.appendChild(t)}I.scrollTop=I.scrollHeight;const e=u[u.length-1];It(Z&&e?.role==="assistant"&&e.status==="IN_PROGRESS")}function Nt(){for(let e=u.length-1;e>=0;e--){const t=u[e];if(t.role==="assistant"&&t.status==="IN_PROGRESS")return t}}const qe=e=>{P||(P=e.conversationId)},Ke=e=>{const t=Nt();t&&(t.content+=e.content,$())},Xe=e=>{const t=u.findIndex(l=>l.id===e.id||l.role==="assistant"&&l.status==="IN_PROGRESS");t>=0?u[t]=e:u.push(e),$(),xe()},Qe=e=>{const t=u.findIndex(l=>l.id===e.id||l.role==="assistant"&&l.status==="IN_PROGRESS");t>=0?u[t]=e:u.push(e),Z=!1,$(),e.status==="DONE"&&k?.({id:e.id,content:e.content})},Ye=e=>{de=e.error,Z=!1,u=u.filter(t=>!t.id.startsWith("temp-")),$()};function Tt(e){const t={id:`ago-intro-${Date.now()}`,conversationId:"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};u.push(t),$();const l=e.match(/\S+\s*/g)??[e];let S=0;K=setInterval(()=>{if(S>=l.length){clearInterval(K),K=void 0,t.status="DONE",Ue&&(t.followUpReplies=Ue),$();return}t.content+=l[S],S++,$()},St)}E.on("message:start",qe),E.on("message:chunk",Ke),E.on("message:answer-complete",Xe),E.on("message:complete",Qe),E.on("message:error",Ye);const Ze=e=>j?.(e),Je=e=>V?.(e);j&&E.on("form:submitted",Ze),V&&E.on("form:error",Je);const Te=[];let et=!1;const tt=e=>{if(et)return;Te.push(e.install(E));let t=e.store.get().submitted;const l=e.store.subscribe(S=>{S.submitted&&!t&&(je.push(_t(S.submitResult)),$()),t=S.submitted});Te.push(l)};for(const e of s??[])e.schema!=null?tt(ct.createFormCollector(e)):ct.loadFormCollector(E,e).then(t=>tt(t)).catch(()=>{});async function we(e,t){const l=e.trim();if(!l&&!t?.length||Z)return;if(T?.(l),Z=!0,de=null,K){clearInterval(K),K=void 0;const w=u.find(G=>G.id.startsWith("ago-intro-"));w&&!w.content?u=u.filter(G=>G!==w):w&&(w.status="DONE")}const S=Date.now();u.push({id:`temp-user-${S}`,conversationId:P||"",content:l,role:"user",status:"DONE",attachments:t&&t.length>0?se.attachmentsFromFiles(t):void 0,createdAt:new Date}),u.push({id:`temp-assistant-${S}`,conversationId:P||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}),$();try{const w=await E.sendMessage(l,{conversationId:P,files:t});w.conversationId&&(P||(P=w.conversationId),ge?.setActiveThread(w.conversationId,w.createdAt));const G=u.find(Q=>Q.id===`temp-user-${S}`);if(G&&(G.id=`user-${S}`,G.conversationId=w.conversationId),!u.some(Q=>Q.id===w.id)){const Q=u.findIndex(Wt=>Wt.id===`temp-assistant-${S}`);Q>=0?u[Q]=w:u.push(w)}u=u.filter(Q=>!Q.id.startsWith("temp-")),Z=!1,$(),g&&Me()}catch(w){de=w instanceof Error?w.message:"Failed to send message",Z=!1,u=u.filter(G=>!G.id.startsWith("temp-")),$()}}async function Me(){try{const e=await E.getConversations();he.splice(0,he.length,...e)}catch{}return he}async function Mt(e){try{const t=(await E.getConversation(e))?.messages??[];t.length>0&&u.length===0&&(u=t,$())}catch{u.length===0&&(ge?.clear(),P=void 0)}}return $(),re&&O?.matches||xe(),P?Mt(P):Pe==="streaming"&&Tt(He),g&&Me(),{client:E,element:be,sendMessage:we,...z||re?{open:Bt,close:Dt,toggle:zt}:{},session:ge,threads:he,refreshThreads:Me,destroy(){K&&clearInterval(K),E.off("message:start",qe),E.off("message:chunk",Ke),E.off("message:answer-complete",Xe),E.off("message:complete",Qe),E.off("message:error",Ye),j&&E.off("form:submitted",Ze),V&&E.off("form:error",Je),et=!0,Te.forEach(e=>e()),be.remove(),N?.remove(),H?.remove(),fe?.remove(),X?.remove(),O?.removeEventListener("change",ot),re&&(document.removeEventListener("keydown",nt),at(),document.documentElement.style.removeProperty("overflow")),o.client||E.destroy()}};function Ce(){if(!U)return;{const t=ve==="left"?"border-right":"border-left";O?.matches?(U.style.width="100%",d.style.borderRadius="0",d.style.removeProperty(t)):(U.style.width=typeof x=="number"?`${x}px`:x,d.style.setProperty(t,`1px solid ${L}`))}const e=m==="left"?"translateX(-100%)":"translateX(100%)";U.style.transform=oe?"translateX(0)":e,U.setAttribute("aria-hidden",oe?"false":"true"),N&&(N.style.display=oe?"none":"flex")}function Oe(){oe=!0,Ce(),xe(),M?.()}function Be(){oe=!1,Ce(),q?.()}function Ot(){oe?Be():Oe()}function Bt(){z?Oe():ue()}function Dt(){z?Be():me()}function zt(){z?Ot():W?me():ue()}function Ft(){return Array.from(d.querySelectorAll('a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0)}function nt(e){if(!W)return;if(e.key==="Escape"){me();return}if(e.key!=="Tab")return;const t=Ft();if(t.length===0){e.preventDefault();return}const l=t[0],S=t[t.length-1],w=document.activeElement;e.shiftKey&&(w===l||!d.contains(w))?(e.preventDefault(),S.focus()):!e.shiftKey&&(w===S||!d.contains(w))&&(e.preventDefault(),l.focus())}function ot(e){z?Ce():!e.matches&&W&&me(),$()}function rt(){return window.visualViewport?.height??window.innerHeight}function it(){const e=window.visualViewport,t=e?.offsetTop??0,l=e?.height??pe,S=Math.min(0,t+l-pe);d.style.top=`${S}px`,H&&(H.style.top=`${t}px`)}function Ee(){ie||(ie=requestAnimationFrame(()=>{ie=0,it()}))}function Ht(){window.visualViewport?.addEventListener("resize",Ee),window.visualViewport?.addEventListener("scroll",Ee)}function at(){window.visualViewport?.removeEventListener("resize",Ee),window.visualViewport?.removeEventListener("scroll",Ee),ie&&(cancelAnimationFrame(ie),ie=0)}function st(){I.scrollTop=I.scrollHeight}function Pt(){const e=h({position:"fixed",top:"0",left:"0",right:"0",height:`calc(${Ve}px + env(safe-area-inset-top))`,display:"none",alignItems:"center",justifyContent:"space-between",padding:"env(safe-area-inset-top) 14px 0",backgroundColor:ee,borderBottom:`1px solid ${L}`,zIndex:"2147483001",fontFamily:Re});if(e.className="ago-chat-widget-mobile-bar",f){const l=document.createElement("img");l.src=f,l.alt="",v(l,{height:"28px",width:"auto"}),e.appendChild(l)}else if(i){const l=document.createElement("span");l.textContent=i,v(l,{fontSize:"15px",fontWeight:"600",color:J,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"}),e.appendChild(l)}else e.appendChild(h({}));const t=document.createElement("button");return t.type="button",t.setAttribute("aria-label","Close"),t.textContent="×",v(t,{border:"none",background:"transparent",fontSize:"26px",lineHeight:"1",color:J,cursor:"pointer",padding:"4px 8px"}),t.addEventListener("click",()=>{me()}),e.appendChild(t),e}function Ut(){return typeof document.startViewTransition=="function"&&!At?.matches&&!!O?.matches}function lt(e){const t=document;if(Ut()&&t.startViewTransition){d.style.setProperty("view-transition-name",ce),H?.style.setProperty("view-transition-name",`${ce}-bar`);const l=()=>{d.style.removeProperty("view-transition-name"),H?.style.removeProperty("view-transition-name")};return t.startViewTransition(e).finished.then(l,l)}return e(),Promise.resolve()}function dt(e){if(e)X&&d.parentElement?.insertBefore(X,d),v(d,{position:"fixed",top:"0",left:"0",right:"0",bottom:"0",height:"var(--ago-vh, 100dvh)",zIndex:"2147483000",border:"none",borderRadius:"0",boxShadow:"none",paddingTop:`calc(${Ve}px + env(safe-area-inset-top))`,paddingBottom:"env(safe-area-inset-bottom)"}),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label",i),document.documentElement.style.overflow="hidden",F&&(F.style.display="none"),H&&(H.style.display="flex");else{X?.remove(),X=void 0;for(const t of["position","top","left","right","bottom","z-index","padding-top","padding-bottom"])d.style.removeProperty(t);d.style.height=ye.height,d.style.border=ye.border,d.style.borderRadius=ye.borderRadius,d.style.boxShadow=ye.boxShadow,d.removeAttribute("role"),d.removeAttribute("aria-modal"),d.removeAttribute("aria-label"),document.documentElement.style.removeProperty("overflow"),F&&(F.style.display="flex"),H&&(H.style.display="none")}}function ue(){if(W||!O?.matches)return Promise.resolve();const e=d.getBoundingClientRect();if(e.height>=rt()*.8)return Promise.resolve();W=!0,X=h({width:`${e.width}px`,height:`${e.height}px`}),X.className="ago-chat-widget-spacer",X.setAttribute("aria-hidden","true"),pe=rt(),d.style.setProperty("--ago-vh",`${pe}px`),it(),Ht();const t=lt(()=>dt(!0));return t.then(()=>{st(),xe()}),st(),M?.(),t}function me(){if(!W)return Promise.resolve();W=!1,at(),d.querySelector("textarea")?.blur();const e=lt(()=>dt(!1));return e.then(()=>d.style.removeProperty("--ago-vh")),pe=0,q?.(),e}}exports.mountChatWidget=pn;exports.renderMarkdown=Ie;
|
|
4
|
+
`)))),o.appendChild(A);continue}if(yt.test(a)){o.appendChild(B("hr",{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"})),r++;continue}const m=a.match(wt);if(m){const p=m[1].length;o.appendChild(B(`h${p}`,{margin:"16px 0 8px 0",fontSize:Jt[p-1],fontWeight:"600",lineHeight:"1.3"},te(m[2]))),r++;continue}if(Ie.test(a)){const p=[];for(;r<i.length&&Ie.test(i[r]);)p.push(i[r].replace(Ie,"")),r++;const f=B("blockquote",{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"});f.appendChild(ke(p.join(`
|
|
5
|
+
`))),o.appendChild(f);continue}if(a.includes("|")&&nn(i[r+1])){const p=[a,i[r+1]];for(r+=2;r<i.length&&i[r].includes("|")&&i[r].trim();)p.push(i[r]),r++;o.appendChild(tn(p));continue}if(le.test(a)){const p=[],f=Fe(a);for(;r<i.length&&i[r].trim()!=="";)if(le.test(i[r])||Fe(i[r])>f)p.push(i[r]),r++;else break;o.appendChild(Et(p));continue}const x=[a];for(r++;r<i.length&&!en(i[r]);)x.push(i[r]),r++;o.appendChild(B("p",{margin:"0 0 8px 0",lineHeight:"1.6"},x.map(p=>te(p)).join("<br>")))}const b=o.lastElementChild;return b&&(b.style.marginBottom="0"),o}function on(n,o){const{isLast:i,isLastOfBlock:r,bubbleStyle:b,showAgentName:a,agentBubble:C,followUpEnabled:m,followUpHandler:x,isMobile:p}=o,f=n.role==="user",A=b==="imessage",R=h({display:"flex",flexDirection:"column",alignItems:f?"flex-end":"flex-start",marginBottom:A&&!r?"2px":"16px"});if(R.className=`ago-message ago-message--${n.role}`,!f&&a&&n.agent){const g=h({fontSize:"13px",fontWeight:"500",color:J,marginBottom:"6px",padding:"0 4px"});g.className="ago-message__agent",g.textContent=n.agent.displayName||n.agent.name,R.appendChild(g)}if(!f&&n.sources&&n.sources.length>0){const g=h({display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px",marginBottom:"10px",width:"100%",maxWidth:"85%"});g.className="ago-message__sources",n.sources.forEach((s,c)=>{const w=s.url?document.createElement("a"):document.createElement("div");s.url&&w instanceof HTMLAnchorElement&&(w.href=s.url,w.target="_blank",w.rel="noopener noreferrer"),v(w,{display:"flex",alignItems:"center",gap:"8px",padding:"8px 10px",border:`1px solid ${L}`,borderRadius:"8px",backgroundColor:ee,textDecoration:"none",color:J,fontSize:"12px",overflow:"hidden"});const $=h({flexShrink:"0",width:"18px",height:"18px",borderRadius:"3px",border:`1px solid ${De}`,color:De,fontSize:"11px",fontWeight:"500",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f0f4ff"});$.textContent=String(c+1);const I=h({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"});I.textContent=s.title,I.title=s.title,w.append($,I),g.appendChild(w)}),R.appendChild(g)}if(n.attachments&&n.attachments.length>0){const g=h({display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"6px",justifyContent:f?"flex-end":"flex-start",maxWidth:"75%"});g.className="ago-message__attachments";for(const s of n.attachments){const c=se.safeAttachmentUrl(s.url);if(se.canInlineImage(s)&&c){const M=document.createElement("a");M.href=c,M.target="_blank",M.rel="noopener noreferrer",v(M,{display:"inline-block",textDecoration:"none"});const q=document.createElement("img");q.src=c,q.alt=s.name,q.loading="lazy",v(q,{maxWidth:"180px",maxHeight:"160px",objectFit:"cover",borderRadius:"10px",border:`1px solid ${L}`,display:"block"}),M.appendChild(q),g.appendChild(M);continue}const w=c?document.createElement("a"):document.createElement("div");c&&w instanceof HTMLAnchorElement&&(w.href=c,w.target="_blank",w.rel="noopener noreferrer"),v(w,{display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"10px",border:`1px solid ${L}`,backgroundColor:f?"rgba(255,255,255,0.12)":ee,color:f?_e:J,fontSize:"13px",textDecoration:"none",maxWidth:"220px"});const $=document.createElement("span");$.textContent="📄",$.setAttribute("aria-hidden","true"),v($,{fontSize:"16px",lineHeight:"1",flexShrink:"0"});const I=h({display:"flex",flexDirection:"column",minWidth:"0"}),j=h({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"160px"});j.textContent=s.name,j.title=s.name,I.appendChild(j);const V=se.formatFileSize(s.fileSize);if(V){const M=h({fontSize:"11px",color:bt});M.textContent=V,I.appendChild(M)}w.append($,I),g.appendChild(w)}R.appendChild(g)}const _=f||C||A,Y=!!n.content||n.status==="IN_PROGRESS"||n.status==="WAITING_CLIENT",D=h({maxWidth:_?A||f?p?"88%":"75%":p?"92%":"85%":"100%",padding:_?"10px 14px":"2px 8px",borderRadius:A?Kt:_?ze:"0",backgroundColor:f?Ae:_?ut:"transparent",color:f?_e:J,overflowWrap:"break-word",textWrap:"pretty",fontSize:"16px",lineHeight:"1.6"});if(D.className="ago-message__content",A&&r){D.style.position="relative";const g=h({position:"absolute",zIndex:"0",bottom:"-2px",width:"20px",height:"20px",background:f?Ae:ut});g.className="ago-message__tail";const s=h({position:"absolute",zIndex:"1",bottom:"-2px",width:"10px",height:"20px",background:xt});s.className="ago-message__tail-mask",f?(g.style.right="-8px",g.style.borderBottomLeftRadius="16px 14px",s.style.right="-10px",s.style.borderBottomLeftRadius="10px"):(g.style.left="-7px",g.style.borderBottomRightRadius="16px 14px",s.style.left="-10px",s.style.borderBottomRightRadius="10px"),D.append(g,s)}if(n.content?D.appendChild(ke(n.content)):(n.status==="IN_PROGRESS"||n.status==="WAITING_CLIENT")&&D.appendChild(an()),Y&&R.appendChild(D),i&&n.followUpReplies&&n.followUpReplies.length>0){const g=h({display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"10px"});g.className="ago-message__followups";for(const s of n.followUpReplies){const c=document.createElement("button");c.type="button",c.className="ago-message__followup-btn",c.textContent=s,c.disabled=!m,v(c,{minHeight:"36px",padding:"6px 14px",fontSize:"14px",borderRadius:ze,border:`1px solid ${L}`,backgroundColor:ee,color:J,cursor:m?"pointer":"default",transition:"border-color 0.15s"}),x&&c.addEventListener("click",()=>x(s)),c.addEventListener("mouseenter",()=>{c.style.borderColor=De}),c.addEventListener("mouseleave",()=>{c.style.borderColor=L}),g.appendChild(c)}R.appendChild(g)}return R}function rn(n){const o=h({display:"flex",alignItems:"center",gap:"8px",padding:"10px 14px",backgroundColor:"#f0fdf4",color:"#15803d",borderRadius:ze,marginTop:"8px",fontSize:"13px",border:"1px solid #bbf7d0"});o.className="ago-form-notice",o.setAttribute("role","status");const i=document.createElement("span");i.textContent="✓",i.setAttribute("aria-hidden","true"),v(i,{fontWeight:"700"});const r=document.createElement("span");return r.textContent=n,o.append(i,r),o}function an(){const n=h({display:"flex",gap:"4px",padding:"4px 0"});for(let o=0;o<3;o++){const i=h({width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#b5bfc8",animation:"ago-pulse 1.2s ease-in-out infinite",animationDelay:`${o*.2}s`});n.appendChild(i)}return n}function sn(){const n="http://www.w3.org/2000/svg",o=document.createElementNS(n,"svg");o.setAttribute("width","26"),o.setAttribute("height","26"),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none");const i=document.createElementNS(n,"path");return i.setAttribute("d","M21 11.5a8.38 8.38 0 0 1-8.5 8.5 8.5 8.5 0 0 1-3.8-.9L3 21l1.9-5.7a8.5 8.5 0 0 1-.9-3.8 8.38 8.38 0 0 1 8.5-8.5 8.38 8.38 0 0 1 8.5 8.5z"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),o.appendChild(i),o}var ht="Form submitted.";function ln(n){if(typeof n=="string")return n||null;if(!n||typeof n!="object")return null;const o=n;if(typeof o.message=="string"&&o.message)return o.message;const i=o.result;if(typeof i=="string"&&i)return i;if(i&&typeof i=="object"){const r=i.message;if(typeof r=="string"&&r)return r}return null}var dn=0;function cn(n){const o=typeof n=="string"?document.querySelector(n):n;if(!o)throw new Error(`mountChatWidget: target "${String(n)}" not found.`);return o}function pn(n,o){const{title:i="Chat",welcomeMessage:r="Hello! How can I help you today?",placeholder:b="Type a message...",allowFiles:a=!1,height:C=500,placement:m="inline",width:x=400,defaultOpen:p=!1,logoUrl:f,showAgentName:A=!1,agentBubble:R=!1,bubbleStyle:_="default",showHeader:Y=!0,theme:D,loadThreads:g=!1,forms:s,formSubmittedMessage:c=ht,onFollowUpClick:w,onMessageSent:$,onMessageReceived:I,onFormSubmitted:j,onFormError:V,onOpen:M,onClose:q}=o,ne=typeof r=="string"?{message:r,mode:"static"}:r,He=ne.message,Pe=ne.mode??"static",St="speed"in ne&&ne.speed||45,We="followUpReplies"in ne&&ne.followUpReplies||void 0;if(!o.client&&!o.config?.baseUrl)throw new se.AgoError("mountChatWidget requires either `client` or `config` (with a baseUrl).","config_missing_base_url");const E=o.client??new se.AgoClient(o.config),Ue=cn(n),z=m==="left"||m==="right",Rt=z&&(o.launcher??!0);let oe=z?p:!0;const It=o.mobile?.breakpoint??768,Ne=o.mobile?.trigger??"tap",Ge=typeof window<"u"&&!!window.matchMedia,O=Ge?window.matchMedia(`(max-width: ${It}px)`):void 0,At=Ge?window.matchMedia("(prefers-reduced-motion: reduce)"):void 0,re=!z&&!!O,Le=o.persistConversation,ge=Le?Gt.createConversationSession(Le===!0?{}:Le):void 0;let P=o.conversationId??ge?.getLastActiveThread()??void 0,u=[],Z=!1,de=null,K;const je=[];function _t(e){if(typeof c=="function"){const l=c(e);if(typeof l=="string"&&l)return l}const t=ln(e);return t||(typeof c=="string"?c:ht)}const he=[],d=h({display:"flex",flexDirection:"column",height:z?"100%":typeof C=="number"?`${C}px`:C,border:`1px solid ${L}`,borderRadius:qt,overflow:"hidden",backgroundColor:ee,fontFamily:Re,textAlign:"left",boxShadow:"rgba(15, 15, 15, 0.08) 0px 2px 16px 0px"});d.className="ago-chat-widget",Xt(d,D);let F;if(Y){if(F=h({padding:"14px 16px",borderBottom:`1px solid ${L}`,backgroundColor:Vt,color:ft,display:"flex",alignItems:"center",gap:"10px"}),F.className="ago-chat-widget__header",f){const t=document.createElement("img");t.src=f,t.alt="Logo",v(t,{height:"24px",width:"auto"}),F.appendChild(t)}const e=document.createElement("h3");if(e.textContent=i,v(e,{margin:"0",fontSize:"15px",fontWeight:"600"}),F.appendChild(e),z){const t=document.createElement("button");t.type="button",t.className="ago-chat-widget__close",t.setAttribute("aria-label","Close"),t.textContent="×",v(t,{marginLeft:"auto",background:"transparent",border:"none",color:ft,fontSize:"22px",lineHeight:"1",cursor:"pointer",padding:"0 2px"}),t.addEventListener("click",()=>Be()),F.appendChild(t)}}const k=h({flex:"1",overflow:"auto",padding:"16px",backgroundColor:xt});k.className="ago-chat-widget__messages",k.setAttribute("role","log"),k.setAttribute("aria-live","polite"),k.setAttribute("aria-relevant","additions text"),k.setAttribute("aria-atomic","false");const{inputRow:Te,setDisabled:kt,focus:xe}=Yt({placeholder:b,allowFiles:a,onSend:(e,t)=>{we(e,t)}});Qt(),d.append(...F?[F]:[],k,Te);let be=d,W,T;const ve=m==="left"?"left":"right";if(z&&(W=h({position:"fixed",top:"0",bottom:"0",[ve]:"0",width:typeof x=="number"?`${x}px`:x,maxWidth:"100vw",display:"flex",zIndex:"2147483000",transition:"transform 0.3s ease",boxShadow:"rgba(15, 15, 15, 0.18) 0px 0px 24px 0px"}),W.className="ago-chat-widget-panel",v(d,{height:"100%",width:"100%",borderRadius:"0",border:"none",boxShadow:"none",[ve==="left"?"borderRight":"borderLeft"]:`1px solid ${L}`}),W.appendChild(d),be=W),Rt){if(T=document.createElement("button"),T.type="button",T.className="ago-chat-widget-launcher",T.setAttribute("aria-label",`Open ${i}`),v(T,{position:"fixed",bottom:"20px",[ve]:"20px",width:"56px",height:"56px",borderRadius:"50%",border:"none",backgroundColor:Ae,color:_e,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"2147483000",boxShadow:"rgba(15, 15, 15, 0.2) 0px 4px 14px 0px",fontFamily:Re}),f){const e=document.createElement("img");e.src=f,e.alt="",v(e,{width:"26px",height:"26px",objectFit:"contain"}),T.appendChild(e)}else T.appendChild(sn());T.addEventListener("click",()=>Oe())}const ce=re?`ago-vt-${++dn}`:"",Ve=52;let U=!1,pe=0,ie=0,H,fe,X;const ye={height:d.style.height,border:d.style.border,borderRadius:d.style.borderRadius,boxShadow:d.style.boxShadow};Ue.appendChild(be),T&&Ue.appendChild(T),Ce(),re&&(H=Pt(),d.insertBefore(H,d.firstChild),fe=document.createElement("style"),fe.id=ce,fe.textContent=`::view-transition-group(${ce}),::view-transition-group(${ce}-bar){animation-duration:0.3s;animation-timing-function:cubic-bezier(0.4,0,0.2,1)}`,document.head.appendChild(fe),(Ne==="focus"||Ne==="tap")&&(d.addEventListener("pointerdown",e=>{if(U||!O?.matches)return;const t=Te.contains(e.target);if(Ne==="tap"){if((e.target instanceof Element?e.target:null)?.closest("button,a[href],[role='button']"))return}else if(!t)return;t&&e.preventDefault(),ue()},!0),d.addEventListener("focusin",e=>{O?.matches&&Te.contains(e.target)&&ue()})),document.addEventListener("keydown",nt)),O&&O.addEventListener("change",ot);const Nt=w!==!1,Lt=w===!1?void 0:w??(e=>{re&&O?.matches&&!U?ue().then(()=>we(e)):we(e)});function N(){if(k.replaceChildren(),u.length===0){if(Pe==="static"){const t=h({textAlign:"center",color:bt,padding:"24px 16px",fontSize:"16px",lineHeight:"1.5"});t.appendChild(ke(He)),k.appendChild(t)}}else u.forEach((t,l)=>{const S=l===u.length-1||u[l+1].role!==t.role;k.appendChild(on(t,{isLast:l===u.length-1,isLastOfBlock:S,bubbleStyle:_,showAgentName:A,agentBubble:R,followUpEnabled:Nt,followUpHandler:Lt,isMobile:!!O?.matches}))});for(const t of je)k.appendChild(rn(t));if(de){const t=h({padding:"10px 14px",backgroundColor:"#fef2f2",color:"#dc2626",borderRadius:"12px",marginTop:"8px",fontSize:"13px",border:"1px solid #fecaca"});t.setAttribute("role","alert"),t.textContent=de,k.appendChild(t)}k.scrollTop=k.scrollHeight;const e=u[u.length-1];kt(Z&&e?.role==="assistant"&&(e.status==="IN_PROGRESS"||e.status==="WAITING_CLIENT"))}function Tt(){for(let e=u.length-1;e>=0;e--){const t=u[e];if(t.role==="assistant"&&(t.status==="IN_PROGRESS"||t.status==="WAITING_CLIENT"))return t}}const qe=e=>{P||(P=e.conversationId)},Ke=e=>{const t=Tt();t&&(t.content+=e.content,N())},Xe=e=>{const t=u.findIndex(l=>l.id===e.id||l.role==="assistant"&&l.status==="IN_PROGRESS");t>=0?u[t]=e:u.push(e),N(),xe()},Qe=e=>{const t=u.findIndex(l=>l.id===e.id||l.role==="assistant"&&l.status==="IN_PROGRESS");t>=0?u[t]=e:u.push(e),Z=!1,N(),e.status==="DONE"&&I?.({id:e.id,content:e.content})},Ye=e=>{de=e.error,Z=!1,u=u.filter(t=>!t.id.startsWith("temp-")),N()};function $t(e){const t={id:`ago-intro-${Date.now()}`,conversationId:"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};u.push(t),N();const l=e.match(/\S+\s*/g)??[e];let S=0;K=setInterval(()=>{if(S>=l.length){clearInterval(K),K=void 0,t.status="DONE",We&&(t.followUpReplies=We),N();return}t.content+=l[S],S++,N()},St)}E.on("message:start",qe),E.on("message:chunk",Ke),E.on("message:answer-complete",Xe),E.on("message:complete",Qe),E.on("message:error",Ye);const Ze=e=>j?.(e),Je=e=>V?.(e);j&&E.on("form:submitted",Ze),V&&E.on("form:error",Je);const $e=[];let et=!1;const tt=e=>{if(et)return;$e.push(e.install(E));let t=e.store.get().submitted;const l=e.store.subscribe(S=>{S.submitted&&!t&&(je.push(_t(S.submitResult)),N()),t=S.submitted});$e.push(l)};for(const e of s??[])e.schema!=null?tt(ct.createFormCollector(e)):ct.loadFormCollector(E,e).then(t=>tt(t)).catch(()=>{});async function we(e,t){const l=e.trim();if(!l&&!t?.length||Z)return;if($?.(l),Z=!0,de=null,K){clearInterval(K),K=void 0;const y=u.find(G=>G.id.startsWith("ago-intro-"));y&&!y.content?u=u.filter(G=>G!==y):y&&(y.status="DONE")}const S=Date.now();u.push({id:`temp-user-${S}`,conversationId:P||"",content:l,role:"user",status:"DONE",attachments:t&&t.length>0?se.attachmentsFromFiles(t):void 0,createdAt:new Date}),u.push({id:`temp-assistant-${S}`,conversationId:P||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}),N();try{const y=await E.sendMessage(l,{conversationId:P,files:t});y.conversationId&&(P||(P=y.conversationId),ge?.setActiveThread(y.conversationId,y.createdAt));const G=u.find(Q=>Q.id===`temp-user-${S}`);if(G&&(G.id=`user-${S}`,G.conversationId=y.conversationId),!u.some(Q=>Q.id===y.id)){const Q=u.findIndex(Ut=>Ut.id===`temp-assistant-${S}`);Q>=0?u[Q]=y:u.push(y)}u=u.filter(Q=>!Q.id.startsWith("temp-")),y.status!=="WAITING_CLIENT"&&(Z=!1),N(),g&&Me()}catch(y){de=y instanceof Error?y.message:"Failed to send message",Z=!1,u=u.filter(G=>!G.id.startsWith("temp-")),N()}}async function Me(){try{const e=await E.getConversations();he.splice(0,he.length,...e)}catch{}return he}async function Mt(e){try{const t=(await E.getConversation(e))?.messages??[];t.length>0&&u.length===0&&(u=t,N())}catch{u.length===0&&(ge?.clear(),P=void 0)}}return N(),re&&O?.matches||xe(),P?Mt(P):Pe==="streaming"&&$t(He),g&&Me(),{client:E,element:be,sendMessage:we,...z||re?{open:Bt,close:Dt,toggle:zt}:{},session:ge,threads:he,refreshThreads:Me,destroy(){K&&clearInterval(K),E.off("message:start",qe),E.off("message:chunk",Ke),E.off("message:answer-complete",Xe),E.off("message:complete",Qe),E.off("message:error",Ye),j&&E.off("form:submitted",Ze),V&&E.off("form:error",Je),et=!0,$e.forEach(e=>e()),be.remove(),T?.remove(),H?.remove(),fe?.remove(),X?.remove(),O?.removeEventListener("change",ot),re&&(document.removeEventListener("keydown",nt),at(),document.documentElement.style.removeProperty("overflow")),o.client||E.destroy()}};function Ce(){if(!W)return;{const t=ve==="left"?"border-right":"border-left";O?.matches?(W.style.width="100%",d.style.borderRadius="0",d.style.removeProperty(t)):(W.style.width=typeof x=="number"?`${x}px`:x,d.style.setProperty(t,`1px solid ${L}`))}const e=m==="left"?"translateX(-100%)":"translateX(100%)";W.style.transform=oe?"translateX(0)":e,W.setAttribute("aria-hidden",oe?"false":"true"),T&&(T.style.display=oe?"none":"flex")}function Oe(){oe=!0,Ce(),xe(),M?.()}function Be(){oe=!1,Ce(),q?.()}function Ot(){oe?Be():Oe()}function Bt(){z?Oe():ue()}function Dt(){z?Be():me()}function zt(){z?Ot():U?me():ue()}function Ft(){return Array.from(d.querySelectorAll('a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0)}function nt(e){if(!U)return;if(e.key==="Escape"){me();return}if(e.key!=="Tab")return;const t=Ft();if(t.length===0){e.preventDefault();return}const l=t[0],S=t[t.length-1],y=document.activeElement;e.shiftKey&&(y===l||!d.contains(y))?(e.preventDefault(),S.focus()):!e.shiftKey&&(y===S||!d.contains(y))&&(e.preventDefault(),l.focus())}function ot(e){z?Ce():!e.matches&&U&&me(),N()}function rt(){return window.visualViewport?.height??window.innerHeight}function it(){const e=window.visualViewport,t=e?.offsetTop??0,l=e?.height??pe,S=Math.min(0,t+l-pe);d.style.top=`${S}px`,H&&(H.style.top=`${t}px`)}function Ee(){ie||(ie=requestAnimationFrame(()=>{ie=0,it()}))}function Ht(){window.visualViewport?.addEventListener("resize",Ee),window.visualViewport?.addEventListener("scroll",Ee)}function at(){window.visualViewport?.removeEventListener("resize",Ee),window.visualViewport?.removeEventListener("scroll",Ee),ie&&(cancelAnimationFrame(ie),ie=0)}function st(){k.scrollTop=k.scrollHeight}function Pt(){const e=h({position:"fixed",top:"0",left:"0",right:"0",height:`calc(${Ve}px + env(safe-area-inset-top))`,display:"none",alignItems:"center",justifyContent:"space-between",padding:"env(safe-area-inset-top) 14px 0",backgroundColor:ee,borderBottom:`1px solid ${L}`,zIndex:"2147483001",fontFamily:Re});if(e.className="ago-chat-widget-mobile-bar",f){const l=document.createElement("img");l.src=f,l.alt="",v(l,{height:"28px",width:"auto"}),e.appendChild(l)}else if(i){const l=document.createElement("span");l.textContent=i,v(l,{fontSize:"15px",fontWeight:"600",color:J,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"}),e.appendChild(l)}else e.appendChild(h({}));const t=document.createElement("button");return t.type="button",t.setAttribute("aria-label","Close"),t.textContent="×",v(t,{border:"none",background:"transparent",fontSize:"26px",lineHeight:"1",color:J,cursor:"pointer",padding:"4px 8px"}),t.addEventListener("click",()=>{me()}),e.appendChild(t),e}function Wt(){return typeof document.startViewTransition=="function"&&!At?.matches&&!!O?.matches}function lt(e){const t=document;if(Wt()&&t.startViewTransition){d.style.setProperty("view-transition-name",ce),H?.style.setProperty("view-transition-name",`${ce}-bar`);const l=()=>{d.style.removeProperty("view-transition-name"),H?.style.removeProperty("view-transition-name")};return t.startViewTransition(e).finished.then(l,l)}return e(),Promise.resolve()}function dt(e){if(e)X&&d.parentElement?.insertBefore(X,d),v(d,{position:"fixed",top:"0",left:"0",right:"0",bottom:"0",height:"var(--ago-vh, 100dvh)",zIndex:"2147483000",border:"none",borderRadius:"0",boxShadow:"none",paddingTop:`calc(${Ve}px + env(safe-area-inset-top))`,paddingBottom:"env(safe-area-inset-bottom)"}),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label",i),document.documentElement.style.overflow="hidden",F&&(F.style.display="none"),H&&(H.style.display="flex");else{X?.remove(),X=void 0;for(const t of["position","top","left","right","bottom","z-index","padding-top","padding-bottom"])d.style.removeProperty(t);d.style.height=ye.height,d.style.border=ye.border,d.style.borderRadius=ye.borderRadius,d.style.boxShadow=ye.boxShadow,d.removeAttribute("role"),d.removeAttribute("aria-modal"),d.removeAttribute("aria-label"),document.documentElement.style.removeProperty("overflow"),F&&(F.style.display="flex"),H&&(H.style.display="none")}}function ue(){if(U||!O?.matches)return Promise.resolve();const e=d.getBoundingClientRect();if(e.height>=rt()*.8)return Promise.resolve();U=!0,X=h({width:`${e.width}px`,height:`${e.height}px`}),X.className="ago-chat-widget-spacer",X.setAttribute("aria-hidden","true"),pe=rt(),d.style.setProperty("--ago-vh",`${pe}px`),it(),Ht();const t=lt(()=>dt(!0));return t.then(()=>{st(),xe()}),st(),M?.(),t}function me(){if(!U)return Promise.resolve();U=!1,at(),d.querySelector("textarea")?.blur();const e=lt(()=>dt(!1));return e.then(()=>d.style.removeProperty("--ago-vh")),pe=0,q?.(),e}}exports.mountChatWidget=pn;exports.renderMarkdown=ke;
|
package/dist/widget.d.cts
CHANGED
|
@@ -39,12 +39,45 @@ declare class AgoClient {
|
|
|
39
39
|
private config;
|
|
40
40
|
/** Conversations already warned about an empty reply (one warning each). */
|
|
41
41
|
private warnedEmptyConversations;
|
|
42
|
+
/** Paused turns awaiting auto-resume, keyed by assistant message id. */
|
|
43
|
+
private pendingResumes;
|
|
44
|
+
/** App-provided gate deciding WHEN a paused turn resumes (see {@link registerResumeGate}). */
|
|
45
|
+
private resumeGate;
|
|
42
46
|
constructor(config: AgoConfig);
|
|
43
47
|
/**
|
|
44
48
|
* Send a message and receive a streaming response
|
|
45
49
|
*/
|
|
46
50
|
sendMessage(content: string, options?: SendMessageOptions): Promise<AgoMessage>;
|
|
47
51
|
private processSSEResponse;
|
|
52
|
+
private resolveClientFunctionsMode;
|
|
53
|
+
/**
|
|
54
|
+
* Register a gate deciding WHEN a paused turn resumes. The SDK still decides
|
|
55
|
+
* *whether* (it resumes once every waiting result is submitted); the gate only
|
|
56
|
+
* delays the continue call — e.g. `useAgoAutoContinueAfterNavigation` waits for
|
|
57
|
+
* the destination page to register its page state. One gate at a time (last
|
|
58
|
+
* registration wins). Returns an unregister function.
|
|
59
|
+
*/
|
|
60
|
+
registerResumeGate(gate: ResumeGate): () => void;
|
|
61
|
+
/**
|
|
62
|
+
* Resume a turn paused on client function results (`WAITING_CLIENT`).
|
|
63
|
+
*
|
|
64
|
+
* Sends the CURRENT page's registered functions and context — the page may
|
|
65
|
+
* have changed since the pause (that's the point of pausing on a navigation) —
|
|
66
|
+
* and streams the continuation through the same event pipeline as
|
|
67
|
+
* `sendMessage`, so `message:chunk` / `message:complete` (or another
|
|
68
|
+
* `message:waiting-client` for chained pauses) fire as usual.
|
|
69
|
+
*
|
|
70
|
+
* The SDK calls this automatically after submitting the waiting results; call
|
|
71
|
+
* it manually only for custom flows (e.g. after restoring a reloaded page via
|
|
72
|
+
* {@link resumePendingClientFunctions}).
|
|
73
|
+
*/
|
|
74
|
+
continueMessage(messageId: string): Promise<AgoMessage>;
|
|
75
|
+
/**
|
|
76
|
+
* Record one of the two auto-resume preconditions for a paused turn and fire
|
|
77
|
+
* the resume when both are in (see {@link PendingResume}).
|
|
78
|
+
*/
|
|
79
|
+
private markResumeSignal;
|
|
80
|
+
private runAutoResume;
|
|
48
81
|
/**
|
|
49
82
|
* Detect a reply that completed as DONE with no content and no activity —
|
|
50
83
|
* today's backend answers an unknown `agent` slug with an empty 200, which
|
|
@@ -77,9 +110,25 @@ declare class AgoClient {
|
|
|
77
110
|
*/
|
|
78
111
|
getMessages(conversationId: string): Promise<AgoMessage[]>;
|
|
79
112
|
/**
|
|
80
|
-
*
|
|
113
|
+
* Resume a turn left paused on client function results by a page reload.
|
|
114
|
+
*
|
|
115
|
+
* A paused turn (pause mode) survives a full reload: the backend keeps the
|
|
116
|
+
* assistant message in `WAITING_CLIENT` with its waiting tool calls. After
|
|
117
|
+
* restoring the conversation (`getConversation`) and re-registering the page's
|
|
118
|
+
* functions, call this: it re-executes each waiting client function through the
|
|
119
|
+
* registry, submits the results, and continues the turn.
|
|
120
|
+
*
|
|
121
|
+
* Opt-in on purpose — re-running functions on reload can be surprising (e.g. a
|
|
122
|
+
* navigation function would navigate again), so the app decides. Returns the
|
|
123
|
+
* resumed turn's final message, or `null` when there was nothing to resume or
|
|
124
|
+
* some waiting function is not registered on this page.
|
|
125
|
+
*/
|
|
126
|
+
resumePendingClientFunctions(conversation: Conversation): Promise<AgoMessage | null>;
|
|
127
|
+
/**
|
|
128
|
+
* Submit form data for a tool call. The response's `resume` field (pause mode
|
|
129
|
+
* only) tells whether the paused turn is ready to be resumed.
|
|
81
130
|
*/
|
|
82
|
-
submitToolCallForm(toolCallId: string, formData: Record<string, unknown>): Promise<
|
|
131
|
+
submitToolCallForm(toolCallId: string, formData: Record<string, unknown>): Promise<SubmitToolCallResult>;
|
|
83
132
|
/**
|
|
84
133
|
* Confirm a tool call
|
|
85
134
|
*/
|
|
@@ -152,6 +201,12 @@ declare class AgoClient {
|
|
|
152
201
|
* the agent know *where* it is after it navigates (e.g. so auto-continuation
|
|
153
202
|
* can apply page state on the destination), not just how to navigate away.
|
|
154
203
|
*
|
|
204
|
+
* Routes may contain `:param` placeholders (`/users/:id`). Each distinct
|
|
205
|
+
* placeholder becomes a top-level string argument of `navigateToPage`
|
|
206
|
+
* (`{ page: "userDetail", id: "42" }`), so one route covers every detail
|
|
207
|
+
* page of an entity. Flat arguments only: nested object parameters are not
|
|
208
|
+
* reliably rendered to the model, so placeholders must not be named `page`.
|
|
209
|
+
*
|
|
155
210
|
* @param navigate - A callback that performs the navigation (e.g. react-router's navigate)
|
|
156
211
|
* @param routes - Map of route names to paths, with descriptions for the LLM
|
|
157
212
|
*/
|
|
@@ -319,6 +374,19 @@ declare interface AgoClientEvents {
|
|
|
319
374
|
*/
|
|
320
375
|
"message:answer-complete": AgoMessage;
|
|
321
376
|
"message:complete": AgoMessage;
|
|
377
|
+
/**
|
|
378
|
+
* The turn paused on client function call(s) (pause mode): the stream closed
|
|
379
|
+
* with status `WAITING_CLIENT` instead of `DONE`. `message:complete` does NOT
|
|
380
|
+
* fire for this stream — it fires when the resumed turn concludes, so one
|
|
381
|
+
* logical turn still emits exactly one `message:complete`. The SDK submits the
|
|
382
|
+
* function results and resumes automatically; listen to this to know the agent
|
|
383
|
+
* is waiting on the page (e.g. to keep a "working…" indicator up).
|
|
384
|
+
*/
|
|
385
|
+
"message:waiting-client": {
|
|
386
|
+
conversationId: string;
|
|
387
|
+
messageId: string;
|
|
388
|
+
waitingToolCallIds: string[];
|
|
389
|
+
};
|
|
322
390
|
/**
|
|
323
391
|
* A reply finished as `DONE` with empty content and no tool calls, client
|
|
324
392
|
* functions, or follow-up replies — usually an unknown `agent` slug (the
|
|
@@ -406,6 +474,16 @@ declare interface AgoConfig {
|
|
|
406
474
|
* event fires regardless of this setting.
|
|
407
475
|
*/
|
|
408
476
|
warnOnEmptyReply?: boolean;
|
|
477
|
+
/**
|
|
478
|
+
* How the agent loop treats client function calls (requires backend support):
|
|
479
|
+
* - `"placeholder"` (default): the turn continues immediately on a placeholder
|
|
480
|
+
* result; the real result is only visible to the agent on later turns.
|
|
481
|
+
* - `"pause"`: the turn stops on client function call(s) with status
|
|
482
|
+
* `WAITING_CLIENT`; once every result is submitted, the SDK resumes the SAME
|
|
483
|
+
* turn via `POST /messages/{id}/continue`, so the agent sees the real results.
|
|
484
|
+
* Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
|
|
485
|
+
*/
|
|
486
|
+
clientFunctionsMode?: ClientFunctionsMode;
|
|
409
487
|
}
|
|
410
488
|
|
|
411
489
|
declare type AgoEventHandler<K extends AgoEventName> = (data: AgoClientEvents[K]) => void;
|
|
@@ -599,6 +677,9 @@ declare interface ClientFunctionSchema {
|
|
|
599
677
|
};
|
|
600
678
|
}
|
|
601
679
|
|
|
680
|
+
/** See {@link AgoConfig.clientFunctionsMode}. */
|
|
681
|
+
declare type ClientFunctionsMode = "placeholder" | "pause";
|
|
682
|
+
|
|
602
683
|
/**
|
|
603
684
|
* A single piece of context the client wants the LLM to know about.
|
|
604
685
|
*/
|
|
@@ -819,7 +900,13 @@ declare interface LoadFormCollectorOptions<V = Record<string, unknown>> extends
|
|
|
819
900
|
name: string;
|
|
820
901
|
}
|
|
821
902
|
|
|
822
|
-
declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCELED"
|
|
903
|
+
declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCELED"
|
|
904
|
+
/**
|
|
905
|
+
* The turn paused on client function call(s) (pause mode): the agent waits for
|
|
906
|
+
* every waiting call to be submitted, then the turn resumes via
|
|
907
|
+
* `continueMessage`. Not a final state.
|
|
908
|
+
*/
|
|
909
|
+
| "WAITING_CLIENT";
|
|
823
910
|
|
|
824
911
|
/**
|
|
825
912
|
* Mount a complete, dependency-free chat widget into any DOM element — no React,
|
|
@@ -1067,6 +1154,17 @@ export declare interface MountChatWidgetOptions {
|
|
|
1067
1154
|
*/
|
|
1068
1155
|
export declare function renderMarkdown(source: string): DocumentFragment;
|
|
1069
1156
|
|
|
1157
|
+
/**
|
|
1158
|
+
* Hook run before a paused turn is resumed, so the app controls WHEN the
|
|
1159
|
+
* continuation fires (e.g. wait for the destination page to mount after a
|
|
1160
|
+
* navigation). It must resolve — throwing or hanging blocks the resume; on
|
|
1161
|
+
* timeout-style situations resolve anyway and let the agent conclude.
|
|
1162
|
+
*/
|
|
1163
|
+
declare type ResumeGate = (info: {
|
|
1164
|
+
conversationId: string;
|
|
1165
|
+
messageId: string;
|
|
1166
|
+
}) => Promise<void> | void;
|
|
1167
|
+
|
|
1070
1168
|
/**
|
|
1071
1169
|
* Options for sending a message
|
|
1072
1170
|
*/
|
|
@@ -1084,6 +1182,8 @@ declare interface SendMessageOptions {
|
|
|
1084
1182
|
* Requires backend support for the `hidden` flag; older backends ignore it.
|
|
1085
1183
|
*/
|
|
1086
1184
|
hidden?: boolean;
|
|
1185
|
+
/** Per-message override of {@link AgoConfig.clientFunctionsMode}. */
|
|
1186
|
+
clientFunctionsMode?: ClientFunctionsMode;
|
|
1087
1187
|
}
|
|
1088
1188
|
|
|
1089
1189
|
/**
|
|
@@ -1125,6 +1225,8 @@ declare interface SSEChunkData {
|
|
|
1125
1225
|
follow_up_replies?: string[];
|
|
1126
1226
|
satisfaction_feedback?: unknown;
|
|
1127
1227
|
ask_to_talk_to_human?: boolean;
|
|
1228
|
+
/** Tool call ids still awaiting a client result, sent with the final `WAITING_CLIENT` event. */
|
|
1229
|
+
waiting_tool_call_ids?: string[];
|
|
1128
1230
|
}
|
|
1129
1231
|
|
|
1130
1232
|
/** The slice of the Web Storage API that {@link createStore} relies on. */
|
|
@@ -1152,6 +1254,21 @@ declare type SubmitConfig<V = Record<string, unknown>> = string | {
|
|
|
1152
1254
|
destination?: string;
|
|
1153
1255
|
} | false;
|
|
1154
1256
|
|
|
1257
|
+
/**
|
|
1258
|
+
* Response of `POST /tool-calls/{id}/submit`. `resume` is only present when the
|
|
1259
|
+
* tool call belongs to a turn paused on client functions (pause mode): `ready`
|
|
1260
|
+
* flips to `true` once ALL waiting calls of that message are submitted, meaning
|
|
1261
|
+
* the turn can be resumed via `continueMessage(resume.message_id)`.
|
|
1262
|
+
*/
|
|
1263
|
+
declare interface SubmitToolCallResult {
|
|
1264
|
+
status: string;
|
|
1265
|
+
result?: unknown;
|
|
1266
|
+
resume?: {
|
|
1267
|
+
message_id: string;
|
|
1268
|
+
ready: boolean;
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1155
1272
|
/**
|
|
1156
1273
|
* Tool call data from SSE stream
|
|
1157
1274
|
*/
|