@cloudbase/agent-ui-miniprogram 0.0.12 → 1.0.1-alpha.7

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/index.esm.js DELETED
@@ -1,1444 +0,0 @@
1
- /**
2
- * AG-UI WeChat Miniprogram SDK Types
3
- */
4
- // ============================================================================
5
- // AG-UI Protocol Types (Local Copy)
6
- // ============================================================================
7
- //
8
- // These types are copied from @ag-ui/core to avoid bundling Zod.
9
- //
10
- // COMPATIBILITY:
11
- // - Based on: @ag-ui/core v0.0.42
12
- // - Source files:
13
- // - ag-ui/sdks/typescript/packages/core/src/events.ts
14
- // - ag-ui/sdks/typescript/packages/core/src/types.ts
15
- //
16
- // MAINTENANCE:
17
- // When updating to a new version of @ag-ui/core, compare the source files
18
- // above and update these types accordingly. Key things to check:
19
- // - New EventType values
20
- // - New event interfaces
21
- // - Changes to Message, Tool, ToolCall, Context, RunAgentInput
22
- //
23
- // ============================================================================
24
- /**
25
- * Event types for AG-UI protocol
26
- * @see @ag-ui/core EventType
27
- */
28
- var EventType;
29
- (function (EventType) {
30
- EventType["TEXT_MESSAGE_START"] = "TEXT_MESSAGE_START";
31
- EventType["TEXT_MESSAGE_CONTENT"] = "TEXT_MESSAGE_CONTENT";
32
- EventType["TEXT_MESSAGE_END"] = "TEXT_MESSAGE_END";
33
- EventType["TEXT_MESSAGE_CHUNK"] = "TEXT_MESSAGE_CHUNK";
34
- EventType["THINKING_TEXT_MESSAGE_START"] = "THINKING_TEXT_MESSAGE_START";
35
- EventType["THINKING_TEXT_MESSAGE_CONTENT"] = "THINKING_TEXT_MESSAGE_CONTENT";
36
- EventType["THINKING_TEXT_MESSAGE_END"] = "THINKING_TEXT_MESSAGE_END";
37
- EventType["TOOL_CALL_START"] = "TOOL_CALL_START";
38
- EventType["TOOL_CALL_ARGS"] = "TOOL_CALL_ARGS";
39
- EventType["TOOL_CALL_END"] = "TOOL_CALL_END";
40
- EventType["TOOL_CALL_CHUNK"] = "TOOL_CALL_CHUNK";
41
- EventType["TOOL_CALL_RESULT"] = "TOOL_CALL_RESULT";
42
- EventType["THINKING_START"] = "THINKING_START";
43
- EventType["THINKING_END"] = "THINKING_END";
44
- EventType["STATE_SNAPSHOT"] = "STATE_SNAPSHOT";
45
- EventType["STATE_DELTA"] = "STATE_DELTA";
46
- EventType["MESSAGES_SNAPSHOT"] = "MESSAGES_SNAPSHOT";
47
- EventType["ACTIVITY_SNAPSHOT"] = "ACTIVITY_SNAPSHOT";
48
- EventType["ACTIVITY_DELTA"] = "ACTIVITY_DELTA";
49
- EventType["RAW"] = "RAW";
50
- EventType["CUSTOM"] = "CUSTOM";
51
- EventType["RUN_STARTED"] = "RUN_STARTED";
52
- EventType["RUN_FINISHED"] = "RUN_FINISHED";
53
- EventType["RUN_ERROR"] = "RUN_ERROR";
54
- EventType["STEP_STARTED"] = "STEP_STARTED";
55
- EventType["STEP_FINISHED"] = "STEP_FINISHED";
56
- })(EventType || (EventType = {}));
57
-
58
- /**
59
- * AG-UI Event Handler
60
- * Processes AG-UI events and updates state accordingly
61
- */
62
- /**
63
- * Create initial processing state
64
- */
65
- function createProcessingState() {
66
- return {
67
- activeMessages: new Map(),
68
- pendingToolCalls: new Map(),
69
- rawToUiMessageMap: new Map()
70
- };
71
- }
72
- /**
73
- * Find the index of the last TextPart in a parts array
74
- */
75
- function findLastTextPartIndex(parts) {
76
- for (let i = parts.length - 1; i >= 0; i--) {
77
- if (parts[i].type === "text") {
78
- return i;
79
- }
80
- }
81
- return -1;
82
- }
83
- /**
84
- * Find the index of a ToolPart by toolCallId in a parts array
85
- */
86
- function findToolPartIndex(parts, toolCallId) {
87
- return parts.findIndex(p => p.type === "tool" && p.toolCallId === toolCallId);
88
- }
89
- /**
90
- * Rebuild UI-optimized messages from raw AG-UI messages.
91
- *
92
- * This utility function transforms the raw message array into a format
93
- * optimized for UI rendering:
94
- * - Filters out tool role messages (they appear as parts in assistant messages)
95
- * - Merges consecutive assistant messages into a single UIMessage with multiple parts
96
- * - Converts text content and tool calls into a unified parts-based structure
97
- *
98
- * @param messages - Raw AG-UI message array
99
- * @returns Array of UIMessage objects optimized for rendering
100
- *
101
- * @example
102
- * ```typescript
103
- * const messages: Message[] = [
104
- * { id: 'm1', role: 'user', content: 'Hello' },
105
- * { id: 'm2', role: 'assistant', content: 'Hi there!' },
106
- * { id: 'm3', role: 'assistant', content: 'How can I help?' },
107
- * ];
108
- *
109
- * const uiMessages = rebuildUiMessages(messages);
110
- * // Result: [
111
- * // { id: 'm1', role: 'user', parts: [{ type: 'text', text: 'Hello' }] },
112
- * // { id: 'm2', role: 'assistant', parts: [
113
- * // { type: 'text', text: 'Hi there!' },
114
- * // { type: 'text', text: 'How can I help?' },
115
- * // ] },
116
- * // ]
117
- * ```
118
- */
119
- function rebuildUiMessages(messages) {
120
- const uiMessages = [];
121
- for (const msg of messages) {
122
- // Skip tool messages
123
- if (msg.role === "tool") {
124
- continue;
125
- }
126
- const lastUiMsg = uiMessages[uiMessages.length - 1];
127
- const isAssistant = msg.role === "assistant";
128
- const shouldMerge = isAssistant && (lastUiMsg === null || lastUiMsg === void 0 ? void 0 : lastUiMsg.role) === "assistant";
129
- // Build parts for this message
130
- const parts = [];
131
- // Add text part if content exists and is a string (ignore binary/structured content for now)
132
- if (msg.content && typeof msg.content === "string") {
133
- parts.push({
134
- id: msg.id,
135
- type: "text",
136
- text: msg.content,
137
- state: "done"
138
- });
139
- }
140
- // Add tool parts from toolCalls
141
- const toolCalls = msg.toolCalls;
142
- if (toolCalls) {
143
- for (const tc of toolCalls) {
144
- let args = {};
145
- try {
146
- args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
147
- } catch (_a) {
148
- // Keep empty args
149
- }
150
- parts.push({
151
- type: "tool",
152
- id: `tool_call_${tc.id}`,
153
- toolCallId: tc.id,
154
- name: tc.function.name,
155
- argsString: tc.function.arguments || "",
156
- args,
157
- status: "completed" // Assume completed in snapshot
158
- });
159
- }
160
- }
161
- if (shouldMerge) {
162
- // Merge into existing assistant uiMessage
163
- lastUiMsg.parts.push(...parts);
164
- } else if (parts.length > 0 || msg.role !== "assistant") {
165
- // Create new uiMessage (always create for non-assistant, only if has parts for assistant)
166
- uiMessages.push({
167
- id: msg.id,
168
- role: msg.role,
169
- parts
170
- });
171
- }
172
- }
173
- return uiMessages;
174
- }
175
- /**
176
- * Process a single AG-UI event and update state
177
- */
178
- function processEvent(event, ctx, processingState) {
179
- var _a, _b;
180
- // Fire raw event callback if provided
181
- (_a = ctx.onRawEvent) === null || _a === void 0 ? void 0 : _a.call(ctx, event);
182
- const state = ctx.getState();
183
- switch (event.type) {
184
- // ========== Run Lifecycle ==========
185
- case EventType.RUN_STARTED:
186
- {
187
- const runStartedEvent = event;
188
- // Validate: server's threadId should match client's
189
- if (runStartedEvent.threadId && state.threadId && runStartedEvent.threadId !== state.threadId) {
190
- console.warn(`[AGUI] threadId mismatch: client="${state.threadId}", server="${runStartedEvent.threadId}". Using client's.`);
191
- }
192
- ctx.setData({
193
- "agui.isRunning": true,
194
- "agui.runId": runStartedEvent.runId,
195
- "agui.error": null
196
- });
197
- break;
198
- }
199
- case EventType.RUN_FINISHED:
200
- {
201
- ctx.setData({
202
- "agui.isRunning": false,
203
- "agui.runId": null,
204
- "agui.activeToolCalls": []
205
- });
206
- // Clear processing state
207
- processingState.activeMessages.clear();
208
- processingState.pendingToolCalls.clear();
209
- processingState.rawToUiMessageMap.clear();
210
- break;
211
- }
212
- case EventType.RUN_ERROR:
213
- {
214
- const runErrorEvent = event;
215
- const error = {
216
- code: "RUNTIME_ERROR",
217
- message: runErrorEvent.message,
218
- recoverable: false,
219
- details: {
220
- code: runErrorEvent.code
221
- }
222
- };
223
- ctx.setData({
224
- "agui.isRunning": false,
225
- "agui.runId": null,
226
- "agui.error": error
227
- });
228
- break;
229
- }
230
- // ========== Text Messages ==========
231
- case EventType.TEXT_MESSAGE_START:
232
- {
233
- const textMessageStartEvent = event;
234
- processingState.activeMessages.set(textMessageStartEvent.messageId, {
235
- id: textMessageStartEvent.messageId,
236
- role: textMessageStartEvent.role,
237
- content: ""
238
- });
239
- // Add new message to state
240
- const newMsg = {
241
- id: textMessageStartEvent.messageId,
242
- role: textMessageStartEvent.role,
243
- content: ""
244
- };
245
- const newIndex = state.messages.length;
246
- ctx.setData({
247
- [`agui.messages[${newIndex}]`]: newMsg
248
- });
249
- // === uiMessages: merge consecutive assistant messages ===
250
- const lastUiMsg = state.uiMessages[state.uiMessages.length - 1];
251
- const isAssistant = textMessageStartEvent.role === "assistant";
252
- const shouldMerge = isAssistant && (lastUiMsg === null || lastUiMsg === void 0 ? void 0 : lastUiMsg.role) === "assistant";
253
- if (shouldMerge) {
254
- // Merge into existing assistant uiMessage - add new TextPart
255
- processingState.rawToUiMessageMap.set(textMessageStartEvent.messageId, lastUiMsg.id);
256
- const newTextPart = {
257
- id: textMessageStartEvent.messageId,
258
- type: "text",
259
- text: "",
260
- state: "streaming"
261
- };
262
- const uiMsgIndex = state.uiMessages.length - 1;
263
- const partIndex = lastUiMsg.parts.length;
264
- ctx.setData({
265
- [`agui.uiMessages[${uiMsgIndex}].parts[${partIndex}]`]: newTextPart
266
- });
267
- } else {
268
- // Create new uiMessage
269
- processingState.rawToUiMessageMap.set(textMessageStartEvent.messageId, textMessageStartEvent.messageId);
270
- const newTextPart = {
271
- id: textMessageStartEvent.messageId,
272
- type: "text",
273
- text: "",
274
- state: "streaming"
275
- };
276
- const newUiMsg = {
277
- id: textMessageStartEvent.messageId,
278
- role: textMessageStartEvent.role,
279
- parts: [newTextPart]
280
- };
281
- const uiMsgIndex = state.uiMessages.length;
282
- ctx.setData({
283
- [`agui.uiMessages[${uiMsgIndex}]`]: newUiMsg
284
- });
285
- }
286
- break;
287
- }
288
- case EventType.TEXT_MESSAGE_CONTENT:
289
- {
290
- const textMessageContentEvent = event;
291
- const activeMsg = processingState.activeMessages.get(textMessageContentEvent.messageId);
292
- if (activeMsg) {
293
- activeMsg.content += textMessageContentEvent.delta;
294
- // Efficient path-based update for messages
295
- const index = state.messages.findIndex(m => m.id === textMessageContentEvent.messageId);
296
- if (index >= 0) {
297
- ctx.setData({
298
- [`agui.messages[${index}].content`]: activeMsg.content
299
- });
300
- }
301
- // === uiMessages: update the corresponding TextPart ===
302
- const uiMsgId = processingState.rawToUiMessageMap.get(textMessageContentEvent.messageId);
303
- if (uiMsgId) {
304
- const uiMsgIndex = state.uiMessages.findIndex(m => m.id === uiMsgId);
305
- if (uiMsgIndex >= 0) {
306
- const uiMsg = state.uiMessages[uiMsgIndex];
307
- // Find the last TextPart (the one being streamed)
308
- const partIndex = findLastTextPartIndex(uiMsg.parts);
309
- if (partIndex >= 0) {
310
- const textPart = uiMsg.parts[partIndex];
311
- ctx.setData({
312
- [`agui.uiMessages[${uiMsgIndex}].parts[${partIndex}].text`]: textPart.text + textMessageContentEvent.delta
313
- });
314
- }
315
- }
316
- }
317
- }
318
- break;
319
- }
320
- case EventType.TEXT_MESSAGE_END:
321
- {
322
- const textMessageEndEvent = event;
323
- // === uiMessages: mark TextPart as done ===
324
- const uiMsgId = processingState.rawToUiMessageMap.get(textMessageEndEvent.messageId);
325
- if (uiMsgId) {
326
- const uiMsgIndex = state.uiMessages.findIndex(m => m.id === uiMsgId);
327
- if (uiMsgIndex >= 0) {
328
- const uiMsg = state.uiMessages[uiMsgIndex];
329
- const partIndex = findLastTextPartIndex(uiMsg.parts);
330
- if (partIndex >= 0) {
331
- ctx.setData({
332
- [`agui.uiMessages[${uiMsgIndex}].parts[${partIndex}].state`]: "done"
333
- });
334
- }
335
- }
336
- }
337
- processingState.activeMessages.delete(textMessageEndEvent.messageId);
338
- break;
339
- }
340
- // ========== Tool Calls ==========
341
- case EventType.TOOL_CALL_START:
342
- {
343
- const toolCallStartEvent = event;
344
- // Find parent message: use provided parentMessageId or fallback to nearest assistant message
345
- let parentMsgId = toolCallStartEvent.parentMessageId;
346
- let parentMsgIndex = -1;
347
- if (parentMsgId) {
348
- parentMsgIndex = state.messages.findIndex(m => m.id === parentMsgId);
349
- }
350
- if (parentMsgIndex < 0) {
351
- // Fallback: find the most recent assistant message
352
- for (let i = state.messages.length - 1; i >= 0; i--) {
353
- if (state.messages[i].role === "assistant") {
354
- parentMsgIndex = i;
355
- parentMsgId = state.messages[i].id;
356
- break;
357
- }
358
- }
359
- }
360
- // Error: no parent assistant message found
361
- if (parentMsgIndex < 0 || !parentMsgId) {
362
- const error = {
363
- code: "INVALID_EVENT",
364
- message: `TOOL_CALL_START for "${toolCallStartEvent.toolCallId}" has no parent assistant message. ` + `Either provide parentMessageId or ensure an assistant message exists.`,
365
- recoverable: false,
366
- details: {
367
- toolCallId: toolCallStartEvent.toolCallId,
368
- toolCallName: toolCallStartEvent.toolCallName
369
- }
370
- };
371
- console.error(`[AGUI] ${error.message}`);
372
- ctx.setData({
373
- "agui.error": error
374
- });
375
- break;
376
- }
377
- processingState.pendingToolCalls.set(toolCallStartEvent.toolCallId, {
378
- id: toolCallStartEvent.toolCallId,
379
- name: toolCallStartEvent.toolCallName,
380
- argsString: "",
381
- parentMessageId: parentMsgId
382
- });
383
- // Add to active tool calls
384
- const toolCallState = {
385
- toolCallId: toolCallStartEvent.toolCallId,
386
- name: toolCallStartEvent.toolCallName,
387
- argsString: "",
388
- args: {},
389
- status: "pending"
390
- };
391
- const toolIndex = state.activeToolCalls.length;
392
- ctx.setData({
393
- [`agui.activeToolCalls[${toolIndex}]`]: toolCallState
394
- });
395
- // Attach tool call to parent assistant message
396
- if (parentMsgIndex >= 0) {
397
- const msg = state.messages[parentMsgIndex];
398
- const existingToolCalls = msg.toolCalls || [];
399
- const newToolCall = {
400
- id: toolCallStartEvent.toolCallId,
401
- type: "function",
402
- function: {
403
- name: toolCallStartEvent.toolCallName,
404
- arguments: ""
405
- }
406
- };
407
- ctx.setData({
408
- [`agui.messages[${parentMsgIndex}].toolCalls`]: [...existingToolCalls, newToolCall]
409
- });
410
- }
411
- // === uiMessages: add ToolPart to the parent assistant uiMessage ===
412
- // Find or create parent assistant uiMessage
413
- let parentUiMsgIndex = -1;
414
- const lastUiMsg = state.uiMessages[state.uiMessages.length - 1];
415
- if ((lastUiMsg === null || lastUiMsg === void 0 ? void 0 : lastUiMsg.role) === "assistant") {
416
- parentUiMsgIndex = state.uiMessages.length - 1;
417
- } else {
418
- // Create a new assistant uiMessage for the tool call
419
- const newUiMsg = {
420
- id: parentMsgId,
421
- role: "assistant",
422
- parts: []
423
- };
424
- parentUiMsgIndex = state.uiMessages.length;
425
- ctx.setData({
426
- [`agui.uiMessages[${parentUiMsgIndex}]`]: newUiMsg
427
- });
428
- }
429
- // Add ToolPart
430
- const toolPart = {
431
- type: "tool",
432
- id: `tool_call_${toolCallStartEvent.toolCallId}`,
433
- toolCallId: toolCallStartEvent.toolCallId,
434
- name: toolCallStartEvent.toolCallName,
435
- argsString: "",
436
- args: {},
437
- status: "pending"
438
- };
439
- const parentUiMsg = state.uiMessages[parentUiMsgIndex] || {
440
- parts: []
441
- };
442
- const toolPartIndex = parentUiMsg.parts.length;
443
- ctx.setData({
444
- [`agui.uiMessages[${parentUiMsgIndex}].parts[${toolPartIndex}]`]: toolPart
445
- });
446
- break;
447
- }
448
- case EventType.TOOL_CALL_ARGS:
449
- {
450
- const toolCallArgsEvent = event;
451
- const pending = processingState.pendingToolCalls.get(toolCallArgsEvent.toolCallId);
452
- if (pending) {
453
- pending.argsString += toolCallArgsEvent.delta;
454
- // Update UI with streaming progress
455
- const index = state.activeToolCalls.findIndex(tc => tc.toolCallId === toolCallArgsEvent.toolCallId);
456
- if (index >= 0) {
457
- ctx.setData({
458
- [`agui.activeToolCalls[${index}].argsString`]: pending.argsString
459
- });
460
- }
461
- // Update arguments in parent message's toolCalls
462
- if (pending.parentMessageId) {
463
- const msgIndex = state.messages.findIndex(m => m.id === pending.parentMessageId);
464
- if (msgIndex >= 0) {
465
- const msg = state.messages[msgIndex];
466
- const tcIndex = (_b = msg.toolCalls) === null || _b === void 0 ? void 0 : _b.findIndex(tc => tc.id === toolCallArgsEvent.toolCallId);
467
- if (tcIndex !== undefined && tcIndex >= 0) {
468
- ctx.setData({
469
- [`agui.messages[${msgIndex}].toolCalls[${tcIndex}].function.arguments`]: pending.argsString
470
- });
471
- }
472
- }
473
- }
474
- // === uiMessages: update ToolPart argsString ===
475
- const lastUiMsg = state.uiMessages[state.uiMessages.length - 1];
476
- if ((lastUiMsg === null || lastUiMsg === void 0 ? void 0 : lastUiMsg.role) === "assistant") {
477
- const uiMsgIndex = state.uiMessages.length - 1;
478
- const toolPartIndex = findToolPartIndex(lastUiMsg.parts, toolCallArgsEvent.toolCallId);
479
- if (toolPartIndex >= 0) {
480
- ctx.setData({
481
- [`agui.uiMessages[${uiMsgIndex}].parts[${toolPartIndex}].argsString`]: pending.argsString
482
- });
483
- }
484
- }
485
- }
486
- break;
487
- }
488
- case EventType.TOOL_CALL_END:
489
- {
490
- const toolCallEndEvent = event;
491
- const pending = processingState.pendingToolCalls.get(toolCallEndEvent.toolCallId);
492
- // Mark as ready - args complete, waiting for execution
493
- const index = state.activeToolCalls.findIndex(tc => tc.toolCallId === toolCallEndEvent.toolCallId);
494
- if (index >= 0) {
495
- // Parse args
496
- let args = {};
497
- if (pending === null || pending === void 0 ? void 0 : pending.argsString) {
498
- try {
499
- args = JSON.parse(pending.argsString);
500
- } catch (_c) {
501
- // Keep empty args on parse failure
502
- }
503
- }
504
- ctx.setData({
505
- [`agui.activeToolCalls[${index}].status`]: "ready",
506
- [`agui.activeToolCalls[${index}].args`]: args
507
- });
508
- }
509
- // === uiMessages: update ToolPart status and parse args ===
510
- const lastUiMsg = state.uiMessages[state.uiMessages.length - 1];
511
- if ((lastUiMsg === null || lastUiMsg === void 0 ? void 0 : lastUiMsg.role) === "assistant") {
512
- const uiMsgIndex = state.uiMessages.length - 1;
513
- const toolPartIndex = findToolPartIndex(lastUiMsg.parts, toolCallEndEvent.toolCallId);
514
- if (toolPartIndex >= 0) {
515
- let args = {};
516
- if (pending === null || pending === void 0 ? void 0 : pending.argsString) {
517
- try {
518
- args = JSON.parse(pending.argsString);
519
- } catch (_d) {
520
- // Keep empty args on parse failure
521
- }
522
- }
523
- ctx.setData({
524
- [`agui.uiMessages[${uiMsgIndex}].parts[${toolPartIndex}].status`]: "ready",
525
- [`agui.uiMessages[${uiMsgIndex}].parts[${toolPartIndex}].args`]: args
526
- });
527
- }
528
- }
529
- break;
530
- }
531
- // ========== Messages Snapshot ==========
532
- case EventType.MESSAGES_SNAPSHOT:
533
- {
534
- const messagesSnapshotEvent = event;
535
- ctx.setData({
536
- "agui.messages": messagesSnapshotEvent.messages,
537
- "agui.uiMessages": rebuildUiMessages(messagesSnapshotEvent.messages)
538
- });
539
- break;
540
- }
541
- }
542
- }
543
-
544
- /******************************************************************************
545
- Copyright (c) Microsoft Corporation.
546
-
547
- Permission to use, copy, modify, and/or distribute this software for any
548
- purpose with or without fee is hereby granted.
549
-
550
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
551
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
552
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
553
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
554
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
555
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
556
- PERFORMANCE OF THIS SOFTWARE.
557
- ***************************************************************************** */
558
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
559
-
560
- function __awaiter(thisArg, _arguments, P, generator) {
561
- function adopt(value) {
562
- return value instanceof P ? value : new P(function (resolve) {
563
- resolve(value);
564
- });
565
- }
566
- return new (P || (P = Promise))(function (resolve, reject) {
567
- function fulfilled(value) {
568
- try {
569
- step(generator.next(value));
570
- } catch (e) {
571
- reject(e);
572
- }
573
- }
574
- function rejected(value) {
575
- try {
576
- step(generator["throw"](value));
577
- } catch (e) {
578
- reject(e);
579
- }
580
- }
581
- function step(result) {
582
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
583
- }
584
- step((generator = generator.apply(thisArg, _arguments || [])).next());
585
- });
586
- }
587
- function __values(o) {
588
- var s = typeof Symbol === "function" && Symbol.iterator,
589
- m = s && o[s],
590
- i = 0;
591
- if (m) return m.call(o);
592
- if (o && typeof o.length === "number") return {
593
- next: function () {
594
- if (o && i >= o.length) o = void 0;
595
- return {
596
- value: o && o[i++],
597
- done: !o
598
- };
599
- }
600
- };
601
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
602
- }
603
- function __await(v) {
604
- return this instanceof __await ? (this.v = v, this) : new __await(v);
605
- }
606
- function __asyncGenerator(thisArg, _arguments, generator) {
607
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
608
- var g = generator.apply(thisArg, _arguments || []),
609
- i,
610
- q = [];
611
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () {
612
- return this;
613
- }, i;
614
- function awaitReturn(f) {
615
- return function (v) {
616
- return Promise.resolve(v).then(f, reject);
617
- };
618
- }
619
- function verb(n, f) {
620
- if (g[n]) {
621
- i[n] = function (v) {
622
- return new Promise(function (a, b) {
623
- q.push([n, v, a, b]) > 1 || resume(n, v);
624
- });
625
- };
626
- if (f) i[n] = f(i[n]);
627
- }
628
- }
629
- function resume(n, v) {
630
- try {
631
- step(g[n](v));
632
- } catch (e) {
633
- settle(q[0][3], e);
634
- }
635
- }
636
- function step(r) {
637
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
638
- }
639
- function fulfill(value) {
640
- resume("next", value);
641
- }
642
- function reject(value) {
643
- resume("throw", value);
644
- }
645
- function settle(f, v) {
646
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
647
- }
648
- }
649
- function __asyncValues(o) {
650
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
651
- var m = o[Symbol.asyncIterator],
652
- i;
653
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
654
- return this;
655
- }, i);
656
- function verb(n) {
657
- i[n] = o[n] && function (v) {
658
- return new Promise(function (resolve, reject) {
659
- v = o[n](v), settle(resolve, reject, v.done, v.value);
660
- });
661
- };
662
- }
663
- function settle(resolve, reject, d, v) {
664
- Promise.resolve(v).then(function (v) {
665
- resolve({
666
- value: v,
667
- done: d
668
- });
669
- }, reject);
670
- }
671
- }
672
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
673
- var e = new Error(message);
674
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
675
- };
676
-
677
- /**
678
- * AG-UI Behavior for WeChat Miniprogram
679
- * Main entry point - provides the Behavior mixin pattern
680
- */
681
- /**
682
- * Create initial state from options
683
- */
684
- function createInitialState(options) {
685
- var _a, _b, _c, _d, _e;
686
- const messages = (_a = options.messages) !== null && _a !== void 0 ? _a : [];
687
- return {
688
- messages,
689
- uiMessages: rebuildUiMessages(messages),
690
- isRunning: false,
691
- runId: null,
692
- activeToolCalls: [],
693
- error: null,
694
- threadId: (_b = options.threadId) !== null && _b !== void 0 ? _b : generateId(),
695
- tools: (_d = (_c = options.tools) === null || _c === void 0 ? void 0 : _c.map(t => ({
696
- name: t.name,
697
- description: t.description,
698
- parameters: t.parameters
699
- }))) !== null && _d !== void 0 ? _d : [],
700
- contexts: (_e = options.contexts) !== null && _e !== void 0 ? _e : []
701
- };
702
- }
703
- /**
704
- * Creates an AG-UI Behavior mixin for WeChat Mini Program components.
705
- *
706
- * This factory function returns a Behavior definition that provides AG-UI
707
- * protocol support via the `agui` namespace on component data.
708
- *
709
- * @param options - Configuration options for the behavior
710
- * @param options.transport - Transport instance for communicating with the agent backend
711
- * @param options.messages - Initial message history to populate the conversation
712
- * @param options.tools - Client tools that the agent can invoke
713
- * @param options.threadId - Custom thread ID (auto-generated if not provided)
714
- * @param options.contexts - Additional context objects to pass to the agent
715
- * @param options.onRawEvent - Callback invoked for each raw AG-UI event received
716
- * @returns A Behavior definition to be mixed into a Component
717
- *
718
- * @example
719
- * ```typescript
720
- * // Basic usage with transport
721
- * const transport = new CloudbaseTransport({ botId: 'your-bot-id' });
722
- * Component({
723
- * behaviors: [createAGUIBehavior({ transport })],
724
- * });
725
- *
726
- * // With initial messages and tools
727
- * Component({
728
- * behaviors: [createAGUIBehavior({
729
- * transport,
730
- * messages: [{ id: 'm1', role: 'user', content: 'Hello' }],
731
- * tools: [{
732
- * name: 'get_weather',
733
- * description: 'Get current weather',
734
- * parameters: { type: 'object', properties: { city: { type: 'string' } } },
735
- * handler: async ({ args }) => ({ temp: 72, city: args.city }),
736
- * }],
737
- * })],
738
- * });
739
- * ```
740
- */
741
- function createAGUIBehavior(options = {}) {
742
- var _a, _b;
743
- // Build toolHandlers map from options (for internal use)
744
- const toolHandlers = new Map((_b = (_a = options.tools) === null || _a === void 0 ? void 0 : _a.map(t => [t.name, t])) !== null && _b !== void 0 ? _b : []);
745
- return Behavior({
746
- data: {
747
- agui: createInitialState(options)
748
- },
749
- lifetimes: {
750
- attached() {
751
- // Initialize internal state (non-serializable)
752
- const instance = {
753
- transport: options.transport || null,
754
- toolHandlers,
755
- processingState: createProcessingState(),
756
- options
757
- };
758
- // Store instance on component
759
- this.__agui = instance;
760
- // Create agui namespace with bound methods and state getters
761
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
762
- const self = this;
763
- self.agui = {
764
- // Methods
765
- init: self._aguiInit.bind(self),
766
- setThreadId: self._aguiSetThreadId.bind(self),
767
- sendMessage: self._aguiSendMessage.bind(self),
768
- appendMessage: self._aguiAppendMessage.bind(self),
769
- setMessages: self._aguiSetMessages.bind(self),
770
- reset: self._aguiReset.bind(self),
771
- addTool: self._aguiAddTool.bind(self),
772
- removeTool: self._aguiRemoveTool.bind(self),
773
- updateTool: self._aguiUpdateTool.bind(self),
774
- clearTools: self._aguiClearTools.bind(self),
775
- // State getters - proxy to this.data.agui for convenience
776
- get messages() {
777
- return self.data.agui.messages;
778
- },
779
- get uiMessages() {
780
- return self.data.agui.uiMessages;
781
- },
782
- get isRunning() {
783
- return self.data.agui.isRunning;
784
- },
785
- get runId() {
786
- return self.data.agui.runId;
787
- },
788
- get activeToolCalls() {
789
- return self.data.agui.activeToolCalls;
790
- },
791
- get error() {
792
- return self.data.agui.error;
793
- },
794
- get threadId() {
795
- return self.data.agui.threadId;
796
- },
797
- get tools() {
798
- return self.data.agui.tools;
799
- },
800
- get contexts() {
801
- return self.data.agui.contexts;
802
- },
803
- // Config getter - exposes current configuration options
804
- get config() {
805
- return getInstance(self).options;
806
- }
807
- };
808
- },
809
- detached() {
810
- const instance = getInstance(this);
811
- if (instance) {
812
- instance.toolHandlers.clear();
813
- instance.processingState.activeMessages.clear();
814
- instance.processingState.pendingToolCalls.clear();
815
- }
816
- }
817
- },
818
- methods: {
819
- // ========== Lifecycle Methods ==========
820
- /**
821
- * Initialize the AG-UI behavior with runtime configuration.
822
- * Call this in the component's `attached` lifecycle if transport
823
- * was not provided in `createAGUIBehavior` options.
824
- *
825
- * @param config - Runtime configuration object
826
- * @param config.transport - Transport instance for agent communication
827
- * @param config.threadId - Optional thread ID to override the generated one
828
- *
829
- * @example
830
- * ```typescript
831
- * Component({
832
- * behaviors: [aguiBehavior],
833
- * lifetimes: {
834
- * attached() {
835
- * this.agui.init({
836
- * transport: new CloudbaseTransport({ botId: 'my-bot' }),
837
- * });
838
- * },
839
- * },
840
- * });
841
- * ```
842
- */
843
- _aguiInit(config) {
844
- const instance = getInstance(this);
845
- instance.transport = config.transport;
846
- if (config.threadId) {
847
- this.setData({
848
- "agui.threadId": config.threadId
849
- });
850
- }
851
- },
852
- // ========== Dynamic Config Setters ==========
853
- /**
854
- * Update the thread ID for subsequent agent runs.
855
- *
856
- * @param threadId - New thread ID to use
857
- */
858
- _aguiSetThreadId(threadId) {
859
- this.setData({
860
- "agui.threadId": threadId
861
- });
862
- },
863
- // ========== Message Methods ==========
864
- /**
865
- * Send a message to the agent and process the streaming response.
866
- *
867
- * This is the primary method for initiating a conversation turn.
868
- * It appends the message(s) to the conversation history and starts
869
- * an agent run. The response will be streamed and state updated reactively.
870
- *
871
- * @param input - Either a string (converted to user message) or an array of Message objects
872
- * @returns Promise that resolves when the agent run completes
873
- *
874
- * @example
875
- * ```typescript
876
- * // Send a simple text message
877
- * await this.agui.sendMessage('What is the weather like?');
878
- *
879
- * // Send a pre-constructed message
880
- * await this.agui.sendMessage([
881
- * { id: 'msg-1', role: 'user', content: 'Hello' },
882
- * ]);
883
- * ```
884
- */
885
- _aguiSendMessage(input) {
886
- return __awaiter(this, void 0, void 0, function* () {
887
- const instance = getInstance(this);
888
- if (!instance.transport) {
889
- const error = {
890
- code: "INIT_ERROR",
891
- message: "Transport not initialized. Call agui.init() first or provide transport in createAGUIBehavior options.",
892
- recoverable: true
893
- };
894
- this.setData({
895
- "agui.error": error
896
- });
897
- return;
898
- }
899
- // Convert text to delta messages array
900
- const deltaMessages = typeof input === "string" ? [{
901
- id: generateId(),
902
- role: "user",
903
- content: input
904
- }] : input;
905
- // Add delta messages to both messages and uiMessages
906
- const currentMessages = this.data.agui.messages;
907
- const newMessages = [...currentMessages, ...deltaMessages];
908
- this.setData({
909
- "agui.messages": newMessages,
910
- // Rebuild uiMessages from full messages to handle merging correctly
911
- "agui.uiMessages": rebuildUiMessages(newMessages),
912
- "agui.error": null,
913
- "agui.isRunning": true
914
- });
915
- // Run the agent with delta messages
916
- yield this.__aguiRunAgent(instance, deltaMessages);
917
- });
918
- },
919
- /**
920
- * Append a single message to the conversation history without triggering an agent run.
921
- * Useful for adding system messages or programmatically inserting messages.
922
- *
923
- * @param message - The message to append
924
- */
925
- _aguiAppendMessage(message) {
926
- const currentMessages = this.data.agui.messages;
927
- const newMessages = [...currentMessages, message];
928
- this.setData({
929
- "agui.messages": newMessages,
930
- "agui.uiMessages": rebuildUiMessages(newMessages)
931
- });
932
- },
933
- /**
934
- * Replace the entire message history.
935
- * Useful for loading a saved conversation or resetting to a specific state.
936
- *
937
- * @param messages - The new message array to set
938
- */
939
- _aguiSetMessages(messages) {
940
- this.setData({
941
- "agui.messages": messages,
942
- "agui.uiMessages": rebuildUiMessages(messages)
943
- });
944
- },
945
- /**
946
- * Reset the AG-UI state to the initial configuration.
947
- * Clears all messages, tool calls, and errors. Restores tools to initial set.
948
- */
949
- _aguiReset() {
950
- var _a;
951
- const instance = getInstance(this);
952
- const opts = instance.options;
953
- // Clear internal state
954
- instance.processingState.activeMessages.clear();
955
- instance.processingState.pendingToolCalls.clear();
956
- // Restore toolHandlers from options
957
- instance.toolHandlers.clear();
958
- for (const tool of (_a = opts.tools) !== null && _a !== void 0 ? _a : []) {
959
- instance.toolHandlers.set(tool.name, tool);
960
- }
961
- // Restore to original options state
962
- this.setData({
963
- agui: createInitialState(opts)
964
- });
965
- },
966
- // ========== Tool Methods ==========
967
- /**
968
- * Register a client tool that the agent can invoke.
969
- * The tool's handler function will be called when the agent requests this tool.
970
- *
971
- * @param tool - The tool definition including name, description, parameters schema, and handler
972
- *
973
- * @example
974
- * ```typescript
975
- * this.agui.addTool({
976
- * name: 'get_weather',
977
- * description: 'Get current weather for a city',
978
- * parameters: {
979
- * type: 'object',
980
- * properties: { city: { type: 'string' } },
981
- * required: ['city'],
982
- * },
983
- * handler: async ({ args }) => {
984
- * const weather = await fetchWeather(args.city);
985
- * return { temperature: weather.temp, conditions: weather.conditions };
986
- * },
987
- * });
988
- * ```
989
- */
990
- _aguiAddTool(tool) {
991
- const instance = getInstance(this);
992
- const state = this.data.agui;
993
- // Store handler internally
994
- instance.toolHandlers.set(tool.name, tool);
995
- // Expose definition to UI (without handler)
996
- const toolDef = {
997
- name: tool.name,
998
- description: tool.description,
999
- parameters: tool.parameters
1000
- };
1001
- this.setData({
1002
- "agui.tools": [...state.tools, toolDef]
1003
- });
1004
- },
1005
- /**
1006
- * Remove a registered tool by name.
1007
- *
1008
- * @param name - The name of the tool to remove
1009
- */
1010
- _aguiRemoveTool(name) {
1011
- const instance = getInstance(this);
1012
- const state = this.data.agui;
1013
- instance.toolHandlers.delete(name);
1014
- this.setData({
1015
- "agui.tools": state.tools.filter(t => t.name !== name)
1016
- });
1017
- },
1018
- /**
1019
- * Update an existing tool's properties.
1020
- * Merges the updates with the existing tool definition.
1021
- *
1022
- * @param name - The name of the tool to update
1023
- * @param updates - Partial tool definition with properties to update
1024
- */
1025
- _aguiUpdateTool(name, updates) {
1026
- const instance = getInstance(this);
1027
- const state = this.data.agui;
1028
- const existing = instance.toolHandlers.get(name);
1029
- if (existing) {
1030
- const updated = Object.assign(Object.assign({}, existing), updates);
1031
- instance.toolHandlers.set(name, updated);
1032
- // Update UI-visible definition
1033
- this.setData({
1034
- "agui.tools": state.tools.map(t => t.name === name ? {
1035
- name: updated.name,
1036
- description: updated.description,
1037
- parameters: updated.parameters
1038
- } : t)
1039
- });
1040
- }
1041
- },
1042
- /**
1043
- * Remove all registered tools.
1044
- */
1045
- _aguiClearTools() {
1046
- const instance = getInstance(this);
1047
- instance.toolHandlers.clear();
1048
- this.setData({
1049
- "agui.tools": []
1050
- });
1051
- },
1052
- // ========== Internal Methods (not exposed via namespace) ==========
1053
- __aguiRunAgent(instance, deltaMessages) {
1054
- return __awaiter(this, void 0, void 0, function* () {
1055
- var _a, e_1, _b, _c;
1056
- const state = this.data.agui;
1057
- // Build request with delta messages only
1058
- const input = {
1059
- threadId: state.threadId,
1060
- runId: generateId(),
1061
- messages: deltaMessages,
1062
- tools: state.tools,
1063
- context: state.contexts,
1064
- state: {},
1065
- forwardedProps: {}
1066
- };
1067
- // Create event handler context
1068
- const handlerCtx = {
1069
- getState: () => this.data.agui,
1070
- setData: updates => this.setData(updates),
1071
- onRawEvent: instance.options.onRawEvent
1072
- };
1073
- try {
1074
- try {
1075
- // Process events from transport
1076
- for (var _d = true, _e = __asyncValues(instance.transport.run(input)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
1077
- _c = _f.value;
1078
- _d = false;
1079
- const event = _c;
1080
- // Cast BaseEvent to AGUIEvent for proper type narrowing
1081
- const typedEvent = event;
1082
- processEvent(typedEvent, handlerCtx, instance.processingState);
1083
- // Handle tool call execution
1084
- if (typedEvent.type === EventType.TOOL_CALL_END) {
1085
- const toolCallEndEvent = typedEvent;
1086
- yield this.__aguiExecuteToolCall(instance, toolCallEndEvent.toolCallId);
1087
- }
1088
- }
1089
- } catch (e_1_1) {
1090
- e_1 = {
1091
- error: e_1_1
1092
- };
1093
- } finally {
1094
- try {
1095
- if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
1096
- } finally {
1097
- if (e_1) throw e_1.error;
1098
- }
1099
- }
1100
- } catch (err) {
1101
- console.error("[AGUI] Transport error:", err);
1102
- const error = {
1103
- code: "TRANSPORT_ERROR",
1104
- message: err instanceof Error ? err.message : "Unknown transport error",
1105
- recoverable: true,
1106
- originalError: err instanceof Error ? err : undefined
1107
- };
1108
- this.setData({
1109
- "agui.error": error,
1110
- "agui.isRunning": false
1111
- });
1112
- }
1113
- });
1114
- },
1115
- __aguiExecuteToolCall(instance, toolCallId) {
1116
- return __awaiter(this, void 0, void 0, function* () {
1117
- const pending = instance.processingState.pendingToolCalls.get(toolCallId);
1118
- if (!pending) return;
1119
- const tool = instance.toolHandlers.get(pending.name);
1120
- // Update status to executing (both activeToolCalls and uiMessages)
1121
- this.__aguiUpdateToolCallStatus(toolCallId, "executing");
1122
- // Parse arguments
1123
- let args = {};
1124
- try {
1125
- args = pending.argsString ? JSON.parse(pending.argsString) : {};
1126
- } catch (err) {
1127
- console.error("[AGUI] Failed to parse tool arguments:", pending.argsString, err);
1128
- const error = {
1129
- code: "PARSE_ERROR",
1130
- message: `Failed to parse tool arguments for ${pending.name}`,
1131
- recoverable: false
1132
- };
1133
- this.__aguiUpdateToolCallStatus(toolCallId, "failed", undefined, error);
1134
- // Add error result and continue conversation
1135
- const toolResultMessage = this.__aguiAddToolResultMessage(toolCallId, JSON.stringify({
1136
- error: error.message
1137
- }));
1138
- yield this.__aguiRunAgent(instance, [toolResultMessage]);
1139
- return;
1140
- }
1141
- // Update parsed args
1142
- const updatedToolCalls = this.data.agui.activeToolCalls.map(tc => tc.toolCallId === toolCallId ? Object.assign(Object.assign({}, tc), {
1143
- args
1144
- }) : tc);
1145
- this.setData({
1146
- "agui.activeToolCalls": updatedToolCalls
1147
- });
1148
- if (!tool) {
1149
- const error = {
1150
- code: "TOOL_NOT_FOUND",
1151
- message: `Tool "${pending.name}" not found`,
1152
- recoverable: false
1153
- };
1154
- this.__aguiUpdateToolCallStatus(toolCallId, "failed", undefined, error);
1155
- // Add error result and continue conversation
1156
- const toolResultMessage = this.__aguiAddToolResultMessage(toolCallId, JSON.stringify({
1157
- error: error.message
1158
- }));
1159
- yield this.__aguiRunAgent(instance, [toolResultMessage]);
1160
- return;
1161
- }
1162
- // Execute tool
1163
- try {
1164
- const result = yield Promise.resolve(tool.handler({
1165
- name: tool.name,
1166
- description: tool.description,
1167
- toolCallId,
1168
- args
1169
- }));
1170
- this.__aguiUpdateToolCallStatus(toolCallId, "completed", result);
1171
- // Add tool result message
1172
- const toolResultMessage = this.__aguiAddToolResultMessage(toolCallId, result);
1173
- // Clean up
1174
- instance.processingState.pendingToolCalls.delete(toolCallId);
1175
- // Continue conversation with tool result as delta
1176
- yield this.__aguiRunAgent(instance, [toolResultMessage]);
1177
- } catch (err) {
1178
- console.error("[AGUI] Tool execution error:", pending.name, err);
1179
- const error = {
1180
- code: "TOOL_EXECUTION_ERROR",
1181
- message: err instanceof Error ? err.message : "Tool execution failed",
1182
- recoverable: false,
1183
- originalError: err instanceof Error ? err : undefined
1184
- };
1185
- this.__aguiUpdateToolCallStatus(toolCallId, "failed", undefined, error);
1186
- // Add tool result with error and continue conversation
1187
- // (same as success path - let LLM handle the error)
1188
- const toolResultMessage = this.__aguiAddToolResultMessage(toolCallId, JSON.stringify({
1189
- error: error.message
1190
- }));
1191
- yield this.__aguiRunAgent(instance, [toolResultMessage]);
1192
- }
1193
- });
1194
- },
1195
- __aguiUpdateToolCallStatus(toolCallId, status, result, error) {
1196
- const state = this.data.agui;
1197
- // Update activeToolCalls
1198
- const activeToolCalls = state.activeToolCalls.map(tc => tc.toolCallId === toolCallId ? Object.assign(Object.assign({}, tc), {
1199
- status,
1200
- result,
1201
- error
1202
- }) : tc);
1203
- // Update uiMessages - find the ToolPart and update it
1204
- const uiMessages = state.uiMessages.map(uiMsg => {
1205
- if (uiMsg.role !== "assistant") return uiMsg;
1206
- const hasToolPart = uiMsg.parts.some(p => p.type === "tool" && p.toolCallId === toolCallId);
1207
- if (!hasToolPart) return uiMsg;
1208
- return Object.assign(Object.assign({}, uiMsg), {
1209
- parts: uiMsg.parts.map(p => p.type === "tool" && p.toolCallId === toolCallId ? Object.assign(Object.assign({}, p), {
1210
- status,
1211
- result,
1212
- error
1213
- }) : p)
1214
- });
1215
- });
1216
- this.setData({
1217
- "agui.activeToolCalls": activeToolCalls,
1218
- "agui.uiMessages": uiMessages
1219
- });
1220
- },
1221
- __aguiAddToolResultMessage(toolCallId, content) {
1222
- const state = this.data.agui;
1223
- const toolMessage = {
1224
- id: generateId(),
1225
- role: "tool",
1226
- toolCallId,
1227
- content
1228
- };
1229
- this.setData({
1230
- "agui.messages": [...state.messages, toolMessage]
1231
- });
1232
- return toolMessage;
1233
- }
1234
- }
1235
- });
1236
- }
1237
- function generateId() {
1238
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
1239
- const r = Math.random() * 16 | 0;
1240
- const v = c === "x" ? r : r & 0x3 | 0x8;
1241
- return v.toString(16);
1242
- });
1243
- }
1244
- /**
1245
- * Get the internal AGUI instance from a component
1246
- */
1247
- function getInstance(component) {
1248
- return component.__agui;
1249
- }
1250
- /**
1251
- * Default AG-UI behavior instance with no static configuration.
1252
- *
1253
- * Use this for a purely imperative usage pattern where all configuration
1254
- * is done at runtime via `agui.init()`.
1255
- *
1256
- * @example
1257
- * ```typescript
1258
- * Component({
1259
- * behaviors: [aguiBehavior],
1260
- * lifetimes: {
1261
- * attached() {
1262
- * this.agui.init({
1263
- * transport: new CloudbaseTransport({ botId: 'my-bot' }),
1264
- * });
1265
- * },
1266
- * },
1267
- * });
1268
- * ```
1269
- */
1270
- const aguiBehavior = createAGUIBehavior();
1271
-
1272
- /**
1273
- * AG-UI Transport Implementations
1274
- */
1275
- /**
1276
- * Mock transport implementation for testing and development.
1277
- *
1278
- * Simulates an AG-UI agent backend by emitting a configurable sequence
1279
- * of events. Useful for unit tests, prototyping, and demo applications.
1280
- *
1281
- * @example
1282
- * ```typescript
1283
- * // Create with predefined events
1284
- * const transport = new MockTransport({
1285
- * events: MockTransport.createTextResponse('Hello, world!'),
1286
- * delayMs: 100, // Simulate network latency
1287
- * });
1288
- *
1289
- * // Or set events dynamically
1290
- * transport.setEvents(MockTransport.createToolCallResponse('get_weather', { city: 'NYC' }));
1291
- * ```
1292
- */
1293
- class MockTransport {
1294
- constructor(options = {}) {
1295
- var _a;
1296
- this.events = options.events || [];
1297
- this.delayMs = (_a = options.delayMs) !== null && _a !== void 0 ? _a : 50;
1298
- }
1299
- /**
1300
- * Set the events to emit during the next `run()` call.
1301
- *
1302
- * @param events - Array of AG-UI events to emit
1303
- */
1304
- setEvents(events) {
1305
- this.events = events;
1306
- }
1307
- /**
1308
- * Create a simple text response event sequence.
1309
- *
1310
- * @param text - The text content of the assistant's response
1311
- * @param messageId - Optional message ID (defaults to "msg-1")
1312
- * @returns Array of events representing a complete text response
1313
- */
1314
- static createTextResponse(text, messageId = "msg-1") {
1315
- return [{
1316
- type: EventType.RUN_STARTED,
1317
- threadId: "thread-1",
1318
- runId: "run-1"
1319
- }, {
1320
- type: EventType.TEXT_MESSAGE_START,
1321
- messageId,
1322
- role: "assistant"
1323
- }, {
1324
- type: EventType.TEXT_MESSAGE_CONTENT,
1325
- messageId,
1326
- delta: text
1327
- }, {
1328
- type: EventType.TEXT_MESSAGE_END,
1329
- messageId
1330
- }, {
1331
- type: EventType.RUN_FINISHED,
1332
- threadId: "thread-1",
1333
- runId: "run-1"
1334
- }];
1335
- }
1336
- /**
1337
- * Create a tool call response event sequence.
1338
- *
1339
- * @param toolName - Name of the tool being called
1340
- * @param args - Arguments to pass to the tool (will be JSON stringified)
1341
- * @param toolCallId - Optional tool call ID (defaults to "tc-1")
1342
- * @returns Array of events representing a tool call (without RUN_FINISHED)
1343
- */
1344
- static createToolCallResponse(toolName, args, toolCallId = "tc-1") {
1345
- return [{
1346
- type: EventType.RUN_STARTED,
1347
- threadId: "thread-1",
1348
- runId: "run-1"
1349
- }, {
1350
- type: EventType.TOOL_CALL_START,
1351
- toolCallId,
1352
- toolCallName: toolName
1353
- }, {
1354
- type: EventType.TOOL_CALL_ARGS,
1355
- toolCallId,
1356
- delta: JSON.stringify(args)
1357
- }, {
1358
- type: EventType.TOOL_CALL_END,
1359
- toolCallId
1360
- }
1361
- // Note: RUN_FINISHED will be emitted after tool execution
1362
- ];
1363
- }
1364
- run(_input) {
1365
- return __asyncGenerator(this, arguments, function* run_1() {
1366
- for (const event of this.events) {
1367
- if (this.delayMs > 0) {
1368
- yield __await(this.delay(this.delayMs));
1369
- }
1370
- yield yield __await(event);
1371
- }
1372
- });
1373
- }
1374
- delay(ms) {
1375
- return new Promise(resolve => setTimeout(resolve, ms));
1376
- }
1377
- }
1378
- /**
1379
- * Production transport for WeChat Cloud Development (Cloudbase).
1380
- *
1381
- * Connects to a WeChat AI Bot configured in the Cloud Development console.
1382
- * Requires the `wx.cloud.extend.AI.bot.sendMessage` API to be available.
1383
- *
1384
- * @example
1385
- * ```typescript
1386
- * const transport = new CloudbaseTransport({
1387
- * botId: 'bot-xxxxxx', // Your bot ID from Cloud Development console
1388
- * });
1389
- *
1390
- * Component({
1391
- * behaviors: [createAGUIBehavior({ transport })],
1392
- * });
1393
- * ```
1394
- */
1395
- class CloudbaseTransport {
1396
- /**
1397
- * Create a new CloudbaseTransport instance.
1398
- *
1399
- * @param options - Configuration options
1400
- * @param options.botId - The bot ID from WeChat Cloud Development console
1401
- */
1402
- constructor(options) {
1403
- this.botId = options.botId;
1404
- }
1405
- run(input) {
1406
- return __asyncGenerator(this, arguments, function* run_2() {
1407
- var _a, e_1, _b, _c;
1408
- var _d, _e, _f, _g;
1409
- // Capture botId before async generator (avoids 'this' context issues after transpilation)
1410
- const botId = this.botId;
1411
- // Check if wx.cloud.extend.AI.bot.sendMessage is available
1412
- if (typeof wx === "undefined" || !((_g = (_f = (_e = (_d = wx.cloud) === null || _d === void 0 ? void 0 : _d.extend) === null || _e === void 0 ? void 0 : _e.AI) === null || _f === void 0 ? void 0 : _f.bot) === null || _g === void 0 ? void 0 : _g.sendMessage)) {
1413
- throw new Error("CloudbaseTransport requires wx.cloud.extend.AI.bot.sendMessage");
1414
- }
1415
- // Start the bot conversation
1416
- const res = yield __await(wx.cloud.extend.AI.bot.sendMessage({
1417
- botId,
1418
- data: input
1419
- }));
1420
- try {
1421
- for (var _h = true, _j = __asyncValues(res.eventStream), _k; _k = yield __await(_j.next()), _a = _k.done, !_a; _h = true) {
1422
- _c = _k.value;
1423
- _h = false;
1424
- const event = _c;
1425
- if (event.json) {
1426
- yield yield __await(event.json);
1427
- }
1428
- }
1429
- } catch (e_1_1) {
1430
- e_1 = {
1431
- error: e_1_1
1432
- };
1433
- } finally {
1434
- try {
1435
- if (!_h && !_a && (_b = _j.return)) yield __await(_b.call(_j));
1436
- } finally {
1437
- if (e_1) throw e_1.error;
1438
- }
1439
- }
1440
- });
1441
- }
1442
- }
1443
-
1444
- export { CloudbaseTransport, EventType, MockTransport, aguiBehavior, createAGUIBehavior, rebuildUiMessages };