@copilotkit/runtime 1.55.1 → 1.55.2-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/agent/converters/aisdk.cjs +215 -0
- package/dist/agent/converters/aisdk.cjs.map +1 -0
- package/dist/agent/converters/aisdk.d.cts +18 -0
- package/dist/agent/converters/aisdk.d.cts.map +1 -0
- package/dist/agent/converters/aisdk.d.mts +18 -0
- package/dist/agent/converters/aisdk.d.mts.map +1 -0
- package/dist/agent/converters/aisdk.mjs +214 -0
- package/dist/agent/converters/aisdk.mjs.map +1 -0
- package/dist/agent/converters/index.d.mts +3 -0
- package/dist/agent/converters/tanstack.cjs +180 -0
- package/dist/agent/converters/tanstack.cjs.map +1 -0
- package/dist/agent/converters/tanstack.d.cts +68 -0
- package/dist/agent/converters/tanstack.d.cts.map +1 -0
- package/dist/agent/converters/tanstack.d.mts +68 -0
- package/dist/agent/converters/tanstack.d.mts.map +1 -0
- package/dist/agent/converters/tanstack.mjs +178 -0
- package/dist/agent/converters/tanstack.mjs.map +1 -0
- package/dist/agent/index.cjs +111 -17
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +61 -4
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +62 -4
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +111 -17
- package/dist/agent/index.mjs.map +1 -1
- package/dist/lib/integrations/nextjs/pages-router.cjs.map +1 -1
- package/dist/lib/integrations/nextjs/pages-router.d.cts.map +1 -1
- package/dist/lib/integrations/nextjs/pages-router.d.mts.map +1 -1
- package/dist/lib/integrations/nextjs/pages-router.mjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.cjs +4 -2
- package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs +4 -2
- package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
- package/dist/lib/runtime/mcp-tools-utils.cjs +1 -1
- package/dist/lib/runtime/mcp-tools-utils.cjs.map +1 -1
- package/dist/lib/runtime/mcp-tools-utils.mjs +1 -1
- package/dist/lib/runtime/mcp-tools-utils.mjs.map +1 -1
- package/dist/package.cjs +3 -2
- package/dist/package.mjs +3 -2
- package/dist/service-adapters/anthropic/utils.cjs +1 -1
- package/dist/service-adapters/anthropic/utils.cjs.map +1 -1
- package/dist/service-adapters/anthropic/utils.mjs +1 -1
- package/dist/service-adapters/anthropic/utils.mjs.map +1 -1
- package/dist/service-adapters/openai/utils.cjs +1 -1
- package/dist/service-adapters/openai/utils.cjs.map +1 -1
- package/dist/service-adapters/openai/utils.mjs +1 -1
- package/dist/service-adapters/openai/utils.mjs.map +1 -1
- package/dist/v2/index.cjs +5 -0
- package/dist/v2/index.d.cts +4 -2
- package/dist/v2/index.d.mts +4 -2
- package/dist/v2/index.mjs +3 -1
- package/package.json +4 -3
- package/src/agent/__tests__/agent-test-helpers.ts +446 -0
- package/src/agent/__tests__/agent.test.ts +593 -0
- package/src/agent/__tests__/converter-aisdk.test.ts +692 -0
- package/src/agent/__tests__/converter-custom.test.ts +319 -0
- package/src/agent/__tests__/converter-tanstack-input.test.ts +211 -0
- package/src/agent/__tests__/converter-tanstack.test.ts +314 -0
- package/src/agent/__tests__/mcp-servers-integration.test.ts +373 -0
- package/src/agent/__tests__/multimodal-tanstack.test.ts +284 -0
- package/src/agent/__tests__/test-helpers.ts +12 -8
- package/src/agent/converters/aisdk.ts +326 -0
- package/src/agent/converters/index.ts +7 -0
- package/src/agent/converters/tanstack.ts +286 -0
- package/src/agent/index.ts +245 -26
- package/src/lib/integrations/nextjs/pages-router.ts +1 -0
- package/src/lib/runtime/copilot-runtime.ts +21 -12
- package/src/lib/runtime/mcp-tools-utils.ts +1 -1
- package/src/service-adapters/anthropic/utils.ts +1 -1
- package/src/service-adapters/openai/utils.ts +1 -1
- package/src/v2/runtime/__tests__/mcp-apps-middleware-integration.test.ts +275 -0
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BaseEvent,
|
|
3
|
+
EventType,
|
|
4
|
+
RunAgentInput,
|
|
5
|
+
Message,
|
|
6
|
+
TextMessageChunkEvent,
|
|
7
|
+
ToolCallArgsEvent,
|
|
8
|
+
ToolCallEndEvent,
|
|
9
|
+
ToolCallStartEvent,
|
|
10
|
+
ToolCallResultEvent,
|
|
11
|
+
} from "@ag-ui/client";
|
|
12
|
+
import { randomUUID } from "@copilotkit/shared";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A TanStack AI content part (text, image, audio, video, or document).
|
|
16
|
+
*/
|
|
17
|
+
export type TanStackContentPart =
|
|
18
|
+
| { type: "text"; content: string }
|
|
19
|
+
| {
|
|
20
|
+
type: "image" | "audio" | "video" | "document";
|
|
21
|
+
source:
|
|
22
|
+
| { type: "data"; value: string; mimeType: string }
|
|
23
|
+
| { type: "url"; value: string; mimeType?: string };
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Message format expected by TanStack AI's `chat()`.
|
|
28
|
+
*/
|
|
29
|
+
export interface TanStackChatMessage {
|
|
30
|
+
role: "user" | "assistant" | "tool";
|
|
31
|
+
content: string | null | TanStackContentPart[];
|
|
32
|
+
name?: string;
|
|
33
|
+
toolCalls?: Array<{
|
|
34
|
+
id: string;
|
|
35
|
+
type: "function";
|
|
36
|
+
function: { name: string; arguments: string };
|
|
37
|
+
}>;
|
|
38
|
+
toolCallId?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Result of converting RunAgentInput to TanStack AI format.
|
|
43
|
+
*/
|
|
44
|
+
export interface TanStackInputResult {
|
|
45
|
+
/** Chat messages (only user/assistant/tool roles; all others excluded) */
|
|
46
|
+
messages: TanStackChatMessage[];
|
|
47
|
+
/** System prompts extracted from system/developer messages, context, and state */
|
|
48
|
+
systemPrompts: string[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Converts AG-UI user message content to TanStack AI format.
|
|
53
|
+
* Handles plain strings, multimodal parts (image/audio/video/document),
|
|
54
|
+
* and legacy BinaryInputContent for backward compatibility.
|
|
55
|
+
*/
|
|
56
|
+
function convertUserContent(
|
|
57
|
+
content: unknown,
|
|
58
|
+
): string | null | TanStackContentPart[] {
|
|
59
|
+
if (!content) return null;
|
|
60
|
+
if (typeof content === "string") return content;
|
|
61
|
+
if (!Array.isArray(content)) return null;
|
|
62
|
+
if (content.length === 0) return "";
|
|
63
|
+
|
|
64
|
+
const parts: TanStackContentPart[] = [];
|
|
65
|
+
|
|
66
|
+
for (const part of content) {
|
|
67
|
+
if (!part || typeof part !== "object" || !("type" in part)) continue;
|
|
68
|
+
|
|
69
|
+
switch ((part as { type: string }).type) {
|
|
70
|
+
case "text": {
|
|
71
|
+
const text = (part as { text?: string }).text;
|
|
72
|
+
if (text != null) parts.push({ type: "text", content: text });
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
case "image":
|
|
77
|
+
case "audio":
|
|
78
|
+
case "video":
|
|
79
|
+
case "document": {
|
|
80
|
+
const source = (part as { source?: any }).source;
|
|
81
|
+
if (!source) break;
|
|
82
|
+
const partType = (part as { type: string }).type as
|
|
83
|
+
| "image"
|
|
84
|
+
| "audio"
|
|
85
|
+
| "video"
|
|
86
|
+
| "document";
|
|
87
|
+
if (source.type === "data") {
|
|
88
|
+
parts.push({
|
|
89
|
+
type: partType,
|
|
90
|
+
source: {
|
|
91
|
+
type: "data",
|
|
92
|
+
value: source.value,
|
|
93
|
+
mimeType: source.mimeType,
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
} else if (source.type === "url") {
|
|
97
|
+
parts.push({
|
|
98
|
+
type: partType,
|
|
99
|
+
source: {
|
|
100
|
+
type: "url",
|
|
101
|
+
value: source.value,
|
|
102
|
+
...(source.mimeType ? { mimeType: source.mimeType } : {}),
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Legacy BinaryInputContent backward compatibility
|
|
110
|
+
case "binary": {
|
|
111
|
+
const legacy = part as {
|
|
112
|
+
mimeType?: string;
|
|
113
|
+
data?: string;
|
|
114
|
+
url?: string;
|
|
115
|
+
};
|
|
116
|
+
const mimeType = legacy.mimeType ?? "application/octet-stream";
|
|
117
|
+
const isImage = mimeType.startsWith("image/");
|
|
118
|
+
|
|
119
|
+
if (legacy.data) {
|
|
120
|
+
const partType = isImage ? "image" : "document";
|
|
121
|
+
parts.push({
|
|
122
|
+
type: partType,
|
|
123
|
+
source: { type: "data", value: legacy.data, mimeType },
|
|
124
|
+
});
|
|
125
|
+
} else if (legacy.url) {
|
|
126
|
+
const partType = isImage ? "image" : "document";
|
|
127
|
+
parts.push({
|
|
128
|
+
type: partType,
|
|
129
|
+
source: { type: "url", value: legacy.url, mimeType },
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return parts.length > 0 ? parts : "";
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Converts a RunAgentInput into the format expected by TanStack AI's `chat()`.
|
|
142
|
+
*
|
|
143
|
+
* - Keeps only user/assistant/tool messages (activity, reasoning, and other roles are also excluded)
|
|
144
|
+
* - Extracts system/developer messages into `systemPrompts`
|
|
145
|
+
* - Appends context entries and application state to `systemPrompts`
|
|
146
|
+
* - Preserves tool calls on assistant messages and toolCallId on tool messages
|
|
147
|
+
*/
|
|
148
|
+
export function convertInputToTanStackAI(
|
|
149
|
+
input: RunAgentInput,
|
|
150
|
+
): TanStackInputResult {
|
|
151
|
+
// Allowlist: only pass user/assistant/tool messages to TanStack.
|
|
152
|
+
// Other roles (system, developer, activity, reasoning) are either
|
|
153
|
+
// extracted into systemPrompts or not applicable.
|
|
154
|
+
const chatRoles = new Set(["user", "assistant", "tool"]);
|
|
155
|
+
const messages: TanStackChatMessage[] = input.messages
|
|
156
|
+
.filter((m: Message) => chatRoles.has(m.role))
|
|
157
|
+
.map((m: Message): TanStackChatMessage => {
|
|
158
|
+
const msg: TanStackChatMessage = {
|
|
159
|
+
role: m.role as "user" | "assistant" | "tool",
|
|
160
|
+
content:
|
|
161
|
+
m.role === "user"
|
|
162
|
+
? convertUserContent(m.content)
|
|
163
|
+
: typeof m.content === "string"
|
|
164
|
+
? m.content
|
|
165
|
+
: null,
|
|
166
|
+
};
|
|
167
|
+
if (m.role === "assistant" && "toolCalls" in m && m.toolCalls) {
|
|
168
|
+
msg.toolCalls = m.toolCalls.map((tc) => ({
|
|
169
|
+
id: tc.id,
|
|
170
|
+
type: "function" as const,
|
|
171
|
+
function: {
|
|
172
|
+
name: tc.function.name,
|
|
173
|
+
arguments: tc.function.arguments,
|
|
174
|
+
},
|
|
175
|
+
}));
|
|
176
|
+
}
|
|
177
|
+
if (m.role === "tool" && "toolCallId" in m) {
|
|
178
|
+
msg.toolCallId = (m as Record<string, unknown>).toolCallId as string;
|
|
179
|
+
}
|
|
180
|
+
return msg;
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
const systemPrompts: string[] = [];
|
|
184
|
+
for (const m of input.messages) {
|
|
185
|
+
if ((m.role === "system" || m.role === "developer") && m.content) {
|
|
186
|
+
systemPrompts.push(
|
|
187
|
+
typeof m.content === "string" ? m.content : JSON.stringify(m.content),
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (input.context?.length) {
|
|
193
|
+
for (const ctx of input.context) {
|
|
194
|
+
systemPrompts.push(`${ctx.description}:\n${ctx.value}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (
|
|
199
|
+
input.state !== undefined &&
|
|
200
|
+
input.state !== null &&
|
|
201
|
+
typeof input.state === "object" &&
|
|
202
|
+
Object.keys(input.state).length > 0
|
|
203
|
+
) {
|
|
204
|
+
systemPrompts.push(
|
|
205
|
+
`Application State:\n\`\`\`json\n${JSON.stringify(input.state, null, 2)}\n\`\`\``,
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return { messages, systemPrompts };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Converts a TanStack AI stream into AG-UI `BaseEvent` objects.
|
|
214
|
+
*
|
|
215
|
+
* This is a pure converter — it does NOT emit lifecycle events
|
|
216
|
+
* (RUN_STARTED / RUN_FINISHED / RUN_ERROR). The caller (Agent class)
|
|
217
|
+
* is responsible for those.
|
|
218
|
+
*/
|
|
219
|
+
export async function* convertTanStackStream(
|
|
220
|
+
stream: AsyncIterable<unknown>,
|
|
221
|
+
abortSignal: AbortSignal,
|
|
222
|
+
): AsyncGenerator<BaseEvent> {
|
|
223
|
+
const messageId = randomUUID();
|
|
224
|
+
|
|
225
|
+
for await (const chunk of stream) {
|
|
226
|
+
if (abortSignal.aborted) break;
|
|
227
|
+
|
|
228
|
+
const raw = chunk as Record<string, unknown>;
|
|
229
|
+
const type = raw.type as string;
|
|
230
|
+
|
|
231
|
+
if (type === "TEXT_MESSAGE_CONTENT" && raw.delta) {
|
|
232
|
+
const textEvent: TextMessageChunkEvent = {
|
|
233
|
+
type: EventType.TEXT_MESSAGE_CHUNK,
|
|
234
|
+
role: "assistant",
|
|
235
|
+
messageId,
|
|
236
|
+
delta: raw.delta as string,
|
|
237
|
+
};
|
|
238
|
+
yield textEvent;
|
|
239
|
+
} else if (type === "TOOL_CALL_START") {
|
|
240
|
+
const startEvent: ToolCallStartEvent = {
|
|
241
|
+
type: EventType.TOOL_CALL_START,
|
|
242
|
+
parentMessageId: messageId,
|
|
243
|
+
toolCallId: raw.toolCallId as string,
|
|
244
|
+
toolCallName: raw.toolCallName as string,
|
|
245
|
+
};
|
|
246
|
+
yield startEvent;
|
|
247
|
+
} else if (type === "TOOL_CALL_ARGS") {
|
|
248
|
+
const argsEvent: ToolCallArgsEvent = {
|
|
249
|
+
type: EventType.TOOL_CALL_ARGS,
|
|
250
|
+
toolCallId: raw.toolCallId as string,
|
|
251
|
+
delta: raw.delta as string,
|
|
252
|
+
};
|
|
253
|
+
yield argsEvent;
|
|
254
|
+
} else if (type === "TOOL_CALL_END") {
|
|
255
|
+
const endEvent: ToolCallEndEvent = {
|
|
256
|
+
type: EventType.TOOL_CALL_END,
|
|
257
|
+
toolCallId: raw.toolCallId as string,
|
|
258
|
+
};
|
|
259
|
+
yield endEvent;
|
|
260
|
+
} else if (type === "TOOL_CALL_RESULT") {
|
|
261
|
+
let serializedContent: string;
|
|
262
|
+
if (typeof raw.content === "string") {
|
|
263
|
+
serializedContent = raw.content;
|
|
264
|
+
} else {
|
|
265
|
+
try {
|
|
266
|
+
serializedContent = JSON.stringify(raw.content ?? raw.result ?? null);
|
|
267
|
+
} catch {
|
|
268
|
+
serializedContent = "[Unserializable tool result]";
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const resultEvent: ToolCallResultEvent = {
|
|
272
|
+
type: EventType.TOOL_CALL_RESULT,
|
|
273
|
+
role: "tool",
|
|
274
|
+
messageId: randomUUID(),
|
|
275
|
+
toolCallId: raw.toolCallId as string,
|
|
276
|
+
content: serializedContent,
|
|
277
|
+
};
|
|
278
|
+
yield resultEvent;
|
|
279
|
+
}
|
|
280
|
+
// Unhandled chunk types are silently ignored.
|
|
281
|
+
// Known gaps: STATE_SNAPSHOT, STATE_DELTA, and REASONING events are not
|
|
282
|
+
// converted from TanStack streams. Shared state and reasoning will not
|
|
283
|
+
// surface when using the TanStack backend. Use the AI SDK backend if these
|
|
284
|
+
// features are required.
|
|
285
|
+
}
|
|
286
|
+
}
|
package/src/agent/index.ts
CHANGED
|
@@ -49,6 +49,8 @@ import { z } from "zod";
|
|
|
49
49
|
import type { StandardSchemaV1, InferSchemaOutput } from "@copilotkit/shared";
|
|
50
50
|
import { schemaToJsonSchema } from "@copilotkit/shared";
|
|
51
51
|
import { jsonSchema as aiJsonSchema } from "ai";
|
|
52
|
+
import { convertAISDKStream } from "./converters/aisdk";
|
|
53
|
+
import { convertTanStackStream } from "./converters/tanstack";
|
|
52
54
|
import {
|
|
53
55
|
StreamableHTTPClientTransport,
|
|
54
56
|
StreamableHTTPClientTransportOptions,
|
|
@@ -656,9 +658,66 @@ export function convertToolDefinitionsToVercelAITools(
|
|
|
656
658
|
}
|
|
657
659
|
|
|
658
660
|
/**
|
|
659
|
-
*
|
|
661
|
+
* Context passed to the user-supplied factory function in factory mode.
|
|
660
662
|
*/
|
|
661
|
-
export interface
|
|
663
|
+
export interface AgentFactoryContext {
|
|
664
|
+
input: RunAgentInput;
|
|
665
|
+
/**
|
|
666
|
+
* Prefer `abortSignal` for most use cases (AI SDK, fetch, custom backends).
|
|
667
|
+
* Provided for backends like TanStack AI that require the full AbortController.
|
|
668
|
+
* Do NOT call `.abort()` on this controller — use `abortRun()` on the agent instead.
|
|
669
|
+
*/
|
|
670
|
+
abortController: AbortController;
|
|
671
|
+
abortSignal: AbortSignal;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Factory config for AI SDK backend.
|
|
676
|
+
* The factory must return an object with a `fullStream` async iterable
|
|
677
|
+
* (compatible with the result of `streamText()` — only `fullStream` is consumed).
|
|
678
|
+
*/
|
|
679
|
+
export interface BuiltInAgentAISDKFactoryConfig {
|
|
680
|
+
type: "aisdk";
|
|
681
|
+
factory: (
|
|
682
|
+
ctx: AgentFactoryContext,
|
|
683
|
+
) =>
|
|
684
|
+
| { fullStream: AsyncIterable<unknown> }
|
|
685
|
+
| Promise<{ fullStream: AsyncIterable<unknown> }>;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Factory config for TanStack AI backend.
|
|
690
|
+
* The factory must return an async iterable of TanStack AI stream chunks.
|
|
691
|
+
*/
|
|
692
|
+
export interface BuiltInAgentTanStackFactoryConfig {
|
|
693
|
+
type: "tanstack";
|
|
694
|
+
factory: (
|
|
695
|
+
ctx: AgentFactoryContext,
|
|
696
|
+
) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* Factory config for a custom backend that directly yields AG-UI events.
|
|
701
|
+
*/
|
|
702
|
+
export interface BuiltInAgentCustomFactoryConfig {
|
|
703
|
+
type: "custom";
|
|
704
|
+
factory: (
|
|
705
|
+
ctx: AgentFactoryContext,
|
|
706
|
+
) => AsyncIterable<BaseEvent> | Promise<AsyncIterable<BaseEvent>>;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* Union of all factory-mode configurations.
|
|
711
|
+
*/
|
|
712
|
+
export type BuiltInAgentFactoryConfig =
|
|
713
|
+
| BuiltInAgentAISDKFactoryConfig
|
|
714
|
+
| BuiltInAgentTanStackFactoryConfig
|
|
715
|
+
| BuiltInAgentCustomFactoryConfig;
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Classic config — BuiltInAgent handles streamText, tools, MCP, state tools, prompt building.
|
|
719
|
+
*/
|
|
720
|
+
export interface BuiltInAgentClassicConfig {
|
|
662
721
|
/**
|
|
663
722
|
* The model to use
|
|
664
723
|
*/
|
|
@@ -760,6 +819,26 @@ export interface BuiltInAgentConfiguration {
|
|
|
760
819
|
providerOptions?: Record<string, any>;
|
|
761
820
|
}
|
|
762
821
|
|
|
822
|
+
/**
|
|
823
|
+
* Configuration for BuiltInAgent.
|
|
824
|
+
*
|
|
825
|
+
* Two modes:
|
|
826
|
+
* - **Classic** (model + params): BuiltInAgent handles everything — streamText, tools, MCP, state tools.
|
|
827
|
+
* - **Factory** (type + factory): You own the LLM call. BuiltInAgent handles lifecycle only.
|
|
828
|
+
*/
|
|
829
|
+
export type BuiltInAgentConfiguration =
|
|
830
|
+
| BuiltInAgentClassicConfig
|
|
831
|
+
| BuiltInAgentFactoryConfig;
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Type guard: returns true if this is a factory-mode config.
|
|
835
|
+
*/
|
|
836
|
+
function isFactoryConfig(
|
|
837
|
+
config: BuiltInAgentConfiguration,
|
|
838
|
+
): config is BuiltInAgentFactoryConfig {
|
|
839
|
+
return "factory" in config;
|
|
840
|
+
}
|
|
841
|
+
|
|
763
842
|
export class BuiltInAgent extends AbstractAgent {
|
|
764
843
|
private abortController?: AbortController;
|
|
765
844
|
|
|
@@ -771,10 +850,25 @@ export class BuiltInAgent extends AbstractAgent {
|
|
|
771
850
|
* Check if a property can be overridden by forwardedProps
|
|
772
851
|
*/
|
|
773
852
|
canOverride(property: OverridableProperty): boolean {
|
|
853
|
+
if (isFactoryConfig(this.config)) return false;
|
|
774
854
|
return this.config?.overridableProperties?.includes(property) ?? false;
|
|
775
855
|
}
|
|
776
856
|
|
|
777
857
|
run(input: RunAgentInput): Observable<BaseEvent> {
|
|
858
|
+
if (isFactoryConfig(this.config)) {
|
|
859
|
+
return this.runFactory(input, this.config);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
if (this.abortController) {
|
|
863
|
+
throw new Error(
|
|
864
|
+
"Agent is already running. Call abortRun() first or create a new instance.",
|
|
865
|
+
);
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// Set synchronously before Observable creation to close TOCTOU window
|
|
869
|
+
this.abortController = new AbortController();
|
|
870
|
+
const abortController = this.abortController;
|
|
871
|
+
|
|
778
872
|
return new Observable<BaseEvent>((subscriber) => {
|
|
779
873
|
// Emit RUN_STARTED event
|
|
780
874
|
const startEvent: RunStartedEvent = {
|
|
@@ -980,8 +1074,6 @@ export class BuiltInAgent extends AbstractAgent {
|
|
|
980
1074
|
const mcpClients: Array<{ close: () => Promise<void> }> = [];
|
|
981
1075
|
|
|
982
1076
|
(async () => {
|
|
983
|
-
const abortController = new AbortController();
|
|
984
|
-
this.abortController = abortController;
|
|
985
1077
|
let terminalEventEmitted = false;
|
|
986
1078
|
let messageId = randomUUID();
|
|
987
1079
|
let reasoningMessageId = randomUUID();
|
|
@@ -1294,7 +1386,12 @@ export class BuiltInAgent extends AbstractAgent {
|
|
|
1294
1386
|
}
|
|
1295
1387
|
|
|
1296
1388
|
case "tool-result": {
|
|
1297
|
-
const toolResult =
|
|
1389
|
+
const toolResult =
|
|
1390
|
+
"output" in part
|
|
1391
|
+
? part.output
|
|
1392
|
+
: "result" in part
|
|
1393
|
+
? part.result
|
|
1394
|
+
: null;
|
|
1298
1395
|
const toolName = "toolName" in part ? part.toolName : "";
|
|
1299
1396
|
toolCallStates.delete(part.toolCallId);
|
|
1300
1397
|
|
|
@@ -1304,32 +1401,42 @@ export class BuiltInAgent extends AbstractAgent {
|
|
|
1304
1401
|
toolResult &&
|
|
1305
1402
|
typeof toolResult === "object"
|
|
1306
1403
|
) {
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1404
|
+
const snapshot = toolResult.snapshot;
|
|
1405
|
+
if (snapshot !== undefined) {
|
|
1406
|
+
const stateSnapshotEvent: StateSnapshotEvent = {
|
|
1407
|
+
type: EventType.STATE_SNAPSHOT,
|
|
1408
|
+
snapshot,
|
|
1409
|
+
};
|
|
1410
|
+
subscriber.next(stateSnapshotEvent);
|
|
1411
|
+
}
|
|
1313
1412
|
} else if (
|
|
1314
1413
|
toolName === "AGUISendStateDelta" &&
|
|
1315
1414
|
toolResult &&
|
|
1316
1415
|
typeof toolResult === "object"
|
|
1317
1416
|
) {
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1417
|
+
const delta = toolResult.delta;
|
|
1418
|
+
if (delta !== undefined) {
|
|
1419
|
+
const stateDeltaEvent: StateDeltaEvent = {
|
|
1420
|
+
type: EventType.STATE_DELTA,
|
|
1421
|
+
delta,
|
|
1422
|
+
};
|
|
1423
|
+
subscriber.next(stateDeltaEvent);
|
|
1424
|
+
}
|
|
1324
1425
|
}
|
|
1325
1426
|
|
|
1326
1427
|
// Always emit the tool result event for the LLM
|
|
1428
|
+
let serializedResult: string;
|
|
1429
|
+
try {
|
|
1430
|
+
serializedResult = JSON.stringify(toolResult);
|
|
1431
|
+
} catch {
|
|
1432
|
+
serializedResult = `[Unserializable tool result from ${toolName || part.toolCallId}]`;
|
|
1433
|
+
}
|
|
1327
1434
|
const resultEvent: ToolCallResultEvent = {
|
|
1328
1435
|
type: EventType.TOOL_CALL_RESULT,
|
|
1329
1436
|
role: "tool",
|
|
1330
1437
|
messageId: randomUUID(),
|
|
1331
1438
|
toolCallId: part.toolCallId,
|
|
1332
|
-
content:
|
|
1439
|
+
content: serializedResult,
|
|
1333
1440
|
};
|
|
1334
1441
|
subscriber.next(resultEvent);
|
|
1335
1442
|
break;
|
|
@@ -1354,15 +1461,29 @@ export class BuiltInAgent extends AbstractAgent {
|
|
|
1354
1461
|
if (abortController.signal.aborted) {
|
|
1355
1462
|
break;
|
|
1356
1463
|
}
|
|
1464
|
+
const err = part.error ?? part.message ?? part.cause;
|
|
1357
1465
|
const runErrorEvent: RunErrorEvent = {
|
|
1358
1466
|
type: EventType.RUN_ERROR,
|
|
1359
|
-
message:
|
|
1360
|
-
|
|
1467
|
+
message:
|
|
1468
|
+
err instanceof Error
|
|
1469
|
+
? err.message
|
|
1470
|
+
: typeof err === "string"
|
|
1471
|
+
? err
|
|
1472
|
+
: `AI SDK stream error: ${JSON.stringify(part)}`,
|
|
1473
|
+
threadId: input.threadId,
|
|
1474
|
+
runId: input.runId,
|
|
1475
|
+
} as RunErrorEvent;
|
|
1361
1476
|
subscriber.next(runErrorEvent);
|
|
1362
1477
|
terminalEventEmitted = true;
|
|
1363
1478
|
|
|
1364
1479
|
// Handle error
|
|
1365
|
-
subscriber.error(
|
|
1480
|
+
if (err instanceof Error) subscriber.error(err);
|
|
1481
|
+
else
|
|
1482
|
+
subscriber.error(
|
|
1483
|
+
new Error(
|
|
1484
|
+
typeof err === "string" ? err : `AI SDK stream error`,
|
|
1485
|
+
),
|
|
1486
|
+
);
|
|
1366
1487
|
break;
|
|
1367
1488
|
}
|
|
1368
1489
|
}
|
|
@@ -1392,8 +1513,10 @@ export class BuiltInAgent extends AbstractAgent {
|
|
|
1392
1513
|
} else {
|
|
1393
1514
|
const runErrorEvent: RunErrorEvent = {
|
|
1394
1515
|
type: EventType.RUN_ERROR,
|
|
1395
|
-
message: error
|
|
1396
|
-
|
|
1516
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1517
|
+
threadId: input.threadId,
|
|
1518
|
+
runId: input.runId,
|
|
1519
|
+
} as RunErrorEvent;
|
|
1397
1520
|
subscriber.next(runErrorEvent);
|
|
1398
1521
|
terminalEventEmitted = true;
|
|
1399
1522
|
subscriber.error(error);
|
|
@@ -1414,10 +1537,103 @@ export class BuiltInAgent extends AbstractAgent {
|
|
|
1414
1537
|
});
|
|
1415
1538
|
}
|
|
1416
1539
|
|
|
1540
|
+
private runFactory(
|
|
1541
|
+
input: RunAgentInput,
|
|
1542
|
+
config: BuiltInAgentFactoryConfig,
|
|
1543
|
+
): Observable<BaseEvent> {
|
|
1544
|
+
if (this.abortController) {
|
|
1545
|
+
throw new Error(
|
|
1546
|
+
"Agent is already running. Call abortRun() first or create a new instance.",
|
|
1547
|
+
);
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
// Set synchronously before Observable creation to close TOCTOU window
|
|
1551
|
+
this.abortController = new AbortController();
|
|
1552
|
+
const controller = this.abortController;
|
|
1553
|
+
|
|
1554
|
+
return new Observable<BaseEvent>((subscriber) => {
|
|
1555
|
+
const startEvent: RunStartedEvent = {
|
|
1556
|
+
type: EventType.RUN_STARTED,
|
|
1557
|
+
threadId: input.threadId,
|
|
1558
|
+
runId: input.runId,
|
|
1559
|
+
};
|
|
1560
|
+
subscriber.next(startEvent);
|
|
1561
|
+
|
|
1562
|
+
const ctx: AgentFactoryContext = {
|
|
1563
|
+
input,
|
|
1564
|
+
abortController: controller,
|
|
1565
|
+
abortSignal: controller.signal,
|
|
1566
|
+
};
|
|
1567
|
+
|
|
1568
|
+
(async () => {
|
|
1569
|
+
try {
|
|
1570
|
+
let events: AsyncIterable<BaseEvent>;
|
|
1571
|
+
|
|
1572
|
+
switch (config.type) {
|
|
1573
|
+
case "aisdk": {
|
|
1574
|
+
const result = await config.factory(ctx);
|
|
1575
|
+
events = convertAISDKStream(result.fullStream, controller.signal);
|
|
1576
|
+
break;
|
|
1577
|
+
}
|
|
1578
|
+
case "tanstack": {
|
|
1579
|
+
const stream = await config.factory(ctx);
|
|
1580
|
+
events = convertTanStackStream(stream, controller.signal);
|
|
1581
|
+
break;
|
|
1582
|
+
}
|
|
1583
|
+
case "custom": {
|
|
1584
|
+
events = await config.factory(ctx);
|
|
1585
|
+
break;
|
|
1586
|
+
}
|
|
1587
|
+
default: {
|
|
1588
|
+
const _exhaustive: never = config;
|
|
1589
|
+
throw new Error(
|
|
1590
|
+
`Unknown agent config type: ${(_exhaustive as BuiltInAgentFactoryConfig).type}`,
|
|
1591
|
+
);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
for await (const event of events) {
|
|
1596
|
+
subscriber.next(event);
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
if (!controller.signal.aborted) {
|
|
1600
|
+
const finishedEvent: RunFinishedEvent = {
|
|
1601
|
+
type: EventType.RUN_FINISHED,
|
|
1602
|
+
threadId: input.threadId,
|
|
1603
|
+
runId: input.runId,
|
|
1604
|
+
};
|
|
1605
|
+
subscriber.next(finishedEvent);
|
|
1606
|
+
}
|
|
1607
|
+
subscriber.complete();
|
|
1608
|
+
} catch (error) {
|
|
1609
|
+
if (controller.signal.aborted) {
|
|
1610
|
+
subscriber.complete();
|
|
1611
|
+
} else {
|
|
1612
|
+
const runErrorEvent: RunErrorEvent = {
|
|
1613
|
+
type: EventType.RUN_ERROR,
|
|
1614
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1615
|
+
threadId: input.threadId,
|
|
1616
|
+
runId: input.runId,
|
|
1617
|
+
} as RunErrorEvent;
|
|
1618
|
+
subscriber.next(runErrorEvent);
|
|
1619
|
+
subscriber.error(error);
|
|
1620
|
+
}
|
|
1621
|
+
} finally {
|
|
1622
|
+
this.abortController = undefined;
|
|
1623
|
+
}
|
|
1624
|
+
})();
|
|
1625
|
+
|
|
1626
|
+
return () => {
|
|
1627
|
+
controller.abort();
|
|
1628
|
+
};
|
|
1629
|
+
});
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1417
1632
|
clone() {
|
|
1418
1633
|
const cloned = new BuiltInAgent(this.config);
|
|
1419
|
-
//
|
|
1420
|
-
//
|
|
1634
|
+
// AbstractAgent.middlewares is private in @ag-ui/client — no public accessor exists.
|
|
1635
|
+
// This coupling is intentional: clone() must preserve middleware chains.
|
|
1636
|
+
// @ts-expect-error accessing private AbstractAgent.middlewares
|
|
1421
1637
|
cloned.middlewares = [...this.middlewares];
|
|
1422
1638
|
return cloned;
|
|
1423
1639
|
}
|
|
@@ -1437,4 +1653,7 @@ export class BasicAgent extends BuiltInAgent {
|
|
|
1437
1653
|
}
|
|
1438
1654
|
}
|
|
1439
1655
|
|
|
1440
|
-
|
|
1656
|
+
/** @deprecated Use BuiltInAgentClassicConfig instead */
|
|
1657
|
+
export type BasicAgentConfiguration = BuiltInAgentClassicConfig;
|
|
1658
|
+
|
|
1659
|
+
export * from "./converters";
|
|
@@ -13,6 +13,7 @@ export const config = {
|
|
|
13
13
|
// This import is needed to fix the type error
|
|
14
14
|
// Fix is currently in TypeScript 5.5 beta, waiting for stable version
|
|
15
15
|
// https://github.com/microsoft/TypeScript/issues/42873#issuecomment-2066874644
|
|
16
|
+
// oxlint-disable-next-line unicorn/require-module-specifiers, typescript/no-useless-empty-export
|
|
16
17
|
export type {} from "@whatwg-node/server";
|
|
17
18
|
|
|
18
19
|
export function copilotRuntimeNextJSPagesRouterEndpoint(
|