@useago/sdk 1.4.3 → 1.4.4
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/dist/AgoClient-CLmtYTJx.cjs +8 -0
- package/dist/{AgoClient-S8oeNnAE.js → AgoClient-Ozz2b1dQ.js} +104 -80
- package/dist/angular.cjs +1 -1
- package/dist/angular.d.cts +30 -2
- package/dist/angular.d.ts +30 -2
- package/dist/angular.js +1 -1
- package/dist/{createConversationSession-CmBq7uGi.cjs → createConversationSession-CUkNp6mZ.cjs} +1 -1
- package/dist/{createConversationSession-DoUHdVNR.js → createConversationSession-QIBN0gLx.js} +1 -1
- package/dist/{createFormCollector-Bz_0IJ0Q.cjs → createFormCollector-DHT1ObOb.cjs} +1 -1
- package/dist/{createFormCollector-vy-QvFja.js → createFormCollector-F3YJfsbg.js} +1 -1
- package/dist/devtools.d.cts +29 -1
- package/dist/devtools.d.ts +29 -1
- package/dist/helpers.d.cts +6 -0
- package/dist/helpers.d.ts +6 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +49 -2
- package/dist/index.d.ts +49 -2
- package/dist/index.js +3 -3
- package/dist/react.cjs +2 -2
- package/dist/react.d.cts +35 -1
- package/dist/react.d.ts +35 -1
- package/dist/react.js +100 -98
- package/dist/testing.d.cts +29 -1
- package/dist/testing.d.ts +29 -1
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +35 -1
- package/dist/vue.d.ts +35 -1
- package/dist/vue.js +22 -21
- package/dist/widget.cjs +1 -1
- package/dist/widget.d.cts +29 -1
- package/dist/widget.d.ts +29 -1
- package/dist/widget.js +3 -3
- package/llms-full.txt +1910 -0
- package/package.json +5 -3
- package/dist/AgoClient-CMDVqNaH.cjs +0 -8
package/dist/{createConversationSession-CmBq7uGi.cjs → createConversationSession-CUkNp6mZ.cjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
const d=require("./createFormCollector-
|
|
1
|
+
const d=require("./createFormCollector-DHT1ObOb.cjs");var f="ago_widget_id",g="ago_last_thread",y=7200*1e3;function v(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.floor(Math.random()*16);return(e==="x"?r:r&3|8).toString(16)})}function _(e={}){const r=e.key??f,i=e.threadKey??g,u=e.ttlMs??y,l=e.storage??(typeof localStorage<"u"?localStorage:void 0);let n=e.widgetId??"";if(!n&&l)try{n=l.getItem(r)??""}catch{}if(n||(n=v()),l)try{l.setItem(r,n)}catch{}const o=d.createStore({value:null,lastMessageAt:null},{key:i,storage:l}),c=o.get();c.value!==null&&s(c.lastMessageAt)&&o.set({value:null,lastMessageAt:null});function s(t){return t===null?!0:Number.isFinite(u)?Date.now()-t>u:!1}return{widgetId:n,key:r,getLastActiveThread(){const{value:t,lastMessageAt:a}=o.get();return t===null||s(a)?null:t},setActiveThread(t,a){const x=a==null?null:a instanceof Date?a.getTime():a;o.set({value:t,lastMessageAt:x})},clear(){o.set({value:null,lastMessageAt:null})}}}Object.defineProperty(exports,"createConversationSession",{enumerable:!0,get:function(){return _}});
|
package/dist/{createConversationSession-DoUHdVNR.js → createConversationSession-QIBN0gLx.js}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as d } from "./createFormCollector-
|
|
1
|
+
import { i as d } from "./createFormCollector-F3YJfsbg.js";
|
|
2
2
|
var f = "ago_widget_id", g = "ago_last_thread", y = 7200 * 1e3;
|
|
3
3
|
function v() {
|
|
4
4
|
return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const C=require("./AgoClient-
|
|
1
|
+
const C=require("./AgoClient-CLmtYTJx.cjs");function W(n,e){const a=e?e.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let s=n;if(e&&a)try{const m=a.getItem(e.key);m!=null&&(s=JSON.parse(m))}catch{}const i=new Set,c=()=>i.forEach(m=>m(s));function b(){if(e&&a)try{a.setItem(e.key,JSON.stringify(s))}catch{}}return{get:()=>s,set:m=>{s=m,b(),c()},subscribe:m=>(i.add(m),()=>{i.delete(m)})}}var T=/^[a-zA-Z0-9_-]{1,40}$/,x=n=>n==null||n==="";function v(n,e){if("anyOf"in n)return n.anyOf.some(c=>v(c,e));if("allOf"in n)return n.allOf.every(c=>v(c,e));const a=e[n.property];if(x(a))return!1;if(Array.isArray(n.value))return n.value.some(c=>String(a)===String(c));if(!n.op)return String(a)===String(n.value);const s=Number(a),i=Number(n.value);if(Number.isNaN(s)||Number.isNaN(i))return!1;switch(n.op){case">=":return s>=i;case"<=":return s<=i;case">":return s>i;case"<":return s<i;default:return C.logger.warn(`Unknown requiredWhen op "${n.op}"; treating as not required.`),!1}}function h(n,e){const a=n.properties??{},s=new Set;for(const c of n.required??[]){const b=a[c]?.requiredWhen;(!b||v(b,e))&&s.add(c)}for(const[c,b]of Object.entries(a))b.requiredWhen&&v(b.requiredWhen,e)&&s.add(c);const i=[...s].filter(c=>x(e[c]));return{missing:i,complete:i.length===0}}function R(n){const e={};for(const[a,s]of Object.entries(n.properties??{}))e[a]={type:s.type,...s.description!=null&&{description:s.description},...s.enum&&{enum:s.enum},...s.default!==void 0&&{default:s.default}};return{type:"object",properties:e,required:[]}}function A(n){const{name:e,description:a,schema:s}=n;if(!T.test(e))throw new Error(`Invalid form collector name "${e}": must match ${T} (it becomes the update_/submit_ function names).`);const i=typeof n.submit=="string"?n.submit?{via:"client",url:n.submit}:!1:n.submit??!1;n.autoSubmit===!0&&!i&&C.logger.warn(`FormCollector "${e}": autoSubmit is ignored because no submit target is configured.`);const c=(n.autoSubmit??!0)&&!!i,b=s.properties??{},m=t=>{const r={};for(const[u,o]of Object.entries(t)){const l=b[u];if(l)if(o==null)r[u]=o;else if(l.type==="number"||l.type==="integer"){const d=typeof o=="number"?o:Number(o);r[u]=Number.isNaN(d)?o:d}else l.type==="boolean"?r[u]=typeof o=="boolean"?o:o==="true"?!0:o==="false"?!1:!!o:r[u]=o}return r},S=n.initialValues??{},f=W({values:S,submitted:!1}),$=t=>{const r=f.get(),u={...r,values:{...r.values,...t}};return f.set(u),u};let g=null;const F=(t,r)=>{g?.emitFormEvent("form:error",{name:e,values:t,error:r})};let y=null;const I=async()=>{const{values:t}=f.get(),{complete:r,missing:u}=h(s,t);if(!r)return{ok:!1,missing:u};if(!i)return{ok:!1,error:"No submit target configured for this form collector."};const o=t;try{let l;if(i.via==="client")if("handler"in i)l=await i.handler(o);else{const d=await fetch(i.url,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(o)});if(!d.ok){const j=`Submit failed: HTTP ${d.status}`;return F(o,j),{ok:!1,error:j}}l=await d.json().catch(()=>{})}else{if(!g)return{ok:!1,error:"Backend submit requires install(client) (or useFormCollector) first."};l=await g.submitFormCollector(e,o)}return f.set({...f.get(),submitted:!0,submitResult:l}),g?.emitFormEvent("form:submitted",{name:e,values:o,result:l}),{ok:!0,result:l}}catch(l){const d=l instanceof Error?l.message:"Submit failed";return C.logger.error(`FormCollector "${e}" submit failed:`,l),F(o,d),{ok:!1,error:d}}},N=()=>y||(y=(async()=>{try{return await I()}finally{y=null}})(),y),k=async()=>{if(!c||!i)return null;const{values:t,submitted:r}=f.get();return r||!h(s,t).complete?null:N()},O={name:`update_${e}`,description:`Fill or update fields of the "${e}" form. ${a} Pass any subset of fields; call it repeatedly to fill the form as the user provides information. Returns the current values and which required fields are still missing.`,parameters:R(s),handler:async t=>{const r=$(m(t)),{missing:u}=h(s,r.values),o=await k();return o?o.ok?{ok:!0,values:r.values,missing:u,submitted:!0}:{ok:!0,values:r.values,missing:u,submitted:!1,submitError:o.error}:{ok:!0,values:r.values,missing:u}}},p=[O];i&&!c&&p.push({name:`submit_${e}`,description:`Submit the completed "${e}" form. Only call this once every required field is collected and the user has confirmed. If fields are missing it returns them instead of submitting.`,parameters:{type:"object",properties:{}},handler:()=>N()});const V="client__",q=i?`submit_${e}`:null,J=t=>{const r=t.functionName??t.toolName;if(r)return r.startsWith(V)?r.slice(8):r},_=t=>{let r={...S},u=!1;for(const o of t){const l=J(o);l===O.name?o.arguments&&(r={...r,...m(o.arguments)}):q&&l===q&&o.status?.toLowerCase()==="done"&&(u=!0)}f.set({values:r,submitted:u})},w=`form:${e}`,E=()=>{const{values:t,submitted:r}=f.get(),{missing:u,complete:o}=h(s,t),l=i?c?" The form is submitted automatically as soon as every required field is filled, so there is no submit function to call.":` When nothing is missing and the user confirms, call submit_${e}.`:"",d=r?`The "${e}" form has been submitted.`:`You are currently collecting information from the user to fill the "${e}" form.`;return{name:`Form: ${e}`,description:`${d} ${a} Some fields are conditionally required; the requiredWhen field in the schema tells you when each becomes required. The form schema is the following: ${JSON.stringify(s)}. Data collected so far: ${JSON.stringify(t)}. Call update_${e} with any fields the user provides; ask only for what is still missing.${l}`,data:{values:t,missing:u,complete:o,submitted:r}}},P=t=>{_((t.messages??[]).flatMap(r=>r.toolCalls??[]))};return{name:e,store:f,functions:p,contextKey:w,contextProvider:E,install:t=>{g=t;for(const u of p)t.register(u);t.addDynamicContext(w,E);const r=f.subscribe(()=>t.notifyContextChanged());return t.on("conversation:loaded",P),()=>{r();for(const u of p)t.unregisterFunction(u.name);t.removeDynamicContext(w),t.off("conversation:loaded",P),g===t&&(g=null)}},hydrate:_,submit:N,getValues:()=>f.get().values,setValues:t=>{$(m(t)),k()},reset:()=>{f.set({values:S,submitted:!1})},getStatus:()=>h(s,f.get().values)}}async function B(n,e){const a=await n.getFormCollector(e.name);return A({name:a.name,description:e.description??a.description,schema:e.schema??a.schema,submit:e.submit??a.submit,initialValues:e.initialValues,autoSubmit:e.autoSubmit??a.autoSubmit})}Object.defineProperty(exports,"createFormCollector",{enumerable:!0,get:function(){return A}});Object.defineProperty(exports,"createStore",{enumerable:!0,get:function(){return W}});Object.defineProperty(exports,"deriveFormStatus",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"loadFormCollector",{enumerable:!0,get:function(){return B}});
|
package/dist/devtools.d.cts
CHANGED
|
@@ -175,7 +175,7 @@ declare class AgoClient {
|
|
|
175
175
|
* ```
|
|
176
176
|
*/
|
|
177
177
|
registerFunction(definition: ClientFunctionDefinition): void;
|
|
178
|
-
registerFunction(name: string, handler: ClientFunctionHandler, schema:
|
|
178
|
+
registerFunction(name: string, handler: ClientFunctionHandler, schema: ClientFunctionRegisterOptions): void;
|
|
179
179
|
/**
|
|
180
180
|
* Short alias for `registerFunction`. Also accepts an array of definitions.
|
|
181
181
|
*
|
|
@@ -484,6 +484,14 @@ declare interface AgoConfig {
|
|
|
484
484
|
* Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
|
|
485
485
|
*/
|
|
486
486
|
clientFunctionsMode?: ClientFunctionsMode;
|
|
487
|
+
/**
|
|
488
|
+
* Max serialized size (bytes) of a client function result before the SDK
|
|
489
|
+
* replaces it with a flagged, truncated preview. Everything a handler
|
|
490
|
+
* returns is sent into the LLM context, so this caps runaway payloads
|
|
491
|
+
* (raw API responses, full tables). Default `50000`. Override per function
|
|
492
|
+
* with `maxResultBytes` on its definition; `Infinity` disables the guard.
|
|
493
|
+
*/
|
|
494
|
+
maxFunctionResultBytes?: number;
|
|
487
495
|
}
|
|
488
496
|
|
|
489
497
|
declare type AgoEventHandler<K extends AgoEventName> = (data: AgoClientEvents[K]) => void;
|
|
@@ -575,6 +583,12 @@ declare interface ClientFunctionDefinition {
|
|
|
575
583
|
description: string;
|
|
576
584
|
parameters: ClientFunctionSchema["parameters"];
|
|
577
585
|
handler: ClientFunctionHandler;
|
|
586
|
+
/**
|
|
587
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
588
|
+
* flagged preview (default: `AgoConfig.maxFunctionResultBytes`, 50 000).
|
|
589
|
+
* `Infinity` disables the guard for this function.
|
|
590
|
+
*/
|
|
591
|
+
maxResultBytes?: number;
|
|
578
592
|
}
|
|
579
593
|
|
|
580
594
|
/**
|
|
@@ -589,6 +603,20 @@ declare interface ClientFunctionInvocation {
|
|
|
589
603
|
conversationId: string;
|
|
590
604
|
}
|
|
591
605
|
|
|
606
|
+
/**
|
|
607
|
+
* Schema-plus-settings object accepted when registering a function: the schema
|
|
608
|
+
* (minus `name`) and SDK-side options that are NOT sent to the backend.
|
|
609
|
+
*/
|
|
610
|
+
declare type ClientFunctionRegisterOptions = Omit<ClientFunctionSchema, "name"> & {
|
|
611
|
+
/**
|
|
612
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
613
|
+
* flagged preview. Overrides the client-level default
|
|
614
|
+
* (`AgoConfig.maxFunctionResultBytes`, 50 000 by default). `Infinity`
|
|
615
|
+
* disables the guard for this function.
|
|
616
|
+
*/
|
|
617
|
+
maxResultBytes?: number;
|
|
618
|
+
};
|
|
619
|
+
|
|
592
620
|
/**
|
|
593
621
|
* Schema for a client-side function that AGO can call
|
|
594
622
|
*/
|
package/dist/devtools.d.ts
CHANGED
|
@@ -175,7 +175,7 @@ declare class AgoClient {
|
|
|
175
175
|
* ```
|
|
176
176
|
*/
|
|
177
177
|
registerFunction(definition: ClientFunctionDefinition): void;
|
|
178
|
-
registerFunction(name: string, handler: ClientFunctionHandler, schema:
|
|
178
|
+
registerFunction(name: string, handler: ClientFunctionHandler, schema: ClientFunctionRegisterOptions): void;
|
|
179
179
|
/**
|
|
180
180
|
* Short alias for `registerFunction`. Also accepts an array of definitions.
|
|
181
181
|
*
|
|
@@ -484,6 +484,14 @@ declare interface AgoConfig {
|
|
|
484
484
|
* Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
|
|
485
485
|
*/
|
|
486
486
|
clientFunctionsMode?: ClientFunctionsMode;
|
|
487
|
+
/**
|
|
488
|
+
* Max serialized size (bytes) of a client function result before the SDK
|
|
489
|
+
* replaces it with a flagged, truncated preview. Everything a handler
|
|
490
|
+
* returns is sent into the LLM context, so this caps runaway payloads
|
|
491
|
+
* (raw API responses, full tables). Default `50000`. Override per function
|
|
492
|
+
* with `maxResultBytes` on its definition; `Infinity` disables the guard.
|
|
493
|
+
*/
|
|
494
|
+
maxFunctionResultBytes?: number;
|
|
487
495
|
}
|
|
488
496
|
|
|
489
497
|
declare type AgoEventHandler<K extends AgoEventName> = (data: AgoClientEvents[K]) => void;
|
|
@@ -575,6 +583,12 @@ declare interface ClientFunctionDefinition {
|
|
|
575
583
|
description: string;
|
|
576
584
|
parameters: ClientFunctionSchema["parameters"];
|
|
577
585
|
handler: ClientFunctionHandler;
|
|
586
|
+
/**
|
|
587
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
588
|
+
* flagged preview (default: `AgoConfig.maxFunctionResultBytes`, 50 000).
|
|
589
|
+
* `Infinity` disables the guard for this function.
|
|
590
|
+
*/
|
|
591
|
+
maxResultBytes?: number;
|
|
578
592
|
}
|
|
579
593
|
|
|
580
594
|
/**
|
|
@@ -589,6 +603,20 @@ declare interface ClientFunctionInvocation {
|
|
|
589
603
|
conversationId: string;
|
|
590
604
|
}
|
|
591
605
|
|
|
606
|
+
/**
|
|
607
|
+
* Schema-plus-settings object accepted when registering a function: the schema
|
|
608
|
+
* (minus `name`) and SDK-side options that are NOT sent to the backend.
|
|
609
|
+
*/
|
|
610
|
+
declare type ClientFunctionRegisterOptions = Omit<ClientFunctionSchema, "name"> & {
|
|
611
|
+
/**
|
|
612
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
613
|
+
* flagged preview. Overrides the client-level default
|
|
614
|
+
* (`AgoConfig.maxFunctionResultBytes`, 50 000 by default). `Infinity`
|
|
615
|
+
* disables the guard for this function.
|
|
616
|
+
*/
|
|
617
|
+
maxResultBytes?: number;
|
|
618
|
+
};
|
|
619
|
+
|
|
592
620
|
/**
|
|
593
621
|
* Schema for a client-side function that AGO can call
|
|
594
622
|
*/
|
package/dist/helpers.d.cts
CHANGED
|
@@ -16,6 +16,12 @@ declare interface ClientFunctionDefinition {
|
|
|
16
16
|
description: string;
|
|
17
17
|
parameters: ClientFunctionSchema["parameters"];
|
|
18
18
|
handler: ClientFunctionHandler;
|
|
19
|
+
/**
|
|
20
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
21
|
+
* flagged preview (default: `AgoConfig.maxFunctionResultBytes`, 50 000).
|
|
22
|
+
* `Infinity` disables the guard for this function.
|
|
23
|
+
*/
|
|
24
|
+
maxResultBytes?: number;
|
|
19
25
|
}
|
|
20
26
|
|
|
21
27
|
/**
|
package/dist/helpers.d.ts
CHANGED
|
@@ -16,6 +16,12 @@ declare interface ClientFunctionDefinition {
|
|
|
16
16
|
description: string;
|
|
17
17
|
parameters: ClientFunctionSchema["parameters"];
|
|
18
18
|
handler: ClientFunctionHandler;
|
|
19
|
+
/**
|
|
20
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
21
|
+
* flagged preview (default: `AgoConfig.maxFunctionResultBytes`, 50 000).
|
|
22
|
+
* `Infinity` disables the guard for this function.
|
|
23
|
+
*/
|
|
24
|
+
maxResultBytes?: number;
|
|
19
25
|
}
|
|
20
26
|
|
|
21
27
|
/**
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./AgoClient-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./AgoClient-CLmtYTJx.cjs"),f=require("./createFormCollector-DHT1ObOb.cjs"),h=require("./createConversationSession-CUkNp6mZ.cjs"),p=require("./createMockClient-BSr-UV8R.cjs");require("./testing.cjs");const g=require("./functions-Djnq-JAo.cjs");function w(e){return e}function S(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function E(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function y(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function F(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 v(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 q(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*k(e,o,l){const a=[];let n=null,i=!1;const m=s=>{a.push(s),n?.()},c=s=>m({type:"start",data:s}),t=s=>m({type:"chunk",data:s}),u=s=>{m({type:"complete",data:s}),i=!0,n?.()},d=s=>{m({type:"error",data:s}),i=!0,n?.()},C=s=>m({type:"toolCall",data:s});e.on("message:start",c),e.on("message:chunk",t),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",C),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",c),e.off("message:chunk",t),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",C)}}function A(e){let o,l,a,n,i,m;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,m=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,m=e?.userJwt||m;const c=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:n,userEmail:i,userJwt:m,debug:c}:null}function T(e){const o=A(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 I(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.autoDetectConfig=A;exports.canInlineImage=r.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=T;exports.createConversationSession=h.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=k;exports.createMockClient=p.createMockClient;exports.createStore=f.createStore;exports.defineFunction=w;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=v;exports.onFunctionInvoke=q;exports.onMessage=S;exports.onMessageChunk=E;exports.onMessageError=F;exports.onMessageStart=y;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=I;
|
package/dist/index.d.cts
CHANGED
|
@@ -186,7 +186,7 @@ export declare class AgoClient {
|
|
|
186
186
|
* ```
|
|
187
187
|
*/
|
|
188
188
|
registerFunction(definition: ClientFunctionDefinition): void;
|
|
189
|
-
registerFunction(name: string, handler: ClientFunctionHandler, schema:
|
|
189
|
+
registerFunction(name: string, handler: ClientFunctionHandler, schema: ClientFunctionRegisterOptions): void;
|
|
190
190
|
/**
|
|
191
191
|
* Short alias for `registerFunction`. Also accepts an array of definitions.
|
|
192
192
|
*
|
|
@@ -495,6 +495,14 @@ export declare interface AgoConfig {
|
|
|
495
495
|
* Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
|
|
496
496
|
*/
|
|
497
497
|
clientFunctionsMode?: ClientFunctionsMode;
|
|
498
|
+
/**
|
|
499
|
+
* Max serialized size (bytes) of a client function result before the SDK
|
|
500
|
+
* replaces it with a flagged, truncated preview. Everything a handler
|
|
501
|
+
* returns is sent into the LLM context, so this caps runaway payloads
|
|
502
|
+
* (raw API responses, full tables). Default `50000`. Override per function
|
|
503
|
+
* with `maxResultBytes` on its definition; `Infinity` disables the guard.
|
|
504
|
+
*/
|
|
505
|
+
maxFunctionResultBytes?: number;
|
|
498
506
|
}
|
|
499
507
|
|
|
500
508
|
/**
|
|
@@ -733,6 +741,12 @@ export declare interface ClientFunctionDefinition {
|
|
|
733
741
|
description: string;
|
|
734
742
|
parameters: ClientFunctionSchema["parameters"];
|
|
735
743
|
handler: ClientFunctionHandler;
|
|
744
|
+
/**
|
|
745
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
746
|
+
* flagged preview (default: `AgoConfig.maxFunctionResultBytes`, 50 000).
|
|
747
|
+
* `Infinity` disables the guard for this function.
|
|
748
|
+
*/
|
|
749
|
+
maxResultBytes?: number;
|
|
736
750
|
}
|
|
737
751
|
|
|
738
752
|
/**
|
|
@@ -747,6 +761,20 @@ export declare interface ClientFunctionInvocation {
|
|
|
747
761
|
conversationId: string;
|
|
748
762
|
}
|
|
749
763
|
|
|
764
|
+
/**
|
|
765
|
+
* Schema-plus-settings object accepted when registering a function: the schema
|
|
766
|
+
* (minus `name`) and SDK-side options that are NOT sent to the backend.
|
|
767
|
+
*/
|
|
768
|
+
export declare type ClientFunctionRegisterOptions = Omit<ClientFunctionSchema, "name"> & {
|
|
769
|
+
/**
|
|
770
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
771
|
+
* flagged preview. Overrides the client-level default
|
|
772
|
+
* (`AgoConfig.maxFunctionResultBytes`, 50 000 by default). `Infinity`
|
|
773
|
+
* disables the guard for this function.
|
|
774
|
+
*/
|
|
775
|
+
maxResultBytes?: number;
|
|
776
|
+
};
|
|
777
|
+
|
|
750
778
|
/**
|
|
751
779
|
* Schema for a client-side function that AGO can call
|
|
752
780
|
*/
|
|
@@ -1244,12 +1272,16 @@ export declare interface FunctionDefinition {
|
|
|
1244
1272
|
*/
|
|
1245
1273
|
export declare class FunctionRegistry {
|
|
1246
1274
|
private functions;
|
|
1275
|
+
private defaultMaxResultBytes;
|
|
1276
|
+
constructor(options?: FunctionRegistryOptions);
|
|
1277
|
+
/** Update the client-level result-size ceiling at runtime. */
|
|
1278
|
+
setDefaultMaxResultBytes(bytes: number): void;
|
|
1247
1279
|
/**
|
|
1248
1280
|
* Register a function that AGO can call.
|
|
1249
1281
|
* Accepts either a single definition object or (name, handler, schema) args.
|
|
1250
1282
|
*/
|
|
1251
1283
|
register(definition: ClientFunctionDefinition): void;
|
|
1252
|
-
register(name: string, handler: ClientFunctionHandler, schema:
|
|
1284
|
+
register(name: string, handler: ClientFunctionHandler, schema: ClientFunctionRegisterOptions): void;
|
|
1253
1285
|
/**
|
|
1254
1286
|
* Unregister a function
|
|
1255
1287
|
*/
|
|
@@ -1270,6 +1302,14 @@ export declare class FunctionRegistry {
|
|
|
1270
1302
|
* Execute a registered function
|
|
1271
1303
|
*/
|
|
1272
1304
|
execute(name: string, args: Record<string, unknown>): Promise<unknown>;
|
|
1305
|
+
/**
|
|
1306
|
+
* Cap the size of a function result before it goes back to the backend.
|
|
1307
|
+
* Everything a handler returns lands in the LLM context, so an unbounded
|
|
1308
|
+
* payload (a raw API response, a full table) inflates cost and can overflow
|
|
1309
|
+
* the model. Oversized results are replaced with a flagged preview so the
|
|
1310
|
+
* agent knows to request less instead of receiving hundreds of KB verbatim.
|
|
1311
|
+
*/
|
|
1312
|
+
private guardResultSize;
|
|
1273
1313
|
/**
|
|
1274
1314
|
* Clear all registered functions
|
|
1275
1315
|
*/
|
|
@@ -1280,6 +1320,11 @@ export declare class FunctionRegistry {
|
|
|
1280
1320
|
get size(): number;
|
|
1281
1321
|
}
|
|
1282
1322
|
|
|
1323
|
+
declare interface FunctionRegistryOptions {
|
|
1324
|
+
/** Client-level default for the result-size ceiling, in bytes. */
|
|
1325
|
+
maxResultBytes?: number;
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1283
1328
|
/**
|
|
1284
1329
|
* Client-side function types
|
|
1285
1330
|
*/
|
|
@@ -1471,6 +1516,8 @@ export declare interface PersistOptions {
|
|
|
1471
1516
|
export declare interface RegisteredFunction {
|
|
1472
1517
|
schema: ClientFunctionSchema;
|
|
1473
1518
|
handler: ClientFunctionHandler;
|
|
1519
|
+
/** Per-function result-size ceiling; falls back to the registry default. */
|
|
1520
|
+
maxResultBytes?: number;
|
|
1474
1521
|
}
|
|
1475
1522
|
|
|
1476
1523
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -186,7 +186,7 @@ export declare class AgoClient {
|
|
|
186
186
|
* ```
|
|
187
187
|
*/
|
|
188
188
|
registerFunction(definition: ClientFunctionDefinition): void;
|
|
189
|
-
registerFunction(name: string, handler: ClientFunctionHandler, schema:
|
|
189
|
+
registerFunction(name: string, handler: ClientFunctionHandler, schema: ClientFunctionRegisterOptions): void;
|
|
190
190
|
/**
|
|
191
191
|
* Short alias for `registerFunction`. Also accepts an array of definitions.
|
|
192
192
|
*
|
|
@@ -495,6 +495,14 @@ export declare interface AgoConfig {
|
|
|
495
495
|
* Older backends ignore the flag, so `"pause"` degrades to legacy behavior.
|
|
496
496
|
*/
|
|
497
497
|
clientFunctionsMode?: ClientFunctionsMode;
|
|
498
|
+
/**
|
|
499
|
+
* Max serialized size (bytes) of a client function result before the SDK
|
|
500
|
+
* replaces it with a flagged, truncated preview. Everything a handler
|
|
501
|
+
* returns is sent into the LLM context, so this caps runaway payloads
|
|
502
|
+
* (raw API responses, full tables). Default `50000`. Override per function
|
|
503
|
+
* with `maxResultBytes` on its definition; `Infinity` disables the guard.
|
|
504
|
+
*/
|
|
505
|
+
maxFunctionResultBytes?: number;
|
|
498
506
|
}
|
|
499
507
|
|
|
500
508
|
/**
|
|
@@ -733,6 +741,12 @@ export declare interface ClientFunctionDefinition {
|
|
|
733
741
|
description: string;
|
|
734
742
|
parameters: ClientFunctionSchema["parameters"];
|
|
735
743
|
handler: ClientFunctionHandler;
|
|
744
|
+
/**
|
|
745
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
746
|
+
* flagged preview (default: `AgoConfig.maxFunctionResultBytes`, 50 000).
|
|
747
|
+
* `Infinity` disables the guard for this function.
|
|
748
|
+
*/
|
|
749
|
+
maxResultBytes?: number;
|
|
736
750
|
}
|
|
737
751
|
|
|
738
752
|
/**
|
|
@@ -747,6 +761,20 @@ export declare interface ClientFunctionInvocation {
|
|
|
747
761
|
conversationId: string;
|
|
748
762
|
}
|
|
749
763
|
|
|
764
|
+
/**
|
|
765
|
+
* Schema-plus-settings object accepted when registering a function: the schema
|
|
766
|
+
* (minus `name`) and SDK-side options that are NOT sent to the backend.
|
|
767
|
+
*/
|
|
768
|
+
export declare type ClientFunctionRegisterOptions = Omit<ClientFunctionSchema, "name"> & {
|
|
769
|
+
/**
|
|
770
|
+
* Max serialized result size in bytes before the SDK truncates it to a
|
|
771
|
+
* flagged preview. Overrides the client-level default
|
|
772
|
+
* (`AgoConfig.maxFunctionResultBytes`, 50 000 by default). `Infinity`
|
|
773
|
+
* disables the guard for this function.
|
|
774
|
+
*/
|
|
775
|
+
maxResultBytes?: number;
|
|
776
|
+
};
|
|
777
|
+
|
|
750
778
|
/**
|
|
751
779
|
* Schema for a client-side function that AGO can call
|
|
752
780
|
*/
|
|
@@ -1244,12 +1272,16 @@ export declare interface FunctionDefinition {
|
|
|
1244
1272
|
*/
|
|
1245
1273
|
export declare class FunctionRegistry {
|
|
1246
1274
|
private functions;
|
|
1275
|
+
private defaultMaxResultBytes;
|
|
1276
|
+
constructor(options?: FunctionRegistryOptions);
|
|
1277
|
+
/** Update the client-level result-size ceiling at runtime. */
|
|
1278
|
+
setDefaultMaxResultBytes(bytes: number): void;
|
|
1247
1279
|
/**
|
|
1248
1280
|
* Register a function that AGO can call.
|
|
1249
1281
|
* Accepts either a single definition object or (name, handler, schema) args.
|
|
1250
1282
|
*/
|
|
1251
1283
|
register(definition: ClientFunctionDefinition): void;
|
|
1252
|
-
register(name: string, handler: ClientFunctionHandler, schema:
|
|
1284
|
+
register(name: string, handler: ClientFunctionHandler, schema: ClientFunctionRegisterOptions): void;
|
|
1253
1285
|
/**
|
|
1254
1286
|
* Unregister a function
|
|
1255
1287
|
*/
|
|
@@ -1270,6 +1302,14 @@ export declare class FunctionRegistry {
|
|
|
1270
1302
|
* Execute a registered function
|
|
1271
1303
|
*/
|
|
1272
1304
|
execute(name: string, args: Record<string, unknown>): Promise<unknown>;
|
|
1305
|
+
/**
|
|
1306
|
+
* Cap the size of a function result before it goes back to the backend.
|
|
1307
|
+
* Everything a handler returns lands in the LLM context, so an unbounded
|
|
1308
|
+
* payload (a raw API response, a full table) inflates cost and can overflow
|
|
1309
|
+
* the model. Oversized results are replaced with a flagged preview so the
|
|
1310
|
+
* agent knows to request less instead of receiving hundreds of KB verbatim.
|
|
1311
|
+
*/
|
|
1312
|
+
private guardResultSize;
|
|
1273
1313
|
/**
|
|
1274
1314
|
* Clear all registered functions
|
|
1275
1315
|
*/
|
|
@@ -1280,6 +1320,11 @@ export declare class FunctionRegistry {
|
|
|
1280
1320
|
get size(): number;
|
|
1281
1321
|
}
|
|
1282
1322
|
|
|
1323
|
+
declare interface FunctionRegistryOptions {
|
|
1324
|
+
/** Client-level default for the result-size ceiling, in bytes. */
|
|
1325
|
+
maxResultBytes?: number;
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1283
1328
|
/**
|
|
1284
1329
|
* Client-side function types
|
|
1285
1330
|
*/
|
|
@@ -1471,6 +1516,8 @@ export declare interface PersistOptions {
|
|
|
1471
1516
|
export declare interface RegisteredFunction {
|
|
1472
1517
|
schema: ClientFunctionSchema;
|
|
1473
1518
|
handler: ClientFunctionHandler;
|
|
1519
|
+
/** Per-function result-size ceiling; falls back to the registry default. */
|
|
1520
|
+
maxResultBytes?: number;
|
|
1474
1521
|
}
|
|
1475
1522
|
|
|
1476
1523
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { a as h, c as A, d as y, f as C, i as E, l as S, m as b, o as v, p as F, r as M, s as I, t as k, u as T } from "./functions-CApuQZ2b.js";
|
|
2
|
-
import { _ as G, a as O, c as _, d as q, f as x, g as L, h as N, l as D, m as d, n as H, o as J, p as R, r as j, s as z, t as c, u as B } from "./AgoClient-
|
|
3
|
-
import { i as $, n as K, r as Q, t as V } from "./createFormCollector-
|
|
4
|
-
import { t as X } from "./createConversationSession-
|
|
2
|
+
import { _ as G, a as O, c as _, d as q, f as x, g as L, h as N, l as D, m as d, n as H, o as J, p as R, r as j, s as z, t as c, u as B } from "./AgoClient-Ozz2b1dQ.js";
|
|
3
|
+
import { i as $, n as K, r as Q, t as V } from "./createFormCollector-F3YJfsbg.js";
|
|
4
|
+
import { t as X } from "./createConversationSession-QIBN0gLx.js";
|
|
5
5
|
import { t as Z } from "./createMockClient-bAZ9KBHC.js";
|
|
6
6
|
import "./testing.js";
|
|
7
7
|
function oe(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-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("./rolldown-runtime-16Nf8qvH.cjs"),F=require("./AgoClient-CLmtYTJx.cjs"),M=require("./createFormCollector-DHT1ObOb.cjs"),V=require("./createMockClient-BSr-UV8R.cjs");let s=require("react");s=W.__toESM(s,1);let o=require("react/jsx-runtime"),P=require("react-markdown");P=W.__toESM(P,1);let T=require("remark-gfm");T=W.__toESM(T,1);function H(e){const[n,r]=(0,s.useState)(!1),t=(0,s.useRef)(null),a=(0,s.useMemo)(()=>{if(t.current&&(t.current.destroy(),t.current=null),!e)return null;const l=new F.AgoClient(e);return t.current=l,l},[e?.baseUrl,e?.widgetId]);return(0,s.useEffect)(()=>(r(!0),()=>{t.current?.destroy(),t.current=null}),[a]),(0,s.useEffect)(()=>{t.current&&e&&t.current.updateConfig({agent:e.agent,defaultAgentId:e.defaultAgentId,permission:e.permission,userEmail:e.userEmail,userJwt:e.userJwt,debug:e.debug,warnOnEmptyReply:e.warnOnEmptyReply})},[e?.agent,e?.defaultAgentId,e?.permission,e?.userEmail,e?.userJwt,e?.debug,e?.warnOnEmptyReply]),{client:a,isReady:n}}var D=(0,s.createContext)(null),Y=({children:e,client:n,tools:r,helpers:t,pageContext:a,...l})=>{const{client:d}=H(n?null:l),c=n||d;return(0,s.useEffect)(()=>{if(!(!r||r.length===0)){for(const p of r)c.register(p);return()=>{for(const p of r)c.unregisterFunction(p.name)}}},[c,r]),(0,s.useEffect)(()=>{if(!t)return;const p=[];return Promise.resolve().then(()=>require("./functions-Djnq-JAo.cjs")).then(u=>u.functions_exports).then(u=>{for(const[b,v]of Object.entries(t)){const I=u[b];if(!I){console.warn(`[AGO] Unknown helper: "${b}"`);continue}const g=v===!0?I:{...I,handler:v};c.register(g),p.push(g.name)}}),()=>{for(const u of p)c.unregisterFunction(u)}},[c,t]),(0,s.useEffect)(()=>{a==="auto"&&c.enableAutoPageContext()},[c,a]),(0,o.jsx)(D.Provider,{value:c,children:e})};function E(){const e=(0,s.useContext)(D);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function _(){return(0,s.useContext)(D)}function L({client:e,conversationId:n}={}){const r=_(),t=e||r;if(!t)throw new Error("useMessages requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[a,l]=(0,s.useState)([]),[d,c]=(0,s.useState)(n),[p,u]=(0,s.useState)(!1),[b,v]=(0,s.useState)(null);(0,s.useEffect)(()=>{n&&n!==d&&(c(n),I(n))},[n]);const I=async g=>{try{l((await t.getMessages(g)).filter(m=>!m.hidden))}catch(m){v(m instanceof Error?m:new Error("Failed to load messages"))}};return(0,s.useEffect)(()=>{const g=f=>f==="IN_PROGRESS"||f==="WAITING_CLIENT",m=f=>{d||c(f.conversationId),u(!0),l(x=>{const C=x.findIndex(h=>h.id===f.messageId);return C>=0?x.map((h,N)=>N===C?{...h,status:"IN_PROGRESS"}:h):x.some(h=>h.role==="assistant"&&g(h.status))?x:[...x,{id:f.messageId,conversationId:f.conversationId,content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}]})},S=f=>{l(x=>{const C=x.findIndex(h=>h.id===f.messageId);return C<0?x:x.map((h,N)=>N===C?{...h,content:h.content+f.content}:h)})},w=f=>{l(x=>{let C=-1;for(let h=x.length-1;h>=0;h--)if(x[h].role==="assistant"&&g(x[h].status)){C=h;break}return C<0?x:[...x.slice(0,C),{...x[C],...f},...x.slice(C+1)]})},i=f=>{l(x=>{const C=x.findIndex(h=>h.id===f.id);return C>=0?[...x.slice(0,C),f,...x.slice(C+1)]:[...x,f]}),u(!1)},y=f=>{v(new Error(f.error)),u(!1)};return t.on("message:start",m),t.on("message:chunk",S),t.on("message:answer-complete",w),t.on("message:complete",i),t.on("message:error",y),()=>{t.off("message:start",m),t.off("message:chunk",S),t.off("message:answer-complete",w),t.off("message:complete",i),t.off("message:error",y)}},[t,d]),{messages:a,isLoading:p,error:b,sendMessage:(0,s.useCallback)(async(g,m)=>{u(!0),v(null);const S={id:`temp-${Date.now()}`,conversationId:d||"",content:g,role:"user",status:"DONE",attachments:m&&m.length>0?F.attachmentsFromFiles(m):void 0,createdAt:new Date},w={id:`temp-assistant-${Date.now()}`,conversationId:d||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};l(i=>[...i,S,w]);try{const i=await t.sendMessage(g,{conversationId:d,files:m});return i.conversationId&&!d&&c(i.conversationId),l(y=>{const f=y.filter(C=>!C.id.startsWith("temp-")),x={...S,id:S.id.replace("temp-","user-"),conversationId:i.conversationId};return f.some(C=>C.id===i.id)?[...f,x].sort((C,h)=>new Date(C.createdAt).getTime()-new Date(h.createdAt).getTime()):[...f,x,i]}),i}catch(i){return v(i instanceof Error?i:new Error("Failed to send message")),u(!1),l(y=>y.filter(f=>!f.id.startsWith("temp-"))),null}},[t,d]),clearMessages:(0,s.useCallback)(()=>{l([]),c(void 0),v(null)},[]),conversationId:d}}var q=({onSend:e,disabled:n=!1,placeholder:r="Type a message...",allowFiles:t=!1,className:a=""})=>{const[l,d]=(0,s.useState)(""),[c,p]=(0,s.useState)([]),u=(0,s.useRef)(null),b=(0,s.useRef)(null),v=(0,s.useCallback)(()=>{const i=b.current;if(!i)return;const y=110;i.style.height="auto",i.style.height=`${Math.min(i.scrollHeight+2,y)}px`,i.style.overflowY=i.scrollHeight+2>y?"auto":"hidden"},[]),I=(0,s.useCallback)(i=>{i.preventDefault(),(l.trim()||c.length>0)&&(e(l.trim(),c.length>0?c:void 0),d(""),p([]),requestAnimationFrame(v))},[l,c,e,v]),g=(0,s.useCallback)(i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),I(i))},[I]),m=(0,s.useCallback)(i=>{const y=Array.from(i.target.files||[]);p(f=>[...f,...y])},[]),S=(0,s.useCallback)(i=>{p(y=>y.filter((f,x)=>x!==i))},[]),w=l.trim()||c.length>0;return(0,o.jsxs)("form",{onSubmit:I,className:`ago-chat-input ${a}`,style:{display:"flex",flexDirection:"column",gap:"8px",padding:"12px 16px",borderTop:"1px solid #dee3e8",backgroundColor:"#fff"},children:[c.length>0&&(0,o.jsx)("div",{className:"ago-chat-input__files",style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:c.map((i,y)=>(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",backgroundColor:"#f0f2f5",borderRadius:"6px",fontSize:"12px",color:"#30373e"},children:[(0,o.jsx)("span",{style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.name}),(0,o.jsx)("button",{type:"button",onClick:()=>S(y),"aria-label":`Remove ${i.name}`,style:{border:"none",background:"none",cursor:"pointer",padding:"0",color:"#6b6d6f",fontSize:"14px",lineHeight:1},children:"×"})]},y))}),(0,o.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"flex-end"},children:[t&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{type:"button",onClick:()=>u.current?.click(),disabled:n,"aria-label":"Attach file",style:{padding:"8px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:n?"not-allowed":"pointer",color:"#6b6d6f",fontSize:"16px",lineHeight:1},children:"+"}),(0,o.jsx)("input",{ref:u,type:"file",multiple:!0,onChange:m,style:{display:"none"}})]}),(0,o.jsx)("textarea",{ref:b,value:l,onChange:i=>{d(i.target.value),v()},onKeyDown:g,placeholder:r,"aria-label":r,disabled:n,rows:1,style:{flex:1,padding:"10px 14px",border:"1px solid #dee3e8",borderRadius:"20px",resize:"none",outline:"none",boxSizing:"border-box",maxHeight:"110px",overflowY:"hidden",fontFamily:"inherit",fontSize:"16px",lineHeight:1.4,color:"#30373e",backgroundColor:"#f8f8f8",transition:"border-color 0.15s"},onFocus:i=>{i.currentTarget.style.borderColor="#1b5fc4"},onBlur:i=>{i.currentTarget.style.borderColor="#dee3e8"}}),(0,o.jsx)("button",{type:"submit",disabled:n||!w,style:{padding:"10px 18px",border:"none",borderRadius:"20px",backgroundColor:n||!w?"#b5bfc8":"#03182f",color:"#fff",cursor:n||!w?"not-allowed":"pointer",fontWeight:500,fontSize:"16px",transition:"background-color 0.15s"},children:"Send"})]})]})},X=({href:e,children:n,...r})=>(0,o.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"#1b5fc4",textDecoration:"underline"},...r,children:n}),Q=({children:e,...n})=>(0,o.jsx)("p",{style:{margin:"0 0 8px 0",lineHeight:"1.6"},...n,children:e}),R=(e,n)=>{const r=({children:t,...a})=>s.default.createElement(`h${e}`,{style:{margin:"16px 0 8px 0",fontSize:n,fontWeight:600,lineHeight:"1.3"},...a},t);return r.displayName=`MarkdownHeading${e}`,r},Z=({children:e,...n})=>(0,o.jsx)("ul",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"disc",listStylePosition:"outside"},...n,children:e}),ee=({children:e,...n})=>(0,o.jsx)("ol",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"decimal",listStylePosition:"outside"},...n,children:e}),te=({children:e,...n})=>(0,o.jsx)("li",{style:{display:"list-item",margin:"2px 0",lineHeight:"1.6"},...n,children:e}),ne=({className:e,children:n,...r})=>e!==void 0||String(n).includes(`
|
|
2
2
|
`)?(0,o.jsx)("code",{style:{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:'"IBM Plex Mono", monospace'},...r,children:n}):(0,o.jsx)("code",{style:{background:"#f0f2f5",padding:"2px 5px",borderRadius:"4px",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},...r,children:n}),re=({children:e,...n})=>(0,o.jsx)("pre",{style:{margin:"0 0 8px 0"},...n,children:e}),oe=({children:e,...n})=>(0,o.jsx)("blockquote",{style:{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"},...n,children:e}),se=({children:e,...n})=>(0,o.jsx)("div",{style:{overflowX:"auto",margin:"0 0 8px 0"},children:(0,o.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"13px"},...n,children:e})}),ae=({children:e,...n})=>(0,o.jsx)("th",{style:{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:600},...n,children:e}),ie=({children:e,...n})=>(0,o.jsx)("td",{style:{border:"1px solid #dee3e8",padding:"6px 10px"},...n,children:e}),le=({alt:e,...n})=>(0,o.jsx)("img",{alt:e??"",style:{maxWidth:"100%",borderRadius:"8px",margin:"4px 0"},...n}),ce=e=>(0,o.jsx)("hr",{style:{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"},...e}),de={a:X,p:Q,h1:R(1,"20px"),h2:R(2,"18px"),h3:R(3,"16px"),h4:R(4,"15px"),h5:R(5,"14px"),h6:R(6,"13px"),ul:Z,ol:ee,li:te,code:ne,pre:re,blockquote:oe,table:se,th:ae,td:ie,img:le,hr:ce},ue=[T.default],$=({content:e})=>(0,o.jsx)(P.default,{remarkPlugins:ue,components:de,children:e}),fe=({attachment:e,isUser:n})=>{const r=F.safeAttachmentUrl(e.url);if(F.canInlineImage(e))return(0,o.jsx)("a",{href:r,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-block",textDecoration:"none"},children:(0,o.jsx)("img",{src:r,alt:e.name,loading:"lazy",style:{maxWidth:"180px",maxHeight:"160px",objectFit:"cover",borderRadius:"10px",border:"1px solid #dee3e8",display:"block"}})});const t=F.formatFileSize(e.fileSize),a=(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{style:{fontSize:"16px",lineHeight:1,flexShrink:0},"aria-hidden":!0,children:"📄"}),(0,o.jsxs)("span",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[(0,o.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"160px"},title:e.name,children:e.name}),t&&(0,o.jsx)("span",{style:{fontSize:"11px",color:"#6b6d6f"},children:t})]})]}),l={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"10px",border:"1px solid #dee3e8",backgroundColor:n?"rgba(255,255,255,0.12)":"#fff",color:n?"#fff":"#30373e",fontSize:"13px",textDecoration:"none",maxWidth:"220px"};return r?(0,o.jsx)("a",{href:r,target:"_blank",rel:"noopener noreferrer",style:l,children:a}):(0,o.jsx)("div",{style:l,children:a})},ge=({source:e,index:n})=>{const r=(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px",width:"100%",minWidth:0},children:[(0,o.jsx)("div",{style:{flexShrink:0,width:"18px",height:"18px",borderRadius:"3px",border:"1px solid #1b5fc4",color:"#1b5fc4",fontSize:"11px",fontWeight:500,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f0f4ff"},children:n+1}),(0,o.jsx)("div",{style:{fontSize:"12px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#30373e"},title:e.title,children:e.title})]}),t={display:"flex",alignItems:"center",padding:"8px 10px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:e.url?"pointer":"default",textDecoration:"none",color:"inherit",minWidth:0,transition:"border-color 0.15s"};return e.url?(0,o.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",style:t,onMouseEnter:a=>{a.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:a=>{a.currentTarget.style.borderColor="#dee3e8"},children:r}):(0,o.jsx)("div",{style:t,children:r})},pe=()=>(0,o.jsxs)("div",{style:{display:"flex",gap:"4px",padding:"4px 0"},children:[[0,1,2].map(e=>(0,o.jsx)("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#b5bfc8",animation:"ago-pulse 1.2s ease-in-out infinite",animationDelay:`${e*.2}s`}},e)),(0,o.jsx)("style",{children:`
|
|
3
3
|
@keyframes ago-pulse {
|
|
4
4
|
0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); }
|
|
5
5
|
40% { opacity: 1; transform: scale(1); }
|
|
6
6
|
}
|
|
7
|
-
`})]}),B=({message:e,className:n="",showAgentName:r=!1,isLast:t=!1,onFollowUpClick:a})=>{const l=e.role==="user",d=e.status==="IN_PROGRESS"||e.status==="WAITING_CLIENT";return(0,o.jsxs)("div",{className:`ago-message ago-message--${e.role} ${n}`,style:{display:"flex",flexDirection:"column",alignItems:l?"flex-end":"flex-start",marginBottom:"16px"},children:[!l&&r&&e.agent&&(0,o.jsx)("div",{className:"ago-message__agent",style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"13px",fontWeight:500,color:"#30373e",marginBottom:"6px",padding:"0 4px"},children:e.agent.displayName||e.agent.name}),!l&&e.sources&&e.sources.length>0&&(0,o.jsx)("div",{className:"ago-message__sources",style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px",marginBottom:"10px",width:"100%",maxWidth:"85%"},children:e.sources.map((c,p)=>(0,o.jsx)(ge,{source:c,index:p},c.id))}),e.attachments&&e.attachments.length>0&&(0,o.jsx)("div",{className:"ago-message__attachments",style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"6px",justifyContent:l?"flex-end":"flex-start",maxWidth:"75%"},children:e.attachments.map(c=>(0,o.jsx)(fe,{attachment:c,isUser:l},c.id))}),(e.content||d)&&(0,o.jsx)("div",{className:"ago-message__content",style:{maxWidth:l?"75%":"100%",padding:l?"10px 14px":"2px 8px",borderRadius:l?"16px":"0",backgroundColor:l?"#03182f":"transparent",color:l?"#fff":"#30373e",wordBreak:"break-word",fontSize:"16px",lineHeight:"1.6"},children:e.content?(0,o.jsx)($,{content:e.content}):d&&(0,o.jsx)(pe,{})}),t&&e.followUpReplies&&e.followUpReplies.length>0&&(0,o.jsx)("div",{className:"ago-message__followups",style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"10px"},children:e.followUpReplies.map((c,p)=>(0,o.jsx)("button",{type:"button",className:"ago-message__followup-btn",disabled:!a,onClick:a?()=>a(c):void 0,style:{minHeight:"36px",padding:"6px 14px",fontSize:"13px",borderRadius:"16px",border:"1px solid #dee3e8",backgroundColor:"#fff",color:"#30373e",cursor:a?"pointer":"default",transition:"border-color 0.15s"},onMouseEnter:u=>{u.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:u=>{u.currentTarget.style.borderColor="#dee3e8"},children:c},p))})]})},xe=({client:e,conversationId:n,title:r="Chat",welcomeMessage:t="Hello! How can I help you today?",placeholder:a="Type a message...",allowFiles:l=!1,height:d=500,logoUrl:c,showAgentName:p=!1,forms:u,onFollowUpClick:C,className:b="",onMessageSent:I,onMessageReceived:g})=>{const m=(0,s.useRef)(null),S=_(),w=e??S,{messages:i,isLoading:y,error:f,sendMessage:x}=L({client:e,conversationId:n});(0,s.useEffect)(()=>{if(!w||!u||u.length===0)return;let k=!1;const A=[];return Promise.all(u.map(j=>j.schema!=null?Promise.resolve(M.createFormCollector(j)):M.loadFormCollector(w,j))).then(j=>{if(!k)for(const J of j)A.push(J.install(w))}).catch(()=>{}),()=>{k=!0,A.forEach(j=>j())}},[w,u?JSON.stringify(u.map(k=>[k.name,k.schema??null,k.submit??!1,k.description??null])):""]),(0,s.useEffect)(()=>{m.current?.scrollIntoView({behavior:"smooth"})},[i]),(0,s.useEffect)(()=>{const k=i[i.length-1];k&&k.role==="assistant"&&k.status==="DONE"&&g&&g({id:k.id,content:k.content})},[i,g]);const v=async(k,A)=>{I?.(k),await x(k,A)},h=i[i.length-1],N=y&&h?.role==="assistant"&&(h.status==="IN_PROGRESS"||h.status==="WAITING_CLIENT"),K=C===!1?void 0:C??(k=>v(k));return(0,o.jsxs)("div",{className:`ago-chat-widget ${b}`,style:{display:"flex",flexDirection:"column",height:typeof d=="number"?`${d}px`:d,border:"1px solid #dee3e8",borderRadius:"16px",overflow:"hidden",backgroundColor:"#fff",fontFamily:'"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',textAlign:"left",boxShadow:"rgba(15, 15, 15, 0.08) 0px 2px 16px 0px"},children:[(0,o.jsxs)("div",{className:"ago-chat-widget__header",style:{padding:"14px 16px",borderBottom:"1px solid #dee3e8",backgroundColor:"#03182f",color:"#e8f0fe",display:"flex",alignItems:"center",gap:"10px"},children:[c&&(0,o.jsx)("img",{src:c,alt:"Logo",style:{height:"24px",width:"auto"}}),(0,o.jsx)("h3",{style:{margin:0,fontSize:"15px",fontWeight:600},children:r})]}),(0,o.jsxs)("div",{className:"ago-chat-widget__messages",role:"log","aria-live":"polite","aria-relevant":"additions text","aria-atomic":!1,style:{flex:1,overflow:"auto",padding:"16px",backgroundColor:"#fbfbfb"},children:[i.length===0?(0,o.jsx)("div",{style:{textAlign:"center",color:"#6b6d6f",padding:"24px 16px",fontSize:"16px",lineHeight:"1.5"},children:t}):i.map((k,A)=>(0,o.jsx)(B,{message:k,showAgentName:p,isLast:A===i.length-1,onFollowUpClick:K},k.id)),f&&(0,o.jsx)("div",{role:"alert",style:{padding:"10px 14px",backgroundColor:"#fef2f2",color:"#dc2626",borderRadius:"12px",marginTop:"8px",fontSize:"13px",border:"1px solid #fecaca"},children:f.message}),(0,o.jsx)("div",{ref:m})]}),(0,o.jsx)(q,{onSend:v,disabled:N,placeholder:a,allowFiles:l})]})};function G({client:e,autoLoad:n=!0}={}){const r=_(),t=e||r;if(!t)throw new Error("useConversation requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[a,l]=(0,s.useState)([]),[d,c]=(0,s.useState)(null),[p,u]=(0,s.useState)(!1),[C,b]=(0,s.useState)(null),I=(0,s.useCallback)(async()=>{u(!0),b(null);try{l(await t.getConversations())}catch(S){b(S instanceof Error?S:new Error("Failed to load conversations"))}finally{u(!1)}},[t]),g=(0,s.useCallback)(async S=>{u(!0),b(null);try{c(await t.getConversation(S))}catch(w){b(w instanceof Error?w:new Error("Failed to load conversation"))}finally{u(!1)}},[t]),m=(0,s.useCallback)(()=>{c(null)},[]);return(0,s.useEffect)(()=>{n&&I()},[n,I]),{conversations:a,currentConversation:d,isLoading:p,error:C,selectConversation:g,startNewConversation:m,refreshConversations:I}}function me(e={}){const n=_(),r=e.client||n;if(!r)throw new Error("useChat requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const t=L({client:r,conversationId:e.conversationId}),a=G({client:r,autoLoad:e.autoLoad});return{messages:t.messages,isLoading:t.isLoading,error:t.error||a.error,sendMessage:t.sendMessage,clearMessages:t.clearMessages,conversationId:t.conversationId,conversations:a.conversations,currentConversation:a.currentConversation,isConversationsLoading:a.isLoading,selectConversation:a.selectConversation,startNewConversation:a.startNewConversation,refreshConversations:a.refreshConversations}}function he(e,n){const r=E(),{name:t,description:a,parameters:l,handler:d}=typeof e=="string"?{name:e,...n}:e,c=(0,s.useRef)(d);c.current=d,(0,s.useEffect)(()=>{const p=u=>c.current(u);return r.registerFunction(t,p,{description:a,parameters:l}),()=>{r.unregisterFunction(t)}},[r,t,a,l])}function ye(e,n){const r=E(),t=(0,s.useRef)(e);t.current=e,(0,s.useEffect)(()=>(r.registerNavigationFunction(a=>t.current(a),n),()=>{r.unregisterNavigationFunction()}),[r,n])}function be(e,n){const r=E(),t=n?.functionName??"setPageState",a=(0,s.useRef)(e);a.current=e,(0,s.useEffect)(()=>{const l=a.current.map(d=>{const c=()=>a.current.find(p=>p.name===d.name)??d;return{name:d.name,description:d.description,schema:d.schema,get:d.get?()=>c().get?.():void 0,set:p=>c().set(p)}});return r.registerPageStateFunction(l,{functionName:t}),()=>{r.unregisterPageStateFunction(t)}},[r,t])}var ve="You have navigated the user to a new page. That page now exposes its editable state through the available setPageState function, and its current values in the page context. If the user's latest request also asked to change something on this page, call setPageState now to apply exactly those changes and nothing else. Otherwise, reply with a short confirmation only.";function z(e){return{navigationFunctions:e?.navigationFunctions??["navigateToPage"],pageStateFunctionName:e?.pageStateFunctionName??"setPageState",continuationPrompt:e?.continuationPrompt??ve,maxDepth:e?.maxDepth??1,readinessTimeoutMs:e?.readinessTimeoutMs??4e3,settleMs:e?.settleMs??150,enabled:e?.enabled??!0}}function Ce(e){const n=E(),r=(0,s.useRef)(z(e));r.current=z(e),(0,s.useEffect)(()=>{const t={navigated:!1,pausedTurnNavigated:!1,depth:0,runId:0,ourSendPending:!1},a=()=>n.getRegisteredFunctions().some(g=>g.name===r.current.pageStateFunctionName),l=g=>new Promise(m=>{let S=!1;const w=x=>{S||(S=!0,clearTimeout(f),n.off("context:changed",y),m(x))},i=()=>setTimeout(()=>w(g===t.runId&&a()),r.current.settleMs),y=()=>{if(g!==t.runId)return w(!1);a()&&(n.off("context:changed",y),i())},f=setTimeout(()=>w(!1),r.current.readinessTimeoutMs);a()?i():n.on("context:changed",y)}),d=async g=>{const m=++t.runId;if(!(!await l(m)||m!==t.runId)){t.depth+=1,t.ourSendPending=!0;try{await n.sendMessage(r.current.continuationPrompt,{conversationId:g,hidden:!0})}catch{t.ourSendPending=!1}}},c=g=>{r.current.navigationFunctions.includes(g.functionName)&&(t.navigated=!0)},p=n.registerResumeGate(async()=>{r.current.enabled&&t.pausedTurnNavigated&&(t.pausedTurnNavigated=!1,await l(++t.runId))}),u=()=>{t.pausedTurnNavigated=t.navigated,t.navigated=!1},C=()=>{t.ourSendPending||(t.depth=0,t.runId+=1)},b=g=>{t.ourSendPending=!1;const m=t.navigated;t.navigated=!1,r.current.enabled&&m&&(t.depth>=r.current.maxDepth||d(g.conversationId))},I=()=>{t.ourSendPending=!1};return n.on("function:invoke",c),n.on("message:start",C),n.on("message:waiting-client",u),n.on("message:complete",b),n.on("message:error",I),()=>{t.runId+=1,p(),n.off("function:invoke",c),n.off("message:start",C),n.off("message:waiting-client",u),n.off("message:complete",b),n.off("message:error",I)}},[n])}function we(e,n){const r=E(),t=(0,s.useId)(),a=n??t,l=(0,s.useRef)(e);l.current=e;const d=typeof e=="function";(0,s.useEffect)(()=>{if(typeof l.current=="function"){const c=()=>l.current();return r.addDynamicContext(a,c),()=>{r.removeDynamicContext(a)}}return r.setContext(a,l.current),()=>{r.removeContext(a)}},[r,a,d,d?"":JSON.stringify(e)])}function U(e){return(0,s.useSyncExternalStore)(e.subscribe,e.get,e.get)}var O={missing:[],complete:!1};function Se(e){const n=E(),r=e.schema!=null,t=JSON.stringify(e.schema??null),a=e.submit,l=a?typeof a=="string"?`client:${a}`:a.via==="backend"?"backend":"handler"in a?"client:handler":`client:${a.url}`:"none",d=JSON.stringify(e.initialValues??null),c=(0,s.useMemo)(()=>r?M.createFormCollector(e):null,[r,e.name,t,l,d,e.autoSubmit]),[p,u]=(0,s.useState)({collector:null,loading:!r,error:null});(0,s.useEffect)(()=>{if(r)return;let y=!1;return u({collector:null,loading:!0,error:null}),M.loadFormCollector(n,e).then(f=>{y||u({collector:f,loading:!1,error:null})}).catch(f=>{y||u({collector:null,loading:!1,error:f instanceof Error?f:new Error(String(f))})}),()=>{y=!0}},[n,r,e.name,l,d,e.autoSubmit]);const C=r?c:p.collector,b=r?!1:p.loading,I=r?null:p.error;(0,s.useEffect)(()=>{if(C)return C.install(n)},[n,C]);const g=(0,s.useMemo)(()=>M.createStore({values:e.initialValues??{},submitted:!1}),[d]),m=U(C?.store??g),S=(0,s.useMemo)(()=>C?.getStatus()??O,[m,C]),w=(0,s.useMemo)(()=>({...m,...S}),[m,S]),i=(0,s.useMemo)(()=>({name:e.name,store:g,functions:[],contextKey:`form:${e.name}`,contextProvider:()=>({name:`Form: ${e.name}`,description:""}),install:()=>()=>{},hydrate:()=>{},submit:async()=>({ok:!1,error:"Form definition not loaded yet."}),getValues:()=>g.get().values,setValues:()=>{},reset:()=>{},getStatus:()=>O}),[e.name,g]);return{...C??i,state:w,loading:b,error:I}}exports.AgoProvider=Y;exports.ChatInput=q;exports.ChatWidget=xe;exports.Markdown=$;exports.Message=B;exports.createFormCollector=M.createFormCollector;exports.createMockClient=V.createMockClient;exports.deriveFormStatus=M.deriveFormStatus;exports.loadFormCollector=M.loadFormCollector;exports.useAgo=H;exports.useAgoAutoContinueAfterNavigation=Ce;exports.useAgoClient=E;exports.useAgoContext=we;exports.useAgoFunction=he;exports.useAgoNavigation=ye;exports.useAgoPageState=be;exports.useAgoStore=U;exports.useChat=me;exports.useConversation=G;exports.useFormCollector=Se;exports.useMessages=L;exports.useOptionalAgoClient=_;
|
|
7
|
+
`})]}),B=({message:e,className:n="",showAgentName:r=!1,isLast:t=!1,onFollowUpClick:a})=>{const l=e.role==="user",d=e.status==="IN_PROGRESS"||e.status==="WAITING_CLIENT";return(0,o.jsxs)("div",{className:`ago-message ago-message--${e.role} ${n}`,style:{display:"flex",flexDirection:"column",alignItems:l?"flex-end":"flex-start",marginBottom:"16px"},children:[!l&&r&&e.agent&&(0,o.jsx)("div",{className:"ago-message__agent",style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"13px",fontWeight:500,color:"#30373e",marginBottom:"6px",padding:"0 4px"},children:e.agent.displayName||e.agent.name}),!l&&e.sources&&e.sources.length>0&&(0,o.jsx)("div",{className:"ago-message__sources",style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px",marginBottom:"10px",width:"100%",maxWidth:"85%"},children:e.sources.map((c,p)=>(0,o.jsx)(ge,{source:c,index:p},c.id))}),e.attachments&&e.attachments.length>0&&(0,o.jsx)("div",{className:"ago-message__attachments",style:{display:"flex",flexWrap:"wrap",gap:"6px",marginBottom:"6px",justifyContent:l?"flex-end":"flex-start",maxWidth:"75%"},children:e.attachments.map(c=>(0,o.jsx)(fe,{attachment:c,isUser:l},c.id))}),(e.content||d)&&(0,o.jsx)("div",{className:"ago-message__content",style:{maxWidth:l?"75%":"100%",padding:l?"10px 14px":"2px 8px",borderRadius:l?"16px":"0",backgroundColor:l?"#03182f":"transparent",color:l?"#fff":"#30373e",wordBreak:"break-word",fontSize:"16px",lineHeight:"1.6"},children:e.content?(0,o.jsx)($,{content:e.content}):d&&(0,o.jsx)(pe,{})}),t&&e.followUpReplies&&e.followUpReplies.length>0&&(0,o.jsx)("div",{className:"ago-message__followups",style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"10px"},children:e.followUpReplies.map((c,p)=>(0,o.jsx)("button",{type:"button",className:"ago-message__followup-btn",disabled:!a,onClick:a?()=>a(c):void 0,style:{minHeight:"36px",padding:"6px 14px",fontSize:"13px",borderRadius:"16px",border:"1px solid #dee3e8",backgroundColor:"#fff",color:"#30373e",cursor:a?"pointer":"default",transition:"border-color 0.15s"},onMouseEnter:u=>{u.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:u=>{u.currentTarget.style.borderColor="#dee3e8"},children:c},p))})]})},xe=({client:e,conversationId:n,title:r="Chat",welcomeMessage:t="Hello! How can I help you today?",placeholder:a="Type a message...",allowFiles:l=!1,height:d=500,logoUrl:c,showAgentName:p=!1,forms:u,onFollowUpClick:b,className:v="",onMessageSent:I,onMessageReceived:g})=>{const m=(0,s.useRef)(null),S=_(),w=e??S,{messages:i,isLoading:y,error:f,sendMessage:x}=L({client:e,conversationId:n});(0,s.useEffect)(()=>{if(!w||!u||u.length===0)return;let k=!1;const A=[];return Promise.all(u.map(j=>j.schema!=null?Promise.resolve(M.createFormCollector(j)):M.loadFormCollector(w,j))).then(j=>{if(!k)for(const J of j)A.push(J.install(w))}).catch(()=>{}),()=>{k=!0,A.forEach(j=>j())}},[w,u?JSON.stringify(u.map(k=>[k.name,k.schema??null,k.submit??!1,k.description??null])):""]),(0,s.useEffect)(()=>{m.current?.scrollIntoView({behavior:"smooth"})},[i]),(0,s.useEffect)(()=>{const k=i[i.length-1];k&&k.role==="assistant"&&k.status==="DONE"&&g&&g({id:k.id,content:k.content})},[i,g]);const C=async(k,A)=>{I?.(k),await x(k,A)},h=i[i.length-1],N=y&&h?.role==="assistant"&&(h.status==="IN_PROGRESS"||h.status==="WAITING_CLIENT"),K=b===!1?void 0:b??(k=>C(k));return(0,o.jsxs)("div",{className:`ago-chat-widget ${v}`,style:{display:"flex",flexDirection:"column",height:typeof d=="number"?`${d}px`:d,border:"1px solid #dee3e8",borderRadius:"16px",overflow:"hidden",backgroundColor:"#fff",fontFamily:'"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',textAlign:"left",boxShadow:"rgba(15, 15, 15, 0.08) 0px 2px 16px 0px"},children:[(0,o.jsxs)("div",{className:"ago-chat-widget__header",style:{padding:"14px 16px",borderBottom:"1px solid #dee3e8",backgroundColor:"#03182f",color:"#e8f0fe",display:"flex",alignItems:"center",gap:"10px"},children:[c&&(0,o.jsx)("img",{src:c,alt:"Logo",style:{height:"24px",width:"auto"}}),(0,o.jsx)("h3",{style:{margin:0,fontSize:"15px",fontWeight:600},children:r})]}),(0,o.jsxs)("div",{className:"ago-chat-widget__messages",role:"log","aria-live":"polite","aria-relevant":"additions text","aria-atomic":!1,style:{flex:1,overflow:"auto",padding:"16px",backgroundColor:"#fbfbfb"},children:[i.length===0?(0,o.jsx)("div",{style:{textAlign:"center",color:"#6b6d6f",padding:"24px 16px",fontSize:"16px",lineHeight:"1.5"},children:t}):i.map((k,A)=>(0,o.jsx)(B,{message:k,showAgentName:p,isLast:A===i.length-1,onFollowUpClick:K},k.id)),f&&(0,o.jsx)("div",{role:"alert",style:{padding:"10px 14px",backgroundColor:"#fef2f2",color:"#dc2626",borderRadius:"12px",marginTop:"8px",fontSize:"13px",border:"1px solid #fecaca"},children:f.message}),(0,o.jsx)("div",{ref:m})]}),(0,o.jsx)(q,{onSend:C,disabled:N,placeholder:a,allowFiles:l})]})};function G({client:e,autoLoad:n=!0}={}){const r=_(),t=e||r;if(!t)throw new Error("useConversation requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[a,l]=(0,s.useState)([]),[d,c]=(0,s.useState)(null),[p,u]=(0,s.useState)(!1),[b,v]=(0,s.useState)(null),I=(0,s.useCallback)(async()=>{u(!0),v(null);try{l(await t.getConversations())}catch(S){v(S instanceof Error?S:new Error("Failed to load conversations"))}finally{u(!1)}},[t]),g=(0,s.useCallback)(async S=>{u(!0),v(null);try{c(await t.getConversation(S))}catch(w){v(w instanceof Error?w:new Error("Failed to load conversation"))}finally{u(!1)}},[t]),m=(0,s.useCallback)(()=>{c(null)},[]);return(0,s.useEffect)(()=>{n&&I()},[n,I]),{conversations:a,currentConversation:d,isLoading:p,error:b,selectConversation:g,startNewConversation:m,refreshConversations:I}}function me(e={}){const n=_(),r=e.client||n;if(!r)throw new Error("useChat requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const t=L({client:r,conversationId:e.conversationId}),a=G({client:r,autoLoad:e.autoLoad});return{messages:t.messages,isLoading:t.isLoading,error:t.error||a.error,sendMessage:t.sendMessage,clearMessages:t.clearMessages,conversationId:t.conversationId,conversations:a.conversations,currentConversation:a.currentConversation,isConversationsLoading:a.isLoading,selectConversation:a.selectConversation,startNewConversation:a.startNewConversation,refreshConversations:a.refreshConversations}}function he(e,n){const r=E(),{name:t,description:a,parameters:l,handler:d,maxResultBytes:c}=typeof e=="string"?{name:e,...n}:e,p=(0,s.useRef)(d);p.current=d,(0,s.useEffect)(()=>{const u=b=>p.current(b);return r.registerFunction(t,u,{description:a,parameters:l,maxResultBytes:c}),()=>{r.unregisterFunction(t)}},[r,t,a,l,c])}function ye(e,n){const r=E(),t=(0,s.useRef)(e);t.current=e,(0,s.useEffect)(()=>(r.registerNavigationFunction(a=>t.current(a),n),()=>{r.unregisterNavigationFunction()}),[r,n])}function be(e,n){const r=E(),t=n?.functionName??"setPageState",a=(0,s.useRef)(e);a.current=e,(0,s.useEffect)(()=>{const l=a.current.map(d=>{const c=()=>a.current.find(p=>p.name===d.name)??d;return{name:d.name,description:d.description,schema:d.schema,get:d.get?()=>c().get?.():void 0,set:p=>c().set(p)}});return r.registerPageStateFunction(l,{functionName:t}),()=>{r.unregisterPageStateFunction(t)}},[r,t])}var ve="You have navigated the user to a new page. That page now exposes its editable state through the available setPageState function, and its current values in the page context. If the user's latest request also asked to change something on this page, call setPageState now to apply exactly those changes and nothing else. Otherwise, reply with a short confirmation only.";function z(e){return{navigationFunctions:e?.navigationFunctions??["navigateToPage"],pageStateFunctionName:e?.pageStateFunctionName??"setPageState",continuationPrompt:e?.continuationPrompt??ve,maxDepth:e?.maxDepth??1,readinessTimeoutMs:e?.readinessTimeoutMs??4e3,settleMs:e?.settleMs??150,enabled:e?.enabled??!0}}function Ce(e){const n=E(),r=(0,s.useRef)(z(e));r.current=z(e),(0,s.useEffect)(()=>{const t={navigated:!1,pausedTurnNavigated:!1,depth:0,runId:0,ourSendPending:!1},a=()=>n.getRegisteredFunctions().some(g=>g.name===r.current.pageStateFunctionName),l=g=>new Promise(m=>{let S=!1;const w=x=>{S||(S=!0,clearTimeout(f),n.off("context:changed",y),m(x))},i=()=>setTimeout(()=>w(g===t.runId&&a()),r.current.settleMs),y=()=>{if(g!==t.runId)return w(!1);a()&&(n.off("context:changed",y),i())},f=setTimeout(()=>w(!1),r.current.readinessTimeoutMs);a()?i():n.on("context:changed",y)}),d=async g=>{const m=++t.runId;if(!(!await l(m)||m!==t.runId)){t.depth+=1,t.ourSendPending=!0;try{await n.sendMessage(r.current.continuationPrompt,{conversationId:g,hidden:!0})}catch{t.ourSendPending=!1}}},c=g=>{r.current.navigationFunctions.includes(g.functionName)&&(t.navigated=!0)},p=n.registerResumeGate(async()=>{r.current.enabled&&t.pausedTurnNavigated&&(t.pausedTurnNavigated=!1,await l(++t.runId))}),u=()=>{t.pausedTurnNavigated=t.navigated,t.navigated=!1},b=()=>{t.ourSendPending||(t.depth=0,t.runId+=1)},v=g=>{t.ourSendPending=!1;const m=t.navigated;t.navigated=!1,r.current.enabled&&m&&(t.depth>=r.current.maxDepth||d(g.conversationId))},I=()=>{t.ourSendPending=!1};return n.on("function:invoke",c),n.on("message:start",b),n.on("message:waiting-client",u),n.on("message:complete",v),n.on("message:error",I),()=>{t.runId+=1,p(),n.off("function:invoke",c),n.off("message:start",b),n.off("message:waiting-client",u),n.off("message:complete",v),n.off("message:error",I)}},[n])}function we(e,n){const r=E(),t=(0,s.useId)(),a=n??t,l=(0,s.useRef)(e);l.current=e;const d=typeof e=="function";(0,s.useEffect)(()=>{if(typeof l.current=="function"){const c=()=>l.current();return r.addDynamicContext(a,c),()=>{r.removeDynamicContext(a)}}return r.setContext(a,l.current),()=>{r.removeContext(a)}},[r,a,d,d?"":JSON.stringify(e)])}function U(e){return(0,s.useSyncExternalStore)(e.subscribe,e.get,e.get)}var O={missing:[],complete:!1};function Se(e){const n=E(),r=e.schema!=null,t=JSON.stringify(e.schema??null),a=e.submit,l=a?typeof a=="string"?`client:${a}`:a.via==="backend"?"backend":"handler"in a?"client:handler":`client:${a.url}`:"none",d=JSON.stringify(e.initialValues??null),c=(0,s.useMemo)(()=>r?M.createFormCollector(e):null,[r,e.name,t,l,d,e.autoSubmit]),[p,u]=(0,s.useState)({collector:null,loading:!r,error:null});(0,s.useEffect)(()=>{if(r)return;let y=!1;return u({collector:null,loading:!0,error:null}),M.loadFormCollector(n,e).then(f=>{y||u({collector:f,loading:!1,error:null})}).catch(f=>{y||u({collector:null,loading:!1,error:f instanceof Error?f:new Error(String(f))})}),()=>{y=!0}},[n,r,e.name,l,d,e.autoSubmit]);const b=r?c:p.collector,v=r?!1:p.loading,I=r?null:p.error;(0,s.useEffect)(()=>{if(b)return b.install(n)},[n,b]);const g=(0,s.useMemo)(()=>M.createStore({values:e.initialValues??{},submitted:!1}),[d]),m=U(b?.store??g),S=(0,s.useMemo)(()=>b?.getStatus()??O,[m,b]),w=(0,s.useMemo)(()=>({...m,...S}),[m,S]),i=(0,s.useMemo)(()=>({name:e.name,store:g,functions:[],contextKey:`form:${e.name}`,contextProvider:()=>({name:`Form: ${e.name}`,description:""}),install:()=>()=>{},hydrate:()=>{},submit:async()=>({ok:!1,error:"Form definition not loaded yet."}),getValues:()=>g.get().values,setValues:()=>{},reset:()=>{},getStatus:()=>O}),[e.name,g]);return{...b??i,state:w,loading:v,error:I}}exports.AgoProvider=Y;exports.ChatInput=q;exports.ChatWidget=xe;exports.Markdown=$;exports.Message=B;exports.createFormCollector=M.createFormCollector;exports.createMockClient=V.createMockClient;exports.deriveFormStatus=M.deriveFormStatus;exports.loadFormCollector=M.loadFormCollector;exports.useAgo=H;exports.useAgoAutoContinueAfterNavigation=Ce;exports.useAgoClient=E;exports.useAgoContext=we;exports.useAgoFunction=he;exports.useAgoNavigation=ye;exports.useAgoPageState=be;exports.useAgoStore=U;exports.useChat=me;exports.useConversation=G;exports.useFormCollector=Se;exports.useMessages=L;exports.useOptionalAgoClient=_;
|