@useago/sdk 1.5.2 → 1.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/AgoClient-BGkFSNZF.cjs +8 -0
  2. package/dist/AgoClient-CW-BLT1_.js +1542 -0
  3. package/dist/angular.cjs +1 -1
  4. package/dist/angular.d.cts +311 -0
  5. package/dist/angular.d.ts +311 -0
  6. package/dist/angular.js +2 -2
  7. package/dist/createConversationSession-BCb0D6bt.cjs +1 -0
  8. package/dist/{createConversationSession-DPrrr70o.js → createConversationSession-C7cnnWKW.js} +3 -3
  9. package/dist/createFormCollector-iCDwAwYJ.js +279 -0
  10. package/dist/createFormCollector-t_fGyuTD.cjs +1 -0
  11. package/dist/createMockClient-Br0TWgLO.js +97 -0
  12. package/dist/createMockClient-BwNLPjeT.cjs +1 -0
  13. package/dist/devtools.d.cts +311 -0
  14. package/dist/devtools.d.ts +311 -0
  15. package/dist/functions-IGSjjvF4.cjs +1 -0
  16. package/dist/helpers.cjs +1 -1
  17. package/dist/helpers.js +1 -1
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.d.cts +510 -0
  20. package/dist/index.d.ts +510 -0
  21. package/dist/index.js +95 -90
  22. package/dist/react.cjs +3 -3
  23. package/dist/react.d.cts +375 -0
  24. package/dist/react.d.ts +375 -0
  25. package/dist/react.js +559 -422
  26. package/dist/rolldown-runtime-16Nf8qvH.cjs +1 -0
  27. package/dist/testing.cjs +1 -1
  28. package/dist/testing.d.cts +311 -0
  29. package/dist/testing.d.ts +311 -0
  30. package/dist/testing.js +1 -1
  31. package/dist/vue.cjs +1 -1
  32. package/dist/vue.d.cts +332 -0
  33. package/dist/vue.d.ts +332 -0
  34. package/dist/vue.js +133 -110
  35. package/dist/widget.cjs +1 -1
  36. package/dist/widget.d.cts +308 -0
  37. package/dist/widget.d.ts +308 -0
  38. package/dist/widget.js +7 -7
  39. package/package.json +1 -1
  40. package/dist/AgoClient-5VGybmvz.cjs +0 -8
  41. package/dist/AgoClient-DXrH2AMi.js +0 -964
  42. package/dist/createConversationSession-0WTqcCLK.cjs +0 -1
  43. package/dist/createFormCollector-1GKKwQV_.cjs +0 -1
  44. package/dist/createFormCollector-DYh90kiG.js +0 -305
  45. package/dist/createMockClient-C-wrjb2C.cjs +0 -1
  46. package/dist/createMockClient-we-XoPom.js +0 -79
  47. package/dist/functions-CPs7omgM.cjs +0 -1
  48. /package/dist/{autoContinue-CP9pJR-V.cjs → autoContinue-CcCTva-D.cjs} +0 -0
  49. /package/dist/{autoContinue-CC8K9mBU.js → autoContinue-D3Mmaaca.js} +0 -0
  50. /package/dist/{functions-tzyOZNp6.js → functions-CApuQZ2b.js} +0 -0
@@ -0,0 +1 @@
1
+ const C=require("./AgoClient-BGkFSNZF.cjs");var W=/^[a-zA-Z0-9_-]{1,40}$/,A=n=>n==null||n==="";function S(n,e){if("anyOf"in n)return n.anyOf.some(c=>S(c,e));if("allOf"in n)return n.allOf.every(c=>S(c,e));const l=e[n.property];if(A(l))return!1;if(Array.isArray(n.value))return n.value.some(c=>String(l)===String(c));if(!n.op)return String(l)===String(n.value);const i=Number(l),a=Number(n.value);if(Number.isNaN(i)||Number.isNaN(a))return!1;switch(n.op){case">=":return i>=a;case"<=":return i<=a;case">":return i>a;case"<":return i<a;default:return C.logger.warn(`Unknown requiredWhen op "${n.op}"; treating as not required.`),!1}}function h(n,e){const l=n.properties??{},i=new Set;for(const c of n.required??[]){const d=l[c]?.requiredWhen;(!d||S(d,e))&&i.add(c)}for(const[c,d]of Object.entries(l))d.requiredWhen&&S(d.requiredWhen,e)&&i.add(c);const a=[...i].filter(c=>A(e[c]));return{missing:a,complete:a.length===0}}function B(n){const e={};for(const[l,i]of Object.entries(n.properties??{}))e[l]={type:i.type,...i.description!=null&&{description:i.description},...i.enum&&{enum:i.enum},...i.default!==void 0&&{default:i.default}};return{type:"object",properties:e,required:[]}}function V(n){const{name:e,description:l,schema:i}=n;if(!W.test(e))throw new Error(`Invalid form collector name "${e}": must match ${W} (it becomes the update_/submit_ function names).`);const a=typeof n.submit=="string"?n.submit?{via:"client",url:n.submit}:!1:n.submit??!1;n.autoSubmit===!0&&!a&&C.logger.warn(`FormCollector "${e}": autoSubmit is ignored because no submit target is configured.`);const c=(n.autoSubmit??!0)&&!!a,d=i.properties??{},$=t=>{const r={};for(const[o,s]of Object.entries(t)){const u=d[o];if(u)if(s==null)r[o]=s;else if(u.type==="number"||u.type==="integer"){const f=typeof s=="number"?s:Number(s);r[o]=Number.isNaN(f)?s:f}else u.type==="boolean"?r[o]=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:!!s:r[o]=s}return r},N=n.initialValues??{},m=C.createStore({values:N,submitted:!1}),w=t=>{const r=m.get(),o={...r,values:{...r.values,...t}};return m.set(o),o};let b=null;const k=(t,r)=>{b?.emitFormEvent("form:error",{name:e,values:t,error:r})};let p=null;const I=async()=>{const{values:t}=m.get(),{complete:r,missing:o}=h(i,t);if(!r)return{ok:!1,missing:o};if(!a)return{ok:!1,error:"No submit target configured for this form collector."};const s=t;try{let u;if(a.via==="client")if("handler"in a)u=await a.handler(s);else{const f=await fetch(a.url,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(s)});if(!f.ok){const j=`Submit failed: HTTP ${f.status}`;return k(s,j),{ok:!1,error:j}}u=await f.json().catch(()=>{})}else{if(!b)return{ok:!1,error:"Backend submit requires install(client) (or useFormCollector) first."};u=await b.submitFormCollector(e,s)}return m.set({...m.get(),submitted:!0,submitResult:u}),b?.emitFormEvent("form:submitted",{name:e,values:s,result:u}),{ok:!0,result:u}}catch(u){const f=u instanceof Error?u.message:"Submit failed";return C.logger.error(`FormCollector "${e}" submit failed:`,u),k(s,f),{ok:!1,error:f}}},F=()=>p||(p=(async()=>{try{return await I()}finally{p=null}})(),p),q=async()=>{if(!c||!a)return null;const{values:t,submitted:r}=m.get();return r||!h(i,t).complete?null:F()},O={name:`update_${e}`,description:`Fill or update fields of the "${e}" form. ${l} 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:B(i),handler:async t=>{const r=w($(t)),{missing:o}=h(i,r.values),s=await q();return s?s.ok?{ok:!0,values:r.values,missing:o,submitted:!0}:{ok:!0,values:r.values,missing:o,submitted:!1,submitError:s.error}:{ok:!0,values:r.values,missing:o}}},y=[O];a&&!c&&y.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:()=>F()});const D="client__",_=a?`submit_${e}`:null,R=t=>{const r=t.functionName??t.toolName;if(r)return r.startsWith(D)?r.slice(8):r},x=t=>{let r={...N},o=!1;for(const s of t){const u=R(s);u===O.name?s.arguments&&(r={...r,...$(s.arguments)}):_&&u===_&&s.status?.toLowerCase()==="done"&&(o=!0)}m.set({values:r,submitted:o})},g=`form:${e}`,v=`${g}:definition`,P=()=>({name:`Form definition: ${e}`,description:`${l} 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(i)}.`,stable:!0}),T=()=>{const{values:t,submitted:r}=m.get(),{missing:o,complete:s}=h(i,t),u=a?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}.`:"",f=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:`${f} The form's schema and field requirements are in the "${v}" client context. Call update_${e} with any fields the user provides; ask only for what is still missing.${u}`,data:{values:t,missing:o,complete:s,submitted:r}}},E=t=>{x((t.messages??[]).flatMap(r=>r.toolCalls??[]))};return{name:e,store:m,functions:y,contextKey:g,contextProvider:T,definitionContextKey:v,definitionContextProvider:P,install:t=>{b=t;for(const o of y)t.register(o);t.addDynamicContext(v,P),t.addDynamicContext(g,T);const r=m.subscribe(()=>t.notifyContextChanged());return t.on("conversation:loaded",E),()=>{r();for(const o of y)t.unregisterFunction(o.name);t.removeDynamicContext(g),t.removeDynamicContext(v),t.off("conversation:loaded",E),b===t&&(b=null)}},hydrate:x,submit:F,getValues:()=>m.get().values,setValues:t=>{w($(t)),q()},reset:()=>{m.set({values:N,submitted:!1})},getStatus:()=>h(i,m.get().values)}}async function L(n,e){const l=await n.getFormCollector(e.name);return V({name:l.name,description:e.description??l.description,schema:e.schema??l.schema,submit:e.submit??l.submit,initialValues:e.initialValues,autoSubmit:e.autoSubmit??l.autoSubmit})}Object.defineProperty(exports,"createFormCollector",{enumerable:!0,get:function(){return V}});Object.defineProperty(exports,"deriveFormStatus",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"loadFormCollector",{enumerable:!0,get:function(){return L}});
@@ -0,0 +1,97 @@
1
+ function v(g = {}) {
2
+ const { overrides: u = {} } = g, a = {
3
+ id: "mock-msg-1",
4
+ conversationId: "mock-conv-1",
5
+ content: "Mock response",
6
+ role: "assistant",
7
+ status: "DONE",
8
+ createdAt: /* @__PURE__ */ new Date()
9
+ }, l = {
10
+ id: "mock-conv-1",
11
+ title: "Mock Conversation",
12
+ lastMessageDate: /* @__PURE__ */ new Date()
13
+ }, o = /* @__PURE__ */ new Map(), c = [], m = {
14
+ sendMessage: async () => a,
15
+ continueMessage: async () => a,
16
+ resumePendingClientFunctions: async () => null,
17
+ registerResumeGate: () => () => {
18
+ },
19
+ getConversations: async () => [l],
20
+ getConversation: async () => l,
21
+ getMessages: async () => [a],
22
+ submitToolCallForm: async () => ({ status: "completed" }),
23
+ confirmToolCall: async () => {
24
+ },
25
+ rejectToolCall: async () => {
26
+ },
27
+ submitFeedback: async () => {
28
+ },
29
+ registerFunction: () => {
30
+ },
31
+ unregisterFunction: () => !0,
32
+ getRegisteredFunctions: () => [],
33
+ executeClientFunction: async () => {
34
+ },
35
+ getContextSnapshot: () => null,
36
+ notifyContextChanged: () => {
37
+ },
38
+ setContext: () => {
39
+ },
40
+ removeContext: () => !0,
41
+ addDynamicContext: () => {
42
+ },
43
+ removeDynamicContext: () => !0,
44
+ registerNavigationFunction: () => {
45
+ },
46
+ unregisterNavigationFunction: () => {
47
+ },
48
+ getConfiguredAgent: () => {
49
+ },
50
+ getHttp: () => ({
51
+ get: async () => ({}),
52
+ post: async () => ({})
53
+ }),
54
+ emitProactiveEvent: (e, t) => {
55
+ const n = o.get(e);
56
+ n && [...n].forEach((s) => s(t));
57
+ },
58
+ on: (e, t) => {
59
+ o.has(e) || o.set(e, /* @__PURE__ */ new Set()), o.get(e).add(t);
60
+ },
61
+ off: (e, t) => {
62
+ o.get(e)?.delete(t);
63
+ },
64
+ once: (e, t) => {
65
+ const n = (...s) => {
66
+ o.get(e)?.delete(n), t(...s);
67
+ };
68
+ o.has(e) || o.set(e, /* @__PURE__ */ new Set()), o.get(e).add(n);
69
+ },
70
+ waitFor: (e, t) => new Promise((n, s) => {
71
+ let r;
72
+ const d = (f) => {
73
+ r && clearTimeout(r), o.get(e)?.delete(d), n(f);
74
+ };
75
+ o.has(e) || o.set(e, /* @__PURE__ */ new Set()), o.get(e).add(d), t?.timeout && (r = setTimeout(() => {
76
+ o.get(e)?.delete(d), s(/* @__PURE__ */ new Error(`waitFor("${e}") timed out after ${t.timeout}ms`));
77
+ }, t.timeout));
78
+ }),
79
+ updateConfig: () => {
80
+ },
81
+ destroy: () => {
82
+ o.clear();
83
+ },
84
+ ...u
85
+ }, i = {};
86
+ for (const [e, t] of Object.entries(m)) i[e] = (...n) => (c.push({
87
+ method: e,
88
+ args: n
89
+ }), t(...n));
90
+ return i.proactive = null, i.__calls = c, i.__callsFor = (e) => c.filter((t) => t.method === e), i.__emitEvent = (e, t) => {
91
+ const n = o.get(e);
92
+ n && [...n].forEach((s) => s(t));
93
+ }, i;
94
+ }
95
+ export {
96
+ v as t
97
+ };
@@ -0,0 +1 @@
1
+ function C(u={}){const{overrides:g={}}=u,a={id:"mock-msg-1",conversationId:"mock-conv-1",content:"Mock response",role:"assistant",status:"DONE",createdAt:new Date},l={id:"mock-conv-1",title:"Mock Conversation",lastMessageDate:new Date},o=new Map,r=[],m={sendMessage:async()=>a,continueMessage:async()=>a,resumePendingClientFunctions:async()=>null,registerResumeGate:()=>()=>{},getConversations:async()=>[l],getConversation:async()=>l,getMessages:async()=>[a],submitToolCallForm:async()=>({status:"completed"}),confirmToolCall:async()=>{},rejectToolCall:async()=>{},submitFeedback:async()=>{},registerFunction:()=>{},unregisterFunction:()=>!0,getRegisteredFunctions:()=>[],executeClientFunction:async()=>{},getContextSnapshot:()=>null,notifyContextChanged:()=>{},setContext:()=>{},removeContext:()=>!0,addDynamicContext:()=>{},removeDynamicContext:()=>!0,registerNavigationFunction:()=>{},unregisterNavigationFunction:()=>{},getConfiguredAgent:()=>{},getHttp:()=>({get:async()=>({}),post:async()=>({})}),emitProactiveEvent:(e,t)=>{const n=o.get(e);n&&[...n].forEach(s=>s(t))},on:(e,t)=>{o.has(e)||o.set(e,new Set),o.get(e).add(t)},off:(e,t)=>{o.get(e)?.delete(t)},once:(e,t)=>{const n=(...s)=>{o.get(e)?.delete(n),t(...s)};o.has(e)||o.set(e,new Set),o.get(e).add(n)},waitFor:(e,t)=>new Promise((n,s)=>{let c;const d=f=>{c&&clearTimeout(c),o.get(e)?.delete(d),n(f)};o.has(e)||o.set(e,new Set),o.get(e).add(d),t?.timeout&&(c=setTimeout(()=>{o.get(e)?.delete(d),s(new Error(`waitFor("${e}") timed out after ${t.timeout}ms`))},t.timeout))}),updateConfig:()=>{},destroy:()=>{o.clear()},...g},i={};for(const[e,t]of Object.entries(m))i[e]=(...n)=>(r.push({method:e,args:n}),t(...n));return i.proactive=null,i.__calls=r,i.__callsFor=e=>r.filter(t=>t.method===e),i.__emitEvent=(e,t)=>{const n=o.get(e);n&&[...n].forEach(s=>s(t))},i}Object.defineProperty(exports,"createMockClient",{enumerable:!0,get:function(){return C}});
@@ -49,6 +49,12 @@ declare class AgoClient {
49
49
  private pendingApprovals;
50
50
  /** App-provided gate deciding WHEN a paused turn resumes (see {@link registerResumeGate}). */
51
51
  private resumeGate;
52
+ /**
53
+ * Proactive-mode controller, set when the client was created with
54
+ * `proactive` options or when `createAgoProactive(client, opts)` was called.
55
+ * `null` otherwise.
56
+ */
57
+ proactive: ProactiveController | null;
52
58
  constructor(config: AgoConfig);
53
59
  /**
54
60
  * Send a message and receive a streaming response
@@ -219,6 +225,14 @@ declare class AgoClient {
219
225
  * Get all registered function schemas
220
226
  */
221
227
  getRegisteredFunctions(): ClientFunctionSchema[];
228
+ /**
229
+ * Execute a registered client function locally, through the same
230
+ * FunctionRegistry path (result-size guard, error wrapping) as agent-invoked
231
+ * calls. Used by proactive nudge actions, where the user's explicit click on
232
+ * the action button constitutes the approval — nothing is submitted to the
233
+ * backend (there is no tool call to answer).
234
+ */
235
+ executeClientFunction(name: string, args: Record<string, unknown>): Promise<unknown>;
222
236
  /**
223
237
  * Register a navigation function that lets AGO navigate users to different pages.
224
238
  *
@@ -320,6 +334,9 @@ declare class AgoClient {
320
334
  */
321
335
  notifyContextChanged(): void;
322
336
  /* Excluded from this release type: emitFormEvent */
337
+ /* Excluded from this release type: emitProactiveEvent */
338
+ /* Excluded from this release type: getHttp */
339
+ /* Excluded from this release type: getConfiguredAgent */
323
340
  /**
324
341
  * Enable automatic capture of the current browser page (URL + title).
325
342
  * Injected as a dynamic context entry named `browser-page`.
@@ -364,6 +381,7 @@ declare class AgoClient {
364
381
  * Clean up resources
365
382
  */
366
383
  destroy(): void;
384
+ /* Excluded from this release type: reviveAfterDestroy */
367
385
  }
368
386
 
369
387
  /**
@@ -480,6 +498,25 @@ declare interface AgoClientEvents {
480
498
  "connection:status": {
481
499
  connected: boolean;
482
500
  };
501
+ /**
502
+ * A proactive nudge passed every governor gate and is ready to display.
503
+ * `useProactiveNudge` / `<AgoNudge>` consume this; custom UIs should call
504
+ * `client.proactive.shown(nudge)` when they render it (impression tracking
505
+ * + frequency caps), then `accept(nudge)` / `dismiss(nudge)`.
506
+ */
507
+ "nudge:ready": ProactiveNudgeInstance;
508
+ /** A nudge was displayed to the user (fires once per nudge). */
509
+ "nudge:shown": {
510
+ nudge: ProactiveNudgeInstance;
511
+ };
512
+ /** The user dismissed the nudge (its trigger is suppressed, see governor). */
513
+ "nudge:dismissed": {
514
+ nudge: ProactiveNudgeInstance;
515
+ };
516
+ /** The user accepted the nudge (its action ran / the chat is being seeded). */
517
+ "nudge:accepted": {
518
+ nudge: ProactiveNudgeInstance;
519
+ };
483
520
  }
484
521
 
485
522
  /**
@@ -541,6 +578,16 @@ declare interface AgoConfig {
541
578
  * with `maxResultBytes` on its definition; `Infinity` disables the guard.
542
579
  */
543
580
  maxFunctionResultBytes?: number;
581
+ /**
582
+ * Enable the proactive mode: declarative triggers evaluated client-side
583
+ * against friction signals (dwell/idle time, rage clicks, route bounces…)
584
+ * that can surface a nudge before the user opens the chat. Equivalent to
585
+ * calling `createAgoProactive(client, proactive)` — the resulting controller
586
+ * is available as `client.proactive`. Requires the tenant-level kill-switch
587
+ * (`GET /api/sdk/v1/config` → `proactive.enabled`) to be on; disabled by
588
+ * default otherwise.
589
+ */
590
+ proactive?: ProactiveOptions;
544
591
  }
545
592
 
546
593
  declare type AgoEventHandler<K extends AgoEventName> = (data: AgoClientEvents[K]) => void;
@@ -878,6 +925,43 @@ declare interface FormSchema {
878
925
  required?: string[];
879
926
  }
880
927
 
928
+ /**
929
+ * HTTP client with authentication headers
930
+ */
931
+ declare class HttpClient {
932
+ private baseUrl;
933
+ private headers;
934
+ constructor(config: AgoConfig);
935
+ /**
936
+ * Update configuration (e.g., JWT token)
937
+ */
938
+ updateConfig(config: Partial<AgoConfig>): void;
939
+ /**
940
+ * Make a GET request
941
+ */
942
+ get<T>(path: string): Promise<T>;
943
+ /**
944
+ * Make a POST request with JSON body.
945
+ *
946
+ * `keepalive: true` lets the request survive a page unload (used by the
947
+ * proactive event tracker's flush-on-hide — sendBeacon can't carry the auth
948
+ * headers, so it's a keepalive fetch instead).
949
+ */
950
+ post<T>(path: string, body?: unknown, options?: {
951
+ keepalive?: boolean;
952
+ }): Promise<T>;
953
+ /**
954
+ * Make a POST request and return the raw Response (for streaming)
955
+ */
956
+ postStream(path: string, body?: unknown): Promise<Response>;
957
+ /**
958
+ * Make a POST request with FormData (for file uploads)
959
+ */
960
+ postFormData(path: string, formData: FormData): Promise<Response>;
961
+ private request;
962
+ private handleErrorResponse;
963
+ }
964
+
881
965
  export declare function initDevPanel(options: DevPanelOptions): void;
882
966
 
883
967
  declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCELED"
@@ -888,6 +972,182 @@ declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCEL
888
972
  */
889
973
  | "WAITING_CLIENT";
890
974
 
975
+ /**
976
+ * Optional action attached to a nudge. Accepting a `functionName` action
977
+ * executes the registered client function (same `FunctionRegistry` path as
978
+ * agent-invoked calls); `setPageState` applies values through the registered
979
+ * page-state controls.
980
+ */
981
+ declare type NudgeAction = {
982
+ label: string;
983
+ functionName: string;
984
+ arguments?: Record<string, unknown>;
985
+ } | {
986
+ label: string;
987
+ setPageState: Record<string, unknown>;
988
+ };
989
+
990
+ /**
991
+ * Controller returned by {@link createAgoProactive} (also available as
992
+ * `client.proactive`).
993
+ */
994
+ declare interface ProactiveController {
995
+ /** Persistently opt this browser out of proactive nudges. */
996
+ optOut(): void;
997
+ /** Undo {@link optOut}. */
998
+ optIn(): void;
999
+ isOptedOut(): boolean;
1000
+ /**
1001
+ * Tell the governor the user is already engaged (e.g. the chat widget is
1002
+ * open) — nudges are suppressed while `true`. Call from the UI layer.
1003
+ */
1004
+ setEngaged(engaged: boolean): void;
1005
+ /** App-pushed field error counter (field NAME only — never values). */
1006
+ signalFieldError(fieldName: string): void;
1007
+ /** Current aggregated friction snapshot. */
1008
+ getSignalsSnapshot(): SignalsSnapshot;
1009
+ /** The nudge currently occupying the single-nudge slot, if any. */
1010
+ getActiveNudge(): ProactiveNudgeInstance | null;
1011
+ /**
1012
+ * Mark the nudge as displayed. Idempotent per nudge; counts it against the
1013
+ * frequency caps, tracks the impression, and emits `nudge:shown`.
1014
+ */
1015
+ shown(nudge: ProactiveNudgeInstance): void;
1016
+ /**
1017
+ * Accept the nudge: run its action (if any), emit `nudge:accepted`, track,
1018
+ * and — for agent nudges or nudges with a `goal` — pre-seed the chat with a
1019
+ * hidden kickoff message so the agent starts the turn with full context.
1020
+ */
1021
+ accept(nudge: ProactiveNudgeInstance): Promise<void>;
1022
+ /** Dismiss the nudge: suppress the trigger, track, emit `nudge:dismissed`. */
1023
+ dismiss(nudge: ProactiveNudgeInstance): void;
1024
+ /** Report a downstream conversion attributable to the nudge (analytics only). */
1025
+ markConverted(nudge: ProactiveNudgeInstance): void;
1026
+ /** Detach everything: listeners, timers, context provider, event flush. */
1027
+ destroy(): void;
1028
+ }
1029
+
1030
+ /** A concrete nudge produced by the engine, carried by every `nudge:*` event. */
1031
+ declare interface ProactiveNudgeInstance {
1032
+ /** Client-generated uuid for this nudge instance (`client_nudge_id`). */
1033
+ id: string;
1034
+ triggerId: string;
1035
+ /** `static` = configured message; `agent` = backend LLM evaluation. */
1036
+ source: "static" | "agent";
1037
+ message: string;
1038
+ action?: NudgeAction;
1039
+ goal?: string;
1040
+ /** See {@link ProactiveTrigger.kickoff}. */
1041
+ kickoff?: string;
1042
+ createdAt: Date;
1043
+ /** Server-side nudge id (agent nudges only). */
1044
+ serverNudgeId?: string;
1045
+ }
1046
+
1047
+ /** Options for {@link createAgoProactive} / `AgoConfig.proactive`. */
1048
+ declare interface ProactiveOptions {
1049
+ triggers: ProactiveTrigger[];
1050
+ /**
1051
+ * Global caps on nudges actually shown. `perSession` is in-memory (page
1052
+ * lifetime); `perDay` is persisted in localStorage with a date rollover —
1053
+ * best-effort by design (private browsing resets it); the costly LLM path is
1054
+ * additionally capped server-side.
1055
+ */
1056
+ frequencyCap?: {
1057
+ perSession?: number;
1058
+ perDay?: number;
1059
+ };
1060
+ /** Evaluation tick, ms. Default 1000. Zero network per tick. */
1061
+ tickMs?: number;
1062
+ /** Storage backend for persisted governance state. Default `localStorage`. */
1063
+ storage?: StorageLike;
1064
+ /** Storage key for persisted governance state. Default `"ago_proactive"`. */
1065
+ storageKey?: string;
1066
+ /** Tuning of the signal detectors (rage-click window, throttles…). */
1067
+ signals?: SignalCollectorTuning;
1068
+ /**
1069
+ * Local demos and tests ONLY: bypass the remote kill-switch. When set, the
1070
+ * `GET /config` fetch is skipped and the kill-switch takes this value.
1071
+ * Leave unset in production — the tenant admin controls the feature, and
1072
+ * the evaluate endpoint stays gated server-side regardless.
1073
+ */
1074
+ enabledOverride?: boolean;
1075
+ }
1076
+
1077
+ /** A declarative proactive trigger. */
1078
+ declare interface ProactiveTrigger {
1079
+ /** Stable id, used for cooldowns, dismissal memory, and analytics. */
1080
+ id: string;
1081
+ /** Conjunction of matchers (see {@link ProactiveTriggerWhen}). */
1082
+ when: ProactiveTriggerWhen;
1083
+ /**
1084
+ * Min time between two firings of this trigger (persisted across reloads).
1085
+ * A firing is the moment the trigger passes the gates — including an agent
1086
+ * evaluation that decides NOT to intervene, so a persistent condition can't
1087
+ * hammer the evaluate endpoint. Default 60 000.
1088
+ */
1089
+ cooldownMs?: number;
1090
+ /**
1091
+ * `'agent'` asks the backend's fast-LLM second filter whether (and how) to
1092
+ * intervene; a `static` object shows the given message with no network call.
1093
+ */
1094
+ intervene: "agent" | {
1095
+ type: "static";
1096
+ message: string;
1097
+ action?: NudgeAction;
1098
+ };
1099
+ /**
1100
+ * What the agent should help with. Sent to the evaluate endpoint, and used to
1101
+ * pre-seed the chat turn when the user accepts the nudge.
1102
+ */
1103
+ goal?: string;
1104
+ /**
1105
+ * User-voice line used to OPEN the conversation when the user accepts this
1106
+ * nudge and no conversation exists yet — a hidden kickoff cannot start one
1107
+ * (the backend rejects it). Sent as a visible user message, so write it in
1108
+ * the app's language ("Oui, aidez-moi à choisir !"). When a conversation is
1109
+ * already open, the SDK sends a hidden meta kickoff instead and this field
1110
+ * is unused. Without it, accepting with no open conversation skips the chat
1111
+ * pre-seed (the nudge action still runs).
1112
+ */
1113
+ kickoff?: string;
1114
+ /**
1115
+ * How long a dismissal of this trigger's nudge suppresses it (persisted).
1116
+ * Default 24h.
1117
+ */
1118
+ resurfaceAfterMs?: number;
1119
+ }
1120
+
1121
+ /**
1122
+ * Conditions of a proactive trigger. Pure conjunction: EVERY specified matcher
1123
+ * must pass against the current {@link SignalsSnapshot}. Numeric fields are
1124
+ * `>=` thresholds.
1125
+ */
1126
+ declare interface ProactiveTriggerWhen {
1127
+ /**
1128
+ * Route pattern the current pathname must match. Supports the SDK's route
1129
+ * styles: exact (`/billing`), `:param` segments (`/users/:id`), single-segment
1130
+ * wildcards (`/a/*` / `/b`), and a trailing `/*` that matches one or more
1131
+ * remaining segments (`/dossier/*`).
1132
+ */
1133
+ route?: string;
1134
+ /** Min time since the last user activity, ms. */
1135
+ idleMs?: number;
1136
+ /** Min time spent on the current route, ms. */
1137
+ dwellMs?: number;
1138
+ /**
1139
+ * Partial deep match against the registered page state (funnel step,
1140
+ * filters…). Every key present here must deep-match the live value.
1141
+ */
1142
+ pageState?: Partial<Record<string, unknown>>;
1143
+ /** Min rage-click bursts on the current route. */
1144
+ rageClicks?: number;
1145
+ /** Min A→B→A→B route oscillations this session. */
1146
+ routeBounces?: number;
1147
+ /** Per-field minimum error counts (field NAME → min count). */
1148
+ fieldErrors?: Record<string, number>;
1149
+ }
1150
+
891
1151
  /**
892
1152
  * Hook run before a paused turn is resumed, so the app controls WHEN the
893
1153
  * continuation fires (e.g. wait for the destination page to mount after a
@@ -920,6 +1180,54 @@ declare interface SendMessageOptions {
920
1180
  clientFunctionsMode?: ClientFunctionsMode;
921
1181
  }
922
1182
 
1183
+ /** Tuning knobs for the collector's detectors. All optional. */
1184
+ declare interface SignalCollectorTuning {
1185
+ /** Min gap between heavy activity work (route checks, notifications), ms. Default 250. */
1186
+ activityThrottleMs?: number;
1187
+ /** Rage click: clicks needed to count a burst. Default 3. */
1188
+ rageClickCount?: number;
1189
+ /** Rage click: max time between first and last click of a burst, ms. Default 1000. */
1190
+ rageClickWindowMs?: number;
1191
+ /** Rage click: max radius between clicks of a burst, px. Default 24. */
1192
+ rageClickRadiusPx?: number;
1193
+ /** Max routes kept in the recent-route sequence. Default 10. */
1194
+ maxRecentRoutes?: number;
1195
+ /** Max typed signals kept in the ring buffer. Default 50. */
1196
+ maxSignals?: number;
1197
+ }
1198
+
1199
+ /**
1200
+ * Aggregated view of the current friction state. Registered as a dynamic
1201
+ * context provider (key `friction_signals`) so it rides along as
1202
+ * `client_context` on every message, and sent as `signals` to the proactive
1203
+ * evaluate endpoint.
1204
+ */
1205
+ declare interface SignalsSnapshot {
1206
+ /** Current pathname. */
1207
+ route: string;
1208
+ /** Time spent on the current route, ms. */
1209
+ dwellMs: number;
1210
+ /** Time since the last user activity (pointer/key/scroll/touch), ms. */
1211
+ idleMs: number;
1212
+ /** Rage-click bursts detected on the current route. */
1213
+ rageClicks: number;
1214
+ /**
1215
+ * A→B→A→B route oscillations detected in the recent route sequence. Rolling
1216
+ * session counter (cross-route by nature); trigger cooldowns and dismissal
1217
+ * memory keep it from re-firing forever.
1218
+ */
1219
+ routeBounces: number;
1220
+ /** App-pushed field error counters (field NAME → count), current route only. */
1221
+ fieldErrors: Record<string, number>;
1222
+ /** Most recent pathnames, oldest first (bounded). */
1223
+ recentRoutes: string[];
1224
+ /**
1225
+ * Merged `AgoStateControl.get()` snapshot of the registered page-state
1226
+ * controls (funnel step, filters…), or `null` when none are registered.
1227
+ */
1228
+ pageState: Record<string, unknown> | null;
1229
+ }
1230
+
923
1231
  /**
924
1232
  * SSE stream chunk data
925
1233
  */
@@ -963,6 +1271,9 @@ declare interface SSEChunkData {
963
1271
  waiting_tool_call_ids?: string[];
964
1272
  }
965
1273
 
1274
+ /** The slice of the Web Storage API that {@link createStore} relies on. */
1275
+ declare type StorageLike = Pick<Storage, "getItem" | "setItem">;
1276
+
966
1277
  /**
967
1278
  * Where a completed form is sent.
968
1279
  * - `"https://..."` (a bare string) — shorthand for `{ via: "client", url }`: the browser