@useago/sdk 0.4.7 → 1.0.1

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 (39) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +10 -0
  4. package/README.md +107 -70
  5. package/dist/{AgoClient-CPqPT5s6.cjs → AgoClient-0x2Du_62.cjs} +1 -1
  6. package/dist/{AgoClient-BrYhSO5M.js → AgoClient-CZYNL25R.js} +29 -20
  7. package/dist/angular.cjs +1 -1
  8. package/dist/angular.d.cts +89 -0
  9. package/dist/angular.d.ts +89 -0
  10. package/dist/angular.js +1 -1
  11. package/dist/{createConversationSession-CGRO0bs2.cjs → createConversationSession-BLZvXMmM.cjs} +1 -1
  12. package/dist/{createConversationSession-Dmqd80DX.js → createConversationSession-Bmqj2rSS.js} +1 -1
  13. package/dist/createFormCollector-Bk0DRhUf.js +257 -0
  14. package/dist/createFormCollector-Ca8wRrxc.cjs +1 -0
  15. package/dist/devtools.d.cts +89 -0
  16. package/dist/devtools.d.ts +89 -0
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.d.cts +47 -0
  19. package/dist/index.d.ts +47 -0
  20. package/dist/index.js +70 -68
  21. package/dist/react.cjs +23 -23
  22. package/dist/react.d.cts +74 -23
  23. package/dist/react.d.ts +74 -23
  24. package/dist/react.js +2154 -2075
  25. package/dist/testing.cjs +1 -0
  26. package/dist/testing.d.cts +571 -0
  27. package/dist/testing.d.ts +571 -0
  28. package/dist/testing.js +4 -0
  29. package/dist/vue.cjs +1 -1
  30. package/dist/vue.d.cts +89 -0
  31. package/dist/vue.d.ts +89 -0
  32. package/dist/vue.js +1 -1
  33. package/dist/widget.cjs +4 -4
  34. package/dist/widget.d.cts +74 -5
  35. package/dist/widget.d.ts +74 -5
  36. package/dist/widget.js +410 -317
  37. package/package.json +30 -9
  38. package/dist/createFormCollector-CPS2phYq.js +0 -245
  39. package/dist/createFormCollector-DaWZsBsI.cjs +0 -1
@@ -0,0 +1,571 @@
1
+ /**
2
+ * Agent information
3
+ */
4
+ declare interface AgoAgent {
5
+ id: string;
6
+ name: string;
7
+ displayName?: string;
8
+ }
9
+
10
+ /**
11
+ * Main SDK client for AGO Chat integration
12
+ */
13
+ declare class AgoClient {
14
+ private httpClient;
15
+ private functionRegistry;
16
+ private contextRegistry;
17
+ private eventEmitter;
18
+ private config;
19
+ constructor(config: AgoConfig);
20
+ /**
21
+ * Send a message and receive a streaming response
22
+ */
23
+ sendMessage(content: string, options?: SendMessageOptions): Promise<AgoMessage>;
24
+ private processSSEResponse;
25
+ private handleClientFunctionInvocation;
26
+ /**
27
+ * Get list of conversations
28
+ */
29
+ getConversations(): Promise<Conversation[]>;
30
+ /**
31
+ * Get a specific conversation with messages
32
+ */
33
+ getConversation(conversationId: string): Promise<Conversation>;
34
+ /**
35
+ * Map the backend's snake_case `tool_call_data` entries onto the camelCase
36
+ * {@link ToolCallData} shape used everywhere else in the SDK. Mirrors
37
+ * `SSEHandler.parseToolCall` so persisted and streamed tool calls match.
38
+ */
39
+ private static mapPersistedToolCalls;
40
+ /**
41
+ * Get messages for a conversation
42
+ */
43
+ getMessages(conversationId: string): Promise<AgoMessage[]>;
44
+ /**
45
+ * Submit form data for a tool call
46
+ */
47
+ submitToolCallForm(toolCallId: string, formData: Record<string, unknown>): Promise<void>;
48
+ /**
49
+ * Confirm a tool call
50
+ */
51
+ confirmToolCall(toolCallId: string): Promise<void>;
52
+ /**
53
+ * Reject a tool call
54
+ */
55
+ rejectToolCall(toolCallId: string): Promise<void>;
56
+ /**
57
+ * Fetch a backend-stored form collector definition by name (the single source
58
+ * of truth for the form's description, schema, and submit target). Used by
59
+ * `loadFormCollector` / the name-only form of `useFormCollector` so the schema
60
+ * lives in the backend instead of being hardcoded in client code.
61
+ */
62
+ getFormCollector(name: string): Promise<FormCollectorDefinition>;
63
+ /**
64
+ * Relay a completed form collector's values to a server-configured destination.
65
+ *
66
+ * Used by `createFormCollector` / `useFormCollector` in `{ via: "backend" }` mode:
67
+ * the browser never holds the destination URL or its secret — the backend resolves
68
+ * `destination` (a named, opted-in tool) and forwards the values from the server.
69
+ */
70
+ submitFormCollector(destination: string, values: Record<string, unknown>): Promise<unknown>;
71
+ /**
72
+ * Submit feedback for a message
73
+ */
74
+ submitFeedback(messageId: string, rating: "positive" | "negative"): Promise<void>;
75
+ /**
76
+ * Register a client-side function that AGO can call.
77
+ * Accepts either a definition object or (name, handler, schema) args.
78
+ *
79
+ * ```ts
80
+ * // Single-object (preferred)
81
+ * client.registerFunction({
82
+ * name: "lookupOrder",
83
+ * description: "Look up an order",
84
+ * parameters: { type: "object", properties: { id: { type: "string" } } },
85
+ * handler: async (args) => fetchOrder(args.id),
86
+ * });
87
+ *
88
+ * // Classic 3-arg form
89
+ * client.registerFunction("lookupOrder", handler, schema);
90
+ * ```
91
+ */
92
+ registerFunction(definition: ClientFunctionDefinition): void;
93
+ registerFunction(name: string, handler: ClientFunctionHandler, schema: Omit<ClientFunctionSchema, "name">): void;
94
+ /**
95
+ * Short alias for `registerFunction`. Also accepts an array of definitions.
96
+ *
97
+ * ```ts
98
+ * client.register(lookupOrder);
99
+ * client.register([lookupOrder, cancelOrder]);
100
+ * ```
101
+ */
102
+ register(definition: ClientFunctionDefinition | ClientFunctionDefinition[]): void;
103
+ /**
104
+ * Unregister a client-side function
105
+ */
106
+ unregisterFunction(name: string): boolean;
107
+ /**
108
+ * Get all registered function schemas
109
+ */
110
+ getRegisteredFunctions(): ClientFunctionSchema[];
111
+ /**
112
+ * Register a navigation function that lets AGO navigate users to different pages.
113
+ * @param navigate - A callback that performs the navigation (e.g. react-router's navigate)
114
+ * @param routes - Map of route names to paths, with descriptions for the LLM
115
+ */
116
+ registerNavigationFunction(navigate: (path: string) => void, routes: Array<{
117
+ name: string;
118
+ path: string;
119
+ description: string;
120
+ }>): void;
121
+ /**
122
+ * Register or update a piece of client-side context.
123
+ * This context is sent with every message so the AI understands the user's situation.
124
+ *
125
+ * ```ts
126
+ * client.setContext("order-page", {
127
+ * name: "Order detail",
128
+ * description: "User is viewing order #123",
129
+ * data: { orderId: "123", status: "shipped" },
130
+ * });
131
+ * ```
132
+ */
133
+ setContext(key: string, entry: ContextEntry): void;
134
+ /**
135
+ * Remove a previously registered context entry.
136
+ */
137
+ removeContext(key: string): boolean;
138
+ /**
139
+ * Register a dynamic context provider. The callback is invoked every time
140
+ * a message is sent, so the AI always gets the freshest data.
141
+ *
142
+ * Use this for context that lives outside React state — global stores,
143
+ * refs, or computed values.
144
+ *
145
+ * ```ts
146
+ * client.addDynamicContext("cart", () => ({
147
+ * name: "Checkout",
148
+ * data: { itemCount: cart.items.length, total: cart.total },
149
+ * }));
150
+ * ```
151
+ */
152
+ addDynamicContext(key: string, provider: DynamicContextProvider): void;
153
+ /**
154
+ * Remove a dynamic context provider.
155
+ */
156
+ removeDynamicContext(key: string): boolean;
157
+ /**
158
+ * Broadcast that the client-side context changed by emitting `context:changed`
159
+ * with the fresh snapshot. The context-mutating methods call this automatically;
160
+ * stateful helpers whose context lives in a store (e.g. `createFormCollector`)
161
+ * call it when their store updates so observers like the dev panel stay live.
162
+ */
163
+ notifyContextChanged(): void;
164
+ /**
165
+ * Enable automatic capture of the current browser page (URL + title).
166
+ * Injected as a dynamic context entry named `browser-page`.
167
+ */
168
+ enableAutoPageContext(): void;
169
+ /**
170
+ * Get the current context snapshot.
171
+ */
172
+ getContextSnapshot(): ContextSnapshot | null;
173
+ /**
174
+ * Subscribe to an event
175
+ */
176
+ on<K extends AgoEventName>(event: K, handler: AgoEventHandler<K>): void;
177
+ /**
178
+ * Unsubscribe from an event
179
+ */
180
+ off<K extends AgoEventName>(event: K, handler: AgoEventHandler<K>): void;
181
+ /**
182
+ * Subscribe to an event once — auto-unsubscribes after the first call.
183
+ */
184
+ once<K extends AgoEventName>(event: K, handler: AgoEventHandler<K>): void;
185
+ /**
186
+ * Returns a Promise that resolves the next time `event` fires.
187
+ *
188
+ * ```ts
189
+ * const msg = await client.waitFor("message:complete", { timeout: 10000 });
190
+ * ```
191
+ */
192
+ waitFor<K extends AgoEventName>(event: K, options?: {
193
+ timeout?: number;
194
+ }): Promise<AgoClientEvents[K]>;
195
+ /**
196
+ * Update client configuration
197
+ */
198
+ updateConfig(config: Partial<AgoConfig>): void;
199
+ /**
200
+ * Clean up resources
201
+ */
202
+ destroy(): void;
203
+ }
204
+
205
+ /**
206
+ * SDK Events
207
+ */
208
+ declare interface AgoClientEvents {
209
+ /**
210
+ * The client-side context changed: a context entry or dynamic provider was
211
+ * added/removed, or a stateful helper (e.g. `createFormCollector`) updated its
212
+ * store. Carries the fresh snapshot so observers — notably the dev panel — can
213
+ * repaint without waiting for the next message. Fires for the form collector's
214
+ * initial install too, so its missing fields show from the start of a conversation.
215
+ */
216
+ "context:changed": ContextSnapshot | null;
217
+ "message:start": {
218
+ conversationId: string;
219
+ messageId: string;
220
+ };
221
+ "message:chunk": {
222
+ content: string;
223
+ conversationId: string;
224
+ messageId: string;
225
+ };
226
+ /**
227
+ * The main answer text is done (backend emitted `status: "DONE"`), but follow-up
228
+ * replies may still be pending. Fires once, before `message:complete`.
229
+ */
230
+ "message:answer-complete": AgoMessage;
231
+ "message:complete": AgoMessage;
232
+ "message:error": {
233
+ error: string;
234
+ conversationId?: string;
235
+ messageId?: string;
236
+ };
237
+ /**
238
+ * A full conversation was loaded from the server (e.g. after a page reload).
239
+ * Carries the messages and their persisted tool calls so stateful helpers —
240
+ * notably `createFormCollector` — can replay them to restore their state.
241
+ */
242
+ "conversation:loaded": Conversation;
243
+ "toolCall:received": ToolCallData;
244
+ "toolCall:form": ToolCallData;
245
+ "function:invoke": ClientFunctionInvocation;
246
+ "function:result": {
247
+ invocationId: string;
248
+ result: unknown;
249
+ error?: string;
250
+ };
251
+ "connection:status": {
252
+ connected: boolean;
253
+ };
254
+ }
255
+
256
+ /**
257
+ * SDK Configuration
258
+ */
259
+ declare interface AgoConfig {
260
+ /** API base URL (e.g., https://YOUR-DOMAIN.useago.com) */
261
+ baseUrl: string;
262
+ /** Widget ID (X-Widget-Id header). Auto-generated if not provided. */
263
+ widgetId?: string;
264
+ /** Default agent (id or slug) for new conversations. Shorthand for `defaultAgentId`. */
265
+ agent?: string;
266
+ /** Default agent ID for new conversations. Prefer `agent`. */
267
+ defaultAgentId?: string;
268
+ /** Permission name to apply to all requests (sent as `X-Widget-Permission`). Mirrors the widget's `window.AGO.permission`. */
269
+ permission?: string;
270
+ /** User email for identification */
271
+ userEmail?: string;
272
+ /** JWT token for authenticated users */
273
+ userJwt?: string;
274
+ /** Enable debug logging */
275
+ debug?: boolean;
276
+ }
277
+
278
+ declare type AgoEventHandler<K extends AgoEventName> = (data: AgoClientEvents[K]) => void;
279
+
280
+ declare type AgoEventName = keyof AgoClientEvents;
281
+
282
+ /**
283
+ * Message from AGO
284
+ */
285
+ declare interface AgoMessage {
286
+ id: string;
287
+ conversationId: string;
288
+ content: string;
289
+ role: "user" | "assistant";
290
+ status: MessageStatus;
291
+ agent?: AgoAgent;
292
+ sources?: AgoSource[];
293
+ toolCalls?: ToolCallData[];
294
+ followUpReplies?: string[];
295
+ createdAt: Date;
296
+ }
297
+
298
+ /**
299
+ * Knowledge source citation
300
+ */
301
+ declare interface AgoSource {
302
+ id: string;
303
+ title: string;
304
+ url?: string;
305
+ }
306
+
307
+ /**
308
+ * Single-object function definition — combines name, schema, and handler.
309
+ *
310
+ * ```ts
311
+ * const fn = defineFunction({
312
+ * name: "lookupOrder",
313
+ * description: "Look up an order by ID",
314
+ * parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
315
+ * handler: async (args) => fetchOrder(args.id as string),
316
+ * });
317
+ * client.registerFunction(fn);
318
+ * ```
319
+ */
320
+ declare interface ClientFunctionDefinition {
321
+ name: string;
322
+ description: string;
323
+ parameters: ClientFunctionSchema["parameters"];
324
+ handler: ClientFunctionHandler;
325
+ }
326
+
327
+ /**
328
+ * Function handler type
329
+ */
330
+ declare type ClientFunctionHandler = (args: Record<string, unknown>) => Promise<unknown> | unknown;
331
+
332
+ declare interface ClientFunctionInvocation {
333
+ invocationId: string;
334
+ functionName: string;
335
+ arguments: Record<string, unknown>;
336
+ conversationId: string;
337
+ }
338
+
339
+ /**
340
+ * Schema for a client-side function that AGO can call
341
+ */
342
+ declare interface ClientFunctionSchema {
343
+ /** Function name (must be unique) */
344
+ name: string;
345
+ /** Description for the LLM to understand when to call this function */
346
+ description: string;
347
+ /** JSON Schema for function parameters */
348
+ parameters: {
349
+ type: "object";
350
+ properties: Record<string, {
351
+ type: string;
352
+ description?: string;
353
+ enum?: string[];
354
+ default?: unknown;
355
+ }>;
356
+ required?: string[];
357
+ };
358
+ }
359
+
360
+ /**
361
+ * A single piece of context the client wants the LLM to know about.
362
+ */
363
+ declare interface ContextEntry {
364
+ /** Human-readable label (e.g. "Order detail", "Current user") */
365
+ name?: string;
366
+ /** Short description of what this context represents */
367
+ description?: string;
368
+ /** Arbitrary structured data the AI should know about */
369
+ data?: Record<string, unknown>;
370
+ }
371
+
372
+ /**
373
+ * Serialised client context sent with each message.
374
+ */
375
+ declare interface ContextSnapshot {
376
+ /** All active context entries keyed by their registration key */
377
+ entries: Record<string, ContextEntry>;
378
+ }
379
+
380
+ /**
381
+ * Conversation/Thread
382
+ */
383
+ declare interface Conversation {
384
+ id: string;
385
+ title: string;
386
+ lastMessageDate: Date;
387
+ messages?: AgoMessage[];
388
+ }
389
+
390
+ /**
391
+ * Create a mock AgoClient for testing. Works with any framework.
392
+ *
393
+ * ```ts
394
+ * import { createMockClient } from "@useago/sdk/testing";
395
+ *
396
+ * const mock = createMockClient();
397
+ * mock.__emitEvent("message:complete", someMessage);
398
+ * expect(mock.__callsFor("sendMessage")).toHaveLength(1);
399
+ * ```
400
+ */
401
+ export declare function createMockClient(options?: MockAgoClientOptions): MockAgoClient;
402
+
403
+ /**
404
+ * A function that returns a fresh context entry on demand.
405
+ * Evaluated every time a message is sent — use it to pull data from stores,
406
+ * refs, or any source that isn't captured by React state.
407
+ */
408
+ declare type DynamicContextProvider = () => ContextEntry | null | undefined;
409
+
410
+ /**
411
+ * The backend-stored shape returned by `GET /api/sdk/v1/forms/{name}` (see
412
+ * {@link AgoClient.getFormCollector}). Mirrors the persistable subset of
413
+ * {@link CreateFormCollectorOptions}: the `submit` here is never the client-only
414
+ * `handler` variant (a function can't be stored server-side).
415
+ */
416
+ declare interface FormCollectorDefinition<V = Record<string, unknown>> {
417
+ name: string;
418
+ description: string;
419
+ schema: FormCollectorSchema;
420
+ /** Server-stored submit target, if any. Absent means collect-only. */
421
+ submit?: SubmitConfig<V>;
422
+ }
423
+
424
+ /**
425
+ * Shape of a form's fields. Mirrors a client function's `parameters` (so the same
426
+ * object feeds the store, the update function, and the dynamic context). Additionally allows the SDK-only per-field `requiredWhen`, which {@link toWireParameters} removes before the schema reaches the LLM.
427
+ */
428
+ declare interface FormCollectorSchema {
429
+ type: "object";
430
+ properties: Record<string, FormFieldSchema>;
431
+ required?: string[];
432
+ }
433
+
434
+ declare interface FormField {
435
+ type: "string" | "number" | "boolean" | "array";
436
+ title?: string;
437
+ description?: string;
438
+ enum?: string[];
439
+ default?: unknown;
440
+ }
441
+
442
+ /**
443
+ * A field's conditional-requiredness rule. The field becomes required exactly
444
+ * when the controlling `property` matches `value` against the answers collected
445
+ * so far:
446
+ * - a single `value`, no `op` — equality (compared as strings);
447
+ * - a single `value` with `op` — numeric comparison (both sides coerced to numbers);
448
+ * - an array `value`, no `op` — "one of": matches when the property equals any
449
+ * listed value.
450
+ *
451
+ * SDK-only — it is stripped from the schema before it reaches the LLM tool
452
+ */
453
+ declare interface FormFieldCondition {
454
+ /** The controlling field whose value the rule tests. */
455
+ property: string;
456
+ /** Comparison operator; omitted means equality. Ignored when `value` is an array. */
457
+ op?: ">=" | "<=" | ">" | "<";
458
+ /**
459
+ * The value(s) to test the controlling field against. A single value is an
460
+ * equality (or, with `op`, a numeric comparison); an array is an "is one of"
461
+ * membership test, e.g. `value: ["1", "2", "3"]`.
462
+ */
463
+ value: string | number | Array<string | number>;
464
+ }
465
+
466
+ /** A single field's schema: the wire-legal keys plus the SDK-only `requiredWhen`. */
467
+ declare interface FormFieldSchema {
468
+ type: string;
469
+ description?: string;
470
+ enum?: string[];
471
+ default?: unknown;
472
+ /**
473
+ * Makes the field required only while this condition holds. Drives the dynamic
474
+ * `missing` list; stripped before the LLM tool — see {@link toWireParameters}.
475
+ */
476
+ requiredWhen?: FormFieldCondition;
477
+ }
478
+
479
+ /**
480
+ * Form schema for tool calls requiring user input
481
+ */
482
+ declare interface FormSchema {
483
+ type: "object";
484
+ properties: Record<string, FormField>;
485
+ required?: string[];
486
+ }
487
+
488
+ declare type MessageStatus = "IN_PROGRESS" | "DONE" | "ERROR" | "TODO" | "CANCELED";
489
+
490
+ export declare interface MockAgoClient extends AgoClient {
491
+ /**
492
+ * Simulate a server-pushed event.
493
+ * ```ts
494
+ * mock.__emitEvent("message:complete", { id: "1", content: "hi", ... });
495
+ * ```
496
+ */
497
+ __emitEvent<K extends AgoEventName>(event: K, data: AgoClientEvents[K]): void;
498
+ /**
499
+ * All recorded method calls: `[methodName, ...args][]`
500
+ */
501
+ __calls: Array<{
502
+ method: string;
503
+ args: unknown[];
504
+ }>;
505
+ /**
506
+ * Get calls for a specific method.
507
+ */
508
+ __callsFor(method: string): Array<{
509
+ method: string;
510
+ args: unknown[];
511
+ }>;
512
+ }
513
+
514
+ export declare interface MockAgoClientOptions {
515
+ overrides?: Partial<Record<string, MockFn>>;
516
+ }
517
+
518
+ declare type MockFn = (...args: any[]) => any;
519
+
520
+ /**
521
+ * Options for sending a message
522
+ */
523
+ declare interface SendMessageOptions {
524
+ /** Existing conversation ID */
525
+ conversationId?: string;
526
+ /** Override default agent */
527
+ agentId?: string;
528
+ /** File attachments */
529
+ files?: File[];
530
+ }
531
+
532
+ /**
533
+ * Where a completed form is sent.
534
+ * - `"https://..."` (a bare string) — shorthand for `{ via: "client", url }`: the browser
535
+ * POSTs the values to that URL.
536
+ * - `{ via: "client", url }` — same, written out.
537
+ * - `{ via: "client", handler }` — the browser runs your own submit logic.
538
+ * - `{ via: "backend", destination }` — the browser relays the values to the backend,
539
+ * which forwards them to the server-configured destination (URL + secret stay server-side).
540
+ * - `false` — collect only, no submit function.
541
+ */
542
+ declare type SubmitConfig<V = Record<string, unknown>> = string | {
543
+ via: "client";
544
+ url: string;
545
+ } | {
546
+ via: "client";
547
+ handler: (values: V) => Promise<unknown> | unknown;
548
+ } | {
549
+ via: "backend";
550
+ destination: string;
551
+ } | false;
552
+
553
+ /**
554
+ * Tool call data from SSE stream
555
+ */
556
+ declare interface ToolCallData {
557
+ id: string;
558
+ type: ToolCallType;
559
+ status: string;
560
+ toolName: string;
561
+ toolDisplayName?: string;
562
+ message?: string;
563
+ formSchema?: FormSchema;
564
+ data?: Record<string, unknown>;
565
+ functionName?: string;
566
+ arguments?: Record<string, unknown>;
567
+ }
568
+
569
+ declare type ToolCallType = "form" | "confirmation_input" | "status_message" | "progress_indicator" | "client_function" | "reasoning" | "mcp_ui_resource";
570
+
571
+ export { }
@@ -0,0 +1,4 @@
1
+ import { t as e } from "./createMockClient-DwdxNwEn.js";
2
+ export {
3
+ e as createMockClient
4
+ };
package/dist/vue.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("./rolldown-runtime-CaekUdDJ.cjs"),p=require("./AgoClient-CPqPT5s6.cjs");let t=require("vue");var I=Symbol("ago-client"),y={install(o,n){const e=new p.AgoClient(n);o.provide(I,e)}};function g(o){if(o)return new p.AgoClient(o);const n=(0,t.inject)(I);if(!n)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return n}function E(o={}){const n=o.client??g(),e=(0,t.ref)([]),s=(0,t.ref)(o.conversationId),i=(0,t.ref)(!1),r=(0,t.ref)(null),c=a=>{s.value||(s.value=a.conversationId)},f=a=>{const u=e.value.findIndex(v=>v.id===a.messageId);u>=0&&(e.value[u]={...e.value[u],content:e.value[u].content+a.content})},m=a=>{const u=e.value.findIndex(v=>v.id===a.id);u>=0?e.value[u]=a:e.value.push(a),i.value=!1},C=a=>{r.value=new Error(a.error),i.value=!1};(0,t.onMounted)(()=>{n.on("message:start",c),n.on("message:chunk",f),n.on("message:complete",m),n.on("message:error",C)}),(0,t.onUnmounted)(()=>{n.off("message:start",c),n.off("message:chunk",f),n.off("message:complete",m),n.off("message:error",C)});async function d(a,u){i.value=!0,r.value=null;const v={id:`temp-${Date.now()}`,conversationId:s.value||"",content:a,role:"user",status:"DONE",createdAt:new Date},L={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};e.value.push(v,L);try{const l=await n.sendMessage(a,{conversationId:s.value,files:u});l.conversationId&&!s.value&&(s.value=l.conversationId),e.value=e.value.filter(w=>!w.id.startsWith("temp-"));const A={...v,id:v.id.replace("temp-","user-"),conversationId:l.conversationId};return e.value.some(w=>w.id===l.id)?e.value.push(A):e.value.push(A,l),l}catch(l){return r.value=l instanceof Error?l:new Error("Failed to send"),i.value=!1,e.value=e.value.filter(A=>!A.id.startsWith("temp-")),null}}function h(){e.value=[],s.value=void 0,r.value=null}return{messages:e,isLoading:i,error:r,conversationId:s,sendMessage:d,clearMessages:h}}function M(o={}){const n=o.client??g(),e=o.autoLoad??!0,s=(0,t.ref)([]),i=(0,t.ref)(null),r=(0,t.ref)(!1),c=(0,t.ref)(null);async function f(){r.value=!0,c.value=null;try{s.value=await n.getConversations()}catch(d){c.value=d instanceof Error?d:new Error("Failed to load conversations")}finally{r.value=!1}}async function m(d){r.value=!0,c.value=null;try{i.value=await n.getConversation(d)}catch(h){c.value=h instanceof Error?h:new Error("Failed to load conversation")}finally{r.value=!1}}function C(){i.value=null}return(0,t.onMounted)(()=>{e&&f()}),{conversations:s,currentConversation:i,isLoading:r,error:c,selectConversation:m,startNewConversation:C,refreshConversations:f}}function N(o={}){const n=E({client:o.client,conversationId:o.conversationId}),e=M({client:o.client,autoLoad:o.autoLoad}),s=(0,t.computed)(()=>n.error.value||e.error.value);return{messages:n.messages,isLoading:n.isLoading,error:s,sendMessage:n.sendMessage,clearMessages:n.clearMessages,conversationId:n.conversationId,conversations:e.conversations,currentConversation:e.currentConversation,isConversationsLoading:e.isLoading,selectConversation:e.selectConversation,startNewConversation:e.startNewConversation,refreshConversations:e.refreshConversations}}function F(o,n){const e=g();(0,t.onMounted)(()=>{e.registerFunction(o,n.handler,{description:n.description,parameters:n.parameters})}),(0,t.onUnmounted)(()=>{e.unregisterFunction(o)})}function S(o,n){const e=g();(0,t.onMounted)(()=>{e.registerNavigationFunction(o,n)}),(0,t.onUnmounted)(()=>{e.unregisterFunction("navigateToPage")})}function _(o,n){const e=g();(0,t.onMounted)(()=>{e.on(o,n)}),(0,t.onUnmounted)(()=>{e.off(o,n)})}function D(o){const n=(0,t.shallowRef)(o.get());return(0,t.onScopeDispose)(o.subscribe(e=>{n.value=e})),n}exports.AGO_CLIENT_KEY=I;exports.AgoPlugin=y;exports.useAgo=g;exports.useAgoEvents=_;exports.useAgoFunction=F;exports.useAgoNavigation=S;exports.useAgoStore=D;exports.useChat=N;exports.useConversation=M;exports.useMessages=E;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("./rolldown-runtime-CaekUdDJ.cjs"),p=require("./AgoClient-0x2Du_62.cjs");let t=require("vue");var I=Symbol("ago-client"),y={install(o,n){const e=new p.AgoClient(n);o.provide(I,e)}};function g(o){if(o)return new p.AgoClient(o);const n=(0,t.inject)(I);if(!n)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return n}function E(o={}){const n=o.client??g(),e=(0,t.ref)([]),s=(0,t.ref)(o.conversationId),i=(0,t.ref)(!1),r=(0,t.ref)(null),c=a=>{s.value||(s.value=a.conversationId)},f=a=>{const u=e.value.findIndex(v=>v.id===a.messageId);u>=0&&(e.value[u]={...e.value[u],content:e.value[u].content+a.content})},m=a=>{const u=e.value.findIndex(v=>v.id===a.id);u>=0?e.value[u]=a:e.value.push(a),i.value=!1},C=a=>{r.value=new Error(a.error),i.value=!1};(0,t.onMounted)(()=>{n.on("message:start",c),n.on("message:chunk",f),n.on("message:complete",m),n.on("message:error",C)}),(0,t.onUnmounted)(()=>{n.off("message:start",c),n.off("message:chunk",f),n.off("message:complete",m),n.off("message:error",C)});async function d(a,u){i.value=!0,r.value=null;const v={id:`temp-${Date.now()}`,conversationId:s.value||"",content:a,role:"user",status:"DONE",createdAt:new Date},L={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};e.value.push(v,L);try{const l=await n.sendMessage(a,{conversationId:s.value,files:u});l.conversationId&&!s.value&&(s.value=l.conversationId),e.value=e.value.filter(w=>!w.id.startsWith("temp-"));const A={...v,id:v.id.replace("temp-","user-"),conversationId:l.conversationId};return e.value.some(w=>w.id===l.id)?e.value.push(A):e.value.push(A,l),l}catch(l){return r.value=l instanceof Error?l:new Error("Failed to send"),i.value=!1,e.value=e.value.filter(A=>!A.id.startsWith("temp-")),null}}function h(){e.value=[],s.value=void 0,r.value=null}return{messages:e,isLoading:i,error:r,conversationId:s,sendMessage:d,clearMessages:h}}function M(o={}){const n=o.client??g(),e=o.autoLoad??!0,s=(0,t.ref)([]),i=(0,t.ref)(null),r=(0,t.ref)(!1),c=(0,t.ref)(null);async function f(){r.value=!0,c.value=null;try{s.value=await n.getConversations()}catch(d){c.value=d instanceof Error?d:new Error("Failed to load conversations")}finally{r.value=!1}}async function m(d){r.value=!0,c.value=null;try{i.value=await n.getConversation(d)}catch(h){c.value=h instanceof Error?h:new Error("Failed to load conversation")}finally{r.value=!1}}function C(){i.value=null}return(0,t.onMounted)(()=>{e&&f()}),{conversations:s,currentConversation:i,isLoading:r,error:c,selectConversation:m,startNewConversation:C,refreshConversations:f}}function N(o={}){const n=E({client:o.client,conversationId:o.conversationId}),e=M({client:o.client,autoLoad:o.autoLoad}),s=(0,t.computed)(()=>n.error.value||e.error.value);return{messages:n.messages,isLoading:n.isLoading,error:s,sendMessage:n.sendMessage,clearMessages:n.clearMessages,conversationId:n.conversationId,conversations:e.conversations,currentConversation:e.currentConversation,isConversationsLoading:e.isLoading,selectConversation:e.selectConversation,startNewConversation:e.startNewConversation,refreshConversations:e.refreshConversations}}function F(o,n){const e=g();(0,t.onMounted)(()=>{e.registerFunction(o,n.handler,{description:n.description,parameters:n.parameters})}),(0,t.onUnmounted)(()=>{e.unregisterFunction(o)})}function S(o,n){const e=g();(0,t.onMounted)(()=>{e.registerNavigationFunction(o,n)}),(0,t.onUnmounted)(()=>{e.unregisterFunction("navigateToPage")})}function _(o,n){const e=g();(0,t.onMounted)(()=>{e.on(o,n)}),(0,t.onUnmounted)(()=>{e.off(o,n)})}function D(o){const n=(0,t.shallowRef)(o.get());return(0,t.onScopeDispose)(o.subscribe(e=>{n.value=e})),n}exports.AGO_CLIENT_KEY=I;exports.AgoPlugin=y;exports.useAgo=g;exports.useAgoEvents=_;exports.useAgoFunction=F;exports.useAgoNavigation=S;exports.useAgoStore=D;exports.useChat=N;exports.useConversation=M;exports.useMessages=E;