@useago/sdk 1.5.0 → 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 +48 -0
  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 +79 -2
  6. package/dist/angular.d.ts +79 -2
  7. package/dist/angular.js +2 -2
  8. package/dist/{createConversationSession-BBYfQLLS.cjs → createConversationSession-0WTqcCLK.cjs} +1 -1
  9. package/dist/{createConversationSession-DCSWShaW.js → createConversationSession-DPrrr70o.js} +1 -1
  10. package/dist/createFormCollector-1GKKwQV_.cjs +1 -0
  11. package/dist/{createFormCollector-sB6rMccD.js → createFormCollector-DYh90kiG.js} +97 -91
  12. package/dist/devtools.d.cts +79 -2
  13. package/dist/devtools.d.ts +79 -2
  14. package/dist/functions-CPs7omgM.cjs +1 -0
  15. package/dist/helpers.cjs +1 -1
  16. package/dist/helpers.d.cts +5 -0
  17. package/dist/helpers.d.ts +5 -0
  18. package/dist/helpers.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.d.cts +95 -4
  21. package/dist/index.d.ts +95 -4
  22. package/dist/index.js +6 -6
  23. package/dist/react.cjs +3 -3
  24. package/dist/react.d.cts +186 -4
  25. package/dist/react.d.ts +186 -4
  26. package/dist/react.js +670 -475
  27. package/dist/testing.cjs +1 -1
  28. package/dist/testing.d.cts +79 -2
  29. package/dist/testing.d.ts +79 -2
  30. package/dist/testing.js +1 -1
  31. package/dist/vue.cjs +1 -1
  32. package/dist/vue.d.cts +79 -2
  33. package/dist/vue.d.ts +79 -2
  34. package/dist/vue.js +1 -1
  35. package/dist/widget.cjs +4 -4
  36. package/dist/widget.d.cts +79 -2
  37. package/dist/widget.d.ts +79 -2
  38. package/dist/widget.js +437 -423
  39. package/llms-full.txt +74 -2
  40. package/package.json +1 -1
  41. package/dist/AgoClient-q39FIjSC.js +0 -912
  42. package/dist/AgoClient-wcPRaIMs.cjs +0 -8
  43. package/dist/createFormCollector-eimwwWEi.cjs +0 -1
  44. package/dist/functions-IGSjjvF4.cjs +0 -1
  45. package/dist/rolldown-runtime-16Nf8qvH.cjs +0 -1
  46. /package/dist/{autoContinue-D3Mmaaca.js → autoContinue-CC8K9mBU.js} +0 -0
  47. /package/dist/{autoContinue-CcCTva-D.cjs → autoContinue-CP9pJR-V.cjs} +0 -0
  48. /package/dist/{createMockClient-CjdCqixj.cjs → createMockClient-C-wrjb2C.cjs} +0 -0
  49. /package/dist/{createMockClient-BUc9PSbo.js → createMockClient-we-XoPom.js} +0 -0
  50. /package/dist/{functions-CApuQZ2b.js → functions-tzyOZNp6.js} +0 -0
package/dist/helpers.d.ts CHANGED
@@ -22,6 +22,11 @@ declare interface ClientFunctionDefinition {
22
22
  * `Infinity` disables the guard for this function.
23
23
  */
24
24
  maxResultBytes?: number;
25
+ /**
26
+ * Require explicit user approval before this function runs. See
27
+ * {@link AgoConfig.approvalPolicy} — pause mode only. ORs with the policy.
28
+ */
29
+ requiresApproval?: boolean;
25
30
  }
26
31
 
27
32
  /**
package/dist/helpers.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a, c as s, d as t, f as e, i as r, l as i, m as l, o as m, p as c, r as g, s as h, t as n, u as p } from "./functions-CApuQZ2b.js";
1
+ import { a, c as s, d as t, f as e, i as r, l as i, m as l, o as m, p as c, r as g, s as h, t as n, u as p } from "./functions-tzyOZNp6.js";
2
2
  export {
3
3
  n as copyToClipboard,
4
4
  g as getLocalStorage,
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./AgoClient-wcPRaIMs.cjs"),h=require("./autoContinue-CcCTva-D.cjs"),f=require("./createFormCollector-eimwwWEi.cjs"),p=require("./createConversationSession-BBYfQLLS.cjs"),w=require("./createMockClient-CjdCqixj.cjs");require("./testing.cjs");const g=require("./functions-IGSjjvF4.cjs");function S(e){return e}function E(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function y(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function F(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function v(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function b(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function q(e,o){return e.on("form:submitted",o),()=>e.off("form:submitted",o)}function M(e,o){return e.on("form:error",o),()=>e.off("form:error",o)}function k(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*T(e,o,l){const a=[];let n=null,i=!1;const c=s=>{a.push(s),n?.()},m=s=>c({type:"start",data:s}),t=s=>c({type:"chunk",data:s}),u=s=>{c({type:"complete",data:s}),i=!0,n?.()},d=s=>{c({type:"error",data:s}),i=!0,n?.()},A=s=>c({type:"toolCall",data:s});e.on("message:start",m),e.on("message:chunk",t),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",A),e.sendMessage(o,l).catch(()=>{i=!0,n?.()});try{for(;!i||a.length>0;)a.length>0?yield a.shift():(await new Promise(s=>{n=s}),n=null)}finally{e.off("message:start",m),e.off("message:chunk",t),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",A)}}function C(e){let o,l,a,n,i,c;if(typeof window<"u"&&window.AGO){const t=window.AGO;o=t.basepath,l=t.widgetId,a=t.agent||t.defaultAgent,n=t.permission,i=t.email,c=t.jwt}if(typeof document<"u"){const t=u=>document.querySelector(`meta[name="${u}"]`)?.getAttribute("content")||void 0;o=o||t("ago-base-url"),l=l||t("ago-widget-id"),a=a||t("ago-agent")||t("ago-agent-id"),n=n||t("ago-permission"),i=i||t("ago-user-email")}if(typeof document<"u"){const t=[document.body,...Array.from(document.querySelectorAll("script[data-ago-base-url]"))].filter(Boolean);for(const u of t)u&&(o=o||u.getAttribute("data-ago-base-url")||void 0,l=l||u.getAttribute("data-ago-widget-id")||void 0,a=a||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,n=n||u.getAttribute("data-ago-permission")||void 0,i=i||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,a=e?.agent||e?.defaultAgentId||a,n=e?.permission||n,i=e?.userEmail||i,c=e?.userJwt||c;const m=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:n,userEmail:i,userJwt:c,debug:m}:null}function I(e){const o=C(e);if(!o)throw new r.AgoError('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.',"config_missing_base_url");return new r.AgoClient(o)}function U(e,o){return{...e,handler:o}}exports.AgoApiError=r.AgoApiError;exports.AgoClient=r.AgoClient;exports.AgoError=r.AgoError;exports.AgoFunctionError=r.AgoFunctionError;exports.AgoNetworkError=r.AgoNetworkError;exports.AgoStreamError=r.AgoStreamError;exports.ClientContextRegistry=r.ClientContextRegistry;exports.EventEmitter=r.EventEmitter;exports.FunctionRegistry=r.FunctionRegistry;exports.SSEHandler=r.SSEHandler;exports.attachAutoContinueAfterNavigation=h.attachAutoContinueAfterNavigation;exports.autoDetectConfig=C;exports.canInlineImage=r.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=I;exports.createConversationSession=p.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=T;exports.createMockClient=w.createMockClient;exports.createStore=f.createStore;exports.defineFunction=S;exports.deriveFormStatus=f.deriveFormStatus;exports.formatFileSize=r.formatFileSize;exports.getLocalStorage=g.getLocalStorage;exports.getUserLocation=g.getUserLocation;exports.highlightElement=g.highlightElement;exports.isStreamNetworkError=r.isStreamNetworkError;exports.loadFormCollector=f.loadFormCollector;exports.logger=r.logger;exports.onFormError=M;exports.onFormSubmitted=q;exports.onFunctionInvoke=k;exports.onMessage=E;exports.onMessageChunk=y;exports.onMessageError=v;exports.onMessageStart=F;exports.onToolCall=b;exports.openUrl=g.openUrl;exports.safeAttachmentUrl=r.safeAttachmentUrl;exports.scrollToElement=g.scrollToElement;exports.setLocalStorage=g.setLocalStorage;exports.setTheme=g.setTheme;exports.showConfirmDialog=g.showConfirmDialog;exports.showNotification=g.showNotification;exports.showToast=g.showToast;exports.submitForm=g.submitForm;exports.trackEvent=g.trackEvent;exports.validateConfig=r.validateConfig;exports.withHandler=U;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./AgoClient-5VGybmvz.cjs"),h=require("./autoContinue-CP9pJR-V.cjs"),f=require("./createFormCollector-1GKKwQV_.cjs"),p=require("./createConversationSession-0WTqcCLK.cjs"),w=require("./createMockClient-C-wrjb2C.cjs");require("./testing.cjs");const g=require("./functions-CPs7omgM.cjs");function S(e){return e}function E(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function y(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function F(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function v(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function b(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function q(e,o){return e.on("form:submitted",o),()=>e.off("form:submitted",o)}function M(e,o){return e.on("form:error",o),()=>e.off("form:error",o)}function k(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*T(e,o,l){const a=[];let n=null,i=!1;const c=s=>{a.push(s),n?.()},m=s=>c({type:"start",data:s}),t=s=>c({type:"chunk",data:s}),u=s=>{c({type:"complete",data:s}),i=!0,n?.()},d=s=>{c({type:"error",data:s}),i=!0,n?.()},A=s=>c({type:"toolCall",data:s});e.on("message:start",m),e.on("message:chunk",t),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",A),e.sendMessage(o,l).catch(()=>{i=!0,n?.()});try{for(;!i||a.length>0;)a.length>0?yield a.shift():(await new Promise(s=>{n=s}),n=null)}finally{e.off("message:start",m),e.off("message:chunk",t),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",A)}}function C(e){let o,l,a,n,i,c;if(typeof window<"u"&&window.AGO){const t=window.AGO;o=t.basepath,l=t.widgetId,a=t.agent||t.defaultAgent,n=t.permission,i=t.email,c=t.jwt}if(typeof document<"u"){const t=u=>document.querySelector(`meta[name="${u}"]`)?.getAttribute("content")||void 0;o=o||t("ago-base-url"),l=l||t("ago-widget-id"),a=a||t("ago-agent")||t("ago-agent-id"),n=n||t("ago-permission"),i=i||t("ago-user-email")}if(typeof document<"u"){const t=[document.body,...Array.from(document.querySelectorAll("script[data-ago-base-url]"))].filter(Boolean);for(const u of t)u&&(o=o||u.getAttribute("data-ago-base-url")||void 0,l=l||u.getAttribute("data-ago-widget-id")||void 0,a=a||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,n=n||u.getAttribute("data-ago-permission")||void 0,i=i||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,a=e?.agent||e?.defaultAgentId||a,n=e?.permission||n,i=e?.userEmail||i,c=e?.userJwt||c;const m=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:n,userEmail:i,userJwt:c,debug:m}:null}function I(e){const o=C(e);if(!o)throw new r.AgoError('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.',"config_missing_base_url");return new r.AgoClient(o)}function U(e,o){return{...e,handler:o}}exports.AgoApiError=r.AgoApiError;exports.AgoClient=r.AgoClient;exports.AgoError=r.AgoError;exports.AgoFunctionError=r.AgoFunctionError;exports.AgoNetworkError=r.AgoNetworkError;exports.AgoStreamError=r.AgoStreamError;exports.ClientContextRegistry=r.ClientContextRegistry;exports.EventEmitter=r.EventEmitter;exports.FunctionRegistry=r.FunctionRegistry;exports.SSEHandler=r.SSEHandler;exports.attachAutoContinueAfterNavigation=h.attachAutoContinueAfterNavigation;exports.autoDetectConfig=C;exports.canInlineImage=r.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=I;exports.createConversationSession=p.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=T;exports.createMockClient=w.createMockClient;exports.createStore=f.createStore;exports.defineFunction=S;exports.deriveFormStatus=f.deriveFormStatus;exports.formatFileSize=r.formatFileSize;exports.getLocalStorage=g.getLocalStorage;exports.getUserLocation=g.getUserLocation;exports.highlightElement=g.highlightElement;exports.isStreamNetworkError=r.isStreamNetworkError;exports.loadFormCollector=f.loadFormCollector;exports.logger=r.logger;exports.onFormError=M;exports.onFormSubmitted=q;exports.onFunctionInvoke=k;exports.onMessage=E;exports.onMessageChunk=y;exports.onMessageError=v;exports.onMessageStart=F;exports.onToolCall=b;exports.openUrl=g.openUrl;exports.safeAttachmentUrl=r.safeAttachmentUrl;exports.scrollToElement=g.scrollToElement;exports.setLocalStorage=g.setLocalStorage;exports.setTheme=g.setTheme;exports.showConfirmDialog=g.showConfirmDialog;exports.showNotification=g.showNotification;exports.showToast=g.showToast;exports.submitForm=g.submitForm;exports.trackEvent=g.trackEvent;exports.validateConfig=r.validateConfig;exports.withHandler=U;
package/dist/index.d.cts CHANGED
@@ -69,6 +69,12 @@ export declare class AgoClient {
69
69
  private warnedEmptyConversations;
70
70
  /** Paused turns awaiting auto-resume, keyed by assistant message id. */
71
71
  private pendingResumes;
72
+ /**
73
+ * Client function invocations held pending user approval, keyed by
74
+ * invocationId (the tool-call id). Populated when {@link requiresApproval}
75
+ * matches; drained by {@link approveFunction} / {@link rejectFunction}.
76
+ */
77
+ private pendingApprovals;
72
78
  /** App-provided gate deciding WHEN a paused turn resumes (see {@link registerResumeGate}). */
73
79
  private resumeGate;
74
80
  constructor(config: AgoConfig);
@@ -119,6 +125,24 @@ export declare class AgoClient {
119
125
  */
120
126
  private maybeFlagEmptyReply;
121
127
  private handleClientFunctionInvocation;
128
+ /**
129
+ * Whether a client function invocation must wait for explicit user approval.
130
+ * True when the {@link AgoConfig.approvalPolicy} returns true OR the function
131
+ * was registered with `requiresApproval: true` — the two OR together.
132
+ */
133
+ private requiresApproval;
134
+ /**
135
+ * Approve a client function call held by the approval gate: run it, submit its
136
+ * result, and let the paused turn resume. No-op if the invocation is unknown
137
+ * (already handled, or never gated).
138
+ */
139
+ approveFunction(invocationId: string): Promise<void>;
140
+ /**
141
+ * Reject a client function call held by the approval gate: submit a rejection
142
+ * result so the agent sees the user declined, and let the paused turn resume
143
+ * (the agent decides what to do next). No-op if the invocation is unknown.
144
+ */
145
+ rejectFunction(invocationId: string): Promise<void>;
122
146
  /**
123
147
  * Get list of conversations
124
148
  */
@@ -148,8 +172,10 @@ export declare class AgoClient {
148
172
  *
149
173
  * Opt-in on purpose — re-running functions on reload can be surprising (e.g. a
150
174
  * navigation function would navigate again), so the app decides. Returns the
151
- * resumed turn's final message, or `null` when there was nothing to resume or
152
- * some waiting function is not registered on this page.
175
+ * resumed turn's final message, or `null` when there was nothing to resume,
176
+ * some waiting function is not registered on this page, or a waiting call is
177
+ * gated by the approval policy (it is held for `approveFunction` /
178
+ * `rejectFunction` and the turn stays paused, exactly as on the live stream).
153
179
  */
154
180
  resumePendingClientFunctions(conversation: Conversation): Promise<AgoMessage | null>;
155
181
  /**
@@ -444,6 +470,15 @@ export declare interface AgoClientEvents {
444
470
  "toolCall:received": ToolCallData;
445
471
  "toolCall:form": ToolCallData;
446
472
  "function:invoke": ClientFunctionInvocation;
473
+ /**
474
+ * A client function call is held pending the user's approval (pause mode +
475
+ * an {@link AgoConfig.approvalPolicy}/`requiresApproval` match). The turn stays
476
+ * at `WAITING_CLIENT`; call `approveFunction(invocationId)` to run it and
477
+ * resume, or `rejectFunction(invocationId)` to decline. Fires after
478
+ * `function:invoke` (which still fires for every call) and instead of the
479
+ * call running immediately.
480
+ */
481
+ "function:awaiting-approval": ClientFunctionInvocation;
447
482
  "function:result": {
448
483
  invocationId: string;
449
484
  result: unknown;
@@ -512,6 +547,20 @@ export declare interface AgoConfig {
512
547
  * Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
513
548
  */
514
549
  clientFunctionsMode?: ClientFunctionsMode;
550
+ /**
551
+ * Gate client function calls behind explicit user approval. Return `true` for
552
+ * an invocation the user must approve/reject before it runs; return `false`
553
+ * (or omit the policy) to let it run immediately as before.
554
+ *
555
+ * Only effective in pause mode (`clientFunctionsMode: "pause"`) — a gated call
556
+ * holds at `WAITING_CLIENT`, the SDK emits `function:awaiting-approval`, and it
557
+ * runs (and the turn resumes) only after `approveFunction(invocationId)`; a
558
+ * `rejectFunction(invocationId)` submits a rejection so the agent sees the
559
+ * decline. In placeholder mode there is no pause to hold, so the policy is a
560
+ * no-op and the call runs normally. A per-function `requiresApproval: true`
561
+ * also gates a call; the policy and the flag OR together.
562
+ */
563
+ approvalPolicy?: (invocation: ClientFunctionInvocation) => boolean;
515
564
  /**
516
565
  * Max serialized size (bytes) of a client function result before the SDK
517
566
  * replaces it with a flagged, truncated preview. Everything a handler
@@ -588,6 +637,11 @@ export declare class AgoNetworkError extends AgoError {
588
637
  export declare interface AgoPageStateOptions {
589
638
  /** Name of the synthesized client function. Defaults to "setPageState". */
590
639
  functionName?: string;
640
+ /**
641
+ * Require explicit user approval before this state change runs. See
642
+ * {@link AgoConfig.approvalPolicy} — pause mode only. Defaults to `false`.
643
+ */
644
+ requiresApproval?: boolean;
591
645
  }
592
646
 
593
647
  /**
@@ -796,6 +850,11 @@ export declare interface ClientFunctionDefinition {
796
850
  * `Infinity` disables the guard for this function.
797
851
  */
798
852
  maxResultBytes?: number;
853
+ /**
854
+ * Require explicit user approval before this function runs. See
855
+ * {@link AgoConfig.approvalPolicy} — pause mode only. ORs with the policy.
856
+ */
857
+ requiresApproval?: boolean;
799
858
  }
800
859
 
801
860
  /**
@@ -822,6 +881,11 @@ export declare type ClientFunctionRegisterOptions = Omit<ClientFunctionSchema, "
822
881
  * disables the guard for this function.
823
882
  */
824
883
  maxResultBytes?: number;
884
+ /**
885
+ * Require explicit user approval before this function runs. See
886
+ * {@link AgoConfig.approvalPolicy} — pause mode only. ORs with the policy.
887
+ */
888
+ requiresApproval?: boolean;
825
889
  };
826
890
 
827
891
  /**
@@ -862,6 +926,19 @@ export declare interface ContextEntry {
862
926
  description?: string;
863
927
  /** Arbitrary structured data the AI should know about */
864
928
  data?: Record<string, unknown>;
929
+ /**
930
+ * Marks the entry as constant for the whole conversation. The backend then
931
+ * pins it right after the system prompt, where LLM providers cache it across
932
+ * turns, instead of re-processing it next to every new user message.
933
+ *
934
+ * Only set this when the entry's content is byte-identical on every message
935
+ * of a conversation (a schema, a capability list, static instructions). A
936
+ * stable entry that changes between messages invalidates the provider's
937
+ * cache for the entire conversation history, which costs more than leaving
938
+ * the flag off. Default: `false` (re-sent near the newest user message).
939
+ * Backends that don't know the flag ignore it.
940
+ */
941
+ stable?: boolean;
865
942
  }
866
943
 
867
944
  /**
@@ -1160,10 +1237,22 @@ export declare interface FormCollector<V = Record<string, unknown>> {
1160
1237
  store: Store<FormCollectorState<V>>;
1161
1238
  /** Client functions to register: `[update]` or `[update, submit]`. */
1162
1239
  functions: ClientFunctionDefinition[];
1163
- /** Dynamic-context key under which the form state is exposed. */
1240
+ /** Dynamic-context key under which the live form state is exposed. */
1164
1241
  contextKey: string;
1165
- /** Dynamic-context provider — re-read on every message. */
1242
+ /**
1243
+ * Dynamic-context provider for the live form state (phase, values, missing)
1244
+ * — re-read on every message. The schema itself rides in the companion
1245
+ * {@link definitionContextProvider} entry.
1246
+ */
1166
1247
  contextProvider: () => ContextEntry;
1248
+ /** Context key of the stable form definition (`<contextKey>:definition`). */
1249
+ definitionContextKey: string;
1250
+ /**
1251
+ * Provider for the form's definition (description + schema): identical on
1252
+ * every message and marked `stable: true`, so the backend can pin it in the
1253
+ * cacheable part of the prompt. Registered/removed by `install` alongside `contextProvider`.
1254
+ */
1255
+ definitionContextProvider: () => ContextEntry;
1167
1256
  /** Register the functions + dynamic context on a client. Returns an uninstall fn. */
1168
1257
  install: (client: AgoClient) => () => void;
1169
1258
  /**
@@ -1567,6 +1656,8 @@ export declare interface RegisteredFunction {
1567
1656
  handler: ClientFunctionHandler;
1568
1657
  /** Per-function result-size ceiling; falls back to the registry default. */
1569
1658
  maxResultBytes?: number;
1659
+ /** Require explicit user approval before running (pause mode only). */
1660
+ requiresApproval?: boolean;
1570
1661
  }
1571
1662
 
1572
1663
  /**
package/dist/index.d.ts CHANGED
@@ -69,6 +69,12 @@ export declare class AgoClient {
69
69
  private warnedEmptyConversations;
70
70
  /** Paused turns awaiting auto-resume, keyed by assistant message id. */
71
71
  private pendingResumes;
72
+ /**
73
+ * Client function invocations held pending user approval, keyed by
74
+ * invocationId (the tool-call id). Populated when {@link requiresApproval}
75
+ * matches; drained by {@link approveFunction} / {@link rejectFunction}.
76
+ */
77
+ private pendingApprovals;
72
78
  /** App-provided gate deciding WHEN a paused turn resumes (see {@link registerResumeGate}). */
73
79
  private resumeGate;
74
80
  constructor(config: AgoConfig);
@@ -119,6 +125,24 @@ export declare class AgoClient {
119
125
  */
120
126
  private maybeFlagEmptyReply;
121
127
  private handleClientFunctionInvocation;
128
+ /**
129
+ * Whether a client function invocation must wait for explicit user approval.
130
+ * True when the {@link AgoConfig.approvalPolicy} returns true OR the function
131
+ * was registered with `requiresApproval: true` — the two OR together.
132
+ */
133
+ private requiresApproval;
134
+ /**
135
+ * Approve a client function call held by the approval gate: run it, submit its
136
+ * result, and let the paused turn resume. No-op if the invocation is unknown
137
+ * (already handled, or never gated).
138
+ */
139
+ approveFunction(invocationId: string): Promise<void>;
140
+ /**
141
+ * Reject a client function call held by the approval gate: submit a rejection
142
+ * result so the agent sees the user declined, and let the paused turn resume
143
+ * (the agent decides what to do next). No-op if the invocation is unknown.
144
+ */
145
+ rejectFunction(invocationId: string): Promise<void>;
122
146
  /**
123
147
  * Get list of conversations
124
148
  */
@@ -148,8 +172,10 @@ export declare class AgoClient {
148
172
  *
149
173
  * Opt-in on purpose — re-running functions on reload can be surprising (e.g. a
150
174
  * navigation function would navigate again), so the app decides. Returns the
151
- * resumed turn's final message, or `null` when there was nothing to resume or
152
- * some waiting function is not registered on this page.
175
+ * resumed turn's final message, or `null` when there was nothing to resume,
176
+ * some waiting function is not registered on this page, or a waiting call is
177
+ * gated by the approval policy (it is held for `approveFunction` /
178
+ * `rejectFunction` and the turn stays paused, exactly as on the live stream).
153
179
  */
154
180
  resumePendingClientFunctions(conversation: Conversation): Promise<AgoMessage | null>;
155
181
  /**
@@ -444,6 +470,15 @@ export declare interface AgoClientEvents {
444
470
  "toolCall:received": ToolCallData;
445
471
  "toolCall:form": ToolCallData;
446
472
  "function:invoke": ClientFunctionInvocation;
473
+ /**
474
+ * A client function call is held pending the user's approval (pause mode +
475
+ * an {@link AgoConfig.approvalPolicy}/`requiresApproval` match). The turn stays
476
+ * at `WAITING_CLIENT`; call `approveFunction(invocationId)` to run it and
477
+ * resume, or `rejectFunction(invocationId)` to decline. Fires after
478
+ * `function:invoke` (which still fires for every call) and instead of the
479
+ * call running immediately.
480
+ */
481
+ "function:awaiting-approval": ClientFunctionInvocation;
447
482
  "function:result": {
448
483
  invocationId: string;
449
484
  result: unknown;
@@ -512,6 +547,20 @@ export declare interface AgoConfig {
512
547
  * Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
513
548
  */
514
549
  clientFunctionsMode?: ClientFunctionsMode;
550
+ /**
551
+ * Gate client function calls behind explicit user approval. Return `true` for
552
+ * an invocation the user must approve/reject before it runs; return `false`
553
+ * (or omit the policy) to let it run immediately as before.
554
+ *
555
+ * Only effective in pause mode (`clientFunctionsMode: "pause"`) — a gated call
556
+ * holds at `WAITING_CLIENT`, the SDK emits `function:awaiting-approval`, and it
557
+ * runs (and the turn resumes) only after `approveFunction(invocationId)`; a
558
+ * `rejectFunction(invocationId)` submits a rejection so the agent sees the
559
+ * decline. In placeholder mode there is no pause to hold, so the policy is a
560
+ * no-op and the call runs normally. A per-function `requiresApproval: true`
561
+ * also gates a call; the policy and the flag OR together.
562
+ */
563
+ approvalPolicy?: (invocation: ClientFunctionInvocation) => boolean;
515
564
  /**
516
565
  * Max serialized size (bytes) of a client function result before the SDK
517
566
  * replaces it with a flagged, truncated preview. Everything a handler
@@ -588,6 +637,11 @@ export declare class AgoNetworkError extends AgoError {
588
637
  export declare interface AgoPageStateOptions {
589
638
  /** Name of the synthesized client function. Defaults to "setPageState". */
590
639
  functionName?: string;
640
+ /**
641
+ * Require explicit user approval before this state change runs. See
642
+ * {@link AgoConfig.approvalPolicy} — pause mode only. Defaults to `false`.
643
+ */
644
+ requiresApproval?: boolean;
591
645
  }
592
646
 
593
647
  /**
@@ -796,6 +850,11 @@ export declare interface ClientFunctionDefinition {
796
850
  * `Infinity` disables the guard for this function.
797
851
  */
798
852
  maxResultBytes?: number;
853
+ /**
854
+ * Require explicit user approval before this function runs. See
855
+ * {@link AgoConfig.approvalPolicy} — pause mode only. ORs with the policy.
856
+ */
857
+ requiresApproval?: boolean;
799
858
  }
800
859
 
801
860
  /**
@@ -822,6 +881,11 @@ export declare type ClientFunctionRegisterOptions = Omit<ClientFunctionSchema, "
822
881
  * disables the guard for this function.
823
882
  */
824
883
  maxResultBytes?: number;
884
+ /**
885
+ * Require explicit user approval before this function runs. See
886
+ * {@link AgoConfig.approvalPolicy} — pause mode only. ORs with the policy.
887
+ */
888
+ requiresApproval?: boolean;
825
889
  };
826
890
 
827
891
  /**
@@ -862,6 +926,19 @@ export declare interface ContextEntry {
862
926
  description?: string;
863
927
  /** Arbitrary structured data the AI should know about */
864
928
  data?: Record<string, unknown>;
929
+ /**
930
+ * Marks the entry as constant for the whole conversation. The backend then
931
+ * pins it right after the system prompt, where LLM providers cache it across
932
+ * turns, instead of re-processing it next to every new user message.
933
+ *
934
+ * Only set this when the entry's content is byte-identical on every message
935
+ * of a conversation (a schema, a capability list, static instructions). A
936
+ * stable entry that changes between messages invalidates the provider's
937
+ * cache for the entire conversation history, which costs more than leaving
938
+ * the flag off. Default: `false` (re-sent near the newest user message).
939
+ * Backends that don't know the flag ignore it.
940
+ */
941
+ stable?: boolean;
865
942
  }
866
943
 
867
944
  /**
@@ -1160,10 +1237,22 @@ export declare interface FormCollector<V = Record<string, unknown>> {
1160
1237
  store: Store<FormCollectorState<V>>;
1161
1238
  /** Client functions to register: `[update]` or `[update, submit]`. */
1162
1239
  functions: ClientFunctionDefinition[];
1163
- /** Dynamic-context key under which the form state is exposed. */
1240
+ /** Dynamic-context key under which the live form state is exposed. */
1164
1241
  contextKey: string;
1165
- /** Dynamic-context provider — re-read on every message. */
1242
+ /**
1243
+ * Dynamic-context provider for the live form state (phase, values, missing)
1244
+ * — re-read on every message. The schema itself rides in the companion
1245
+ * {@link definitionContextProvider} entry.
1246
+ */
1166
1247
  contextProvider: () => ContextEntry;
1248
+ /** Context key of the stable form definition (`<contextKey>:definition`). */
1249
+ definitionContextKey: string;
1250
+ /**
1251
+ * Provider for the form's definition (description + schema): identical on
1252
+ * every message and marked `stable: true`, so the backend can pin it in the
1253
+ * cacheable part of the prompt. Registered/removed by `install` alongside `contextProvider`.
1254
+ */
1255
+ definitionContextProvider: () => ContextEntry;
1167
1256
  /** Register the functions + dynamic context on a client. Returns an uninstall fn. */
1168
1257
  install: (client: AgoClient) => () => void;
1169
1258
  /**
@@ -1567,6 +1656,8 @@ export declare interface RegisteredFunction {
1567
1656
  handler: ClientFunctionHandler;
1568
1657
  /** Per-function result-size ceiling; falls back to the registry default. */
1569
1658
  maxResultBytes?: number;
1659
+ /** Require explicit user approval before running (pause mode only). */
1660
+ requiresApproval?: boolean;
1570
1661
  }
1571
1662
 
1572
1663
  /**
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
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-CApuQZ2b.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-q39FIjSC.js";
3
- import { t as $ } from "./autoContinue-D3Mmaaca.js";
4
- import { i as Q, n as V, r as W, t as X } from "./createFormCollector-sB6rMccD.js";
5
- import { t as Z } from "./createConversationSession-DCSWShaW.js";
6
- import { t as oe } from "./createMockClient-BUc9PSbo.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";
7
7
  import "./testing.js";
8
8
  function re(e) {
9
9
  return e;
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-wcPRaIMs.cjs"),J=require("./autoContinue-CcCTva-D.cjs"),I=require("./createFormCollector-eimwwWEi.cjs"),V=require("./createMockClient-CjdCqixj.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 q(e){const[t,r]=(0,s.useState)(!1),n=(0,s.useRef)(null),a=(0,s.useMemo)(()=>{if(n.current&&(n.current.destroy(),n.current=null),!e)return null;const l=new F.AgoClient(e);return n.current=l,l},[e?.baseUrl,e?.widgetId]);return(0,s.useEffect)(()=>(r(!0),()=>{n.current?.destroy(),n.current=null}),[a]),(0,s.useEffect)(()=>{n.current&&e&&n.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:t}}var z=(0,s.createContext)(null),Y=({children:e,client:t,tools:r,helpers:n,pageContext:a,...l})=>{const{client:d}=q(t?null:l),c=t||d;return(0,s.useEffect)(()=>{if(!(!r||r.length===0)){for(const g of r)c.register(g);return()=>{for(const g of r)c.unregisterFunction(g.name)}}},[c,r]),(0,s.useEffect)(()=>{if(!n)return;const g=[];return Promise.resolve().then(()=>require("./functions-IGSjjvF4.cjs")).then(f=>f.functions_exports).then(f=>{for(const[b,C]of Object.entries(n)){const j=f[b];if(!j){console.warn(`[AGO] Unknown helper: "${b}"`);continue}const h=C===!0?j:{...j,handler:C};c.register(h),g.push(h.name)}}),()=>{for(const f of g)c.unregisterFunction(f)}},[c,n]),(0,s.useEffect)(()=>{a==="auto"&&c.enableAutoPageContext()},[c,a]),(0,o.jsx)(z.Provider,{value:c,children:e})};function M(){const e=(0,s.useContext)(z);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function N(){return(0,s.useContext)(z)}function L({client:e,conversationId:t}={}){const r=N(),n=e||r;if(!n)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)(t),[g,f]=(0,s.useState)(!1),[b,C]=(0,s.useState)(null);(0,s.useEffect)(()=>{t&&t!==d&&(c(t),j(t))},[t]);const j=async h=>{try{l((await n.getMessages(h)).filter(y=>!y.hidden))}catch(y){C(y instanceof Error?y:new Error("Failed to load messages"))}};return(0,s.useEffect)(()=>{const h=u=>u==="IN_PROGRESS"||u==="WAITING_CLIENT",y=u=>{d||c(u.conversationId),f(!0),l(p=>{const m=p.findIndex(x=>x.id===u.messageId);return m>=0?p.map((x,_)=>_===m?{...x,status:"IN_PROGRESS"}:x):p.some(x=>x.role==="assistant"&&h(x.status))?p:[...p,{id:u.messageId,conversationId:u.conversationId,content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}]})},S=u=>{l(p=>{const m=p.findIndex(x=>x.id===u.messageId);return m<0?p:p.map((x,_)=>_===m?{...x,content:x.content+u.content}:x)})},k=u=>{l(p=>{let m=-1;for(let x=p.length-1;x>=0;x--)if(p[x].role==="assistant"&&h(p[x].status)){m=x;break}return m<0?p:[...p.slice(0,m),{...p[m],...u},...p.slice(m+1)]})},i=u=>{l(p=>{const m=p.findIndex(x=>x.id===u.id);return m>=0?[...p.slice(0,m),u,...p.slice(m+1)]:[...p,u]}),f(!1)},v=u=>{C(new Error(u.error)),f(!1)};return n.on("message:start",y),n.on("message:chunk",S),n.on("message:answer-complete",k),n.on("message:complete",i),n.on("message:error",v),()=>{n.off("message:start",y),n.off("message:chunk",S),n.off("message:answer-complete",k),n.off("message:complete",i),n.off("message:error",v)}},[n,d]),{messages:a,isLoading:g,error:b,sendMessage:(0,s.useCallback)(async(h,y)=>{f(!0),C(null);const S={id:`temp-${Date.now()}`,conversationId:d||"",content:h,role:"user",status:"DONE",attachments:y&&y.length>0?F.attachmentsFromFiles(y):void 0,createdAt:new Date},k={id:`temp-assistant-${Date.now()}`,conversationId:d||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};l(i=>[...i,S,k]);try{const i=await n.sendMessage(h,{conversationId:d,files:y});return i.conversationId&&!d&&c(i.conversationId),l(v=>{const u=v.filter(m=>!m.id.startsWith("temp-")),p={...S,id:S.id.replace("temp-","user-"),conversationId:i.conversationId};return u.some(m=>m.id===i.id)?[...u,p].sort((m,x)=>new Date(m.createdAt).getTime()-new Date(x.createdAt).getTime()):[...u,p,i]}),i}catch(i){return C(i instanceof Error?i:new Error("Failed to send message")),f(!1),l(v=>v.filter(u=>!u.id.startsWith("temp-"))),null}},[n,d]),clearMessages:(0,s.useCallback)(()=>{l([]),c(void 0),C(null)},[]),conversationId:d}}var H=({onSend:e,disabled:t=!1,placeholder:r="Type a message...",allowFiles:n=!1,className:a=""})=>{const[l,d]=(0,s.useState)(""),[c,g]=(0,s.useState)([]),f=(0,s.useRef)(null),b=(0,s.useRef)(null),C=(0,s.useCallback)(()=>{const i=b.current;if(!i)return;const v=110;i.style.height="auto",i.style.height=`${Math.min(i.scrollHeight+2,v)}px`,i.style.overflowY=i.scrollHeight+2>v?"auto":"hidden"},[]),j=(0,s.useCallback)(i=>{i.preventDefault(),(l.trim()||c.length>0)&&(e(l.trim(),c.length>0?c:void 0),d(""),g([]),requestAnimationFrame(C))},[l,c,e,C]),h=(0,s.useCallback)(i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),j(i))},[j]),y=(0,s.useCallback)(i=>{const v=Array.from(i.target.files||[]);g(u=>[...u,...v])},[]),S=(0,s.useCallback)(i=>{g(v=>v.filter((u,p)=>p!==i))},[]),k=l.trim()||c.length>0;return(0,o.jsxs)("form",{onSubmit:j,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,v)=>(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(v),"aria-label":`Remove ${i.name}`,style:{border:"none",background:"none",cursor:"pointer",padding:"0",color:"#6b6d6f",fontSize:"14px",lineHeight:1},children:"×"})]},v))}),(0,o.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"flex-end"},children:[n&&(0,o.jsxs)(o.Fragment,{children:[(0,o.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,o.jsx)("input",{ref:f,type:"file",multiple:!0,onChange:y,style:{display:"none"}})]}),(0,o.jsx)("textarea",{ref:b,value:l,onChange:i=>{d(i.target.value),C()},onKeyDown:h,placeholder:r,"aria-label":r,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:i=>{i.currentTarget.style.borderColor="#1b5fc4"},onBlur:i=>{i.currentTarget.style.borderColor="#dee3e8"}}),(0,o.jsx)("button",{type:"submit",disabled:t||!k,style:{padding:"10px 18px",border:"none",borderRadius:"20px",backgroundColor:t||!k?"#b5bfc8":"#03182f",color:"#fff",cursor:t||!k?"not-allowed":"pointer",fontWeight:500,fontSize:"16px",transition:"background-color 0.15s"},children:"Send"})]})]})},X=({href:e,children:t,...r})=>(0,o.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"#1b5fc4",textDecoration:"underline"},...r,children:t}),Q=({children:e,...t})=>(0,o.jsx)("p",{style:{margin:"0 0 8px 0",lineHeight:"1.6"},...t,children:e}),R=(e,t)=>{const r=({children:n,...a})=>s.default.createElement(`h${e}`,{style:{margin:"16px 0 8px 0",fontSize:t,fontWeight:600,lineHeight:"1.3"},...a},n);return r.displayName=`MarkdownHeading${e}`,r},Z=({children:e,...t})=>(0,o.jsx)("ul",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"disc",listStylePosition:"outside"},...t,children:e}),ee=({children:e,...t})=>(0,o.jsx)("ol",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"decimal",listStylePosition:"outside"},...t,children:e}),te=({children:e,...t})=>(0,o.jsx)("li",{style:{display:"list-item",margin:"2px 0",lineHeight:"1.6"},...t,children:e}),ne=({className:e,children:t,...r})=>e!==void 0||String(t).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:t}):(0,o.jsx)("code",{style:{background:"#f0f2f5",padding:"2px 5px",borderRadius:"4px",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},...r,children:t}),re=({children:e,...t})=>(0,o.jsx)("pre",{style:{margin:"0 0 8px 0"},...t,children:e}),oe=({children:e,...t})=>(0,o.jsx)("blockquote",{style:{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"},...t,children:e}),se=({children:e,...t})=>(0,o.jsx)("div",{style:{overflowX:"auto",margin:"0 0 8px 0"},children:(0,o.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"13px"},...t,children:e})}),ae=({children:e,...t})=>(0,o.jsx)("th",{style:{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:600},...t,children:e}),ie=({children:e,...t})=>(0,o.jsx)("td",{style:{border:"1px solid #dee3e8",padding:"6px 10px"},...t,children:e}),le=({alt:e,...t})=>(0,o.jsx)("img",{alt:e??"",style:{maxWidth:"100%",borderRadius:"8px",margin:"4px 0"},...t}),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],O=({content:e})=>(0,o.jsx)(P.default,{remarkPlugins:ue,components:de,children:e}),fe=({attachment:e,isUser:t})=>{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 n=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}),n&&(0,o.jsx)("span",{style:{fontSize:"11px",color:"#6b6d6f"},children:n})]})]}),l={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 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:t})=>{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:t+1}),(0,o.jsx)("div",{style:{fontSize:"12px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#30373e"},title:e.title,children:e.title})]}),n={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:n,onMouseEnter:a=>{a.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:a=>{a.currentTarget.style.borderColor="#dee3e8"},children:r}):(0,o.jsx)("div",{style:n,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
- `})]}),$=({message:e,className:t="",showAgentName:r=!1,isLast:n=!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} ${t}`,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,g)=>(0,o.jsx)(ge,{source:c,index:g},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)(O,{content:e.content}):d&&(0,o.jsx)(pe,{})}),n&&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,g)=>(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:f=>{f.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:f=>{f.currentTarget.style.borderColor="#dee3e8"},children:c},g))})]})},xe=({client:e,conversationId:t,title:r="Chat",welcomeMessage:n="Hello! How can I help you today?",placeholder:a="Type a message...",allowFiles:l=!1,height:d=500,logoUrl:c,showAgentName:g=!1,forms:f,onFollowUpClick:b,className:C="",onMessageSent:j,onMessageReceived:h})=>{const y=(0,s.useRef)(null),S=N(),k=e??S,{messages:i,isLoading:v,error:u,sendMessage:p}=L({client:e,conversationId:t});(0,s.useEffect)(()=>{if(!k||!f||f.length===0)return;let w=!1;const A=[];return Promise.all(f.map(E=>E.schema!=null?Promise.resolve(I.createFormCollector(E)):I.loadFormCollector(k,E))).then(E=>{if(!w)for(const U of E)A.push(U.install(k))}).catch(()=>{}),()=>{w=!0,A.forEach(E=>E())}},[k,f?JSON.stringify(f.map(w=>[w.name,w.schema??null,w.submit??!1,w.description??null])):""]),(0,s.useEffect)(()=>{y.current?.scrollIntoView({behavior:"smooth"})},[i]),(0,s.useEffect)(()=>{const w=i[i.length-1];w&&w.role==="assistant"&&w.status==="DONE"&&h&&h({id:w.id,content:w.content})},[i,h]);const m=async(w,A)=>{j?.(w),await p(w,A)},x=i[i.length-1],_=v&&x?.role==="assistant"&&(x.status==="IN_PROGRESS"||x.status==="WAITING_CLIENT"),K=b===!1?void 0:b??(w=>m(w));return(0,o.jsxs)("div",{className:`ago-chat-widget ${C}`,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:n}):i.map((w,A)=>(0,o.jsx)($,{message:w,showAgentName:g,isLast:A===i.length-1,onFollowUpClick:K},w.id)),u&&(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:u.message}),(0,o.jsx)("div",{ref:y})]}),(0,o.jsx)(H,{onSend:m,disabled:_,placeholder:a,allowFiles:l})]})};function B({client:e,autoLoad:t=!0}={}){const r=N(),n=e||r;if(!n)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),[g,f]=(0,s.useState)(!1),[b,C]=(0,s.useState)(null),j=(0,s.useCallback)(async()=>{f(!0),C(null);try{l(await n.getConversations())}catch(S){C(S instanceof Error?S:new Error("Failed to load conversations"))}finally{f(!1)}},[n]),h=(0,s.useCallback)(async S=>{f(!0),C(null);try{c(await n.getConversation(S))}catch(k){C(k instanceof Error?k:new Error("Failed to load conversation"))}finally{f(!1)}},[n]),y=(0,s.useCallback)(()=>{c(null)},[]);return(0,s.useEffect)(()=>{t&&j()},[t,j]),{conversations:a,currentConversation:d,isLoading:g,error:b,selectConversation:h,startNewConversation:y,refreshConversations:j}}function me(e={}){const t=N(),r=e.client||t;if(!r)throw new Error("useChat requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const n=L({client:r,conversationId:e.conversationId}),a=B({client:r,autoLoad:e.autoLoad});return{messages:n.messages,isLoading:n.isLoading,error:n.error||a.error,sendMessage:n.sendMessage,clearMessages:n.clearMessages,conversationId:n.conversationId,conversations:a.conversations,currentConversation:a.currentConversation,isConversationsLoading:a.isLoading,selectConversation:a.selectConversation,startNewConversation:a.startNewConversation,refreshConversations:a.refreshConversations}}function he(e,t){const r=M(),{name:n,description:a,parameters:l,handler:d,maxResultBytes:c}=typeof e=="string"?{name:e,...t}:e,g=(0,s.useRef)(d);g.current=d,(0,s.useEffect)(()=>{const f=b=>g.current(b);return r.registerFunction(n,f,{description:a,parameters:l,maxResultBytes:c}),()=>{r.unregisterFunction(n)}},[r,n,a,l,c])}function ye(e,t){const r=M(),n=(0,s.useRef)(e);n.current=e,(0,s.useEffect)(()=>(r.registerNavigationFunction(a=>n.current(a),t),()=>{r.unregisterNavigationFunction()}),[r,t])}function be(e,t){const r=M(),n=t?.functionName??"setPageState",a=(0,s.useRef)(e);a.current=e,(0,s.useEffect)(()=>{const l=a.current.map(d=>{const c=()=>a.current.find(g=>g.name===d.name)??d;return{name:d.name,description:d.description,schema:d.schema,get:d.get?()=>c().get?.():void 0,set:g=>c().set(g)}});return r.registerPageStateFunction(l,{functionName:n}),()=>{r.unregisterPageStateFunction(n)}},[r,n])}function ve(e){const t=M(),r=(0,s.useRef)(e);r.current=e,(0,s.useEffect)(()=>J.attachAutoContinueAfterNavigation(t,()=>r.current),[t])}function Ce(e,t){const r=M(),n=(0,s.useId)(),a=t??n,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 G(e){return(0,s.useSyncExternalStore)(e.subscribe,e.get,e.get)}var D={missing:[],complete:!1};function we(e){const t=M(),r=e.schema!=null,n=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?I.createFormCollector(e):null,[r,e.name,n,l,d,e.autoSubmit]),[g,f]=(0,s.useState)({collector:null,loading:!r,error:null});(0,s.useEffect)(()=>{if(r)return;let v=!1;return f({collector:null,loading:!0,error:null}),I.loadFormCollector(t,e).then(u=>{v||f({collector:u,loading:!1,error:null})}).catch(u=>{v||f({collector:null,loading:!1,error:u instanceof Error?u:new Error(String(u))})}),()=>{v=!0}},[t,r,e.name,l,d,e.autoSubmit]);const b=r?c:g.collector,C=r?!1:g.loading,j=r?null:g.error;(0,s.useEffect)(()=>{if(b)return b.install(t)},[t,b]);const h=(0,s.useMemo)(()=>I.createStore({values:e.initialValues??{},submitted:!1}),[d]),y=G(b?.store??h),S=(0,s.useMemo)(()=>b?.getStatus()??D,[y,b]),k=(0,s.useMemo)(()=>({...y,...S}),[y,S]),i=(0,s.useMemo)(()=>({name:e.name,store:h,functions:[],contextKey:`form:${e.name}`,contextProvider:()=>({name:`Form: ${e.name}`,description:""}),install:()=>()=>{},hydrate:()=>{},submit:async()=>({ok:!1,error:"Form definition not loaded yet."}),getValues:()=>h.get().values,setValues:()=>{},reset:()=>{},getStatus:()=>D}),[e.name,h]);return{...b??i,state:k,loading:C,error:j}}exports.AgoProvider=Y;exports.ChatInput=H;exports.ChatWidget=xe;exports.Markdown=O;exports.Message=$;exports.createFormCollector=I.createFormCollector;exports.createMockClient=V.createMockClient;exports.deriveFormStatus=I.deriveFormStatus;exports.loadFormCollector=I.loadFormCollector;exports.useAgo=q;exports.useAgoAutoContinueAfterNavigation=ve;exports.useAgoClient=M;exports.useAgoContext=Ce;exports.useAgoFunction=he;exports.useAgoNavigation=ye;exports.useAgoPageState=be;exports.useAgoStore=G;exports.useChat=me;exports.useConversation=B;exports.useFormCollector=we;exports.useMessages=L;exports.useOptionalAgoClient=N;
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;