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