@useago/sdk 1.5.2 → 1.5.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +10 -0
  3. package/dist/AgoClient-BW0YZsis.js +1681 -0
  4. package/dist/AgoClient-Ba3ICq4K.cjs +8 -0
  5. package/dist/angular.cjs +1 -1
  6. package/dist/angular.d.cts +352 -0
  7. package/dist/angular.d.ts +352 -0
  8. package/dist/angular.js +1 -1
  9. package/dist/{createConversationSession-DPrrr70o.js → createConversationSession-BjsgjL-v.js} +3 -3
  10. package/dist/createConversationSession-okoz3teC.cjs +1 -0
  11. package/dist/createFormCollector-BWIh1pMl.cjs +1 -0
  12. package/dist/createFormCollector-Bay2UpRv.js +279 -0
  13. package/dist/createMockClient-DcuNlufr.js +97 -0
  14. package/dist/createMockClient-Dw-cyISN.cjs +1 -0
  15. package/dist/devtools.d.cts +352 -0
  16. package/dist/devtools.d.ts +352 -0
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.d.cts +564 -0
  19. package/dist/index.d.ts +564 -0
  20. package/dist/index.js +97 -90
  21. package/dist/react.cjs +3 -3
  22. package/dist/react.d.cts +430 -0
  23. package/dist/react.d.ts +430 -0
  24. package/dist/react.js +600 -443
  25. package/dist/testing.cjs +1 -1
  26. package/dist/testing.d.cts +352 -0
  27. package/dist/testing.d.ts +352 -0
  28. package/dist/testing.js +1 -1
  29. package/dist/vue.cjs +1 -1
  30. package/dist/vue.d.cts +373 -0
  31. package/dist/vue.d.ts +373 -0
  32. package/dist/vue.js +133 -110
  33. package/dist/widget.cjs +1 -1
  34. package/dist/widget.d.cts +349 -0
  35. package/dist/widget.d.ts +349 -0
  36. package/dist/widget.js +7 -7
  37. package/llms-full.txt +29 -0
  38. package/package.json +1 -1
  39. package/dist/AgoClient-5VGybmvz.cjs +0 -8
  40. package/dist/AgoClient-DXrH2AMi.js +0 -964
  41. package/dist/createConversationSession-0WTqcCLK.cjs +0 -1
  42. package/dist/createFormCollector-1GKKwQV_.cjs +0 -1
  43. package/dist/createFormCollector-DYh90kiG.js +0 -305
  44. package/dist/createMockClient-C-wrjb2C.cjs +0 -1
  45. package/dist/createMockClient-we-XoPom.js +0 -79
package/dist/angular.d.ts CHANGED
@@ -1,3 +1,19 @@
1
+ declare interface ActivityEntry {
2
+ ts: number;
3
+ actor: "user" | "agent";
4
+ name: string;
5
+ summary: string;
6
+ data?: Record<string, unknown>;
7
+ }
8
+
9
+ declare interface ActivityInput {
10
+ actor?: "user" | "agent";
11
+ name: string;
12
+ summary: string;
13
+ data?: Record<string, unknown>;
14
+ ts?: number;
15
+ }
16
+
1
17
  /**
2
18
  * Agent information
3
19
  */
@@ -53,6 +69,8 @@ declare class AgoClient {
53
69
  private functionRegistry;
54
70
  private contextRegistry;
55
71
  private eventEmitter;
72
+ private activityLedger;
73
+ private lastSentPageState;
56
74
  private config;
57
75
  /** Conversations already warned about an empty reply (one warning each). */
58
76
  private warnedEmptyConversations;
@@ -66,6 +84,12 @@ declare class AgoClient {
66
84
  private pendingApprovals;
67
85
  /** App-provided gate deciding WHEN a paused turn resumes (see {@link registerResumeGate}). */
68
86
  private resumeGate;
87
+ /**
88
+ * Proactive-mode controller, set when the client was created with
89
+ * `proactive` options or when `createAgoProactive(client, opts)` was called.
90
+ * `null` otherwise.
91
+ */
92
+ proactive: ProactiveController | null;
69
93
  constructor(config: AgoConfig);
70
94
  /**
71
95
  * Send a message and receive a streaming response
@@ -236,6 +260,14 @@ declare class AgoClient {
236
260
  * Get all registered function schemas
237
261
  */
238
262
  getRegisteredFunctions(): ClientFunctionSchema[];
263
+ /**
264
+ * Execute a registered client function locally, through the same
265
+ * FunctionRegistry path (result-size guard, error wrapping) as agent-invoked
266
+ * calls. Used by proactive nudge actions, where the user's explicit click on
267
+ * the action button constitutes the approval — nothing is submitted to the
268
+ * backend (there is no tool call to answer).
269
+ */
270
+ executeClientFunction(name: string, args: Record<string, unknown>): Promise<unknown>;
239
271
  /**
240
272
  * Register a navigation function that lets AGO navigate users to different pages.
241
273
  *
@@ -337,6 +369,9 @@ declare class AgoClient {
337
369
  */
338
370
  notifyContextChanged(): void;
339
371
  /* Excluded from this release type: emitFormEvent */
372
+ /* Excluded from this release type: emitProactiveEvent */
373
+ /* Excluded from this release type: getHttp */
374
+ /* Excluded from this release type: getConfiguredAgent */
340
375
  /**
341
376
  * Enable automatic capture of the current browser page (URL + title).
342
377
  * Injected as a dynamic context entry named `browser-page`.
@@ -346,6 +381,19 @@ declare class AgoClient {
346
381
  * Get the current context snapshot.
347
382
  */
348
383
  getContextSnapshot(): ContextSnapshot | null;
384
+ private buildSendContext;
385
+ /**
386
+ * Record something the user just did so the agent is aware of it on the next
387
+ * message. `actor` defaults to `"user"`. Keep `summary` short and high-signal
388
+ * (no raw payloads, secrets, or PII).
389
+ */
390
+ recordActivity(entry: ActivityInput): void;
391
+ /** Recent user + agent actions, oldest first (a copy). */
392
+ getRecentActivity(): ActivityEntry[];
393
+ clearActivity(): void;
394
+ private addActivity;
395
+ private recordAgentAction;
396
+ private registerActivityContext;
349
397
  /**
350
398
  * Subscribe to an event
351
399
  */
@@ -381,6 +429,7 @@ declare class AgoClient {
381
429
  * Clean up resources
382
430
  */
383
431
  destroy(): void;
432
+ /* Excluded from this release type: reviveAfterDestroy */
384
433
  }
385
434
 
386
435
  /**
@@ -497,6 +546,27 @@ export declare interface AgoClientEvents {
497
546
  "connection:status": {
498
547
  connected: boolean;
499
548
  };
549
+ /**
550
+ * A proactive nudge passed every governor gate and is ready to display.
551
+ * `useProactiveNudge` / `<AgoNudge>` consume this; custom UIs should call
552
+ * `client.proactive.shown(nudge)` when they render it (impression tracking
553
+ * + frequency caps), then `accept(nudge)` / `dismiss(nudge)`.
554
+ */
555
+ "nudge:ready": ProactiveNudgeInstance;
556
+ /** A nudge was displayed to the user (fires once per nudge). */
557
+ "nudge:shown": {
558
+ nudge: ProactiveNudgeInstance;
559
+ };
560
+ /** The user dismissed the nudge (its trigger is suppressed, see governor). */
561
+ "nudge:dismissed": {
562
+ nudge: ProactiveNudgeInstance;
563
+ };
564
+ /** The user accepted the nudge (its action ran / the chat is being seeded). */
565
+ "nudge:accepted": {
566
+ nudge: ProactiveNudgeInstance;
567
+ };
568
+ /** A user- or agent-action was recorded into the activity ledger. */
569
+ "activity:recorded": ActivityEntry;
500
570
  }
501
571
 
502
572
  /**
@@ -558,6 +628,24 @@ export declare interface AgoConfig {
558
628
  * with `maxResultBytes` on its definition; `Infinity` disables the guard.
559
629
  */
560
630
  maxFunctionResultBytes?: number;
631
+ /**
632
+ * Max number of recent actions kept in the in-memory activity ledger that
633
+ * rides along as the `activity:recent` context entry. Older entries drop
634
+ * first. Default `10`. Larger values give the agent more history at the cost
635
+ * of tokens on every message. Each entry's `data` is also size-clamped (long
636
+ * strings truncated, large arrays capped) so one event can't bloat the context.
637
+ */
638
+ maxActivityEntries?: number;
639
+ /**
640
+ * Enable the proactive mode: declarative triggers evaluated client-side
641
+ * against friction signals (dwell/idle time, rage clicks, route bounces…)
642
+ * that can surface a nudge before the user opens the chat. Equivalent to
643
+ * calling `createAgoProactive(client, proactive)` — the resulting controller
644
+ * is available as `client.proactive`. Requires the tenant-level kill-switch
645
+ * (`GET /api/sdk/v1/config` → `proactive.enabled`) to be on; disabled by
646
+ * default otherwise.
647
+ */
648
+ proactive?: ProactiveOptions;
561
649
  }
562
650
 
563
651
  declare type AgoEventHandler<K extends AgoEventName> = (data: AgoClientEvents[K]) => void;
@@ -992,6 +1080,43 @@ declare interface FormSchema {
992
1080
  required?: string[];
993
1081
  }
994
1082
 
1083
+ /**
1084
+ * HTTP client with authentication headers
1085
+ */
1086
+ declare class HttpClient {
1087
+ private baseUrl;
1088
+ private headers;
1089
+ constructor(config: AgoConfig);
1090
+ /**
1091
+ * Update configuration (e.g., JWT token)
1092
+ */
1093
+ updateConfig(config: Partial<AgoConfig>): void;
1094
+ /**
1095
+ * Make a GET request
1096
+ */
1097
+ get<T>(path: string): Promise<T>;
1098
+ /**
1099
+ * Make a POST request with JSON body.
1100
+ *
1101
+ * `keepalive: true` lets the request survive a page unload (used by the
1102
+ * proactive event tracker's flush-on-hide — sendBeacon can't carry the auth
1103
+ * headers, so it's a keepalive fetch instead).
1104
+ */
1105
+ post<T>(path: string, body?: unknown, options?: {
1106
+ keepalive?: boolean;
1107
+ }): Promise<T>;
1108
+ /**
1109
+ * Make a POST request and return the raw Response (for streaming)
1110
+ */
1111
+ postStream(path: string, body?: unknown): Promise<Response>;
1112
+ /**
1113
+ * Make a POST request with FormData (for file uploads)
1114
+ */
1115
+ postFormData(path: string, formData: FormData): Promise<Response>;
1116
+ private request;
1117
+ private handleErrorResponse;
1118
+ }
1119
+
995
1120
  declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCELED"
996
1121
  /**
997
1122
  * The turn paused on client function call(s) (pause mode): the agent waits for
@@ -1000,6 +1125,21 @@ declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCEL
1000
1125
  */
1001
1126
  | "WAITING_CLIENT";
1002
1127
 
1128
+ /**
1129
+ * Optional action attached to a nudge. Accepting a `functionName` action
1130
+ * executes the registered client function (same `FunctionRegistry` path as
1131
+ * agent-invoked calls); `setPageState` applies values through the registered
1132
+ * page-state controls.
1133
+ */
1134
+ declare type NudgeAction = {
1135
+ label: string;
1136
+ functionName: string;
1137
+ arguments?: Record<string, unknown>;
1138
+ } | {
1139
+ label: string;
1140
+ setPageState: Record<string, unknown>;
1141
+ };
1142
+
1003
1143
  declare interface Observable<T> {
1004
1144
  subscribe(observer: {
1005
1145
  next?: (value: T) => void;
@@ -1009,6 +1149,167 @@ declare interface Observable<T> {
1009
1149
  };
1010
1150
  }
1011
1151
 
1152
+ /**
1153
+ * Controller returned by {@link createAgoProactive} (also available as
1154
+ * `client.proactive`).
1155
+ */
1156
+ declare interface ProactiveController {
1157
+ /** Persistently opt this browser out of proactive nudges. */
1158
+ optOut(): void;
1159
+ /** Undo {@link optOut}. */
1160
+ optIn(): void;
1161
+ isOptedOut(): boolean;
1162
+ /**
1163
+ * Tell the governor the user is already engaged (e.g. the chat widget is
1164
+ * open) — nudges are suppressed while `true`. Call from the UI layer.
1165
+ */
1166
+ setEngaged(engaged: boolean): void;
1167
+ /** App-pushed field error counter (field NAME only — never values). */
1168
+ signalFieldError(fieldName: string): void;
1169
+ /** Current aggregated friction snapshot. */
1170
+ getSignalsSnapshot(): SignalsSnapshot;
1171
+ /** The nudge currently occupying the single-nudge slot, if any. */
1172
+ getActiveNudge(): ProactiveNudgeInstance | null;
1173
+ /**
1174
+ * Mark the nudge as displayed. Idempotent per nudge; counts it against the
1175
+ * frequency caps, tracks the impression, and emits `nudge:shown`.
1176
+ */
1177
+ shown(nudge: ProactiveNudgeInstance): void;
1178
+ /**
1179
+ * Accept the nudge: run its action (if any), emit `nudge:accepted`, track,
1180
+ * and — for agent nudges or nudges with a `goal` — pre-seed the chat with a
1181
+ * hidden kickoff message so the agent starts the turn with full context.
1182
+ */
1183
+ accept(nudge: ProactiveNudgeInstance): Promise<void>;
1184
+ /** Dismiss the nudge: suppress the trigger, track, emit `nudge:dismissed`. */
1185
+ dismiss(nudge: ProactiveNudgeInstance): void;
1186
+ /** Report a downstream conversion attributable to the nudge (analytics only). */
1187
+ markConverted(nudge: ProactiveNudgeInstance): void;
1188
+ /** Detach everything: listeners, timers, context provider, event flush. */
1189
+ destroy(): void;
1190
+ }
1191
+
1192
+ /** A concrete nudge produced by the engine, carried by every `nudge:*` event. */
1193
+ declare interface ProactiveNudgeInstance {
1194
+ /** Client-generated uuid for this nudge instance (`client_nudge_id`). */
1195
+ id: string;
1196
+ triggerId: string;
1197
+ /** `static` = configured message; `agent` = backend LLM evaluation. */
1198
+ source: "static" | "agent";
1199
+ message: string;
1200
+ action?: NudgeAction;
1201
+ goal?: string;
1202
+ /** See {@link ProactiveTrigger.kickoff}. */
1203
+ kickoff?: string;
1204
+ createdAt: Date;
1205
+ /** Server-side nudge id (agent nudges only). */
1206
+ serverNudgeId?: string;
1207
+ }
1208
+
1209
+ /** Options for {@link createAgoProactive} / `AgoConfig.proactive`. */
1210
+ declare interface ProactiveOptions {
1211
+ triggers: ProactiveTrigger[];
1212
+ /**
1213
+ * Global caps on nudges actually shown. `perSession` is in-memory (page
1214
+ * lifetime); `perDay` is persisted in localStorage with a date rollover —
1215
+ * best-effort by design (private browsing resets it); the costly LLM path is
1216
+ * additionally capped server-side.
1217
+ */
1218
+ frequencyCap?: {
1219
+ perSession?: number;
1220
+ perDay?: number;
1221
+ };
1222
+ /** Evaluation tick, ms. Default 1000. Zero network per tick. */
1223
+ tickMs?: number;
1224
+ /** Storage backend for persisted governance state. Default `localStorage`. */
1225
+ storage?: StorageLike;
1226
+ /** Storage key for persisted governance state. Default `"ago_proactive"`. */
1227
+ storageKey?: string;
1228
+ /** Tuning of the signal detectors (rage-click window, throttles…). */
1229
+ signals?: SignalCollectorTuning;
1230
+ /**
1231
+ * Local demos and tests ONLY: bypass the remote kill-switch. When set, the
1232
+ * `GET /config` fetch is skipped and the kill-switch takes this value.
1233
+ * Leave unset in production — the tenant admin controls the feature, and
1234
+ * the evaluate endpoint stays gated server-side regardless.
1235
+ */
1236
+ enabledOverride?: boolean;
1237
+ }
1238
+
1239
+ /** A declarative proactive trigger. */
1240
+ declare interface ProactiveTrigger {
1241
+ /** Stable id, used for cooldowns, dismissal memory, and analytics. */
1242
+ id: string;
1243
+ /** Conjunction of matchers (see {@link ProactiveTriggerWhen}). */
1244
+ when: ProactiveTriggerWhen;
1245
+ /**
1246
+ * Min time between two firings of this trigger (persisted across reloads).
1247
+ * A firing is the moment the trigger passes the gates — including an agent
1248
+ * evaluation that decides NOT to intervene, so a persistent condition can't
1249
+ * hammer the evaluate endpoint. Default 60 000.
1250
+ */
1251
+ cooldownMs?: number;
1252
+ /**
1253
+ * `'agent'` asks the backend's fast-LLM second filter whether (and how) to
1254
+ * intervene; a `static` object shows the given message with no network call.
1255
+ */
1256
+ intervene: "agent" | {
1257
+ type: "static";
1258
+ message: string;
1259
+ action?: NudgeAction;
1260
+ };
1261
+ /**
1262
+ * What the agent should help with. Sent to the evaluate endpoint, and used to
1263
+ * pre-seed the chat turn when the user accepts the nudge.
1264
+ */
1265
+ goal?: string;
1266
+ /**
1267
+ * User-voice line used to OPEN the conversation when the user accepts this
1268
+ * nudge and no conversation exists yet — a hidden kickoff cannot start one
1269
+ * (the backend rejects it). Sent as a visible user message, so write it in
1270
+ * the app's language ("Oui, aidez-moi à choisir !"). When a conversation is
1271
+ * already open, the SDK sends a hidden meta kickoff instead and this field
1272
+ * is unused. Without it, accepting with no open conversation skips the chat
1273
+ * pre-seed (the nudge action still runs).
1274
+ */
1275
+ kickoff?: string;
1276
+ /**
1277
+ * How long a dismissal of this trigger's nudge suppresses it (persisted).
1278
+ * Default 24h.
1279
+ */
1280
+ resurfaceAfterMs?: number;
1281
+ }
1282
+
1283
+ /**
1284
+ * Conditions of a proactive trigger. Pure conjunction: EVERY specified matcher
1285
+ * must pass against the current {@link SignalsSnapshot}. Numeric fields are
1286
+ * `>=` thresholds.
1287
+ */
1288
+ declare interface ProactiveTriggerWhen {
1289
+ /**
1290
+ * Route pattern the current pathname must match. Supports the SDK's route
1291
+ * styles: exact (`/billing`), `:param` segments (`/users/:id`), single-segment
1292
+ * wildcards (`/a/*` / `/b`), and a trailing `/*` that matches one or more
1293
+ * remaining segments (`/dossier/*`).
1294
+ */
1295
+ route?: string;
1296
+ /** Min time since the last user activity, ms. */
1297
+ idleMs?: number;
1298
+ /** Min time spent on the current route, ms. */
1299
+ dwellMs?: number;
1300
+ /**
1301
+ * Partial deep match against the registered page state (funnel step,
1302
+ * filters…). Every key present here must deep-match the live value.
1303
+ */
1304
+ pageState?: Partial<Record<string, unknown>>;
1305
+ /** Min rage-click bursts on the current route. */
1306
+ rageClicks?: number;
1307
+ /** Min A→B→A→B route oscillations this session. */
1308
+ routeBounces?: number;
1309
+ /** Per-field minimum error counts (field NAME → min count). */
1310
+ fieldErrors?: Record<string, number>;
1311
+ }
1312
+
1012
1313
  /**
1013
1314
  * Factory function that returns an Angular-compatible provider.
1014
1315
  * Use in your app's `providers` array or `bootstrapApplication`:
@@ -1065,6 +1366,54 @@ declare interface SendMessageOptions {
1065
1366
  clientFunctionsMode?: ClientFunctionsMode;
1066
1367
  }
1067
1368
 
1369
+ /** Tuning knobs for the collector's detectors. All optional. */
1370
+ declare interface SignalCollectorTuning {
1371
+ /** Min gap between heavy activity work (route checks, notifications), ms. Default 250. */
1372
+ activityThrottleMs?: number;
1373
+ /** Rage click: clicks needed to count a burst. Default 3. */
1374
+ rageClickCount?: number;
1375
+ /** Rage click: max time between first and last click of a burst, ms. Default 1000. */
1376
+ rageClickWindowMs?: number;
1377
+ /** Rage click: max radius between clicks of a burst, px. Default 24. */
1378
+ rageClickRadiusPx?: number;
1379
+ /** Max routes kept in the recent-route sequence. Default 10. */
1380
+ maxRecentRoutes?: number;
1381
+ /** Max typed signals kept in the ring buffer. Default 50. */
1382
+ maxSignals?: number;
1383
+ }
1384
+
1385
+ /**
1386
+ * Aggregated view of the current friction state. Registered as a dynamic
1387
+ * context provider (key `friction_signals`) so it rides along as
1388
+ * `client_context` on every message, and sent as `signals` to the proactive
1389
+ * evaluate endpoint.
1390
+ */
1391
+ declare interface SignalsSnapshot {
1392
+ /** Current pathname. */
1393
+ route: string;
1394
+ /** Time spent on the current route, ms. */
1395
+ dwellMs: number;
1396
+ /** Time since the last user activity (pointer/key/scroll/touch), ms. */
1397
+ idleMs: number;
1398
+ /** Rage-click bursts detected on the current route. */
1399
+ rageClicks: number;
1400
+ /**
1401
+ * A→B→A→B route oscillations detected in the recent route sequence. Rolling
1402
+ * session counter (cross-route by nature); trigger cooldowns and dismissal
1403
+ * memory keep it from re-firing forever.
1404
+ */
1405
+ routeBounces: number;
1406
+ /** App-pushed field error counters (field NAME → count), current route only. */
1407
+ fieldErrors: Record<string, number>;
1408
+ /** Most recent pathnames, oldest first (bounded). */
1409
+ recentRoutes: string[];
1410
+ /**
1411
+ * Merged `AgoStateControl.get()` snapshot of the registered page-state
1412
+ * controls (funnel step, filters…), or `null` when none are registered.
1413
+ */
1414
+ pageState: Record<string, unknown> | null;
1415
+ }
1416
+
1068
1417
  /**
1069
1418
  * SSE stream chunk data
1070
1419
  */
@@ -1108,6 +1457,9 @@ declare interface SSEChunkData {
1108
1457
  waiting_tool_call_ids?: string[];
1109
1458
  }
1110
1459
 
1460
+ /** The slice of the Web Storage API that {@link createStore} relies on. */
1461
+ declare type StorageLike = Pick<Storage, "getItem" | "setItem">;
1462
+
1111
1463
  /**
1112
1464
  * Where a completed form is sent.
1113
1465
  * - `"https://..."` (a bare string) — shorthand for `{ via: "client", url }`: the browser
package/dist/angular.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as o } from "./AgoClient-DXrH2AMi.js";
1
+ import { t as o } from "./AgoClient-BW0YZsis.js";
2
2
  import { t as c } from "./autoContinue-CC8K9mBU.js";
3
3
  var s = class {
4
4
  constructor(t) {
@@ -1,4 +1,4 @@
1
- import { i as d } from "./createFormCollector-DYh90kiG.js";
1
+ import { h as d } from "./AgoClient-BW0YZsis.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) => {
@@ -6,7 +6,7 @@ function v() {
6
6
  return (e === "x" ? r : r & 3 | 8).toString(16);
7
7
  });
8
8
  }
9
- function D(e = {}) {
9
+ function h(e = {}) {
10
10
  const r = e.key ?? f, c = e.threadKey ?? g, u = e.ttlMs ?? y, l = e.storage ?? (typeof localStorage < "u" ? localStorage : void 0);
11
11
  let n = e.widgetId ?? "";
12
12
  if (!n && l) try {
@@ -54,5 +54,5 @@ function D(e = {}) {
54
54
  };
55
55
  }
56
56
  export {
57
- D as t
57
+ h as t
58
58
  };
@@ -0,0 +1 @@
1
+ const d=require("./AgoClient-Ba3ICq4K.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}),s=o.get();s.value!==null&&c(s.lastMessageAt)&&o.set({value:null,lastMessageAt:null});function c(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||c(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 _}});
@@ -0,0 +1 @@
1
+ const C=require("./AgoClient-Ba3ICq4K.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}});